Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 80 additions & 28 deletions pm-stack/opencode-claimant/claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ def log_fire(
supervision: "List[Dict] | None" = None,
babysitter: "Dict | None" = None,
nudges: "Dict | None" = None,
gate_diagnostic: "Dict | None" = None,
) -> None:
"""Append a fire log entry to fires.jsonl.

Expand Down Expand Up @@ -374,42 +375,79 @@ def log_fire(
"supervision": supervision,
"babysitter": babysitter,
"nudges": nudges,
"gate_diagnostic": gate_diagnostic,
}

with FIRES_FILE.open("a") as f:
f.write(json.dumps(fire_entry) + "\n")


def run_poll() -> Dict[str, Any]:
"""Run poll.py to discover candidates and get system state."""
poll_script = PRIMARY_CLONE / "pm-stack" / "opencode-claimant" / "poll.py"
# Preserve #13134’s production poll window; queue health has its own 15s cap.
POLL_MAX_SECONDS = 300
GATE_MAX_SECONDS = 315
_POLL_PHASES = ("session_census", "active_sessions", "broker_reads", "ledger_read", "snapshot")
_gate_diagnostic = None

if not poll_script.exists():
raise FileNotFoundError(f"poll.py not found at {poll_script}")

# Run poll.py from the primary clone. The 300s ceiling covers the
# aggregate of poll.py's per-call timeouts (15s server GET, 30s broker
# POSTs) plus the growing OpenCode session store (28k+ root sessions
# made the full poll take ~51s on 2026-11-22, permanently above the
# old 30s cap, so every live fire failed its own gate as
# "gate_unknown" -- #3026 fire log 2026-11-23T01:48Z/01:53Z).
# Single-instance lock keeps overlapping fires impossible; a slow poll
# only delays the fire, it cannot double-launch.
result = subprocess.run(
["python3", str(poll_script)],
cwd=str(PRIMARY_CLONE),
capture_output=True,
text=True,
timeout=300,

class PollFailure(RuntimeError):
def __init__(self, category, phase):
self.category = category
self.phase = phase
super().__init__(f"{category} during {phase}")


def _poll_last_phase(stderr):
if isinstance(stderr, bytes):
stderr = stderr.decode("utf-8", errors="replace")
phases = {
f"claimant-poll-phase:{phase}": phase for phase in _POLL_PHASES
}
return next(
(phases[line] for line in reversed((stderr or "").splitlines()) if line in phases),
"poll_start",
)

if result.returncode != 0:
raise RuntimeError(f"poll.py failed: {result.stderr}")

def run_poll(*, timeout=POLL_MAX_SECONDS) -> Dict[str, Any]:
"""Read a snapshot within one deadline; never log child output on error."""
poll_script = PRIMARY_CLONE / "pm-stack" / "opencode-claimant" / "poll.py"
if timeout <= 0:
raise PollFailure("deadline", "poll_start")
if not poll_script.exists():
raise PollFailure("entrypoint_missing", "poll_start")
try:
result = subprocess.run(
["python3", str(poll_script)],
cwd=str(PRIMARY_CLONE),
env={**os.environ, "OPENCODE_CLAIMANT_POLL_SECONDS": str(timeout)},
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired as e:
raise PollFailure("deadline", _poll_last_phase(e.stderr)) from None
except OSError:
raise PollFailure("spawn_error", "poll_start") from None
phase = _poll_last_phase(result.stderr)
if result.returncode != 0:
raise PollFailure("child_exit", phase)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as e:
raise RuntimeError(f"poll.py returned invalid JSON: {e}")
data = json.loads(result.stdout)
except (TypeError, ValueError):
raise PollFailure("invalid_snapshot", phase) from None
if not isinstance(data, dict) or not isinstance(data.get("candidates"), list):
raise PollFailure("invalid_snapshot", phase)
if type(data.get("cap_room")) is not int or data["cap_room"] < 0:
raise PollFailure("incomplete_snapshot", "session_census")
queues = data.get("queues")
if not isinstance(queues, dict) or any(
not isinstance(queues.get(q), dict) or queues[q].get("read_ok") is not True
for q in QUEUES
):
raise PollFailure("incomplete_snapshot", "broker_reads")
if data.get("ledger_readable") is not True:
raise PollFailure("incomplete_snapshot", "ledger_read")
return data


_poll_module = None
Expand Down Expand Up @@ -908,11 +946,14 @@ def gate_step() -> Optional[bool]:
(`_fire_candidates`) that main() threads into every log_fire
call and launch_step's candidate set.
"""
global _fire_candidates, _fire_health
global _fire_candidates, _fire_health, _gate_diagnostic
_gate_diagnostic = None
started = time.monotonic()
_fire_candidates = None
_fire_health = run_queue_health()
try:
poll_data = run_poll()
remaining = GATE_MAX_SECONDS - (time.monotonic() - started)
poll_data = run_poll(timeout=min(POLL_MAX_SECONDS, remaining))
candidates = poll_data.get("candidates", [])
_fire_candidates = list(candidates)

