From 689f4b6485db1a531f0efe7084062e91f1f6edb3 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Mon, 16 Nov 2026 06:21:34 -0600 Subject: [PATCH] fix(opencode-claimant): count claimant roots only toward the session cap (#5016) Ruling session-cap-5016: the concurrency cap is the claimant's launch budget. Scheduled fleet sessions (lane runners, the claimant's own fire, sweeps, the conductor) are infrastructure outside it; only claimant work roots consume slots. A server-active root whose clock has not moved for ACTIVE_SET_STALE_MS (2 h) is a zombie (#5016's ~18 h session) and releases its slot. - poll.py: is_scheduled_session / is_claimant_root_session, count_active_claimant_roots, staleness bound on active-set members; summarize_cap and get_active_root_session_count count claimant roots. - claimant.py: cap_step's counter delegates to the claimant count. - test_poll.py: TestClaimantCapAccounting (census-mix oracle from #5016, scheduled-population invariant sweep, staleness boundary). - prompt.md/README.md: the cap's meaning stated as claimant roots only. Cap value unchanged (36; raised from 12 to 20 to 36 on 2026-11-05). --- pm-stack/opencode-claimant/README.md | 11 +- pm-stack/opencode-claimant/claimant.py | 11 +- pm-stack/opencode-claimant/poll.py | 123 ++++++++++++++++--- pm-stack/opencode-claimant/prompt.md | 20 +-- pm-stack/opencode-claimant/test_poll.py | 155 ++++++++++++++++++++++++ 5 files changed, 292 insertions(+), 28 deletions(-) diff --git a/pm-stack/opencode-claimant/README.md b/pm-stack/opencode-claimant/README.md index 07049c5e59..95b23cd422 100644 --- a/pm-stack/opencode-claimant/README.md +++ b/pm-stack/opencode-claimant/README.md @@ -29,7 +29,13 @@ Main execution script that implements the 6-step process: 3. **Cap** (Step 3): Checks concurrency limits - Queries OpenCode server for active root sessions - - Uses 36-session cap (raised from 12→20→36 on 2026-11-05) + - Counts CLAIMANT roots only (ruling `session-cap-5016`, #5016): + scheduled fleet sessions — lane runners, the claimant's own fire, + sweeps, the conductor — are infrastructure outside the cap + - A server-active root silent past `ACTIVE_SET_STALE_MS` (2 h) is a + zombie and releases its slot (#5016's 18h session) + - Uses 36-session cap (raised from 12→20→36 on 2026-11-05; the + value is unchanged by #5016) - Returns cap_room (available slots) or -1 if unknown 4. **Launch** (Step 4): Creates sessions and binds tasks @@ -49,7 +55,8 @@ Candidate discovery and system state reporting: - **get_candidates()**: Discovers unbound opencode-lane tasks from all four queues - **get_stuck_bound()**: Identifies bound tasks with stuck sessions (placeholder implementation) -- **get_active_root_session_count()**: Queries OpenCode server for active session count +- **get_active_root_session_count()**: Queries OpenCode server for the + active claimant root session count (scheduled fleet sessions excluded) - Outputs JSON with candidates, stuck_bound list, and cap_room ### launch_one.py diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index 3c024ddbe7..d352b81d5f 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -301,10 +301,13 @@ def _load_poll_module(): def get_active_root_session_count() -> int: - """Get the count of active root sessions from the OpenCode server. + """Get the count of active CLAIMANT root sessions from the OpenCode + server. Delegates to poll.py: fetch the session list and the server's - active set, then count_active_roots over both. Returns -1 + active set, then count_active_claimant_roots over both — scheduled + fleet sessions (lane runners, the claimant's own fire) are outside + the cap per ruling `session-cap-5016` (#5016). Returns -1 (unknown) when either read fails, so cap_step fails closed.""" try: poll = _load_poll_module() @@ -314,7 +317,9 @@ def get_active_root_session_count() -> int: active_ids = poll.fetch_active_ids() if active_ids is None: return -1 # Unknown - count = poll.count_active_roots(sessions, int(time.time() * 1000), active_ids) + count = poll.count_active_claimant_roots( + sessions, int(time.time() * 1000), active_ids + ) return -1 if count is None else count except Exception as e: print(f"Warning: Could not get active session count: {e}") diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index b9e453f279..3e7e57a072 100755 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -47,12 +47,20 @@ # closed (see fetch below) "live_root_sessions": int | null, # all root sessions; # null = server unreadable - "active_root_sessions": int | null, # roots still active - # (see is_active_root) + "active_root_sessions": int | null, # CLAIMANT roots still + # active (see + # count_active_claimant_roots): + # scheduled fleet sessions + # (lane runners, the + # claimant's own fire, + # sweeps) are outside the + # cap (#5016, ruling + # session-cap-5016) "cap": 36, "concurrency_cap": 36, - "cap_room": int | null # CAP - active roots; - # null when count unknown + "cap_room": int | null # CAP - active claimant + # roots; null when count + # unknown } Read-only by construction: claimed rows come from the queue-broker's @@ -66,9 +74,10 @@ become a launch decision. The pure classification functions (is_candidate, is_active_root, -count_active_roots, summarize_cap, parse_lease_ms, is_stuck_bound) -are the contract test_poll.py pins; claimant.py counts through the -same functions so the two entry points cannot diverge in shape. +count_active_roots, count_active_claimant_roots, is_scheduled_session, +summarize_cap, parse_lease_ms, is_stuck_bound) are the contract +test_poll.py pins; claimant.py counts through the same functions so +the two entry points cannot diverge in shape. """ import ast @@ -102,6 +111,32 @@ # 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 +# A root in the server's active set normally counts no matter what its +# stored markers say (a resumed session keeps an earlier run's idle +# marker). But `/api/session/active` also keeps reporting sessions whose +# client died mid-run: #5016's zombie sat there for ~18 hours, silent, +# with no outcome and no idle marker, holding a cap slot. OpenCode +# refreshes `time.updated` on every step, so a session whose clock has +# not moved for this long is a zombie, not work. Two hours is 4x the +# 30-minute marker window and far beyond any single legitimate silent +# step (the longest builds are held under the fleet build lock and +# still emit progress), so a live session can never be mistaken for +# this. Releasing a slot only changes cap accounting; it never kills +# the session, so the blast radius of a false positive is one extra +# launch slot, not lost work. +ACTIVE_SET_STALE_MS = 2 * 60 * 60 * 1000 + +# Ruling `session-cap-5016` (#5016): the cap is the claimant's launch +# budget. Every fleet-scheduled session is infrastructure, outside it: +# scheduled lane runners ("Queue lane (scheduled) - ..."), the +# claimant's own fire ("Opencode lane claimant/executor - ..."), the +# conductor and the sweeps all carry metadata.openchamber.kind == +# "scheduled". The title prefixes are the fallback for legacy rows +# written before OpenChamber stamped that marker. +SCHEDULED_TITLE_PREFIXES = ( + "Queue lane (scheduled)", + "Opencode lane claimant/executor", +) # Packaged fleet binary via its repo-queue argv0 alias # (~/.local/bin/repo-queue -> ~/.local/bin/fleet); the hand-built @@ -376,6 +411,38 @@ def is_root_session(s): return isinstance(s, dict) and not s.get("parentID") and not s.get("parent_id") +def is_scheduled_session(s): + """True iff `s` is a fleet-SCHEDULED session: infrastructure that + is outside the claimant's launch cap (#5016, ruling + `session-cap-5016`). + + The machine-readable marker is `metadata.openchamber.kind == + "scheduled"`, stamped by OpenChamber on every scheduled task's + session (lane runners, the claimant fire itself, the conductor, + the sweeps — verified live 2026-11-16 across 366 roots). The + title prefixes fall back for legacy rows created before that + marker existed. Unknown/malformed metadata is NOT scheduled: + counting an extra root can only tighten the cap, never + manufacture room.""" + if not isinstance(s, dict): + return False + metadata = s.get("metadata") + openchamber = metadata.get("openchamber") if isinstance(metadata, dict) else None + if isinstance(openchamber, dict) and openchamber.get("kind") == "scheduled": + return True + title = s.get("title") + if isinstance(title, str): + return title.startswith(SCHEDULED_TITLE_PREFIXES) + return False + + +def is_claimant_root_session(s): + """A root session that consumes a claimant cap slot: work the + claimant owns. Scheduled fleet roots never do (see + is_scheduled_session).""" + return is_root_session(s) and not is_scheduled_session(s) + + def _active_root_state(s, now_ms, active_ids=None): """True (proven active), False (proven inactive), or None (the entry's timing cannot be read, so its activity is UNKNOWN — see @@ -386,8 +453,18 @@ def _active_root_state(s, now_ms, active_ids=None): # 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. + # counts the root no matter what its stored markers say — unless + # the session's clock has not moved for ACTIVE_SET_STALE_MS, the + # zombie case the active set cannot express (#5016: ~18h silent, + # no outcome, no idle, still "running"). An entry whose timing is + # unreadable keeps membership: cap counts stay conservative. if active_ids is not None and s.get("id") in active_ids: + timing = _session_timing(s) + if timing is None: + return True + _idle, updated = timing + if updated and now_ms - updated >= ACTIVE_SET_STALE_MS: + return False return True # Terminal markers are decidable without a readable clock # (#8853): a finished root stays finished even when its @@ -421,8 +498,19 @@ def count_active_roots(sessions, now_ms, active_ids=None): return sum(1 for state in states if state) +def count_active_claimant_roots(sessions, now_ms, active_ids=None): + """Active roots that consume a claimant cap slot (#5016, ruling + `session-cap-5016`): claimant work roots only. + + Scheduled fleet sessions are filtered out BEFORE classification, + so a malformed timing on a lane runner can no longer make the cap + unknown either — it was never the claimant's slot to lose.""" + claimant_roots = [s for s in sessions if is_claimant_root_session(s)] + return count_active_roots(claimant_roots, now_ms, active_ids) + + def summarize_cap(sessions, active_ids, now_ms): - """(live_root_sessions, active_root_sessions, cap_room). + """(live_root_sessions, active_claimant_roots, cap_room). Either server read failing makes the active count UNKNOWN, never zero: a resumed root's stored markers read as finished, so falling @@ -430,13 +518,15 @@ def summarize_cap(sessions, active_ids, now_ms): 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. - """ + + `live_root_sessions` stays every root (a census fact); only the + counted active set is narrowed to claimant roots (#5016).""" 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) + active = count_active_claimant_roots(roots, now_ms, active_ids) if active is None: return len(roots), None, None return len(roots), active, max(0, CAP - active) @@ -749,17 +839,18 @@ def get_stuck_bound(rows, session_by_id, active_ids, now_ms): def get_active_root_session_count(): - """Count of active root sessions, or -1 when either server read - fails (the sentinel claimant.py's cap_step has always used). - Counting itself is count_active_roots over the verified live - session shape — the same function claimant.py now delegates to.""" + """Count of active CLAIMANT root sessions, or -1 when either server + read fails (the sentinel claimant.py's cap_step has always used). + Counting is count_active_claimant_roots: scheduled fleet sessions + (lane runners, the claimant's own fire) are outside the cap per + ruling `session-cap-5016` (#5016).""" sessions = fetch_sessions() if sessions is None: return -1 active_ids = fetch_active_ids() if active_ids is None: return -1 - count = count_active_roots(sessions, int(time.time() * 1000), active_ids) + count = count_active_claimant_roots(sessions, int(time.time() * 1000), active_ids) return -1 if count is None else count diff --git a/pm-stack/opencode-claimant/prompt.md b/pm-stack/opencode-claimant/prompt.md index c3b5ff852e..ca6127af43 100644 --- a/pm-stack/opencode-claimant/prompt.md +++ b/pm-stack/opencode-claimant/prompt.md @@ -109,12 +109,17 @@ outage is recoverable, a double-launch's damage is not. it.) Retain the candidate list from the start of each fire; a task recovered during supervision is eligible on the next fire, not this one. -- Concurrency cap: **36** 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; poll.py counts a root as +- Concurrency cap: **36** active CLAIMANT root sessions — the + claimant's launch budget (ruling `session-cap-5016`, #5016). + Scheduled fleet sessions — lane runners, this fire's own session, + sweeps, the conductor — are infrastructure and are OUTSIDE the cap. + Count with poll.py (OpenCode server `GET /api/session` on + http://127.0.0.1:13420, root sessions that are not + `metadata.openchamber.kind == "scheduled"`; 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. + activity in the last 30 min, and a server-active root silent past 2 h + is a zombie that releases its slot; poll.py reports the free slots 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 @@ -198,7 +203,7 @@ exhausted" --reason-class deterministic` with `--execution 2. GATE: run the CLI `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 `cap_room` 0 (active root sessions at the +3. CAP: if poll.py reports `cap_room` 0 (claimant root sessions at the 36 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 @@ -302,7 +307,8 @@ queue task and issue>, "model": {"id": , - Never work a task yourself; you claim/bind/launch/record only. - Never launch for a task whose issue carries `held`, `user/owned`, `do-not-merge`, or `do-not-auto-edit` — skip and log it. -- Never exceed the 36-session cap, never double-bind a task, never +- Never exceed the 36-slot claimant cap (claimant roots only; scheduled + fleet sessions do not count), never double-bind a task, never bind a session id you did not just create. - No credential value ever enters a prompt, log, or task record; the queue CLI and poll.py reach the queue-broker with the broker's client diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index f71ec0f529..bb7c92b1bf 100755 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -121,6 +121,161 @@ def test_known_counts_give_room(self): self.assertEqual((live, active, room), (2, 1, poll.CAP - 1)) +class TestClaimantCapAccounting(unittest.TestCase): + """#5016, ruling `session-cap-5016`: the concurrency cap is the + claimant's LAUNCH budget. Scheduled fleet sessions (lane runners, + the claimant's own fire, sweeps, the conductor) are infrastructure + and never consume a slot; claimant work roots do; a server-active + root silent past ACTIVE_SET_STALE_MS is a zombie and releases its + slot (#5016's 18h session). + + Oracle: the census table on #5016 — 11 scheduled lane runners, the + claimant's own fire, 1 genuinely running bound work session, 1 + unbound ~18h zombie — plus the invariant that the count equals the + number of live claimant work roots regardless of how many scheduled + roots sit beside them.""" + + def lane_runner(self, i=0, **over): + s = { + "id": f"ses_lane_{i}", + "title": f"Queue lane (scheduled) - code 2026-11-03 1{i}:00", + "metadata": {"openchamber": {"kind": "scheduled"}}, + "time": {"created": NOW - 90 * MIN, "updated": NOW - 90 * MIN}, + } + s.update(over) + return s + + def claimant_fire(self, **over): + s = { + "id": "ses_fire", + "title": "Opencode lane claimant/executor - #3026 2026-11-03 10:10", + "metadata": {"openchamber": {"kind": "scheduled"}}, + "time": {"created": NOW - 10 * MIN, "updated": NOW - 1 * MIN}, + } + s.update(over) + return s + + def work_root(self, sid="ses_work", **over): + s = { + "id": sid, + "title": f"Queue task 8067 - 5016 claimant cap", + "time": {"created": NOW - 30 * MIN, "updated": NOW - 1 * MIN}, + } + s.update(over) + return s + + def test_lane_runner_never_consumes_a_claimant_slot(self): + live, active, room = poll.summarize_cap( + [self.lane_runner(0), self.lane_runner(1), self.work_root()], + {"ses_lane_0", "ses_lane_1", "ses_work"}, + NOW, + ) + self.assertEqual((live, active, room), (3, 1, poll.CAP - 1)) + + def test_claimant_fire_session_does_not_count_itself(self): + _live, active, _room = poll.summarize_cap( + [self.claimant_fire()], {"ses_fire"}, NOW + ) + self.assertEqual(active, 0) + + def test_claimant_work_roots_do_count(self): + roots = [self.work_root(f"ses_w{i}") for i in range(12)] + _live, active, room = poll.summarize_cap(roots, {r["id"] for r in roots}, NOW) + self.assertEqual(active, 12) + self.assertEqual(room, max(0, poll.CAP - 12)) + + def test_scheduled_roots_never_change_claimant_headroom(self): + # Invariant sweep: lane-runner population must not move the + # claimant count at any size (0..40), the exact shape that + # starved the fleet on 2026-11-03. + for n in range(41): + sessions = [self.lane_runner(i) for i in range(n)] + [self.work_root()] + active_ids = {s["id"] for s in sessions} + _live, active, room = poll.summarize_cap(sessions, active_ids, NOW) + self.assertEqual(active, 1, f"n={n}") + self.assertEqual(room, poll.CAP - 1, f"n={n}") + + def test_issue_5016_census_mix(self): + # 11 lane runners + the claimant fire + 1 running bound work + # session + the 18h unbound zombie (a lane runner, still in the + # server's active set). Claimant count must be 1, not 14. + sessions = [self.lane_runner(i) for i in range(11)] + sessions.append(self.claimant_fire()) + sessions.append(self.work_root()) + zombie = self.lane_runner( + 99, + title="Queue lane (scheduled) - opencode 2026-11-02 16:00", + time={"created": NOW - 19 * 60 * MIN, "updated": NOW - 18 * 60 * MIN}, + ) + sessions.append(zombie) + active_ids = {s["id"] for s in sessions} + live, active, room = poll.summarize_cap(sessions, active_ids, NOW) + self.assertEqual(live, len(sessions)) + self.assertEqual(active, 1) + self.assertEqual(room, poll.CAP - 1) + + def test_active_set_zombie_releases_its_slot_after_the_bound(self): + zombie = self.work_root( + "ses_zombie", + time={ + "created": NOW - 19 * 60 * MIN, + "updated": NOW - poll.ACTIVE_SET_STALE_MS, + }, + ) + self.assertFalse(poll.is_active_root(zombie, NOW, {"ses_zombie"})) + _live, active, _room = poll.summarize_cap([zombie], {"ses_zombie"}, NOW) + self.assertEqual(active, 0) + + def test_boundary_just_inside_the_staleness_bound_still_counts(self): + s = self.work_root( + "ses_zombie", + time={ + "created": NOW - 19 * 60 * MIN, + "updated": NOW - poll.ACTIVE_SET_STALE_MS + 1, + }, + ) + self.assertTrue(poll.is_active_root(s, NOW, {"ses_zombie"})) + + def test_zombie_does_not_need_a_terminal_marker(self): + # #5016's zombie has no outcome and no time.idle; silence past + # the bound is the whole evidence. + s = self.work_root( + "ses_zombie", + time={"created": NOW - 19 * 60 * MIN, "updated": NOW - 18 * 60 * MIN}, + ) + self.assertIsNone(s.get("outcome")) + self.assertIsNone((s.get("time") or {}).get("idle")) + self.assertFalse(poll.is_active_root(s, NOW, {"ses_zombie"})) + + def test_scheduled_marker_survives_missing_metadata(self): + # The title is the fallback when a legacy row carries no + # metadata (rows created before OpenChamber stamped `kind`). + legacy = self.lane_runner(0, metadata=None) + self.assertTrue(poll.is_scheduled_session(legacy)) + self.assertFalse(poll.is_scheduled_session(self.work_root())) + self.assertFalse(poll.is_scheduled_session({"id": "x", "metadata": "soon"})) + self.assertFalse(poll.is_scheduled_session(None)) + + def test_claimant_root_count_delegates_to_the_exclusion(self): + sessions = [self.lane_runner(i) for i in range(3)] + [ + self.work_root("ses_w0"), + self.work_root("ses_w1"), + ] + self.assertEqual( + poll.count_active_claimant_roots( + sessions, NOW, {"ses_lane_0", "ses_w0", "ses_w1"} + ), + 2, + ) + + def test_unreadable_active_set_stays_unknown_with_scheduled_roots(self): + _live, active, room = poll.summarize_cap( + [self.lane_runner(0), self.work_root()], None, NOW + ) + self.assertIsNone(active) + self.assertIsNone(room) + + class TestWrongShapeTime(unittest.TestCase): """#6868: a wrong-shaped `time` / timestamp must never raise out of the classifiers, and must fail closed: never counted as a