From de40c86d7cec21be7a458629d51a14c7499b4749 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 6 Nov 2026 11:03:30 +0000 Subject: [PATCH] fix(batch): workers outlive the watcher's systemd tick; ended workers are reaped (#592) KillMode=process on the oneshot unit: under the default control-group, systemd killed the claude --bg daemon (and every worker) when the tick exited, as happened in pilot live shift 1. claude agents states in _digest.ENDED_STATES (failed, killed, error, ...) are now a crash at once (re-dispatched once) or a refused close-out, never read as alive. Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 10 +++++- agents/conductors/batch/_digest.py | 11 +++++++ agents/conductors/batch/_orchestrator.py | 13 +++++--- bin/systemd/pyauto-orchestrator.service | 6 ++++ tests/test_batch_watch.py | 7 ++++ tests/test_orchestrator_closeout.py | 9 ++++++ tests/test_orchestrator_dispatch.py | 41 ++++++++++++++++++++++++ 7 files changed, 92 insertions(+), 5 deletions(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index aaf30764..429f6398 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -296,7 +296,15 @@ workers are ever launched there. write `~/.config/pyauto/orchestrator.env` with `PYAUTO_BRAIN`, `PYAUTO_MIND`, `PYAUTO_SHIFT_BRIEF` (and `PYAUTO_ORCHESTRATOR_FAKE=1` until 3b), then `systemctl --user daemon-reload && systemctl --user enable --now -pyauto-orchestrator.timer`. To stop a shift, `touch /STOP`; to remove the +pyauto-orchestrator.timer`. The service carries `KillMode=process`: under the +default (`control-group`) systemd killed every process a tick started when the +tick exited, including the `claude --bg` daemon the first worker launched, so +live shift 1 (2026-11-06) lost all three workers about 30 seconds after spawn +(PyAutoBrain#592). A copy installed before then must be copied again +(`daemon-reload`). Separately, a worker or close-out whose `claude agents` +state is in `_digest.ENDED_STATES` (`failed`, `killed`, `error`, …) is reaped +at once, as a crash (worker, re-dispatched once) or a refusal (close-out), +never read as alive. To stop a shift, `touch /STOP`; to remove the watcher, `systemctl --user disable --now pyauto-orchestrator.timer`. ## Running diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index e8d5a4b5..537a0b36 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -138,6 +138,15 @@ def task_state(task: str, counters: dict, health, *, live: bool = False, return "; ".join(parts), True +#: `claude agents` states for a session that has ended without succeeding. A +#: real worker in one of these with no `.done` is a crash at once — it can never +#: write one late, so it gets no grace (PyAutoBrain#592: three `failed` workers +#: held their leases for 40 minutes, read as alive). An unknown word is still +#: read as alive; add it here once seen. `_orchestrator` reaps by this set. +ENDED_STATES = frozenset({"failed", "error", "errored", "killed", "stopped", + "crashed", "cancelled", "canceled", "exited"}) + + def _lease_state(lease: dict, agents) -> str: """A held lease, as the live view words it (the digest never sees one).""" since = lease.get("started") or lease.get("heartbeat") or "?" @@ -147,6 +156,8 @@ def _lease_state(lease: dict, agents) -> str: if not agent: return f"running (pid {lease.get('pid', '?')}, since {since})" state = agents.state(agent) if agents is not None else None + if state in ENDED_STATES: + return f"ended ({state}, agent {agent}) — the next tick reaps it as a crash" if state == "blocked": return f"blocked on a person (agent {agent})" if state is None: diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index da098989..d2c5f414 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -55,6 +55,8 @@ #: A real worker `blocked` (waiting on a human) this long is parked: its lease #: is released, the task is not re-dispatched, and the digest names it. STALL_GRACE_S = 900 +#: Sessions that ended without succeeding — reaped as crashes (`_digest`, #592). +ENDED_STATES = _digest.ENDED_STATES #: The worker prompt every real worker starts from (never a bare session). WORKER_TEMPLATE = Path(__file__).with_name("worker_template.md") CLOSEOUT_TEMPLATE = Path(__file__).with_name("closeout_template.md") @@ -427,7 +429,8 @@ def _reap(slot: Path, counters: dict, now: _dt.datetime, grace_s: float, path = lease_dir / f"{task}.json" real = bool(lease.get("agent_id")) and not lease.get("pid") state = agents.state(lease["agent_id"]) if real else None - finished = done_marker.exists() or state == "done" or ( + ended = real and state in ENDED_STATES + finished = done_marker.exists() or state == "done" or ended or ( real and state is None and now >= _parse_iso(lease["expires"])) if real and finished: sid = agents.session_of(lease["agent_id"]) or lease.get("session_id") @@ -459,14 +462,15 @@ def _reap(slot: Path, counters: dict, now: _dt.datetime, grace_s: float, else: path.write_text(json.dumps(lease, sort_keys=True)) continue - alive = (state not in (None, "done")) if real else _alive(int(lease.get("pid", 0))) + alive = (state not in (None, "done") and not ended) if real \ + else _alive(int(lease.get("pid", 0))) if alive: lease.pop("stalled_since", None) lease["heartbeat"] = _iso(now) lease["expires"] = _iso(now + _dt.timedelta(seconds=grace_s)) path.write_text(json.dumps(lease, sort_keys=True)) continue - if now < _parse_iso(lease["expires"]) and state != "done": + if now < _parse_iso(lease["expires"]) and state != "done" and not ended: continue # gone, but inside the grace for a late `.done` path.unlink(missing_ok=True) counters["crashes"] += 1 @@ -757,7 +761,8 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti continue real = bool(co.get("agent_id")) state = agents.state(co["agent_id"]) if real else None - gone = (state in (None, "done")) if real else not _alive(int(co.get("pid") or 0)) + gone = (state in (None, "done") or state in ENDED_STATES) if real \ + else not _alive(int(co.get("pid") or 0)) if gone: # Never retried: a close-out that ended without a verdict is the # human's to look at, not a second unattended attempt. diff --git a/bin/systemd/pyauto-orchestrator.service b/bin/systemd/pyauto-orchestrator.service index 99a4637b..0d1d0875 100644 --- a/bin/systemd/pyauto-orchestrator.service +++ b/bin/systemd/pyauto-orchestrator.service @@ -6,5 +6,11 @@ Description=PyAuto shift watcher — one tick (deterministic, no LLM) [Service] Type=oneshot +# Stop only the tick itself when it exits. The default (control-group) kills +# every process the tick started, and the first `claude --bg` starts the +# background-session daemon inside this unit, so the workers died with the tick +# (pilot live shift 1, 2026-11-06, PyAutoBrain#592). After changing this, copy +# the unit again and run `systemctl --user daemon-reload`. +KillMode=process EnvironmentFile=%h/.config/pyauto/orchestrator.env ExecStart=/usr/bin/env python3 ${PYAUTO_BRAIN}/bin/orchestrator_watch.py --brief ${PYAUTO_SHIFT_BRIEF} --mind ${PYAUTO_MIND} diff --git a/tests/test_batch_watch.py b/tests/test_batch_watch.py index f8d8f390..0153d443 100644 --- a/tests/test_batch_watch.py +++ b/tests/test_batch_watch.py @@ -169,6 +169,13 @@ def test_before_dispatched_the_header_says_not_yet_open(tmp_path): assert "not yet open — opens in 45m" in text +def test_an_ended_worker_shows_as_ended_not_running(tmp_path): + brief, slot = _record(tmp_path), _live_slot(tmp_path) + text = _watch.render(_watch.snapshot(brief, slot, NOW, agents=Agents({"a1": "failed"}), + health=_health)) + assert "- running — ended (failed, agent a1) — the next tick reaps it as a crash" in text + + def test_time_left_formats(): at = NOW + _dt.timedelta(minutes=7) assert _watch._time_left(NOW, at) == "7m left" diff --git a/tests/test_orchestrator_closeout.py b/tests/test_orchestrator_closeout.py index ce3cf9bb..21550733 100644 --- a/tests/test_orchestrator_closeout.py +++ b/tests/test_orchestrator_closeout.py @@ -180,6 +180,15 @@ def test_a_refused_closeout_is_digested_and_never_retried(tmp_path): assert f"{PR1} — awaiting /prm — close-out refused: decision-taken label" in d +def test_a_failed_closeout_is_refused_not_read_as_running(tmp_path): + mind, brief, home, sp = _shift(tmp_path) + _tick(brief, mind, home, sp, 1) + _tick(brief, mind, home, sp, 2, agents=Agents({"co000001": "failed"})) + c = orch.read_counters(orch.slot_dir(brief, home)) + assert c["closeouts"][PR1]["state"] == "refused" + assert c["closeouts"][PR1]["why"] == "the close-out session ended without a verdict" + + def test_a_closeout_that_ends_without_a_verdict_is_refused_not_retried(tmp_path): mind, brief, home, sp = _shift(tmp_path) _tick(brief, mind, home, sp, 1) diff --git a/tests/test_orchestrator_dispatch.py b/tests/test_orchestrator_dispatch.py index 4e5a4269..2890a058 100644 --- a/tests/test_orchestrator_dispatch.py +++ b/tests/test_orchestrator_dispatch.py @@ -24,6 +24,7 @@ sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) sys.path.insert(0, str(BATCH)) import _brief # noqa: E402 +import _digest # noqa: E402 import _orchestrator as orch # noqa: E402 NOW = _dt.datetime(2026, 11, 4, 9, 0, tzinfo=_dt.timezone.utc) @@ -239,6 +240,46 @@ def test_done_without_its_marker_is_a_crash(tmp_path): assert orch.read_counters(slot)["crashes"] == 1 +@pytest.mark.parametrize("state", ["failed", "killed", "error"]) +def test_an_ended_worker_is_a_crash_at_once_and_redispatched(tmp_path, state): + """PyAutoBrain#592: systemd killed three workers; `claude agents` said + `failed` and the watcher read them as alive for 40 minutes.""" + mind, brief, home = _shift(tmp_path) + slot = orch.slot_dir(brief, home) + claude = FakeClaude() + _tick(brief, mind, home, NOW, claude, grace_s=3600) + # Well inside the lease grace: an ended session can never write a late .done. + r = _tick(brief, mind, home, NOW + _dt.timedelta(minutes=3), claude, + agents=_agents({"t1": state}, slot), tokens=lambda s: 7, grace_s=3600) + assert r["reaped"] == [{"task": "t1", "event": "dead", "redispatch": "allowed"}] + assert [s["task"] for s in r["spawned"]] == ["t1"] + c = orch.read_counters(slot) + assert c["crashes"] == 1 and c["redispatched"] == {"t1": 1} and c["tokens"] == 7 + + +def test_an_ended_worker_with_its_done_marker_still_counts_as_done(tmp_path): + mind, brief, home = _shift(tmp_path) + slot = orch.slot_dir(brief, home) + claude = FakeClaude() + _tick(brief, mind, home, NOW, claude) + (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/5\n") + r = _tick(brief, mind, home, NOW + _dt.timedelta(minutes=3), claude, + agents=_agents({"t1": "failed"}, slot)) + assert r["reaped"][0]["event"] == "done" + assert orch.read_counters(slot)["crashes"] == 0 + + +def test_ended_states_are_the_digests(): + assert orch.ENDED_STATES is _digest.ENDED_STATES and "failed" in orch.ENDED_STATES + assert "working" not in orch.ENDED_STATES and "blocked" not in orch.ENDED_STATES + + +def test_the_unit_template_keeps_workers_alive_after_the_tick(): + unit = (BRAIN / "bin" / "systemd" / "pyauto-orchestrator.service").read_text() + lines = [l.strip() for l in unit.splitlines() if not l.strip().startswith("#")] + assert "KillMode=process" in lines and "Type=oneshot" in lines + + def test_a_vanished_worker_waits_out_the_lease_grace(tmp_path): mind, brief, home = _shift(tmp_path) slot = orch.slot_dir(brief, home)