Expand Down Expand Up @@ -947,7 +988,17 @@ def gate_step() -> Optional[bool]:

return False
except Exception as e:
print(f"Gate check failed: {e}")
category, phase = (
(e.category, e.phase)
if isinstance(e, PollFailure)
else ("unexpected_error", "gate")
)
_gate_diagnostic = {
"category": category,
"phase": phase,
"elapsed_ms": round((time.monotonic() - started) * 1000),
}
print(f"Gate check failed: {category} during {phase}")
return None


Expand Down Expand Up @@ -2014,6 +2065,7 @@ def _fire(mode: str):
[],
None,
[{"reason": "gate_unknown"}],
gate_diagnostic=_gate_diagnostic,
health=fire_health,
supervision=supervision_records,
babysitter=babysitter_record,
Expand Down
44 changes: 39 additions & 5 deletions pm-stack/opencode-claimant/poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,24 @@ def is_stale_binding(row, binding):
return bool(binding.get("session_id"))


_POLL_DEADLINE = None


def _poll_timeout(default):
if _POLL_DEADLINE is None:
return default
remaining = _POLL_DEADLINE - time.monotonic()
if remaining <= 0:
raise TimeoutError("poll budget exhausted")
return min(default, remaining)


def _poll_phase(name):
if _POLL_DEADLINE is not None:
print(f"claimant-poll-phase:{name}", file=sys.stderr, flush=True)
_poll_timeout(30)


def fetch_ledger_bindings(task_ids):
"""task id -> lane-ledger dict for the given tasks, read-only.

Expand Down Expand Up @@ -289,7 +307,7 @@ def fetch_ledger_bindings(task_ids):
[sys.executable, str(TURSO_EXEC), LEDGER_DB, sql_path],
capture_output=True,
text=True,
timeout=60,
timeout=_poll_timeout(60),
)
finally:
os.unlink(sql_path)
Expand Down Expand Up @@ -570,7 +588,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=15) as res:
with urllib.request.urlopen(req, timeout=_poll_timeout(15)) as res:
data = json.loads(res.read() or "null")
except urllib.error.HTTPError:
if raise_http_errors:
Expand All @@ -597,6 +615,7 @@ def fetch_sessions():
represented by None, matching the other optional server reads."""
sessions = []
cursor = None
seen_cursors = set()
while True:
query = {"limit": SESSION_FETCH_LIMIT}
if cursor:
Expand All @@ -610,6 +629,9 @@ def fetch_sessions():
cursor = page_cursor.get("next") if isinstance(page_cursor, dict) else None
if not cursor:
return sessions
if not isinstance(cursor, str) or cursor in seen_cursors:
return None
seen_cursors.add(cursor)


def fetch_active_ids():
Expand Down Expand Up @@ -662,7 +684,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=30)
conn = _UnixHTTPConnection(url[len("unix://") :], timeout=_poll_timeout(30))
try:
conn.request("POST", path, body=payload, headers=headers)
with conn.getresponse() as res:
Expand All @@ -685,7 +707,7 @@ def _broker_post(path, body):
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as res:
with urllib.request.urlopen(req, timeout=_poll_timeout(30)) 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]}")
Expand Down Expand Up @@ -732,11 +754,15 @@ def _fetch_rows(queue, status):
print(f"Warning: Could not poll queue {queue}: {e}", file=sys.stderr)
_READ_ERRORS[(queue, status)] = str(e)[:200]
return []
total = data.get("total") if isinstance(data, dict) else None
if isinstance(data, dict):
data = data.get("rows") or []
data = data.get("rows")
if not isinstance(data, list):
_READ_ERRORS[(queue, status)] = "unexpected broker response shape"
return []
if len(data) >= LIST_LIMIT or (type(total) is int and total > len(data)):
_READ_ERRORS[(queue, status)] = "broker page may be incomplete"
return []
rows = []
for row in data:
if not isinstance(row, dict):
Expand Down Expand Up @@ -946,11 +972,16 @@ def get_active_root_session_count():


