Repository navigation
fix(agents): agent containers are born unless-stopped (#2541) - #2591
Conversation
Rule #1 — the requirements delta lands before the implementation. RESTART-001..008 state the guarantee the fix has to meet: every durable agent container born `unless-stopped` from one constant, re-baked unconditionally on recreate, guarded in both directions by CI, plus the three consequences the change creates (restarting becomes reachable, two RestartCount alert paths go live, network recreation now bites every agent in a backoff loop) and the compose half of the same bug. Also corrects ADOPT-006's fence reason list: the #1559 recovery rebuild no longer drops `unless-stopped` — it shares the tail that bakes it. Co-Authored-By: Claude Opus 5 <[email protected]>
Docker's default restart policy is `no`, so every agent container Trinity
created stayed Exited after a host reboot. `trinity-system` was the only one
with a policy. The 2026-09-04 power-off brought back 11 of 19 agents — exactly
the cohort a manual `docker update` had patched after the first occurrence
(2026-07-23) — and left 8 dead ~42h, `marshal` among them.
- capabilities.py: AGENT_RESTART_POLICY = {"Name": "unless-stopped"}, one home
beside AGENT_TMPFS_MOUNT / AGENT_LOG_CONFIG. Deliberately not env-tunable,
unlike both siblings: a safety floor, not a policy dial, and `always` must
not be reachable (#1638).
- crud.py: the create site passes it.
- lifecycle.py: the shared recreate tail bakes it UNCONDITIONALLY, replacing
#1816's carry-forward. Faithful carry-forward carries `no` forward forever,
and the tail's other caller — the #1559 recovery rebuild — passed nothing at
all, so a recovered agent was rebuilt on `no` even when it had
`unless-stopped`. #1816's intent is served better as a fleet-wide guarantee.
Its now-dead `old_host_config` extraction is deleted with it.
- system_agent_service.py: the literal becomes the shared constant.
- docker_service.py: `restarting` normalizes to `stopped` on BOTH copy-pasted
normalizers. That state becomes reachable for every agent with this change —
the frontend filters on exact equality, so passed through verbatim an agent
restarting after a reboot appears in neither running nor stopped.
`unless-stopped`, never `always`: Trinity stops agents via container.stop(),
which sets Docker's manual-stop flag, so a quarantined agent stays down.
Refs #2541
Co-Authored-By: Claude Opus 5 <[email protected]>
…2541) Same bug one directory up. docker-compose.prod.yml and .hosted.yml both carry `restart: unless-stopped` on all three; the BASE file did not — and that is the file `start.sh` uses without --hosted, i.e. the README quickstart and the source install in docs/AGENT_INSTALL_GUIDE.md. 7 of its 10 services already had it, so the omission is oversight, not design; test_2280_hosted_compose_parity guards prod<->hosted wholesale and compares the base file to nothing, which is exactly how it drifted while the other two stayed correct. Anyone following the quickstart was running a Trinity whose own control plane did not survive a host reboot. Rendered proof, all three files: docker compose -f <file> config -> backend/frontend/redis: unless-stopped (*-init one-shots stay "no", deliberately) Refs #2541 Co-Authored-By: Claude Opus 5 <[email protected]>
…ences - test_1484: the create path plumbs AGENT_RESTART_POLICY into containers_run. Fails without the fix with KeyError: 'restart_policy' (verified). The harness stubs `capabilities`, so this pins the plumbing; the value is pinned against the real module in the guard. - test_1816: the five tests that pinned #1816's carry-forward are rewritten, not deleted — a behaviour change has to update its characterization, and #1816's intent must be visibly preserved. The recreate assertion is now parametrized over what the old container had (no / unless-stopped / always / empty / null / absent) and asserts the SAME answer for all six: a recreate normalizes, it does not preserve. It needed a new fixture that intercepts at containers_run instead of at the tail, because #2541 moved the property into the tail where the old fixture cannot see it. Adds the third broken path nothing covered: recreate_missing_container's #1559 rebuild. - test_2541_restart_policy_parity: the AST drift guard. Three departures from #1871's: it pins the VALUE (ast.Name AGENT_RESTART_POLICY, not mere presence — {"Name": "always"} would pass a presence check and break RESTART-002); it adds `<x>.containers.run`, docker-py's third creation form, which #1871 does not match and which makes the docker_utils _HELPER_LAYER exemption load-bearing for the first time; and it checks BOTH directions. - test_2541_restart_policy_effects: restarting normalizes to stopped on both copy-pasted normalizers, the two RestartCount alert branches keep their threshold, and every long-lived service in all three compose files declares a restart policy (*-init one-shots must declare "no" explicitly). Guard proved against planted violations in the real tree, both directions: durable, policy removed -> crud.py:2009 (durable, no policy) transient, policy added -> crud.py:1862 (transient WITH a policy) restored -> CLEAN Compose assertion proved by reverting the base-file fix -> frontend, redis. Refs #2541 Co-Authored-By: Claude Opus 5 <[email protected]>
- docs/migrations/AGENT_RESTART_POLICY_2026-09.md (new): the one-shot sweep for the existing fleet, plus the three operational consequences an operator will otherwise meet in production — never `docker compose down` on a Trinity host (a recreated agent network now leaves every agent in a dockerd backoff loop, not just trinity-system, and it fails silently because restarting reads as stopped); "Agent X restarting frequently" alerts are new; a daemon-driven restart skips the start_agent_internal ladder, so a config-drifted agent returns on its stale config. - architecture/agent-lifecycle.md: the owning area file gets the constant, the sites, why unconditional, why not `always`, the guard's three departures from #1871's, and the cost — involuntary reboots were a free fleet-wide cold-start boundary and this removes one, so base-image adoption gets rarer. - feature-flows/container-capabilities.md: restart_policy in all four create-site kwarg lists + a Container Restart Policy section mirroring log rotation. - feature-flows/agent-lifecycle.md: the "Restart-policy carry-forward (#1816)" paragraph is rewritten, not amended — that mechanism is retired. - feature-flows/internal-system-agent.md: two corrections. The #1559 fence no longer loses `unless-stopped` (every other reason stands), and the staleness mechanism it describes for trinity-system is now the whole fleet's. - learnings.md: appended. The first occurrence left no entry at all, which is mechanically why a written fix sat on a local branch for 671 commits and the bug recurred at 4x the cost. - feature-flows.md: Recent Updates row. Refs #2541 Co-Authored-By: Claude Opus 5 <[email protected]>
/update-tests tail step. Inserted next to test_1871_log_config_parity so the
two guards for the same bug class ("the create path is never one call site")
sit together, with the departures from #1871's scan spelled out — value-not-
presence, the third docker-py creation form, and the both-directions rule —
so a reader of the registry can tell why there are two similar guards.
.claude/agents/test-runner.md is a curated subset, not a per-file catalog (it
lists neither #1871, #1816 nor #1484), so no entry is added there.
Refs #2541
Co-Authored-By: Claude Opus 5 <[email protected]>
…ision row /sync-feature-flows found one flow-doc site the first docs pass missed: agent-lifecycle.md quoted the status normalizer verbatim, tuple and all, so it now claimed the pre-#2541 behaviour. Updated, and annotated with the fact the code comment carries — the block exists twice and a third mapping disagrees by construction — since a doc that shows one copy is how a reader concludes there is one copy. Plus the #2541 Revision History row. Refs #2541 Co-Authored-By: Claude Opus 5 <[email protected]>
… passes through The docstring contrasts this function's explicit classification against `list_all_agents_fast`, which "falls through with `else: normalized_status = docker_status`, which passes `paused`, `restarting` and ... `removing` straight to the caller". That was true until ~110 lines above in this same file, where #2541 folded `restarting` into the stopped tuple on BOTH normalizers precisely so all three mappings agree — which is what the new comment at the list-all site and RESTART-005 say. Left as-is, the file asserted the opposite of itself in prose, in the one place a reader goes to learn why the three mappings differ. `paused` and `removing` do still fall through, so the contrast survives; only `restarting` moves out of the list, with a pointer to why. Co-Authored-By: Claude Opus 5 <[email protected]>
…ncy-stop is the sharp one RESTART-002 says a deliberately quarantined agent stays down across a reboot, qualified on the manual-stop flag only being set when the stop *succeeds*. The qualification cited `_restore_stopped_state` (#2092) — a recreate-path detail. The path the requirement actually exists for is `POST /api/ops/emergency-stop`, which stops the fleet in parallel through `_stop_agent_container` and catches per agent, returning `{"result": "error"}` for the ones that did not stop. Such an agent is still running, and #2541 removes the accidental backstop that used to kill it at the next reboot. That is the right trade — the alternative is `always`, which breaks the whole guarantee — but it changes what an operator must do: read the emergency-stop response and re-issue for any agent not reported `stopped`. States it in all three homes that carry the sentence, so none goes stale against the others. Co-Authored-By: Claude Opus 5 <[email protected]>
…ings The new restart-policy test left three, where every other section break in the file has two. Co-Authored-By: Claude Opus 5 <[email protected]>
Verification
|
| Suite | Failures | Cause |
|---|---|---|
test_736_a2a_outbound_edges.py |
5 | IPv4-mapped-IPv6 / CGNAT |
test_ent399_ipv6_origin.py |
2 | same family |
test_1484_create_agent_characterization.py — the file this PR adds its
prior-art regression test to — passed clean, all 42.
Pass 2 (--skip-unit --skip-agent --keep) — RESULT: PASS
| Stage | Result |
|---|---|
| preflight | OK |
build + import main in the built backend image |
OK (29s) |
boot + /health |
OK (14s) |
| integration | OK — 70 passed, 13 skipped, 2 deselected |
The integration stage genuinely ran; it is not the known utils.safe_yaml
collection-abort case (log shows collection succeeded and 83 tests executed).
--skip-agent is sound here: nothing under docker/base-image/ changed.
Runtime proof — a real daemon, not a kwarg assertion
A unit test asserting restart_policy= was passed to containers_run is not
proof the daemon applied it. Against the verify stack, with a real agent created
through POST /api/agents:
1. Born unless-stopped
agent-rp-proof id=56ca03ac37e0 RestartPolicy=unless-stopped
2. Survives a recreate — resources changed → stop → start →
recreate_reason: config_drift, new container id:
agent-rp-proof id=3d38789105be RestartPolicy=unless-stopped (was 56ca03ac37e0)
3. The daemon actually honours it — the acceptance criterion. Killing the
container's keepalive from inside makes PID 1 exit unasked, which is the shape
of the incident (the 2026-09-04 agents died 137 having never been asked to
stop):
before: State=running RestartCount=0
after: State=running RestartCount=1 ExitCode=0
dockerd brought it back with no operator action. That is the fleet surviving a
reboot.
Worth recording for RESTART-002:
docker killdoes not demonstrate this,
and shouldn't. moby'skillWithSignalsets the sameHasBeenManuallyStopped
flagdocker stopdoes, sounless-stoppedcorrectly declines to restart a
killed container. My first attempt useddocker killand read as a failure —
it was the requirement working exactly as written.
4. RESTART-005 live — with dockerd's backoff driven up so the restarting
window lasts seconds, and a docker inspect sample on both sides of the API
call so a race cannot hide:
docker before='restarting' GET /api/agents status='stopped' docker after='restarting'
An earlier sample at RestartCount=3 read running — that was a genuine race
(the backoff was still sub-second), not a defect; it is why the final sample
brackets the call.
RESTART-006 was observed incidentally: RestartCount reached 9 during the
proof. Before this PR that counter never moved for a regular agent, which is
exactly why the two monitoring_service alert branches have never fired.
Guard proves itself, both directions
Planted against the real tree, then reverted byte-identical:
- remove
crud.py's kwarg →services/agent_service/crud.py:2009 (durable, no policy) - add a policy to the alpine chown helper →
services/agent_service/crud.py:1862 (transient WITH a policy) - clean tree →
20 passed
Suites
test_2541_restart_policy_parity.py + test_2541_restart_policy_effects.py +
the rewritten test_1816_system_agent_adoption.py → 101 passed;
test_1484_create_agent_characterization.py → 42 passed.
Not proven here
The agent stage was skipped (--skip-agent), so this run did not build the
agent base image — correct, since no docker/base-image/ file changed, but it
means the runtime proof used the host's existing trinity-agent-base:latest
rather than a per-run build. The restart policy is set by the backend, not the
base image, so this does not weaken points 1–4.
…e-2541 # Conflicts: # docs/memory/feature-flows.md # docs/memory/learnings.md
dolho
left a comment
There was a problem hiding this comment.
/review — PR #2591 (AndriiPasternak31/issue-2541 → dev)
Files: 19 (+1263/−130) · Scope: CLEAN. #2541 asked for the already-written fix to land; what landed is better than the prior-art branch, because it also kills the carry-forward that made the policy sticky.
Verified locally: pytest tests/unit/test_2541_restart_policy_{effects,parity}.py tests/unit/test_1816_system_agent_adoption.py tests/unit/test_1484_create_agent_characterization.py → 143 passed. old_host_config has no remaining reader in lifecycle.py (grep clean, module compiles). All five compose files carry restart: unless-stopped on every long-lived service — the two init containers correctly stay no.
Two calls I want to record as right, because both were the tempting-wrong-way:
- Baking the constant unconditionally instead of carrying the old policy forward. #1816's carry-forward was faithful and therefore propagated
noforever, and the #1559 recovery rebuild passed nothing at all — so a recovered agent was downgraded. Making the shared tail the retrofit seam turns "don't loseunless-stopped" from a per-caller obligation into a fleet-wide property.docker_service.pyandsystem_agent_service.pynow name the same constant, so the by-name parity guard can actually pin all three create sites. unless-stopped, notalways, argued as a safety property. I checked the premise rather than the prose: there is nocontainer.kill()anywhere insrc/backend(only subprocessproc.kill()in git/backup/fork paths), so every Trinity stop goes throughdocker_utils.container_stop→ Docker's manual-stop flag → honoured. A quarantined agent stays down across a reboot. The claim holds.
The self-declared side effects (RESTART-005/006/007) being written down at all is what makes this reviewable. RESTART-005 checks out: every backend consumer of the normalized status tests != "running", so folding restarting into stopped changes nothing server-side and fixes the frontend's exact-equality buckets, where the agent previously appeared in neither list.
Critical
None.
Informational
[I1] The repo's own deploy script violates the standing rule this PR introduces (Confidence: 7/10)
scripts/deploy/gcp-deploy.sh:199
--command="cd ${REMOTE_DIR} && sudo docker compose -f docker-compose.prod.yml down && sudo docker compose -f docker-compose.prod.yml up -d --build"
RESTART-007 states the remedy as "never docker compose down on a Trinity host", and restart_services() does exactly that on the production path. Being fair about the blast radius, because the requirements note is worse than reality: compose down cannot remove trinity-agent-network while agent containers hold endpoints on it, so with a live fleet this degrades to a warning, and post-#2541 a rebooted host brings agents back up, which narrows the window rather than widening it. The reachable case is a host where the fleet is already down.
Still worth fixing here rather than filing: it is a one-token change (up -d --build alone recreates changed services and reuses the existing network), it is in the same blast radius the PR just documented, and a standing rule contradicted by the repo's own script is a rule that will lose.
scripts/deploy/clean.sh:41 is not this — it is an intentional teardown and correctly stops agents first.
[I2] A user-facing doc now gives advice opposite to the standing rule (Confidence: 9/10)
docs/user-docs/guides/deploying/local-development.md:156
Important:
stop.shrunsdocker compose down…
stop.sh:48 runs docker compose "${COMPOSE_FILES[@]}" stop, and docs/memory/feature-flows/hosted-install.md:136 already pins "stop.sh never runs compose down" as a tested property. The sentence was merely stale before; after RESTART-007 it teaches a local dev the one command the runbook now warns against. One-line fix, and the PR is already touching the doc set.
[I3] The runbook covers "quarantine by stop" but not "quarantine by policy" (Confidence: 6/10)
docs/migrations/AGENT_RESTART_POLICY_2026-09.md:34-43
The unconditional re-bake in _provision_folders_and_run_agent_container silently reverts an operator's docker update --restart=no agent-x — intended, and correct as the retrofit seam. But recreate fires from nine predicates plus base-image drift, i.e. unattended, so an operator who reaches for docker update instead of stop gets a quarantine that lifts itself hours later with no trace. The runbook explains the manual-stop flag; it does not say "quarantine with stop, never with --restart no". One sentence beside the existing note.
Clean
- Concurrency / lifecycle: no new shared state; the policy is a frozen module constant, deliberately not env-tunable, with the #1638 reasoning stated (the only other reachable values are strictly worse).
- Auth boundaries: no endpoint, dependency or principal touched.
- Enum completeness (4.12 — the category that needs code outside the diff): both
restartingsites are changed together and the docstring inagent_container_statesis updated to match, so all three normalizers agree. Checked every consumer ofget_agent_status_from_container/list_all_agents_fast—subscription_auto_switch:473,525,github_pat_propagation:331,monitoring_service:1068,heartbeat_service:268,session_cleanup:157— every one tests== "running"or!= "running", so none changes behaviour. The frontendrunningAgents/stoppedAgentsfilters strictly improve. - Incomplete-fix completeness (4.14): this is the second occurrence (2026-07-23 manual
docker update, then 2026-09-04), and the fix reaches all three create sites plus both recreate paths rather than the reported one.learnings.mdentry written. - Docs: RESTART-005/006/007 recorded in
requirements/infrastructure.mdwith their downsides named, not just the win.
Summary
Critical: 0 · Informational: 3 · Scope: clean.
Approving. [I1] and [I2] are two one-line edits I'd like in this PR since it is already the one that makes them matter — but neither changes the behaviour being shipped, and holding a 42-hour-outage fix on a shell script's && would be the wrong trade.
# Conflicts: # docs/memory/feature-flows.md # docs/memory/learnings.md
|
Resolve by running |
|
Resolve by merging |
Fixes #2541
Docker's default restart policy is
no. Every agent container Trinity createdwas born with it, so a host reboot left the agent
Exiteduntil somebodystarted it by hand.
trinity-systemwas the only container in the backendcreated with a policy. The 2026-09-04 power-off brought back 11 of 19 agents —
exactly the cohort a manual
docker updatehad patched after the firstoccurrence (2026-07-23) — and left 8 dead ~42 hours,
marshal(the fleetconductor) among them: 48 failed dispatches, ~168 lost
fleet-pollruns, 17schedules dark.
What lands
AGENT_RESTART_POLICY = {"Name": "unless-stopped"}inagent_service/capabilities.py, besideAGENT_TMPFS_MOUNTandAGENT_LOG_CONFIG, imported by all three create sites (crud.py,lifecycle.py's shared recreate tail,system_agent_service.py— which hadthe only correct policy and now names the shared constant so a by-name guard
can pin all three).
Deliberately not operator-tunable, unlike both siblings. This is a safety
floor, not a policy dial: the only other reachable values are
always(breaksthe guarantee below) and
on-failure:N(strictly weaker), and a typo must notreach either — the #1638 lesson.
unless-stopped, neveralways, is a safety property rather than anavailability preference. Trinity stops agents through
container.stop(),which sets Docker's manual-stop flag;
unless-stoppedhonours it, so an agentan operator deliberately quarantined stays down across a reboot.
alwayswouldresurrect it.
The part the issue did not predict: #1816's carry-forward is retired
The recreate tail now bakes the policy unconditionally, and #1816's
restart_policyparameter + itsold_host_configextraction are deleted.Carrying the old container's policy forward is faithful, and therefore carries
noforward forever — which is why the fleet was split rather than uniformlybroken. And the tail's other caller, the #1559 recovery rebuild, passed
nothing at all, so a recovered agent was rebuilt on
noeven when it hadunless-stopped— a third broken path neither the issue nor the prior-artcommit noticed. Every sibling property at that call site (
cap_drop,cap_add,security_opt,tmpfs,log_config,network,mem_limit,nano_cpus) wasalready unconditional; the restart policy was the sole exception, and that
asymmetry was the bug.
#1816's intent survives, strictly stronger —
trinity-systemkeepsunless-stoppedacross a recreate by construction rather than by copy. Fivetests in
test_1816_system_agent_adoption.pypinned the carry-forward and arerewritten; that file is the real blast radius of this PR and is where a reviewer
should look hardest.
recreate_missing_container's 409 fence does not move— #2541 removes one item from its reason list (it no longer drops the policy);
every other reason stands.
Consequences, shipped with the cause rather than discovered in production
restartingbecomes reachable for every agent, most visiblyas the transient state during the very reboot recovery this exists to produce.
Both of
docker_service.py's copy-pasted normalizers now map it tostopped,agreeing with
agent_container_states. Passed through verbatim it matchedneither of the frontend's exact-equality filters, so a restarting agent
appeared in neither
runningAgentsnorstoppedAgents— a loud failurerendered invisible.
RestartCountbranches inmonitoring_servicehaveeffectively never fired for a regular agent (Docker only increments it under a
policy). They go live fleet-wide. Desirable, but a surface no operator has
seen before.
trinity-agent-network(anydocker compose down) now leaves every agent retrying in a dockerd backoff loop insteadof one container failing once, loudly. Standing rule + remedy in the runbook.
boundary for base-image adoption.
unless-stoppedremoves it, so adoptiongets rarer.
POST /api/ops/fleet/restart(fix: fleet restart adopts rebuilt base images through the canonical lifecycle path (#1860) #1912) is the remedy.The compose half of the same bug
backend,frontendandredishad norestart:in the basedocker-compose.yml— the filestart.shuses without--hosted, i.e. theREADME quickstart and the source install — while prod and hosted were correct.
A self-hosted Trinity's own control plane did not survive a host reboot either.
test_2280_hosted_compose_parityguards prod↔hosted wholesale and compares thebase file to nothing, which is why it was invisible.
Guard
tests/unit/test_2541_restart_policy_parity.py— the second property to provethe
learnings.md(2026-07-10) "the create path is never one call site" classafter #1871's
log_config. Three deliberate departures from that guard, eachwith a reason in the file:
ast.Name("AGENT_RESTART_POLICY"),and a separate test reads the constant out of
capabilities.py's AST and pinsit to
unless-stopped. A presence check would admit{"Name": "always"}.<x>.containers.run(...), the formdocker_utils.pyitself uses, which bug: container logs are unbounded — no json-file max-size anywhere (compose, agent SDK, or daemon); filled the disk and wedged dockerd on 2026-07-27 #1871's matcher misses. A dedicated testasserts the helper-layer exemption is load-bearing here so it cannot rot into
reassurance.
remove=Truecreate must carry no policy. Thatreverse is protective, not decorative: all five of Trinity's transient helpers
are non-detached, where docker-py never sets
auto_remove, so the daemonaccepts the combination, the helper exits, the policy restarts it, the
post-
wait()remove()409s, and a forever-restarting orphan leaks(reproduced against a live daemon while planning).
Proved against the real tree both ways before merge: removing
crud.py's kwargreports
crud.py:2009 (durable, no policy); adding one to the alpine chownhelper reports
crud.py:1862 (transient WITH a policy).Existing fleet
Creation-time, like
log_config— existing containers keepnountil they arerecreated. The create-path fix closes the population (the set of
restart=nocontainers is now finite and can never grow), which is what makes a one-shot
operator sweep genuinely one-shot rather than a bridge to the next incident:
docs/migrations/AGENT_RESTART_POLICY_2026-09.md.Explicitly not covered
So the next incident is recognised as a different gap: a container that was
removed (only
recreate_missing_containerrebuilds it, and neverautonomously), and a container that runs but whose agent is wedged. Docker's
restart policy is not a desired-state reconciler. A daemon-driven restart also
bypasses the
start_agent_internalladder, so a config-drifted agent returns onits stale config — the right trade for a reboot.
Verification
tests/unit/test_2541_restart_policy_parity.py(20) +..._effects.py(6) +the rewritten
test_1816_system_agent_adoption.py— 101 passedtest_1484_create_agent_characterization.py— 42 passed/validate-pr— clean (requirements, architecture area file, 3 feature flows +index, security, test adequacy)
/verify-local— see the comment belowacceptance criterion) — see the comment below
Docs
Requirements §8.5d (RESTART-001…008) + an ADOPT-006 correction ·
architecture/agent-lifecycle.md· three feature flows + the index row ·a dated
learnings.mdentry (the first occurrence produced none, which is whythe class was not recognised on sight the second time) · the migration runbook.
🤖 Generated with Claude Code