From 8d9834663a02ad9aab6c9aa674af0a2864b0c429 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 18:57:46 -0500 Subject: [PATCH 1/3] claimant: count only active root sessions toward the 12 cap (#3026 gate) poll.py counted every root GET /api/session returns; finished-but-unarchived sessions accumulate forever (50 roots at the gate check, 46 finished), pinning cap_room at 0 and deadlocking live mode. A root now counts only while active: no terminal marker (time.idle / outcome, the finished shape verified on the live server) and activity within 30 min (a marker-less root silent longer is a zombie, not a worker). poll.py reports active_root_sessions beside the raw live_root_sessions; cap_room derives from the active count; an unreadable server still yields cap_room null (fails closed). prompt.md cap step now reads cap_room; README known-gap marked resolved. Tests: new test_poll.py 9/9 (child/idle/outcome/stale/boundary/created-fallback/mixed count); bun test 7/7 unchanged. Live poll from this branch: live_root_sessions 50, active_root_sessions 0, cap_room 12, candidates 0. Queue task 4408 (parallel-run gate for #3026). --- pm-stack/opencode-claimant/README.md | 25 +++++--- pm-stack/opencode-claimant/poll.py | 61 +++++++++++++++---- pm-stack/opencode-claimant/prompt.md | 13 ++-- pm-stack/opencode-claimant/test_poll.py | 80 +++++++++++++++++++++++++ 4 files changed, 155 insertions(+), 24 deletions(-) create mode 100644 pm-stack/opencode-claimant/test_poll.py diff --git a/pm-stack/opencode-claimant/README.md b/pm-stack/opencode-claimant/README.md index efde292882..7d38a8d125 100644 --- a/pm-stack/opencode-claimant/README.md +++ b/pm-stack/opencode-claimant/README.md @@ -63,16 +63,23 @@ defect, not a launch. ## Tests `bun test` in this directory (merge idempotence, prompt embedding, -store-shape refusal). The worked example for slice 1 is +store-shape refusal); `python3 -m unittest test_poll.py` here covers +poll.py's active-only cap counting. The worked example for slice 1 is `install.mjs --dry-run` against the live store plus a shadow `poll.py` run: both are read-only and are recorded on #3026. -## Known gap found by the first shadow poll (2026-10-31) +## Known gap found by the first shadow poll (2026-10-31) — RESOLVED by the gate -`poll.py` counts every root session `GET /api/session` returns — 41 at -the first shadow run, most of them finished-but-unarchived lane -sessions. So `cap_room` reads 0 even when few sessions are active. -Shadow mode is unaffected (it launches nothing), but the gate packet -must refine the count to active sessions (recent activity / busy -status) before live mode is enabled; until then the cap fails closed, -which is the safe direction. +`poll.py` originally counted every root session `GET /api/session` +returns — 41 at the first shadow run, most of them +finished-but-unarchived lane sessions, so `cap_room` read 0 even when +few sessions were active. The gate refinement (task 4408) counts only +**active** roots toward the cap: a finished session carries +`time.idle` and an `outcome` (both verified on the live server: 50 +roots, 46 finished, at the gate check), a running one carries neither, +and a marker-less root silent for 30+ minutes is treated as a zombie, +not a worker. `poll.py` still reports the raw root total as +`live_root_sessions` alongside the new `active_root_sessions`; +`cap_room` derives from the active count. An unreadable server still +yields `cap_room: null` — the cap fails closed, which is the safe +direction. diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index 6dfa131e59..373e33f2c3 100644 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -7,9 +7,13 @@ "candidates": [ {id, queue, priority, worker_id, lease_until, issue_number} ... ], # claimed, progress.lane == # "opencode", no session_id - "live_root_sessions": int | null, # null = server unreadable + "live_root_sessions": int | null, # all root sessions; + # null = server unreadable + "active_root_sessions": int | null, # roots still active + # (see is_active_root) "cap": 12, - "cap_room": int | null # null when count unknown + "cap_room": int | null # CAP - active roots; + # null when count unknown } Read-only by construction: it issues only PostgREST GETs (through the @@ -22,6 +26,7 @@ import json import os import sys +import time import urllib.request import base64 @@ -32,6 +37,37 @@ "repo-health-nix-pilot", ] CAP = 12 +# A root session counts toward the cap only while it is active: no +# terminal marker and recent activity. GET /api/session returns every +# finished-but-unarchived session forever (50 roots at the #3026 gate +# check, 46 of them finished), so counting all roots pins cap_room at +# 0 and deadlocks the claimant. A finished session carries time.idle +# and an outcome; a running one carries neither. A marker-less session +# silent longer than this window is indistinguishable from a zombie +# whose client died mid-run, so it stops counting too — the claimant +# fires every 10 min and a working session updates far more often. +ACTIVE_WINDOW_MS = 30 * 60 * 1000 + + +def is_root_session(s): + return isinstance(s, dict) and not s.get("parentID") \ + and not s.get("parent_id") + + +def is_active_root(s, now_ms): + if not is_root_session(s): + return False + t = s.get("time") or {} + if t.get("idle") or s.get("outcome"): + return False + updated = t.get("updated") or t.get("created") or 0 + return now_ms - updated < ACTIVE_WINDOW_MS + + +def count_active_roots(sessions, now_ms): + return sum(1 for s in sessions if is_active_root(s, now_ms)) + + HELPER = os.environ.get( "REPO_QUEUE_HELPER", os.path.expanduser("~/hatch/tools/repo-queue.py")) OPENCODE_URL = os.environ.get("OPENCODE_URL", "http://127.0.0.1:13420") @@ -47,7 +83,7 @@ def load_helper(): return mod -def live_root_sessions(): +def fetch_sessions(): try: with open(AUTH_FILE) as f: password = json.load(f)["password"] @@ -65,10 +101,7 @@ def live_root_sessions(): data = data["data"] if not isinstance(data, list): return None - roots = [s for s in data - if isinstance(s, dict) and not s.get("parentID") - and not s.get("parent_id")] - return len(roots) + return data def main(): @@ -98,10 +131,18 @@ def main(): out["candidates"].extend(cands) out["candidates"].sort(key=lambda c: (c["priority"] is None, c["priority"] or 0)) - count = live_root_sessions() - out["live_root_sessions"] = count + sessions = fetch_sessions() out["cap"] = CAP - out["cap_room"] = None if count is None else max(0, CAP - count) + if sessions is None: + out["live_root_sessions"] = None + out["active_root_sessions"] = None + out["cap_room"] = None + else: + roots = [s for s in sessions if is_root_session(s)] + active = count_active_roots(roots, int(time.time() * 1000)) + out["live_root_sessions"] = len(roots) + out["active_root_sessions"] = active + out["cap_room"] = max(0, CAP - active) print(json.dumps(out, indent=1)) return 0 diff --git a/pm-stack/opencode-claimant/prompt.md b/pm-stack/opencode-claimant/prompt.md index 8bc27d48a0..927ef76b44 100644 --- a/pm-stack/opencode-claimant/prompt.md +++ b/pm-stack/opencode-claimant/prompt.md @@ -34,10 +34,12 @@ Never claim, bind, launch, or mutate a task in shadow mode. are claimed, lane-assigned `opencode` in their progress, and carry no bound `session_id` yet — the unbound launches this task exists to close — plus the live root-session count for the cap. -- Concurrency cap: **12** live root sessions across the fleet. Count +- Concurrency cap: **12** active root sessions across the fleet. Count with poll.py (OpenCode server `GET /api/session` on - http://127.0.0.1:13420, root sessions only). If the count is at or - above the cap, launch nothing this fire. + http://127.0.0.1:13420, root sessions only; poll.py counts a root as + active only with no terminal marker — `time.idle`/`outcome` — and + activity in the last 30 min, and reports it as `cap_room`). If + `cap_room` is 0 or null, launch nothing this fire. - Route: the task packet's route when it names one, else the Workhorse default — scheduled-task execution route `providerID: "opencode-route"`, `modelID: "workhorse"`, agent @@ -62,8 +64,9 @@ Never claim, bind, launch, or mutate a task in shadow mode. 2. GATE: run the helper `health` for the four queues. If every queue shows 0 claimed-with-lane-opencode unbound candidates (poll.py returns an empty candidate list), end the fire quietly. -3. CAP: if poll.py reports the live root-session count >= 12, end the - fire; record the saturation in the fire log (step 6). +3. CAP: if poll.py reports `cap_room` 0 (active root sessions at the + 12 cap) or null (server unreadable), end the fire; record the + saturation in the fire log (step 6). 4. For each candidate, highest queue priority first, while cap room remains: a. Re-verify the task is still claimed, still lane `opencode`, diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py new file mode 100644 index 0000000000..697b085e80 --- /dev/null +++ b/pm-stack/opencode-claimant/test_poll.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Tests for poll.py's active-only cap counting (#3026 gate). + +Run: python3 -m unittest pm-stack/opencode-claimant/test_poll.py + +Fixtures mirror the live server's session shape (GET /api/session, +verified 2026-10-31): a finished root session carries time.idle and an +outcome; a running one carries neither. Non-dict / child entries must +never count. +""" +import importlib.util +import unittest +from pathlib import Path + +_spec = importlib.util.spec_from_file_location( + "poll", Path(__file__).resolve().parent / "poll.py") +poll = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(poll) + +NOW = 1_793_500_000_000 +MIN = 60 * 1000 + + +def root(**over): + s = {"id": "ses_x", "time": {"created": NOW - 5 * MIN, + "updated": NOW - 1 * MIN}} + s.update(over) + return s + + +class TestIsActiveRoot(unittest.TestCase): + def test_fresh_markerless_root_is_active(self): + self.assertTrue(poll.is_active_root(root(), NOW)) + + def test_child_session_never_active(self): + self.assertFalse(poll.is_active_root(root(parentID="ses_p"), NOW)) + self.assertFalse(poll.is_active_root(root(parent_id="ses_p"), NOW)) + + def test_idle_marker_is_finished(self): + s = root() + s["time"]["idle"] = NOW + self.assertFalse(poll.is_active_root(s, NOW)) + + def test_outcome_is_finished(self): + self.assertFalse(poll.is_active_root(root(outcome="failed"), NOW)) + self.assertFalse(poll.is_active_root(root(outcome="completed"), NOW)) + + def test_stale_markerless_root_is_a_zombie(self): + s = root() + s["time"]["updated"] = NOW - 31 * MIN + self.assertFalse(poll.is_active_root(s, NOW)) + + def test_window_boundary_is_excluded(self): + s = root() + s["time"]["updated"] = NOW - poll.ACTIVE_WINDOW_MS + self.assertFalse(poll.is_active_root(s, NOW)) + s["time"]["updated"] = NOW - poll.ACTIVE_WINDOW_MS + 1 + self.assertTrue(poll.is_active_root(s, NOW)) + + def test_created_is_the_fallback_clock(self): + s = {"id": "ses_x", "time": {"created": NOW - 1 * MIN}} + self.assertTrue(poll.is_active_root(s, NOW)) + + def test_non_dict_and_timeless_entries_never_active(self): + self.assertFalse(poll.is_active_root("nope", NOW)) + self.assertFalse(poll.is_active_root({"id": "ses_x"}, NOW)) + + def test_count_active_roots_over_a_mixed_list(self): + finished = root(outcome="failed") + finished["time"]["idle"] = NOW + sessions = [root(), root(), finished, + root(parentID="ses_p"), + {"id": "ses_old", + "time": {"created": NOW - 90 * MIN, + "updated": NOW - 90 * MIN}}] + self.assertEqual(poll.count_active_roots(sessions, NOW), 2) + + +if __name__ == "__main__": + unittest.main() From 95a416786f5c148946257bba3300020ef38506d0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 19:04:31 -0500 Subject: [PATCH 2/3] claimant: server active set overrides stored outcome (Codex P1 on #3262) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A resumed root session keeps its stored outcome/time.idle from the earlier run while mid-run again; the marker predicate alone would exclude it and could over-launch past the cap. poll.py now also reads GET /api/session/active and counts any root in that set regardless of stored markers — the same override the aggregator session mapper applies (pm-stack/aggregator/src/sources/opencode.ts). If the active endpoint is unreadable, counting falls back to the marker+recency predicate. Tests 11/11 (resumed-session + active-set-overrides-staleness cases added); live poll unchanged: 50 roots, 0 active, cap_room 12. --- pm-stack/opencode-claimant/README.md | 6 +++- pm-stack/opencode-claimant/poll.py | 44 ++++++++++++++++++++++--- pm-stack/opencode-claimant/test_poll.py | 18 ++++++++++ 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/pm-stack/opencode-claimant/README.md b/pm-stack/opencode-claimant/README.md index 7d38a8d125..ce38b4ce94 100644 --- a/pm-stack/opencode-claimant/README.md +++ b/pm-stack/opencode-claimant/README.md @@ -78,7 +78,11 @@ few sessions were active. The gate refinement (task 4408) counts only `time.idle` and an `outcome` (both verified on the live server: 50 roots, 46 finished, at the gate check), a running one carries neither, and a marker-less root silent for 30+ minutes is treated as a zombie, -not a worker. `poll.py` still reports the raw root total as +not a worker. A root the server itself holds in `GET +/api/session/active` always counts — a resumed session keeps its +stored outcome from the earlier run while it is mid-run again, so the +server's active set overrides the stored markers (the same rule the +aggregator's session mapper applies). `poll.py` still reports the raw root total as `live_root_sessions` alongside the new `active_root_sessions`; `cap_room` derives from the active count. An unreadable server still yields `cap_room: null` — the cap fails closed, which is the safe diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index 373e33f2c3..8e9025e368 100644 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -54,9 +54,16 @@ def is_root_session(s): and not s.get("parent_id") -def is_active_root(s, now_ms): +def is_active_root(s, now_ms, active_ids=None): if not is_root_session(s): return False + # The server's active set is authoritative: a RESUMED session keeps + # its stored outcome/idle from the earlier run while it is mid-run + # again (the aggregator's mapper overrides stored outcomes the same + # way, pm-stack/aggregator/src/sources/opencode.ts). Membership + # counts the root no matter what its stored markers say. + if active_ids is not None and s.get("id") in active_ids: + return True t = s.get("time") or {} if t.get("idle") or s.get("outcome"): return False @@ -64,8 +71,9 @@ def is_active_root(s, now_ms): return now_ms - updated < ACTIVE_WINDOW_MS -def count_active_roots(sessions, now_ms): - return sum(1 for s in sessions if is_active_root(s, now_ms)) +def count_active_roots(sessions, now_ms, active_ids=None): + return sum(1 for s in sessions + if is_active_root(s, now_ms, active_ids)) HELPER = os.environ.get( @@ -83,6 +91,33 @@ def load_helper(): return mod +def fetch_active_ids(): + """Session ids the server currently holds active (GET + /api/session/active), or None when unreadable. The response's data + is a map keyed by session id (a list shape is accepted too).""" + try: + with open(AUTH_FILE) as f: + password = json.load(f)["password"] + except Exception: + return None + req = urllib.request.Request( + OPENCODE_URL.rstrip("/") + "/api/session/active") + token = base64.b64encode(f"opencode:{password}".encode()).decode() + req.add_header("Authorization", f"Basic {token}") + try: + with urllib.request.urlopen(req, timeout=15) as res: + data = json.loads(res.read() or "null") + except Exception: + return None + if isinstance(data, dict) and "data" in data: + data = data["data"] + if isinstance(data, dict): + return set(data.keys()) + if isinstance(data, list): + return {x for x in data if isinstance(x, str)} + return None + + def fetch_sessions(): try: with open(AUTH_FILE) as f: @@ -139,7 +174,8 @@ def main(): out["cap_room"] = None else: roots = [s for s in sessions if is_root_session(s)] - active = count_active_roots(roots, int(time.time() * 1000)) + active = count_active_roots(roots, int(time.time() * 1000), + fetch_active_ids()) out["live_root_sessions"] = len(roots) out["active_root_sessions"] = active out["cap_room"] = max(0, CAP - active) diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index 697b085e80..461d9c4184 100644 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -65,6 +65,20 @@ def test_non_dict_and_timeless_entries_never_active(self): self.assertFalse(poll.is_active_root("nope", NOW)) self.assertFalse(poll.is_active_root({"id": "ses_x"}, NOW)) + def test_resumed_session_counts_via_the_active_set(self): + # A resumed root keeps its stored outcome/idle from the earlier + # run; the server's active set overrides those markers. + s = root(outcome="failed") + s["time"]["idle"] = NOW + self.assertFalse(poll.is_active_root(s, NOW, set())) + self.assertFalse(poll.is_active_root(s, NOW, None)) + self.assertTrue(poll.is_active_root(s, NOW, {"ses_x"})) + + def test_active_set_membership_overrides_staleness(self): + s = root() + s["time"]["updated"] = NOW - 90 * MIN + self.assertTrue(poll.is_active_root(s, NOW, {"ses_x"})) + def test_count_active_roots_over_a_mixed_list(self): finished = root(outcome="failed") finished["time"]["idle"] = NOW @@ -74,6 +88,10 @@ def test_count_active_roots_over_a_mixed_list(self): "time": {"created": NOW - 90 * MIN, "updated": NOW - 90 * MIN}}] self.assertEqual(poll.count_active_roots(sessions, NOW), 2) + # The same list with ses_old in the server's active set (a + # resumed zombie-looking root) counts it too. + self.assertEqual( + poll.count_active_roots(sessions, NOW, {"ses_old"}), 3) if __name__ == "__main__": From 3003d99c5cc11a2484168779a1e126990c61846d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 19:08:29 -0500 Subject: [PATCH 3/3] claimant: fail closed when /api/session/active is unreadable (Codex P1 on #3262) summarize_cap(): an unreadable active set makes the active count unknown (active_root_sessions/cap_room null, claimant launches nothing) instead of falling back to stored markers, which read resumed roots as finished. Same fail-closed rule the session list already had. Tests 14/14 incl. the three summarize_cap branches; live poll unchanged (50 roots, 0 active, cap_room 12). --- pm-stack/opencode-claimant/poll.py | 37 +++++++++++++++++-------- pm-stack/opencode-claimant/test_poll.py | 19 +++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index 8e9025e368..b52c8a2a74 100644 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -76,6 +76,25 @@ def count_active_roots(sessions, now_ms, active_ids=None): if is_active_root(s, now_ms, active_ids)) +def summarize_cap(sessions, active_ids, now_ms): + """(live_root_sessions, active_root_sessions, cap_room). + + Either server read failing makes the active count UNKNOWN, never + zero: a resumed root's stored markers read as finished, so falling + back to markers alone when /api/session/active is unreadable could + report cap_room 12 over 12 running sessions. Unknown propagates as + None and the claimant launches nothing — the same fail-closed rule + the session list itself has always had. + """ + if sessions is None: + return None, None, None + roots = [s for s in sessions if is_root_session(s)] + if active_ids is None: + return len(roots), None, None + active = count_active_roots(roots, now_ms, active_ids) + return len(roots), active, max(0, CAP - active) + + HELPER = os.environ.get( "REPO_QUEUE_HELPER", os.path.expanduser("~/hatch/tools/repo-queue.py")) OPENCODE_URL = os.environ.get("OPENCODE_URL", "http://127.0.0.1:13420") @@ -168,17 +187,13 @@ def main(): c["priority"] or 0)) sessions = fetch_sessions() out["cap"] = CAP - if sessions is None: - out["live_root_sessions"] = None - out["active_root_sessions"] = None - out["cap_room"] = None - else: - roots = [s for s in sessions if is_root_session(s)] - active = count_active_roots(roots, int(time.time() * 1000), - fetch_active_ids()) - out["live_root_sessions"] = len(roots) - out["active_root_sessions"] = active - out["cap_room"] = max(0, CAP - active) + live, active, room = summarize_cap( + sessions, + fetch_active_ids() if sessions is not None else None, + int(time.time() * 1000)) + out["live_root_sessions"] = live + out["active_root_sessions"] = active + out["cap_room"] = room print(json.dumps(out, indent=1)) return 0 diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index 461d9c4184..74f51c3389 100644 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -94,5 +94,24 @@ def test_count_active_roots_over_a_mixed_list(self): poll.count_active_roots(sessions, NOW, {"ses_old"}), 3) +class TestSummarizeCap(unittest.TestCase): + def test_unreadable_session_list_is_unknown(self): + self.assertEqual(poll.summarize_cap(None, set(), NOW), + (None, None, None)) + + def test_unreadable_active_set_is_unknown_not_zero(self): + # Fail closed: markers alone must never become a launch + # decision when /api/session/active cannot be read. + live, active, room = poll.summarize_cap([root()], None, NOW) + self.assertEqual(live, 1) + self.assertIsNone(active) + self.assertIsNone(room) + + def test_known_counts_give_room(self): + live, active, room = poll.summarize_cap( + [root(), root(outcome="failed")], set(), NOW) + self.assertEqual((live, active, room), (2, 1, poll.CAP - 1)) + + if __name__ == "__main__": unittest.main()