| 1 | """Run-scoped fetch memo (U3, R5): one network fetch per distinct key per run, |
| 2 | shared by concurrent callers as independent copies. A failure reaches only the |
| 3 | callers already waiting on it; a later call fetches again.""" |
| 4 | |
| 5 | import threading |
| 6 | from concurrent.futures import ThreadPoolExecutor |
| 7 | |
| 8 | import pytest |
| 9 | |
| 10 | from lib import fetch_memo, health, http |
| 11 | |
| 12 | |
| 13 | def _fetch_counter(payload): |
| 14 | calls = [] |
| 15 | |
| 16 | def _fetch(): |
| 17 | calls.append(1) |
| 18 | return payload |
| 19 | |
| 20 | return calls, _fetch |
| 21 | |
| 22 | |
| 23 | def test_concurrent_same_key_fetches_once_and_returns_independent_copies(): |
| 24 | release = threading.Event() |
| 25 | arrived = threading.Barrier(4, timeout=5) |
| 26 | calls = [] |
| 27 | |
| 28 | def _slow(): |
| 29 | calls.append(1) |
| 30 | release.wait(timeout=5) |
| 31 | return {"items": [{"id": "a", "tags": []}]} |
| 32 | |
| 33 | def _call(): |
| 34 | arrived.wait() |
| 35 | return fetch_memo.fetch_once(("tiktok", "q"), _slow, timeout=10) |
| 36 | |
| 37 | with ThreadPoolExecutor(max_workers=4) as pool: |
| 38 | futures = [pool.submit(_call) for _ in range(4)] |
| 39 | # Let every caller reach the memo before the owner finishes. |
| 40 | threading.Timer(0.2, release.set).start() |
| 41 | results = [f.result(timeout=10) for f in futures] |
| 42 | |
| 43 | assert len(calls) == 1 |
| 44 | assert all(r == {"items": [{"id": "a", "tags": []}]} for r in results) |
| 45 | results[0]["items"][0]["tags"].append("mutated") |
| 46 | assert all(r["items"][0]["tags"] == [] for r in results[1:]) |
| 47 | |
| 48 | |
| 49 | def test_sequential_same_key_serves_an_independent_copy(): |
| 50 | calls, fetch = _fetch_counter({"items": [{"id": "a"}]}) |
| 51 | first = fetch_memo.fetch_once(("youtube", "q"), fetch, timeout=1) |
| 52 | first["items"].append({"id": "mutated"}) |
| 53 | second = fetch_memo.fetch_once(("youtube", "q"), fetch, timeout=1) |
| 54 | assert len(calls) == 1 |
| 55 | assert second == {"items": [{"id": "a"}]} |
| 56 | |
| 57 | |
| 58 | def test_different_keys_fetch_separately(): |
| 59 | calls, fetch = _fetch_counter({"items": []}) |
| 60 | fetch_memo.fetch_once(("youtube", "q", "2026-09-01", "2026-10-01", "default"), fetch, timeout=1) |
| 61 | fetch_memo.fetch_once(("youtube", "q", "2026-09-02", "2026-10-01", "default"), fetch, timeout=1) |
| 62 | fetch_memo.fetch_once(("youtube", "q", "2026-09-01", "2026-10-01", "deep"), fetch, timeout=1) |
| 63 | assert len(calls) == 3 |
| 64 | |
| 65 | |
| 66 | def test_owner_failure_reaches_concurrent_waiters_and_a_later_call_refetches(): |
| 67 | release = threading.Event() |
| 68 | arrived = threading.Barrier(3, timeout=5) |
| 69 | calls = [] |
| 70 | boom = RuntimeError("HTTP 503: Service Unavailable") |
| 71 | |
| 72 | def _failing(): |
| 73 | calls.append(1) |
| 74 | release.wait(timeout=5) |
| 75 | raise boom |
| 76 | |
| 77 | def _call(): |
| 78 | arrived.wait() |
| 79 | return fetch_memo.fetch_once(("x", "q"), _failing, timeout=10) |
| 80 | |
| 81 | with ThreadPoolExecutor(max_workers=3) as pool: |
| 82 | futures = [pool.submit(_call) for _ in range(3)] |
| 83 | threading.Timer(0.2, release.set).start() |
| 84 | errors = [] |
| 85 | for future in futures: |
| 86 | with pytest.raises(RuntimeError) as exc_info: |
| 87 | future.result(timeout=10) |
| 88 | errors.append(exc_info.value) |
| 89 | |
| 90 | assert len(calls) == 1 |
| 91 | assert all(err is boom for err in errors) |
| 92 | |
| 93 | later_calls, later = _fetch_counter({"items": [{"id": "b"}]}) |
| 94 | assert fetch_memo.fetch_once(("x", "q"), later, timeout=1) == {"items": [{"id": "b"}]} |
| 95 | assert len(later_calls) == 1 |
| 96 | |
| 97 | |
| 98 | def test_uncacheable_result_reaches_waiters_but_a_later_call_refetches(): |
| 99 | calls, fetch = _fetch_counter({"items": [], "error": "HTTP 429"}) |
| 100 | clean = lambda value: not value.get("error") # noqa: E731 |
| 101 | fetch_memo.fetch_once(("tiktok", "q"), fetch, timeout=1, cacheable=clean) |
| 102 | fetch_memo.fetch_once(("tiktok", "q"), fetch, timeout=1, cacheable=clean) |
| 103 | assert len(calls) == 2 |
| 104 | |
| 105 | |
| 106 | def test_swallowed_failure_reaches_waiters_and_is_not_cached(): |
| 107 | # Source adapters swallow HTTP errors into the stream's failure sink. A |
| 108 | # waiter must see the owner's failure, and the result must not be cached. |
| 109 | release = threading.Event() |
| 110 | arrived = threading.Barrier(2, timeout=5) |
| 111 | calls = [] |
| 112 | |
| 113 | def _swallow_429(): |
| 114 | calls.append(1) |
| 115 | release.wait(timeout=5) |
| 116 | http._record_failure(http.HTTPError("HTTP 429: Too Many Requests", status_code=429)) |
| 117 | return {"items": []} |
| 118 | |
| 119 | def _call(): |
| 120 | arrived.wait() |
| 121 | with http.capture_failures() as sink: |
| 122 | result = fetch_memo.fetch_once(("instagram", "q"), _swallow_429, timeout=10) |
| 123 | return result, [f.status_code for f in sink] |
| 124 | |
| 125 | with ThreadPoolExecutor(max_workers=2) as pool: |
| 126 | futures = [pool.submit(_call) for _ in range(2)] |
| 127 | threading.Timer(0.2, release.set).start() |
| 128 | results = [f.result(timeout=10) for f in futures] |
| 129 | |
| 130 | assert len(calls) == 1 |
| 131 | assert all(sink == [429] for _result, sink in results) |
| 132 | fetch_memo.fetch_once(("instagram", "q"), _swallow_429, timeout=1) |
| 133 | assert len(calls) == 2 |
| 134 | |
| 135 | |
| 136 | def test_waiter_times_out_instead_of_blocking_past_its_budget(): |
| 137 | release = threading.Event() |
| 138 | owner_started = threading.Event() |
| 139 | |
| 140 | def _hung(): |
| 141 | owner_started.set() |
| 142 | release.wait(timeout=5) |
| 143 | return {"items": []} |
| 144 | |
| 145 | owner = threading.Thread( |
| 146 | target=fetch_memo.fetch_once, args=(("youtube", "q"), _hung), kwargs={"timeout": 10}, |
| 147 | daemon=True, |
| 148 | ) |
| 149 | owner.start() |
| 150 | assert owner_started.wait(timeout=5) |
| 151 | try: |
| 152 | with pytest.raises(fetch_memo.MemoWaitTimeout) as exc_info: |
| 153 | fetch_memo.fetch_once(("youtube", "q"), _hung, timeout=0.1) |
| 154 | assert exc_info.value.outcome_state == health.TIMEOUT |
| 155 | finally: |
| 156 | release.set() |
| 157 | owner.join(timeout=5) |
| 158 | |
| 159 | |
| 160 | def test_reset_forgets_cached_results(): |
| 161 | calls, fetch = _fetch_counter({"items": []}) |
| 162 | fetch_memo.fetch_once(("youtube", "q"), fetch, timeout=1) |
| 163 | fetch_memo.reset() |
| 164 | fetch_memo.fetch_once(("youtube", "q"), fetch, timeout=1) |
| 165 | assert len(calls) == 2 |
| 166 |