def main():
global _POLL_DEADLINE
raw_budget = os.environ.get("OPENCODE_CLAIMANT_POLL_SECONDS")
_POLL_DEADLINE = time.monotonic() + min(300.0, max(0.0, float(raw_budget))) if raw_budget else None
_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
session_by_id = {}
if sessions:
Expand All @@ -963,6 +994,7 @@ def main():
# 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:
Expand All @@ -971,7 +1003,9 @@ def main():
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]
Expand Down
69 changes: 67 additions & 2 deletions pm-stack/opencode-claimant/test_claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def fake_run(cmd, **kwargs):
def test_vanished_candidate_is_a_recorded_skip(self):
calls = {"n": 0}

def poll_stub():
def poll_stub(**_kwargs):
calls["n"] += 1
if calls["n"] == 1:
return {"candidates": [dict(CANDIDATE)]}
Expand Down Expand Up @@ -800,7 +800,7 @@ class TestMainFireLog(unittest.TestCase):
def test_main_records_launch_skips_in_fires_entry(self):
calls = {"n": 0}

def poll_stub():
def poll_stub(**_kwargs):
calls["n"] += 1
# The gate (call 1) sees the candidate and main threads
# it into launch_step as the fire-start snapshot (#8038);
Expand Down Expand Up @@ -1578,6 +1578,71 @@ def test_no_launchable_candidate_no_handback(self):
self.assertEqual(calls, empty_calls())


class TestBoundedPoll(unittest.TestCase):
def snapshot(self):
return {
"candidates": [],
"cap_room": 36,
"ledger_readable": True,
"queues": {q: {"read_ok": True} for q in claimant.QUEUES},
}

def poll(self, snapshot):
result = subprocess.CompletedProcess(
[], 0, json.dumps(snapshot), "claimant-poll-phase:snapshot\n"
)
with patch.object(Path, "exists", return_value=True), patch.object(
claimant.subprocess, "run", return_value=result
) as child:
data = claimant.run_poll(timeout=12)
self.assertEqual(child.call_args.kwargs["timeout"], 12)
self.assertEqual(child.call_args.kwargs["env"]["OPENCODE_CLAIMANT_POLL_SECONDS"], "12")
return data

def test_healthy_snapshot_keeps_decision(self):
snapshot = self.snapshot()
self.assertEqual(self.poll(snapshot), snapshot)
snapshot["candidates"] = [dict(CANDIDATE)]
self.assertEqual(self.poll(snapshot), snapshot)

def test_incomplete_snapshot_cannot_launch_even_with_candidate(self):
for field, bad, phase in (
("cap_room", None, "session_census"),
("ledger_readable", False, "ledger_read"),
("queues", {}, "broker_reads"),
("queues", {q: {"read_ok": False} for q in claimant.QUEUES}, "broker_reads"),
):
with self.subTest(field=field, bad=bad):
snapshot = self.snapshot()
snapshot["candidates"] = [dict(CANDIDATE)]
snapshot[field] = bad
with self.assertRaises(claimant.PollFailure) as raised:
self.poll(snapshot)
self.assertEqual(raised.exception.category, "incomplete_snapshot")
self.assertEqual(raised.exception.phase, phase)

def test_hard_timeout_reports_only_fixed_phase_not_stderr(self):
exc = subprocess.TimeoutExpired(
["fixture"], 3, stderr=b"private diagnostic\nclaimant-poll-phase:broker_reads\n"
)
with patch.object(Path, "exists", return_value=True), patch.object(
claimant.subprocess, "run", side_effect=exc
):
with self.assertRaises(claimant.PollFailure) as raised:
claimant.run_poll(timeout=3)
self.assertEqual(str(raised.exception), "deadline during broker_reads")

def test_gate_spends_only_remaining_budget_and_records_fixed_category(self):
with patch.object(claimant.time, "monotonic", side_effect=[10.0, 27.0, 28.0]), patch.object(
claimant, "run_queue_health", return_value=None
), patch.object(claimant, "run_poll", side_effect=claimant.PollFailure("deadline", "broker_reads")) as read:
self.assertIsNone(claimant.gate_step())
read.assert_called_once_with(timeout=298.0)
self.assertEqual(claimant._gate_diagnostic, {
"category": "deadline", "phase": "broker_reads", "elapsed_ms": 18000
})


if __name__ == "__main__":
unittest.main()

Expand Down
Loading