Files
momentum devandClaude Fable 5 dd13c41fc8 test(019): de-flake watchlist concurrency test — assert single-snapshot consistency
The test compared len(w) and list(w) as two SEPARATE locked reads, so the
churn thread could mutate between them (30 vs 31) — a bug in the test, not the
Watchlist (each read is individually consistent; there is no torn-read
guarantee ACROSS two calls). Now snapshots once and asserts that snapshot never
tears + concurrent contains/slice never raise. 5/5 green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-19 10:46:43 -05:00

60 lines
1.9 KiB
Python

"""Thread-safe watchlist (plan 019): discovery mutates it on its own thread
while ingest/arm iterate it on the scheduler thread. A list-like object that
locks internally, so existing readers (len, `in`, `for`) work unchanged and
every read sees a consistent snapshot — never a torn/half-updated list."""
import threading
from runtime.watchlist import Watchlist
def test_listlike_reads():
w = Watchlist(["AAA", "BBB"])
assert len(w) == 2
assert "AAA" in w and "ZZZ" not in w
assert list(w) == ["AAA", "BBB"]
assert w.snapshot() == ("AAA", "BBB")
def test_add_dedupes_and_preserves_order():
w = Watchlist(["AAA"])
w.extend(["BBB", "AAA", "CCC"]) # AAA already present -> not duplicated
assert list(w) == ["AAA", "BBB", "CCC"]
w.append("DDD")
assert "DDD" in w
def test_trim_keeps_most_recent():
w = Watchlist(["A", "B", "C", "D", "E"])
w.trim(3) # bound to newest 3
assert list(w) == ["C", "D", "E"]
w.trim(10) # no-op when under cap
assert len(w) == 3
def test_concurrent_mutation_never_tears():
w = Watchlist([f"S{i}" for i in range(20)])
stop = threading.Event()
errs = []
def churn():
i = 0
while not stop.is_set():
w.extend([f"N{i}"]); w.trim(30); i += 1
def read():
try:
for _ in range(20000):
s = w.snapshot() # ONE consistent locked read
assert len(s) == len(tuple(s)) # the snapshot never tears
_ = "S0" in w # concurrent contains never raises
_ = w[:5] # concurrent slice never raises
except Exception as e: # noqa: BLE001
errs.append(e)
finally:
stop.set()
t = threading.Thread(target=churn); t.start()
read(); t.join()
assert not errs