diff --git a/pm-stack/opencode-claimant/bench_poll_timing.py b/pm-stack/opencode-claimant/bench_poll_timing.py new file mode 100644 index 0000000000..b8f839de5d --- /dev/null +++ b/pm-stack/opencode-claimant/bench_poll_timing.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""bench_poll_timing.py — the #13135 timing acceptance for poll.py, +runnable anywhere (CI runner included): 10 end-to-end poll.py runs +against fixture backends, p99 wall time must stay under the 30s +pre-#13112 gate budget. + +The fixtures reproduce the production read shape the issue measured +(43–100s wall, ~2s CPU) at its low end, with fixed per-read delays: + + - session list: 28,000 sessions paginated at poll.py's 200/page, + 100ms per page -> ~14s sequential + - active-id set: 1s + - broker /list: 3s per read x 8 reads -> ~24s sequential + - ledger SELECT (stub turso-exec): 5s + +Sequential total ~44s; a poll that overlaps the independent reads +lands near max(session list, broker) + ledger ~19s. Delays are +server-side sleeps in a threading fixture server, so the fixture +itself never serializes poll.py's reads. + +Argument contract (#3352): bench_poll_timing.py [POLL_PY] — zero +arguments benches the sibling poll.py, one argument benches that +file; anything else is a usage error (exit 2) before any work runs. +Exit 0 iff all 10 runs exit 0 and p99 < 30s. +""" + +import json +import os +import subprocess +import sys +import tempfile +import threading +import time +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +RUNS = 10 +P99_BUDGET_S = 30.0 +TOTAL_SESSIONS = 28_000 +PAGE_DELAY_S = 0.10 +ACTIVE_DELAY_S = 1.0 +BROKER_DELAY_S = 3.0 +LEDGER_DELAY_S = 5.0 + +CANDIDATE_ROW = { + "id": 42, + "status": "claimed", + "priority": 1, + "progress": {"lane": "opencode", "stage": "handed_off"}, +} + + +class FixtureHandler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _json(self, payload): + body = json.dumps(payload).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + parsed = urllib.parse.urlparse(self.path) + if parsed.path == "/api/session": + time.sleep(PAGE_DELAY_S) + query = urllib.parse.parse_qs(parsed.query) + limit = int(query["limit"][0]) + start = int(query.get("cursor", ["0"])[0]) + now_ms = int(time.time() * 1000) + page = [ + { + "id": f"ses_{i}", + "time": {"created": now_ms - 600_000, "updated": now_ms - 60_000}, + } + for i in range(start, min(start + limit, TOTAL_SESSIONS)) + ] + nxt = start + limit if start + limit < TOTAL_SESSIONS else None + self._json({"data": page, "cursor": {"next": str(nxt) if nxt else None}}) + elif parsed.path == "/api/session/active": + time.sleep(ACTIVE_DELAY_S) + self._json({"data": {}}) + else: + self.send_response(404) + self.end_headers() + + def do_POST(self): + parsed = urllib.parse.urlparse(self.path) + if parsed.path != "/list": + self.send_response(404) + self.end_headers() + return + time.sleep(BROKER_DELAY_S) + length = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(length) or b"{}") + rows = [] + if body.get("status") == "claimed" and body.get("queue") == ( + "repo-health-code-pilot" + ): + rows = [CANDIDATE_ROW] + self._json({"ok": True, "rows": rows}) + + +def main(): + if len(sys.argv) > 2: + print( + f"bench_poll_timing.py: unexpected argument {sys.argv[2]!r}; " + "usage: python3 bench_poll_timing.py [POLL_PY]", + file=sys.stderr, + ) + return 2 + poll_py = ( + Path(sys.argv[1]).resolve() + if len(sys.argv) == 2 + else Path(__file__).resolve().parent / "poll.py" + ) + if not poll_py.is_file(): + print(f"bench_poll_timing.py: poll.py not found at {poll_py}", file=sys.stderr) + return 2 + + server = ThreadingHTTPServer(("127.0.0.1", 0), FixtureHandler) + server.daemon_threads = True + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with tempfile.TemporaryDirectory(prefix="poll-bench-") as tmp: + home = Path(tmp) + auth = home / ".local" / "state" / "opencode" / "service-prod.json" + auth.parent.mkdir(parents=True) + auth.write_text(json.dumps({"password": "bench"})) + tools = home / "tools" + tools.mkdir() + (tools / "turso-exec.py").write_text( + "import time\n" + f"time.sleep({LEDGER_DELAY_S})\n" + 'print("[0] ok affected=0 rowid=None rows=[]")\n' + ) + token = home / "token" + token.write_text("bench-token\n") + env = dict( + os.environ, + HOME=tmp, + OPENCODE_URL=f"http://127.0.0.1:{port}", + OPENCODE_AUTH_FILE=str(auth), + REPO_QUEUE_BROKER_URL=f"http://127.0.0.1:{port}", + REPO_QUEUE_TOKEN_FILE=str(token), + ) + times = [] + for i in range(RUNS): + start = time.monotonic() + result = subprocess.run( + [sys.executable, str(poll_py)], + env=env, + capture_output=True, + text=True, + timeout=300, + ) + elapsed = time.monotonic() - start + times.append(elapsed) + print(f"run {i + 1}/{RUNS}: {elapsed:.2f}s exit={result.returncode}") + if result.returncode != 0: + print(result.stderr[-2000:], file=sys.stderr) + return 1 + out = json.loads(result.stdout) + if len(out["candidates"]) != 1 or out["cap_room"] is None: + print( + "bench_poll_timing.py: poll output lost its fixture " + f"shape: candidates={len(out['candidates'])} " + f"cap_room={out['cap_room']}", + file=sys.stderr, + ) + return 1 + ordered = sorted(times) + # Nearest-rank p99 over RUNS samples. + p99 = ordered[min(RUNS, max(1, -(-99 * RUNS // 100))) - 1] + print( + f"runs={RUNS} min={ordered[0]:.2f}s " + f"median={ordered[RUNS // 2]:.2f}s p99={p99:.2f}s " + f"budget={P99_BUDGET_S:.0f}s" + ) + return 0 if p99 < P99_BUDGET_S else 1 + finally: + server.shutdown() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index 7d24662b43..2e3300ff28 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -284,13 +284,43 @@ def read_mode() -> str: _code_source: "Dict[str, Any] | None" = None +def _read_git_ref(git_dir: "Path", ref: str) -> "str | None": + """Resolve a git ref to its commit sha by reading .git directly. + + Loose ref first, then packed-refs. Returns None when the ref is + not recorded anywhere. Pure file reads: no git binary is spawned, + so this stays usable under the hermetic suite's no-subprocess + guard (#13135). + """ + try: + sha = (git_dir.joinpath(*ref.split("/"))).read_text().strip() + except OSError: + sha = "" + if len(sha) == 40 and all(c in "0123456789abcdef" for c in sha): + return sha + try: + packed = (git_dir / "packed-refs").read_text().splitlines() + except OSError: + return None + for line in packed: + if line.startswith("#") or line.startswith("^"): + continue + parts = line.split(" ", 1) + if len(parts) == 2 and parts[1].strip() == ref and len(parts[0]) == 40: + return parts[0] + return None + + def read_code_source() -> "Dict[str, Any]": """Read the primary clone's checked-out branch and commit. - Fail-open by design: this is provenance for the fire log, never - a gate. Any git failure (no git binary, not a checkout, timeout) - yields state "unreadable" with branch/commit None rather than - raising - a fire must never abort because its own provenance + Reads .git directly (HEAD plus loose/packed refs) instead of + spawning `git rev-parse`: the fire path never forks for its own + provenance, and the read stays usable under the hermetic suite's + no-subprocess guard (#13135). Fail-open by design: this is + provenance for the fire log, never a gate. Any unreadable .git + layout yields state "unreadable" with branch/commit None rather + than raising - a fire must never abort because its own provenance read failed. The result is cached per process: one fire is one process, and the checkout does not change under a running fire. """ @@ -305,25 +335,28 @@ def read_code_source() -> "Dict[str, Any]": } _code_source = source try: - branch = subprocess.run( - ["git", "-C", str(PRIMARY_CLONE), "rev-parse", "--abbrev-ref", "HEAD"], - capture_output=True, - text=True, - timeout=10, - ) - commit = subprocess.run( - ["git", "-C", str(PRIMARY_CLONE), "rev-parse", "HEAD"], - capture_output=True, - text=True, - timeout=10, - ) - if branch.returncode != 0 or commit.returncode != 0: - source["state"] = "unreadable" - return source - source["branch"] = branch.stdout.strip() or None - source["commit"] = commit.stdout.strip() or None - if source["branch"] is None or source["commit"] is None: - source["state"] = "unreadable" + git_dir = PRIMARY_CLONE / ".git" + if git_dir.is_file(): + # Worktree / linked checkout: .git holds "gitdir: ". + target = git_dir.read_text().strip() + if not target.startswith("gitdir:"): + raise ValueError("unexpected .git file") + git_dir = Path(target[len("gitdir:") :].strip()) + if not git_dir.is_absolute(): + git_dir = PRIMARY_CLONE / git_dir + head = (git_dir / "HEAD").read_text().strip() + if head.startswith("ref:"): + ref = head[len("ref:") :].strip() + branch = ref[len("refs/heads/") :] if ref.startswith("refs/heads/") else ref + commit = _read_git_ref(git_dir, ref) + elif len(head) == 40 and all(c in "0123456789abcdef" for c in head): + branch, commit = "HEAD", head # detached HEAD, as rev-parse reports it + else: + raise ValueError("unparsable HEAD") + if not branch or commit is None: + raise ValueError("ref unresolvable") + source["branch"] = branch + source["commit"] = commit except Exception: source["state"] = "unreadable" return source diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index 09328eeb74..e5ca7cf9b5 100755 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -73,6 +73,13 @@ launch room: an unreadable session list or active set must never become a launch decision. +The reads themselves are independent, so main() runs them +concurrently (#13135): the session list, the active set and every +queue's row reads overlap, and the ledger read starts the moment +the queue reads land. Each read is bounded at its transport (the +*_READ_TIMEOUT_S constants) and a read slower than SLOW_READ_MS +leaves a recorded slow-read note (see _timed_read). + The pure classification functions (is_candidate, is_active_root, count_active_roots, count_active_claimant_roots, is_scheduled_session, summarize_cap, parse_lease_ms, is_stuck_bound) are the contract @@ -94,6 +101,7 @@ import urllib.request import urllib.error import urllib.parse +from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path @@ -182,6 +190,20 @@ def _required_home() -> Path: # could only ever under-report candidates, never invent one. LIST_LIMIT = 500 +# Per-read timeouts (#13135): every external read below is bounded at +# its transport, so one slow backend degrades the poll — fail-closed +# None/[] plus the recorded notes — instead of silently eating the +# claimant's gate budget. The values are the historical ones; the +# broker's 30s is pinned by test_poll_transport.py. +SERVER_READ_TIMEOUT_S = 15 # one OpenCode server GET (one session page) +BROKER_READ_TIMEOUT_S = 30 # one queue-broker /list POST +LEDGER_READ_TIMEOUT_S = 60 # the turso-exec ledger SELECT subprocess +# A read slower than this earns a recorded slow-read note (stderr + +# slow_reads()) even when it succeeds: the degradation signal must be +# visible in the claimant fire log before a read gets anywhere near +# its timeout, not only after it fails. +SLOW_READ_MS = 5000 + # Read-only lane-ledger read for the #5508 stale-binding check: the # turso-exec helper (the same credential-free read path pr-diff-review # uses for agent_repo_snapshots) runs a SELECT against the fleet-queue @@ -307,7 +329,7 @@ def fetch_ledger_bindings(task_ids): [sys.executable, str(TURSO_EXEC), LEDGER_DB, sql_path], capture_output=True, text=True, - timeout=_poll_timeout(60), + timeout=_poll_timeout(LEDGER_READ_TIMEOUT_S), ) finally: os.unlink(sql_path) @@ -588,7 +610,7 @@ def _server_get(path, *, include_envelope=False, raise_http_errors=False): token = base64.b64encode(f"opencode:{credential}".encode()).decode() req.add_header("Authorization", f"Basic {token}") try: - with urllib.request.urlopen(req, timeout=_poll_timeout(15)) as res: + with urllib.request.urlopen(req, timeout=_poll_timeout(SERVER_READ_TIMEOUT_S)) as res: data = json.loads(res.read() or "null") except urllib.error.HTTPError: if raise_http_errors: @@ -684,7 +706,7 @@ def _broker_post(path, body): if url.startswith("unix://"): # Same HTTP API/auth as TCP, but the URL suffix is a literal socket # path, not an HTTP base URL. Never append /list to that filename. - conn = _UnixHTTPConnection(url[len("unix://") :], timeout=_poll_timeout(30)) + conn = _UnixHTTPConnection(url[len("unix://") :], timeout=_poll_timeout(BROKER_READ_TIMEOUT_S)) try: conn.request("POST", path, body=payload, headers=headers) with conn.getresponse() as res: @@ -707,13 +729,47 @@ def _broker_post(path, body): headers=headers, method="POST", ) - with urllib.request.urlopen(req, timeout=_poll_timeout(30)) as res: + with urllib.request.urlopen(req, timeout=_poll_timeout(BROKER_READ_TIMEOUT_S)) as res: data = json.loads(res.read() or "null") if isinstance(data, dict) and data.get("ok") is False: raise RuntimeError(f"broker {path} failed: {str(data.get('error'))[:200]}") return data +# Slow-read notes from the most recent poll cycle (#13135): one +# {"read", "elapsed_ms"} dict per external read that took at least +# SLOW_READ_MS, in completion order. A slow read still returns its +# normal result — the note is the recorded degradation signal (also +# printed to stderr, where the claimant fire log shows it), so a +# backend drifting toward its timeout is visible polls before it +# starts failing closed. +_SLOW_READS = [] + + +def slow_reads(): + """Slow-read notes recorded by the latest poll cycle; empty when + every read finished inside SLOW_READ_MS.""" + return list(_SLOW_READS) + + +def _timed_read(name, fn, *args): + """Run one external read, recording a slow-read note when it takes + at least SLOW_READ_MS. The result — and any exception — is exactly + fn's own: timing never changes a read's fail-closed semantics.""" + start = time.monotonic() + try: + return fn(*args) + finally: + elapsed_ms = int((time.monotonic() - start) * 1000) + if elapsed_ms >= SLOW_READ_MS: + _SLOW_READS.append({"read": name, "elapsed_ms": elapsed_ms}) + print( + f"Note: slow read {name} took {elapsed_ms}ms " + f"(slow-read threshold {SLOW_READ_MS}ms)", + file=sys.stderr, + ) + + # Read failures from the most recent poll cycle, keyed (queue, status) # -> first-line error text (#8042). _fetch_rows still returns [] on a # failure — a queue that cannot be read contributes no candidates and @@ -981,35 +1037,74 @@ def main(): ) _poll_phase("session_census") now_ms = int(time.time() * 1000) - # Sessions first: stuck-bound classification (#4758) needs the - # session list and the server's active set, and the cap summary - # below reuses the same two reads. - sessions = fetch_sessions() - _poll_phase("active_sessions") - active_ids = fetch_active_ids() if sessions is not None else None + _READ_ERRORS.clear() + _SLOW_READS.clear() + # #13135: the poll's external reads are independent — the session + # list, the server's active set, and every queue's claimed and + # handed_off rows — so they run concurrently instead of strictly + # sequentially; the poll's wall time becomes the slowest single + # read (each bounded at its transport by _poll_timeout, which + # caps the named *_READ_TIMEOUT_S at the remaining poll budget) + # rather than the sum of all of them. The lane-ledger read still + # waits: it needs the candidate-shaped task ids from every queue. + # It runs the moment the queue reads land, overlapping any session + # read still in flight. Results are consumed in the original + # QUEUES order, so the printed JSON is unchanged in shape and + # ordering. The _poll_phase markers fire in consumption order in + # this parallel flow (broker reads, then ledger, then the session + # census), not submission order. + with ThreadPoolExecutor(max_workers=2 + 2 * len(QUEUES)) as pool: + sessions_f = pool.submit(_timed_read, "session list", fetch_sessions) + active_f = pool.submit( + _timed_read, "active session ids", fetch_active_ids + ) + row_futures = { + q: ( + pool.submit( + _timed_read, f"queue {q} claimed rows", fetch_claimed_rows, q + ), + pool.submit( + _timed_read, + f"queue {q} handed_off rows", + fetch_handed_off_rows, + q, + ), + ) + for q in QUEUES + } + # Fetch every queue's rows first so the lane ledger is read + # ONCE for the whole poll (#5508): candidate-shaped rows from + # claimed and handed_off rows alike are decided against the + # same ledger snapshot. + _poll_phase("broker_reads") + per_queue = {} + shaped_ids = [] + for q in QUEUES: + rows = row_futures[q][0].result() + handed_off_rows = row_futures[q][1].result() + shaped = get_candidates(rows) + get_handed_off_candidates( + handed_off_rows + ) + per_queue[q] = (rows, handed_off_rows, shaped) + shaped_ids.extend(r.get("id") for r in shaped) + _poll_phase("ledger_read") + bindings = _timed_read( + "ledger bindings", fetch_ledger_bindings, shaped_ids + ) + _poll_phase("snapshot") + sessions = sessions_f.result() + _poll_phase("active_sessions") + # The active set is only meaningful alongside the session + # list; when the list is unreadable the original code never + # fetched it, and the cap fails closed either way. + active_ids = active_f.result() if sessions is not None else None session_by_id = {} if sessions: for s in sessions: if isinstance(s, dict) and s.get("id"): session_by_id[s["id"]] = s - _READ_ERRORS.clear() out = {"queues": {}, "candidates": [], "stuck_bound": [], "stale_binding": []} - # Fetch every queue's rows first so the lane ledger is read ONCE - # for the whole poll (#5508): candidate-shaped rows from claimed - # and handed_off rows alike are decided against the same ledger - # snapshot. - _poll_phase("broker_reads") - per_queue = {} - shaped_ids = [] - for q in QUEUES: - rows = fetch_claimed_rows(q) - handed_off_rows = fetch_handed_off_rows(q) - shaped = get_candidates(rows) + get_handed_off_candidates(handed_off_rows) - per_queue[q] = (rows, handed_off_rows, shaped) - shaped_ids.extend(r.get("id") for r in shaped) - _poll_phase("ledger_read") - bindings = fetch_ledger_bindings(shaped_ids) - _poll_phase("snapshot") + out["ledger_readable"] = bindings is not None for q in QUEUES: rows, handed_off_rows, shaped = per_queue[q] diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index b9d6435a44..ffffc6e987 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -1719,36 +1719,20 @@ def tearDown(self): claimant._code_source = None def _make_clone(self, tmp: str) -> Path: + # A static .git layout written with plain file writes (#13135): + # the hermetic suite's audit guard forbids subprocess spawns, + # so the fixture cannot run `git init` — and read_code_source() + # reads .git directly, so no git binary is needed for the read + # either. The commit sha is a fixed 40-hex placeholder; the + # tests assert shape (branch, 40-char commit), not history. clone = Path(tmp) / "clone" - clone.mkdir() - env = dict(os.environ) - env.update( - { - "GIT_AUTHOR_NAME": "test", - "GIT_AUTHOR_EMAIL": "test@example.invalid", - "GIT_COMMITTER_NAME": "test", - "GIT_COMMITTER_EMAIL": "test@example.invalid", - } - ) - subprocess.run( - ["git", "init", "-b", "main", str(clone)], - check=True, - capture_output=True, - env=env, + git_dir = clone / ".git" + (git_dir / "refs" / "heads").mkdir(parents=True) + (git_dir / "HEAD").write_text("ref: refs/heads/main\n") + (git_dir / "refs" / "heads" / "main").write_text( + "0123456789abcdef0123456789abcdef01234567\n" ) (clone / "f.txt").write_text("x") - subprocess.run( - ["git", "-C", str(clone), "add", "f.txt"], - check=True, - capture_output=True, - env=env, - ) - subprocess.run( - ["git", "-C", str(clone), "commit", "-m", "init"], - check=True, - capture_output=True, - env=env, - ) return clone def test_reads_branch_and_commit(self): diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index 9c1da28209..5979bd5ae7 100755 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -9,9 +9,12 @@ never count. """ +import contextlib import importlib.util +import io import json import tempfile +import time import unittest import urllib.error import urllib.parse @@ -993,5 +996,174 @@ def test_repeated_census_cursor_is_incomplete(self): self.assertEqual(request.call_count, 2) +class TestReadTimeoutConstants(unittest.TestCase): + """#13135: every external read is bounded at its transport. The + constants carry the historical values — the broker's 30s is also + pinned end-to-end by test_poll_transport.py — and the slow-read + threshold sits far below every timeout so drift is noted before + a read can fail.""" + + def test_timeouts_carry_the_historical_values(self): + self.assertEqual(poll.SERVER_READ_TIMEOUT_S, 15) + self.assertEqual(poll.BROKER_READ_TIMEOUT_S, 30) + self.assertEqual(poll.LEDGER_READ_TIMEOUT_S, 60) + + def test_slow_threshold_below_every_timeout(self): + self.assertLess(poll.SLOW_READ_MS, poll.SERVER_READ_TIMEOUT_S * 1000) + self.assertLess(poll.SLOW_READ_MS, poll.BROKER_READ_TIMEOUT_S * 1000) + self.assertLess(poll.SLOW_READ_MS, poll.LEDGER_READ_TIMEOUT_S * 1000) + + +class TestTimedRead(unittest.TestCase): + """#13135: _timed_read records a slow-read note for a read that + takes at least SLOW_READ_MS and is otherwise transparent — same + result, same exceptions.""" + + def setUp(self): + poll._SLOW_READS.clear() + + def tearDown(self): + poll._SLOW_READS.clear() + + def test_fast_read_records_no_note(self): + with patch.object(poll, "SLOW_READ_MS", 60_000): + self.assertEqual(poll._timed_read("fast", lambda: 42), 42) + self.assertEqual(poll.slow_reads(), []) + + def test_slow_read_records_note_and_returns_result(self): + def slow(): + time.sleep(0.05) + return "rows" + + with patch.object(poll, "SLOW_READ_MS", 10): + with contextlib.redirect_stderr(io.StringIO()) as err: + self.assertEqual(poll._timed_read("queue q claimed rows", slow), "rows") + notes = poll.slow_reads() + self.assertEqual(len(notes), 1) + self.assertEqual(notes[0]["read"], "queue q claimed rows") + self.assertGreaterEqual(notes[0]["elapsed_ms"], 10) + self.assertIn("slow read queue q claimed rows", err.getvalue()) + + def test_slow_failing_read_still_records_and_propagates(self): + def slow_fail(): + time.sleep(0.05) + raise RuntimeError("backend down") + + with patch.object(poll, "SLOW_READ_MS", 10): + with contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(RuntimeError): + poll._timed_read("ledger bindings", slow_fail) + self.assertEqual([n["read"] for n in poll.slow_reads()], ["ledger bindings"]) + + +class TestMainParallelReads(unittest.TestCase): + """#13135: main() runs the independent external reads concurrently + and the printed JSON keeps its exact shape and semantics. Every + fetch is stubbed; no broker, server or subprocess is touched.""" + + SLEEP_S = 0.25 + + def run_main(self, sessions_ok): + now = int(time.time() * 1000) + live_root = { + "id": "ses_live", + "time": {"created": now - 5 * MIN, "updated": now - MIN}, + } + candidate = { + "id": 42, + "status": "claimed", + "priority": 1, + "progress": {"lane": "opencode", "stage": "handed_off"}, + } + + def fake_sessions(): + time.sleep(self.SLEEP_S) + return [live_root] if sessions_ok else None + + def fake_active(): + time.sleep(self.SLEEP_S) + return set() + + def fake_claimed(queue): + time.sleep(self.SLEEP_S) + return [dict(candidate)] if queue == poll.QUEUES[0] else [] + + def fake_handed_off(queue): + time.sleep(self.SLEEP_S) + return [] + + def fake_bindings(ids): + time.sleep(self.SLEEP_S) + return {} + + stdout = io.StringIO() + start = time.monotonic() + with ( + patch.object(poll, "fetch_sessions", side_effect=fake_sessions), + patch.object(poll, "fetch_active_ids", side_effect=fake_active), + patch.object(poll, "fetch_claimed_rows", side_effect=fake_claimed), + patch.object(poll, "fetch_handed_off_rows", side_effect=fake_handed_off), + patch.object(poll, "fetch_ledger_bindings", side_effect=fake_bindings), + contextlib.redirect_stdout(stdout), + contextlib.redirect_stderr(io.StringIO()), + ): + rc = poll.main() + elapsed = time.monotonic() - start + return rc, json.loads(stdout.getvalue()), elapsed + + def test_reads_overlap_and_output_shape_is_unchanged(self): + rc, out, elapsed = self.run_main(True) + self.assertEqual(rc, 0) + # 11 stubbed reads of SLEEP_S each: sequential would take + # ~2.75s; concurrent must finish in a small multiple of one + # read (the ledger read still waits for the queue reads). + self.assertLess(elapsed, 6 * self.SLEEP_S) + self.assertEqual( + set(out), + { + "queues", + "candidates", + "stuck_bound", + "stale_binding", + "ledger_readable", + "live_root_sessions", + "active_root_sessions", + "cap", + "concurrency_cap", + "cap_room", + }, + ) + self.assertEqual(set(out["queues"]), set(poll.QUEUES)) + for entry in out["queues"].values(): + self.assertEqual( + set(entry), + { + "claimed", + "handed_off", + "candidates", + "stuck_bound", + "stale_binding", + "read_ok", + "read_errors", + }, + ) + self.assertTrue(entry["read_ok"]) + self.assertEqual([c["id"] for c in out["candidates"]], [42]) + self.assertEqual(out["candidates"][0]["queue"], poll.QUEUES[0]) + self.assertTrue(out["ledger_readable"]) + self.assertEqual(out["live_root_sessions"], 1) + self.assertEqual(out["active_root_sessions"], 1) + self.assertEqual(out["cap_room"], poll.CAP - 1) + + def test_unreadable_session_list_still_fails_closed(self): + rc, out, _elapsed = self.run_main(False) + self.assertEqual(rc, 0) + self.assertIsNone(out["live_root_sessions"]) + self.assertIsNone(out["active_root_sessions"]) + self.assertIsNone(out["cap_room"]) + # Queue discovery is unaffected by the server outage. + self.assertEqual([c["id"] for c in out["candidates"]], [42]) + + if __name__ == "__main__": unittest.main()