Repository navigation
fix(subagents): attribute crash-orphaned runs and notify requesters - #136476
zeroaltitude wants to merge 38 commits into
Conversation
A subagent run that is in flight when the gateway dies is only discovered
later, when a fresh boot sweeps the registry. Two code paths then recorded a
causally empty string — "subagent run lost active execution context" and
"session completed before registry settled" — and a third, the orphan prune in
reconcileOrphanedRun, deleted the row outright with nothing but a [warn] log.
The spawning session, the only party that can decide to retry, was never told
at all.
That silence is not merely unhelpful, it is actively misleading. The reap
timestamp is an arbitrarily late clock reading: it includes however long the
host stayed down. In the incident behind this issue a run that executed for
5m36s was reaped after a 34-minute VM outage and so appeared to have lived
40m35s, which is the evidence that talked an earlier investigation into
confidently diagnosing a "run timeout" on a run whose timeout was disabled.
subagent-orphan-attribution.ts correlates an orphaned run against the
gateway_boot_lifecycle rows that were already being persisted, and renders a
message naming the cause, the restart timestamp, the prior boot id, the fact
that the prior boot ended without a clean stop, the true elapsed lifetime and
the recorded assistant-message count. Elapsed is computed from the best
available death evidence and never from the reap; each evidence class carries
its own bound, so the message says "at least" or "at most" rather than
overclaiming. The run's own start time is explicitly rejected as activity
evidence, since accepting it would report a 0s lifetime — a stronger claim than
the honest upper bound. When the evidence does not support a claim at all (the
owning boot recorded any deliberate stop, no boot owned the run, no successor
boot exists), attribution returns null and callers keep their existing wording,
so a clean shutdown can never be misattributed.
Telling "the gateway process died" apart from "the host rebooted under us"
matters because the remedies differ, and neither was previously recoverable
from the database. A host_boot_id column on gateway_boot_lifecycle gives it
directly: same id across the gap means the process alone died, a changed id
means the machine went down. The kernel value from /proc is authoritative; the
os.uptime() fallback is bucketed and anything derived from it is reported as
inferred rather than observed. Legacy rows predating the column produce no
host-continuity claim.
For the notification defect, a run that died having recorded no assistant
output now completes through completeSubagentRunWithRecovery with
sendFarewell: true rather than being silently pruned, which routes it through
the existing announce surface — subagent-announce.ts already renders
outcome.error into the requester-facing status label, so no new notification
channel was invented. Output-bearing runs keep the existing prune path; the
loud failure is reserved for the case the requester cannot reconstruct on its
own.
The stale-active reap block moved out of subagent-registry-sweeper.ts into
subagent-registry-sweeper-orphan.ts so the decision reads as one thing. That
incidentally brings the sweeper from 723 to 679 lines, under the 700-line
oxlint max-lines budget it was already violating on main.
Schema change is additive only (ensureColumn plus the CREATE TABLE), with
openclaw-state-db.generated.d.ts regenerated via db:kysely:gen. No destructive
migration.
Deliberately out of scope, noted as follow-up: re-attaching an orphaned run on
registry rebuild instead of completing it as an error. A truthful failure beats
a silent one, and resilience is a larger change than accurate error text.
Validation (topic worktree):
pnpm tsgo:core clean
pnpm tsgo:core:test clean
pnpm vitest run src/agents/subagents/ 102 files, 2506 tests passed
incl. subagent-orphan-attribution.test.ts 22 passed
incl. subagent-registry-sweeper-orphan-attribution 12 passed
pnpm vitest run src/infra/gateway-boot-lifecycle.test.ts
src/state/openclaw-state-db.test.ts + neighbours 255 passed
pnpm config:schema:check ok
pnpm plugin-sdk:surface:check 0 forbidden subpaths
pnpm check:import-cycles 0 runtime value cycles
pnpm db:kysely:check clean
pnpm oxlint <touched files> clean
git diff --check clean
Beads: openclaw-vaon
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThe PR attributes crash-orphaned subagents using persisted boot history and settles them through canonical requester completion. Example: A child starts at 22:49:16, records activity at 22:54:52, and is reaped at 23:29:51 after a restart.
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 4 items remain Keep this PR open: maintainer-supported crash attribution remains distinct from merged orphan completion, and both prior findings are resolved. Priority: P2 Decision needed
Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe subagent registry restores and sweeps persisted child runs; session observations and Gateway boot history feed canonical terminal persistence, requester notification, and cleanup. flowchart TD
A[Persisted child runs] --> B[Registry restore and sweeper]
C[Child session observation] --> B
D[Gateway boot history worker] --> E[Crash attribution]
B --> E
E --> F[Canonical completion owner]
F --> G[Requester notification]
F --> H[Guarded cleanup]
Technical reviewBest possible solution: Retain bounded crash attribution within the existing registry completion and boot-lifecycle owners under an accepted storage contract. Do we have a high-confidence way to reproduce the issue? Current-main source supplies generic orphan errors and reap-based completion timing; the reported crash sequence and supplied historical Gateway trace support the failure mechanism, but this read-only review ran no target code. Is this the best way to solve the issue? The existing completion owner is the appropriate repair boundary, and conservative boot correlation avoids inventing exact downtime; host-continuity persistence needs a recorded owner decision. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d1f7bc91f81f. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +731, Tests +1429, Other +711. Total +2871 across 31 files. Added test files: 6. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (29 earlier review cycles; latest 8 shown)
Reviewed October 13, 2026, 9:39 PM ET / October 14, 2026, 01:39 UTC (Revision 30). |
Keep stale active restored runs under the sweeper so it can publish a causally attributed terminal result, while continuing to prune queued orphans. Resolve host boot identity outside the state transaction and reject attribution when later run activity disproves the inferred death window. Add persisted-restart coverage for retention, attributed sweep, and misleading downtime suppression. Beads: openclaw-fzif
|
Addressed the two findings at exact head
The new persisted-registry restart regression proves the row survives restoration and then reaches an attributed terminal requester outcome. Validation passes 98/98 focused assertions, @clawsweeper re-review Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Orphan attribution now overrides the diagnostic reader's 64-row default so rapid restart sequences cannot hide the run's owning boot. Cover both the default cap and a 70-row retained-history attribution read.\n\nBeads: openclaw-fzif\n\nCo-Authored-By: Claude <[email protected]>
|
Fixed the retained-history P1 on signed head The attribution loader now explicitly reads the complete retained boot window instead of inheriting the shared diagnostic reader’s 64-row default. A real SQLite regression inserts 70 retained boots, confirms the default reader returns only 64, then confirms the attribution-sized read returns all 70 oldest-first—including the owning boot that previously disappeared. The focused attribution + lifecycle suites pass 38/38 in this round; combined with the prior exact-head validation, the branch has 136/136 focused assertions plus The separate request for a redacted full persisted-Gateway restart trace remains open; the source defect is corrected first so that proof cannot accidentally validate only the short-history case. @clawsweeper re-review Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Attribution only accepts boots without a recorded completion, so the exact boot-completion evidence variant could never execute. Keep the deliberate-stop coverage at the public resolver, make helper state private, and replace reset-only exports with an explicit forced cache refresh used by the persistence test. Validation: - focused orphan attribution and persistence tests (41/41) - pnpm tsgo:core - pnpm deadcode:exports - exact-head changed-file gate - exact-head isolated Gateway crash/restart proof - autoreview: no P0-P2 findings Beads: openclaw-fzif
|
Exact-head persisted-Gateway proof is complete at signed The proof starts a real isolated Gateway and provider, creates a parent agent turn that calls the real {"beforeCrash":{"registryStatus":"running","taskStatus":"running","childCommandAlive":true},"restart":{"priorBootAbrupt":true,"bootRows":2,"sameHostBootId":true},"recovered":{"attributedRequesterEvent":true,"requesterHistoryVisible":true,"registryStatus":"retired","taskStatus":"failed","sessionDeleteCount":1}}This directly closes the existing-database upgrade and requester-delivery proof asks. The branch also removed unreachable exact-lifetime evidence and test-only reset exports identified during final autoreview. Exact-head validation: 63/63 focused assertions, @clawsweeper re-review Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Keep uptime-derived restart diagnoses generic and resolve fresh persisted terminal child outcomes before applying crash attribution. Co-Authored-By: Claude <[email protected]>
…(review feedback)
Two review findings from ClawSweeper revision 29.
[P2] Resolve orphan classification before skipping restored resumption.
`resolveSubagentRunOrphanReason` returns a deferred `{ read }` object for the
ordinary case — an unended, nonqueued run with a child session key and no
retained obligation — so `Boolean(...)` over its result was true for every such
run without ever inspecting `sessionEntry` or `orphanReason`. Restoration
therefore handed the sweeper every active restored run, including recent
children whose sessions had already finished, leaving their requesters
unsettled until a later sweep. That inverted the predicate's own documented
distinction (333e43c: recover interrupted owners while allowing completed
sessions to resume normal settlement).
The session-entry conditions now live in one exported pure classifier,
`classifySubagentRunOrphanFromSessionEntry`. The deferred reader delegates to
it, so both forms agree by construction, and the restore predicate finishes the
classification against the child session entry the restorer already read for
that exact owner — no second worker round trip.
Measured: `keeps restored recovery dormant until the Gateway lifecycle
activates it` (subagent-registry.persistence.resume.test.ts, unchanged on this
branch and unchanged from origin/main) timed out at 120s on the previous head
because the restored running row was never resumed and `waitForAgent` was never
called. It passes now. `origin/main` does not contain the sweeper-ownership
clause at all, so both the clause and that red were this branch's. Reverting
only the predicate, with the classifier extraction kept, fails exactly the two
new "resumes a recent child" cases and none of the six orphan-handoff cases.
[P2] Enter the history read before replacing its selected run.
`runHistoryReadRaceScenario` called the helper and replaced the row
synchronously, but the helper awaits the session observation first, so
`assertReadCurrent` retired it before `loadGatewayBootSegmentsForAttribution`
ran. The scenario passed without exercising the guard it advertised.
The window is now entered deterministically rather than by timing: the run's
recorded child session key is blank, which is the `missing-session-entry` orphan
whose classification needs no session read, so the history read is the only read
the helper suspends on. The harness starts that read itself with the cache
seeded stale and awaits it first; the helper's call finds the same load in
flight and queues behind it, so the successor is installed while the helper is
inside the real round trip. Two new assertions count the selection checks — two
before the read, exactly one after it — so the scenario cannot pass vacuously.
Verified by deletion, as the review asked. With the post-history `isCurrent()`
check removed from production: the new scenario fails (96 assertions, 1 failed,
and only that counting assertion fails — every other race assertion still
passes, because the downstream `expectedEntry` and `recoveryCurrent` fences
catch the replacement, which is precisely why the old assertions could not
isolate this guard), while the previous scenario still reported "94 assertions,
0 failed. All runtime assertions passed." It certified a guard that was not in
the tree.
Validation (PATH=/home/linuxbrew/.linuxbrew/bin, git 2.55 so the ratchet lanes
actually evaluate):
- pnpm check:changed -> EXIT 0, 37 check lanes, including line-cap growth,
max-lines suppression, SQLite worker, first-party mock export, plugin
boundaries (eligibleForRemoval=0), typecheck core / core tests / scripts.
- scripts/check-database-worker-ratchet.mts --base origin/main -> no T1 growth.
- pnpm deadcode:unused-files -> 0 entries on both the production and full-tree
scans.
- git diff --check -> clean.
- Focused suites via scripts/run-vitest.mjs across 10 files: 143 passed,
0 failed (was 134 passed / 1 failed on the previous head).
- pnpm tsx scripts/proof-136476-orphan-owner-binding.ts -> 96 assertions,
0 failed. Reverting both sweeper files to b099c4f -> 13 failed.
- git merge-tree --write-tree --name-only upstream/main HEAD -> identical
eight-file conflict set before and after; no conflict surface added.
Beads: openclaw-cy3n
Round 25 — both revision-29 findings addressedHead [P2] Resolve orphan classification before skipping restored resumption —
|
|
🦞👀 Re-review progress:
|
|
This pull request has been automatically marked as stale after 7 days without qualifying human activity. |
An explicit cron run reads its authorized job definition and private scratch separately inside a SQLite read transaction. Read both in one dialect-layer LEFT JOIN so they share a statement snapshot, removing three SQL statements per SQLite run without another worker request. The job reader keeps its all-column authorization relation, ordered narrow projection, exact returned-ID check, existing decoder/config revision and legacy creation fallback. Missing scratch still reports revision 0; deletion keeps its revision tombstone. The standalone maintenance reader remains. No schema, cache, write, receipt, claim-before-effect, delivery authority, FIFO or 64-receipt retention change. PostgreSQL retains the shared reader's outer read-only transaction and rollback: its exact-job read is 4→3 SQL, not 4→1. SQLite exact-job is 4→1, heartbeat 3→1; PostgreSQL heartbeat remains 3→3. Accepted noncontract edges: an absent/malformed job can now require scratch SELECT privilege, and malformed job plus unsafe numeric scratch can reject the numeric data first. These do not remove the existing caller/source/cancellation checks. The production delta is +3 lines: one joined query replaces the transaction and duplicate read while sharing NULL handling with heartbeat. Existing test files cover read-after-write, tombstones, missing jobs/monitors and both database engines. No new suite or runner is added. Acceptance was registered before measurement: the committed `scripts/bench-cron-run.mts` drives signed WebSocket `cron.run` against an isolated synthetic Gateway/provider, once cold and twice warm. Each run must produce one start, one finish, one Responses request and exact-run history verification. Compare execution, history verification and settlement separately and together, plus shutdown and the entire invocation. The scratch owner must fall from 4→1 SQL with 1 request and 0 MAIN throughout; no cost may be deferred outside the run. Keep cold/warm separate and report median/p95/range. Three same-platform alternating pairs when calm, or one pair plus source attribution under campaign load. Counts and profiles make no latency/CPU-speed claim; timing claims require the timing lock, load below 24 and ≥5 alternating samples per arm. A 20% user-facing regression stops acceptance. Delivery mode none does not claim an external-send proof. The same-platform explicit comparison (baseline 814e732, candidate 93a6c4) gives: | SQL / requests / MAIN | Baseline | Candidate | | --- | --- | --- | | Cold execution + verification + settlement | 257 / 80 / 0 | 254 / 78 / 0 | | Warm 1 | 247 / 64 / 0 | 235 / 60 / 0 | | Warm 2 | 252 / 61 / 0 | 245 / 65 / 0 | | Warm median | 249.5 / 62.5 / 0 | 240 / 62.5 / 0 | | Warm descriptive p95 | 252 / 64 / 0 | 245 / 65 / 0 | | Warm range | 247–252 / 61–64 / 0 | 235–245 / 60–65 / 0 | | Shutdown | 22 / 6 / 5 | 40 / 10 / 5 | | Whole invocation | 1383 / 356 / 58 | 1369 / 352 / 58 | Each of the three runs completed one start, finish, Responses request and exact history verification. The scratch owner is exactly 4/1/0 → 1/1/0 in every run, all in its execution phase, with no extra or deferred scratch requests. All execution/verification/settlement phases are SQL-error-free and runtime MAIN remains zero. The count comparison is diagnostic, not an error-free full invocation: the frozen analyzer rejects two failed shutdown `state_leases` DELETEs (`database is locked`). Shutdown exceeds the 20% stop threshold; it was stopped and explicitly accepted by the coordinator as inherited after an independent main shutdown-lock reproduction. The separate SHUTDOWNLOCK lane owns that repair. The scratch join changes no lease code or writes. No latency or CPU-speed claim is made. The frozen 3.1.5 standard workload is a different scheduled `cron.add` flow: three valid baselines gave 06.cron 231/62/0, 235/65/0, 233/63/0 (median 233/63/0), versus ordinary warm 45/12/0. The descriptive excess is 188 SQL/51 requests, not causal subtraction. One extra standard setup aborted before any Gateway; it supplies no performance evidence. The existing scratch source is identical across that baseline and the explicit baseline. Full current-standard delta is deferred to the next census. Validation: count regression red on baseline (2 SELECTs and BEGIN/COMMIT), all 17 scratch-store tests green on the candidate; two isolated Codex P0–P2 reviews scoped-clean. The existing two-engine conformance test passed on actual SQLite and PostgreSQL 17, with catalog/trigger parity and cleanup verified. Test cost: scratch cases totaled 6.528 s (125.95 s file duration, mostly transform); the two engine cases totaled 1.846 s (260.62 s file duration, mostly transform). The candidate build and official source-freshness check passed at measured runtime head 93a6c4d; the three-sample invocation completed with the shutdown limitation above. Exact-head CI run 40176443806 completed successfully: 39 successful jobs, 26 skipped, no failures, including all three actual PostgreSQL shards, production/test types, lint, source contracts, Madge, and worker/T1/dialect ratchets. The earlier run passed types, lint and source contracts but found a worker-inventory omission: the new direct query was conservatively labeled T1. Head a187ecf corrects only inventory metadata and regenerates its snapshot: the worker snapshot and its private heartbeat helper are W, while the native Doctor reader stays T3. No runtime or SQL change is involved. The generated snapshot also catches up existing main classifications; targeted script lint and formatting pass. The two production reviews remain valid; this tooling-only correction adds no production review round. PG review approved the semantics at 68c24c4, and the coordinator explicitly carried REVIEW-OK to 93a6c4d because only benchmark TypeScript annotations changed. Candidate counts and the inherited-shutdown disposition are recorded; the corrected head’s CI and all three PG shards passed. The test-only import relocation avoids another open PR's adjacent import change; production bytes remain identical to both isolated reviews and database proof. The benchmark annotations fix CI TS7022 without changing emitted behavior. Final-head overlap at a187ecf: complete shared-index base-versus-candidate merge-tree comparison covers 21 peers (#183410, #183285, #181057, #180871, #180286, #180139, #169241, #168956, #168615, #167546, #167471, #165039, #161997, #157922, #157693, #156613, #141004, #137788, #136476, #129388, #121204). No new source conflict paths, regions or messages. Six peers (#181057, #180871, #180139, #169241, #129388, #121204) have added or changed conflicts confined to the fully generated worker inventory. The coordinator explicitly accepted this class because main's snapshot was stale and generated outputs must be regenerated, not hand-edited. The same exact-head disposition carries PG REVIEW-OK because runtime bytes are unchanged. Exact-head CI and all three PostgreSQL shards passed. PG checklist: (1) read-only; existing writer transaction/advisory-lock, DML/conflict and cross-store commit ordering unchanged. (2) At most one joined row via the existing composite primary keys, original job fields plus four scratch fields, unchanged 256 KiB scratch write bound. (3) No cache/generation or invalidation change; one statement snapshot, existing outer PG read transaction retained. (4) No schema/admission/identity/retry/probe change. (5) Same worker owner, one request, no MAIN expansion; target 4→1 SQL in all three real Gateway runs, with the inherited shutdown failure disclosed above. (6) Actual PostgreSQL 17 and SQLite owner conformance passed; all three final-head PostgreSQL CI shards and the other selected static checks passed. Knip was run separately because ordinary PR CI excludes it. The canonical candidate export scan failed with 26 script, 20 production and 16 full-tree findings; none is in a changed file. All 62 occurrences (52 unique file/symbol pairs), scanner/config/compiler inputs and package inputs are unchanged from merge-base dada70f. The only removed imports, runSqliteReadSnapshotSync and loadCronRows, both retain multiple real production consumers. Current-main diagnostic sections reported 14 script and 7 production findings; main has already repaired 40 candidate occurrences in unrelated changes. Its separate full-tree scan was intentionally stopped after the coordinator accepted the source-attributed inherited findings; it is not a passing full-main scan. No ignored exports, baselines or unrelated code were changed. The failed candidate scan is explicitly accepted as inherited; all branch changes and selected CI static checks pass. Pre-merge shared-index refresh retains 17 open peers from that audit. Only #180871 moved (f140f16); its fresh base-versus-candidate comparison still adds conflicts solely in the generated worker inventory, within the coordinator-accepted class. No new source conflicts. Co-authored-by: Peter Steinberger <[email protected]>
An explicit cron run reads its authorized job definition and private scratch separately inside a SQLite read transaction. Read both in one dialect-layer LEFT JOIN so they share a statement snapshot, removing three SQL statements per SQLite run without another worker request. The job reader keeps its all-column authorization relation, ordered narrow projection, exact returned-ID check, existing decoder/config revision and legacy creation fallback. Missing scratch still reports revision 0; deletion keeps its revision tombstone. The standalone maintenance reader remains. No schema, cache, write, receipt, claim-before-effect, delivery authority, FIFO or 64-receipt retention change. PostgreSQL retains the shared reader's outer read-only transaction and rollback: its exact-job read is 4→3 SQL, not 4→1. SQLite exact-job is 4→1, heartbeat 3→1; PostgreSQL heartbeat remains 3→3. Accepted noncontract edges: an absent/malformed job can now require scratch SELECT privilege, and malformed job plus unsafe numeric scratch can reject the numeric data first. These do not remove the existing caller/source/cancellation checks. The production delta is +3 lines: one joined query replaces the transaction and duplicate read while sharing NULL handling with heartbeat. Existing test files cover read-after-write, tombstones, missing jobs/monitors and both database engines. No new suite or runner is added. Acceptance was registered before measurement: the committed `scripts/bench-cron-run.mts` drives signed WebSocket `cron.run` against an isolated synthetic Gateway/provider, once cold and twice warm. Each run must produce one start, one finish, one Responses request and exact-run history verification. Compare execution, history verification and settlement separately and together, plus shutdown and the entire invocation. The scratch owner must fall from 4→1 SQL with 1 request and 0 MAIN throughout; no cost may be deferred outside the run. Keep cold/warm separate and report median/p95/range. Three same-platform alternating pairs when calm, or one pair plus source attribution under campaign load. Counts and profiles make no latency/CPU-speed claim; timing claims require the timing lock, load below 24 and ≥5 alternating samples per arm. A 20% user-facing regression stops acceptance. Delivery mode none does not claim an external-send proof. The same-platform explicit comparison (baseline 814e732, candidate 93a6c4) gives: | SQL / requests / MAIN | Baseline | Candidate | | --- | --- | --- | | Cold execution + verification + settlement | 257 / 80 / 0 | 254 / 78 / 0 | | Warm 1 | 247 / 64 / 0 | 235 / 60 / 0 | | Warm 2 | 252 / 61 / 0 | 245 / 65 / 0 | | Warm median | 249.5 / 62.5 / 0 | 240 / 62.5 / 0 | | Warm descriptive p95 | 252 / 64 / 0 | 245 / 65 / 0 | | Warm range | 247–252 / 61–64 / 0 | 235–245 / 60–65 / 0 | | Shutdown | 22 / 6 / 5 | 40 / 10 / 5 | | Whole invocation | 1383 / 356 / 58 | 1369 / 352 / 58 | Each of the three runs completed one start, finish, Responses request and exact history verification. The scratch owner is exactly 4/1/0 → 1/1/0 in every run, all in its execution phase, with no extra or deferred scratch requests. All execution/verification/settlement phases are SQL-error-free and runtime MAIN remains zero. The count comparison is diagnostic, not an error-free full invocation: the frozen analyzer rejects two failed shutdown `state_leases` DELETEs (`database is locked`). Shutdown exceeds the 20% stop threshold; it was stopped and explicitly accepted by the coordinator as inherited after an independent main shutdown-lock reproduction. The separate SHUTDOWNLOCK lane owns that repair. The scratch join changes no lease code or writes. No latency or CPU-speed claim is made. The frozen 3.1.5 standard workload is a different scheduled `cron.add` flow: three valid baselines gave 06.cron 231/62/0, 235/65/0, 233/63/0 (median 233/63/0), versus ordinary warm 45/12/0. The descriptive excess is 188 SQL/51 requests, not causal subtraction. One extra standard setup aborted before any Gateway; it supplies no performance evidence. The existing scratch source is identical across that baseline and the explicit baseline. Full current-standard delta is deferred to the next census. Validation: count regression red on baseline (2 SELECTs and BEGIN/COMMIT), all 17 scratch-store tests green on the candidate; two isolated Codex P0–P2 reviews scoped-clean. The existing two-engine conformance test passed on actual SQLite and PostgreSQL 17, with catalog/trigger parity and cleanup verified. Test cost: scratch cases totaled 6.528 s (125.95 s file duration, mostly transform); the two engine cases totaled 1.846 s (260.62 s file duration, mostly transform). The candidate build and official source-freshness check passed at measured runtime head 93a6c4d; the three-sample invocation completed with the shutdown limitation above. Exact-head CI run 40176443806 completed successfully: 39 successful jobs, 26 skipped, no failures, including all three actual PostgreSQL shards, production/test types, lint, source contracts, Madge, and worker/T1/dialect ratchets. The earlier run passed types, lint and source contracts but found a worker-inventory omission: the new direct query was conservatively labeled T1. Head a187ecf corrects only inventory metadata and regenerates its snapshot: the worker snapshot and its private heartbeat helper are W, while the native Doctor reader stays T3. No runtime or SQL change is involved. The generated snapshot also catches up existing main classifications; targeted script lint and formatting pass. The two production reviews remain valid; this tooling-only correction adds no production review round. PG review approved the semantics at 68c24c4, and the coordinator explicitly carried REVIEW-OK to 93a6c4d because only benchmark TypeScript annotations changed. Candidate counts and the inherited-shutdown disposition are recorded; the corrected head’s CI and all three PG shards passed. The test-only import relocation avoids another open PR's adjacent import change; production bytes remain identical to both isolated reviews and database proof. The benchmark annotations fix CI TS7022 without changing emitted behavior. Final-head overlap at a187ecf: complete shared-index base-versus-candidate merge-tree comparison covers 21 peers (openclaw#183410, openclaw#183285, openclaw#181057, openclaw#180871, openclaw#180286, openclaw#180139, openclaw#169241, openclaw#168956, openclaw#168615, openclaw#167546, openclaw#167471, openclaw#165039, openclaw#161997, openclaw#157922, openclaw#157693, openclaw#156613, openclaw#141004, openclaw#137788, openclaw#136476, openclaw#129388, openclaw#121204). No new source conflict paths, regions or messages. Six peers (openclaw#181057, openclaw#180871, openclaw#180139, openclaw#169241, openclaw#129388, openclaw#121204) have added or changed conflicts confined to the fully generated worker inventory. The coordinator explicitly accepted this class because main's snapshot was stale and generated outputs must be regenerated, not hand-edited. The same exact-head disposition carries PG REVIEW-OK because runtime bytes are unchanged. Exact-head CI and all three PostgreSQL shards passed. PG checklist: (1) read-only; existing writer transaction/advisory-lock, DML/conflict and cross-store commit ordering unchanged. (2) At most one joined row via the existing composite primary keys, original job fields plus four scratch fields, unchanged 256 KiB scratch write bound. (3) No cache/generation or invalidation change; one statement snapshot, existing outer PG read transaction retained. (4) No schema/admission/identity/retry/probe change. (5) Same worker owner, one request, no MAIN expansion; target 4→1 SQL in all three real Gateway runs, with the inherited shutdown failure disclosed above. (6) Actual PostgreSQL 17 and SQLite owner conformance passed; all three final-head PostgreSQL CI shards and the other selected static checks passed. Knip was run separately because ordinary PR CI excludes it. The canonical candidate export scan failed with 26 script, 20 production and 16 full-tree findings; none is in a changed file. All 62 occurrences (52 unique file/symbol pairs), scanner/config/compiler inputs and package inputs are unchanged from merge-base 71bc695. The only removed imports, runSqliteReadSnapshotSync and loadCronRows, both retain multiple real production consumers. Current-main diagnostic sections reported 14 script and 7 production findings; main has already repaired 40 candidate occurrences in unrelated changes. Its separate full-tree scan was intentionally stopped after the coordinator accepted the source-attributed inherited findings; it is not a passing full-main scan. No ignored exports, baselines or unrelated code were changed. The failed candidate scan is explicitly accepted as inherited; all branch changes and selected CI static checks pass. Pre-merge shared-index refresh retains 17 open peers from that audit. Only openclaw#180871 moved (f140f16); its fresh base-versus-candidate comparison still adds conflicts solely in the generated worker inventory, within the coordinator-accepted class. No new source conflicts. Co-authored-by: Peter Steinberger <[email protected]>
|
Thanks @zeroaltitude for the investigation and crash-attribution work. Closing as superseded by the restart redesign in #185730 ( Verified against current main This does not claim crash notifications were fixed: adding them would restore behavior retired by that redesign. Passive boot-history diagnostics could still be useful separately. No contributor code was run, and #136554 is unchanged. Thank you for the detailed evidence. |
Recreates #135490 after the repository author-PR ceiling was corrected and portfolio slots were deliberately reprioritized.
What Problem This Solves
Subagents orphaned by a Gateway crash are later reaped with generic or misleading text, and no-output runs can be deleted without notifying the requester. A real 5m36s run reaped after a 34-minute VM outage appeared to have run for 40m35s, leading incident response toward a false timeout diagnosis.
Why This Change Was Made
The orphan reconciler correlates runs with persisted Gateway and host boot lifecycle evidence, reports bounded elapsed time from the best available death signal, and declines attribution when evidence is insufficient or later run activity disproves the inferred death window.
Before crash attribution, the sweeper resolves any fresh persisted terminal child state. Attributed crash completions are explicitly recovery outcomes, so even a delayed restart beyond the original run deadline preserves the crash diagnosis and bounded death timestamp instead of converting it to a timeout. Startup restoration preserves eligible active orphans for requester-visible completion while still pruning queued orphans.
Host boot identity is resolved before each immediate SQLite write transaction. Its nullable column is owned by the canonical startup-additive registry, allowing same-version databases missing the column to be classified and repaired safely.
Crash recovery carries real authority — it can persist a terminal result, notify a requester, and clean up a session — so every completion request the orphan reconciler issues is now bound to the exact registry row it inspected, and that binding survives the retry and restart-drain paths. A same-id successor that takes the slot while the completion waits on the terminal lock is left untouched.
The recorded diagnostic no longer states facts the registry cannot back. Captured
resultTextandfallbackResultTextare alternative result snapshots, not message records, so the text reports recorded-output presence rather than an invented assistant-message count. The interval between the run's last recorded activity and the restart is described as exactly that, not as an asserted Gateway outage duration — last activity can precede the crash, so that interval is an upper bound on downtime.User Impact
Requesters learn that a child was orphaned and why, while diagnostics avoid inventing lifetimes from a late reap timestamp. Legacy rows, clean shutdowns, runs active after a successor boot, uptime-derived identities, and already-terminal child sessions are not over-attributed. A requester whose run was replaced or released mid-recovery is not told the successor failed.
Evidence
Authority-chain proof
Withdrawn claim (round 24). An earlier revision of this section reported "three scenarios, 46 assertions,
All runtime assertions passed." plus an 8-assertion differential. Those numbers were measured on an older head. At headb099c4fa5c3the harness did not execute at all — it died on its first persistence call withTypeError: persistSubagentRunsToDisk is not a function, because thepersistSubagentRunsToDisk/…OrThrow/…AsyncOrThrowfamily andloadSubagentRegistryFromSqlite's old module home were removed fromorigin/main(the lifecycle controller persists throughmutateSubagentRunsnow and no longer acceptspersist*options at all). Those numbers are withdrawn, not restated. Everything below was produced by running the repaired harness on the current head.scripts/proof-136476-orphan-owner-binding.tsexercises resumption, requeue, release and replacement during queued completion and reads the final effects back out of a real SQLite state database.Real, not mocked and not vitest:
reconcileStaleActiveSubagentRun,createSubagentRegistryCompletionRuntime,SubagentLifecycleController(its actual terminal completion lock,expectedEntryguard and terminal-effect chain), the realmutateSubagentRunspublication path inside that controller,persistRegistryFixture/loadSubagentRegistryFromSqliteagainst a tempOPENCLAW_STATE_DIR, andrecordGatewayBootStart/readGatewayBootLifecycleSegments. Stubs exist only at the transport edge (announce flow, completion-reply capture, gateway call, requester settle wake, browser cleanup) and are recorders, so "was the requester notified" is an observed fact. One row is written directly — the crashed predecessor boot, because the production writer can only ever record the current pid; it is inserted through the same schema with a foreign pid, no completion time and no outcome.Six scenarios, 96 assertions,
All runtime assertions passed.:current (control) — the run goes durably terminal in SQLite with the attributed crash error, the published row is still the inspected run's own owner, the requester is notified exactly once, cleanup dispatches.
replaced — a successor row takes the runId while the completion is queued. Its in-memory record and its durable SQLite row are byte-identical to their pre-recovery snapshots; announce, completion-reply capture, gateway call, browser cleanup, requester settle wake and context-engine end notification are all zero.
released — the row is deleted while the completion is queued. The durable row is byte-identical to its pre-recovery snapshot and nothing is delivered.
resumed (new) — the same row acquires a live execution context while the completion is queued.
expectedEntrystill identifies its owner, so only the execution-authority fence can stop the terminal write, the notification and the cleanup.queued (new) — the same run is republished as queued while the completion is queued. The republished row satisfies
isSameSubagentRunOwner, so the controller would still admit it; the durable row must stay queued and byte-identical.history-read race (repaired, round 25) — a successor takes the runId during the real read-worker round trip for boot history, after the helper has consumed its session observation and before it has decided anything.
Corrected claim (round 25). As shipped at head
093609122f5this scenario did not reach the boundary it advertised, and the review was right: the helper awaits session reconciliation first, so a replacement installed synchronously after the call landed in that earlier read andassertReadCurrentretired the helper beforeloadGatewayBootSegmentsForAttributionever ran. The window is now entered deterministically rather than by timing. The run's recorded child session key is blank — themissing-session-entryorphan, whose classification resolves without a session worker read — so the history read is the only read the helper suspends on; the harness starts that read itself with the cache seeded stale and awaits it first, and the helper's own call finds the same load in flight and queues behind it. The successor is therefore installed while the helper is inside the real round trip. Two assertions count the selection checks (two before the read, exactly one after it) so the scenario cannot pass vacuously again.Verified by deletion, as the review asked. With the post-history
isCurrent()check removed fromsubagent-registry-sweeper-orphan.tsand nothing else changed, the repaired scenario fails — and only the counting assertion fails:Every other race assertion still passed in that condition, because the downstream
expectedEntryidentity guard and therecoveryCurrentfence catch the replacement on their own. That is exactly why the previous assertion set could not isolate this guard — and with the guard still deleted, the previous scenario reported94 assertions, 0 failed. All runtime assertions passed.It certified a guard that was not in the tree.The harness is discriminating, not green-by-construction. Re-measured at the round-25 head with the 96-assertion harness (the previous text's "94 assertions, 12 failed" was measured on the round-24 harness and is superseded, not restated). Reverting only
subagent-registry-sweeper-orphan.tsandsubagent-registry-sweeper.tstob099c4fa5c3and changing nothing else fails 13 assertions. Twelve are the reported P1: the resumed and requeued rows are written durably terminal with the dead run's crash error andendedReason: subagent-error, and announce, browser cleanup, requester settle wake and the context-engine end notification all fire against live work. The thirteenth is the new pre-read selection count, which reads0on the reverted helper — it does not re-assert the selection before the history read at all:The control scenario also prints the real recorded error, which is where the two diagnostic corrections are visible in production output rather than in a test string:
Regression coverage
Nine cases in
subagent-registry-lifecycle-orphan-settlement.test-support.tsdrive the same boundary through the real caller → retry runtime → terminal lock path: three originating helper paths (persisted terminal, attributed orphan, lost context) × current/replaced/released ownership.Three further cases in
subagent-registry-sweeper-orphan-contracts.test.tsrun the sweeper against the real session-reconciliation module rather than a mock of it — which is why the two reconciliation defects below were invisible to the existing orphan suite, whosevi.mockreturns a reason string where production returns a deferred observation. Reverting only the two source files tob099c4fa5c3fails all three:Eight further cases in
subagent-restore-resume-ownership.test.ts(round 25) pin the restore path's resume/handoff predicate against the real reconciliation module; see Restored-run resumption for its differential.A tenth lifecycle case (
does not reopen successor cleanup after orphan persistence fails twice) was removed, not repaired: its premise was apersistOrThrowoption onSubagentLifecycleControllerthat no longer exists onorigin/main— terminal writes go throughmutateSubagentRunsnow — so the seam it injected a failure at cannot be reached and the case had never compiled since the base merge. A duplicate copy ofdoes not apply a queued interrupted completion to a same-id successor, resurrected by that same base merge in its older pre-createDeferredCoreform, was also removed;origin/main's current copy (which additionally asserts the rejection outcome) is retained.Restored-run resumption (round 25)
The restore path's resume/handoff predicate had the same defect as the proof scenario above, in the opposite direction:
resolveSubagentRunOrphanReasonreturns a deferred{ read }object for the ordinary case — an unended, nonqueued run with a child session key and no retained obligation — soBoolean(...)over its result was true for every such run, without ever inspectingsessionEntryororphanReason. Restoration handed the sweeper every active restored run, including recent children whose sessions had already finished cleanly, leaving their requesters unsettled until a later sweep. That inverts the distinction the predicate's own provenance names (333e43cd52e: recover interrupted owners while allowing completed sessions to resume normal settlement), which is the before-merge provenance item this round closes.The three session-entry conditions now live in one exported pure classifier,
classifySubagentRunOrphanFromSessionEntry. The deferred reader delegates to it, so the deferred and immediate forms agree by construction, and the restore predicate finishes the classification against the child session entry the restorer already read for that exact owner — no second worker round trip, and the recordedchildAgentIdscoping of that read is untouched.An existing test was red on the previous head and is green now.
keeps restored recovery dormant until the Gateway lifecycle activates it(subagent-registry.persistence.resume.test.ts:568) seeds a restored running child with a written child session, activates the Gateway, and waits forrecoveryRuntime.waitForAgent. On head093609122f5it timed out at 120s — the row was never resumed, so the wait never happened. That file is byte-identical toorigin/mainon this branch, andorigin/maindoes not contain the sweeper-ownership clause at all, so both the clause and the red were this branch's:Eight new cases in
subagent-restore-resume-ownership.test.tspin the predicate directly against the real reconciliation module (the existing restore suitevi.mocksresolveSubagentRunOrphanReasonto() => null, which is why neither it nor the type checker could see this). Reverting only the predicate, with the classifier extraction kept, fails exactly the two cases that assert resumption and none of the six that assert the orphan handoff:Preserved positive trace
The parent-head isolated production proof used two real Gateway processes and one persisted state directory:
runningwhile the child command was alive.{"beforeCrash":{"registryStatus":"running","taskStatus":"running","childCommandAlive":true},"restart":{"priorBootAbrupt":true,"bootRows":2,"sameHostBootId":true},"recovered":{"attributedRequesterEvent":true,"requesterHistoryVisible":true,"registryStatus":"retired","taskStatus":"failed","sessionDeleteCount":1}}That trace was recorded on an earlier head and is not claimed as a fresh run on this one; it is preserved because it covers ordinary crash recovery, which the new harness does not replace. A real SQLite regression also retains 70 boot rows, proving the attribution reader overrides the ordinary 64-row diagnostic cap and preserves the oldest owning boot.
Data-model compatibility (round 21)
gateway_boot_lifecycle.host_boot_idis a bare nullableTEXTcolumn registered as a lazy additive column. The upgrade and rollback contracts were measured against real SQLite (ad-hoc script, not a committed harness — a committedscripts/proof-*.tswould have to be registered inconfig/knip.config.ts):C1a is recorded deliberately: the naive schema comparison does report the extra column. It is tolerated only because
STATE_PERSISTENT_SCHEMA_COMPATIBILITYandOPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITYsetallowCompatibleAdditiveColumns: true, andhost_boot_id TEXTsatisfiesisCompatibleAdditiveColumnDefinition(bare, nullable, STRICT datatype, no default or constraint). That rule predates this branch; this change relies on it rather than introducing it.Round 21b (below) supersedes the older-binary model used above with the real released package.
Released-binary rollback (round 21b)
Round 21's older-binary model was replaced with the real thing: the npm package
[email protected](the currentlatestdist-tag, same package version as this branch) was downloaded withnpm pack, extracted, and its dependencies installed. Its own bundledcollectSqliteSchemaIssues,OPENCLAW_STATE_SCHEMA_SQL,STATE_PERSISTENT_SCHEMA_COMPATIBILITYandOPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITYwere loaded and executed — no modeling, no hand-edited schema.R3 is the load-bearing line: although R2 shows the released schema differs from this branch in more than just our column, the only thing this branch's preflight reports on a released-shaped database is
gateway_boot_lifecycle.host_boot_id. R5 is its mirror: the released binary finds nothing at all to complain about in the upgraded database.What is still not covered. The candidate side of the upgrade is this source tree, not a packed-and-installed candidate build. R3→R4 upgrades state that a released binary's own schema created, which is the substance of the concern, but it is not an
npm installof a packaged candidate. That remains unproven and is not claimed.Gate
Round 24 corrects an earlier claim here too. The previous text described a full serial gate on head
a17a91548b5and namedplugin boundariesas an inherited red lane. On headb099c4fa5c3the branch did not type-check at all:tsgo:coreexited 2 (subagent-registry.persistence.orphan.test-support.tsawaited nothing from the now-asyncgetSubagentRunByChildSessionKey),tsgo:core:testexited 2 with seven more errors insubagent-registry-lifecycle.test.ts, andtsgo:scriptsexited 2 on the proof harness. Those suites therefore had not executed on this branch since its last base merge. Theplugin boundarieslane is green on this head.At the round-25 head
cbce78e043athe complete changed-file gate is green.check:changedprints no summary block on success, so the authoritative signal is the exit code plus the lane headers, read individually from the log:Lanes include
line-cap growth ratchet(30 changed source files, no new violations or over-cap growth),max-lines suppression ratchet,SQLite worker ratchet,first-party mock export ratchet,plugin boundaries(eligibleForRemoval=0),typecheck core,typecheck core tests,typecheck scripts,runtime import cycles,conflict markersand the per-file lint/format lanes. The ratchet lanes require git ≥ 2.35 forgit cat-file --batch-checkobject streaming; on a host whose defaultgitis 2.34 they bail before evaluating anything, which is why they had never reported on this branch before round 24. This gate ran under git 2.55.Focused suites via
scripts/run-vitest.mjsacross ten files: 143 passed, 0 failed (unit-fast 31, infra 41, agents-support 71), against 134 passed / 1 failed on head093609122f5.Two ratchet failures were real and are fixed rather than suppressed (an earlier revision of this section said "three" and listed two; the count was wrong, the list was right):
subagent-registry-lifecycle.test.ts(5451 → 5644),subagent-registry-restore.ts(700 → 703) andopenclaw-state-read.worker.ts(700 → 705). Resolved by four coherent sibling extractions —openclaw-state-read.update-runs.kernel.ts(theupdateRuns.*read dispatch),subagent-restore-resume-ownership.ts(the "another owner holds this restored run" predicate),subagent-registry-lifecycle-fixtures.test-support.ts(the completion-request fixtures) andsubagent-registry-lifecycle-orphan-settlement.test-support.ts(the orphan-settlement cases). No coverage trimmed, nomax-linessuppression added.gateway-boot-lifecycle-read.kernel.tscounted as a new main-thread T1 SQL caller. Its only value import isopenclaw-state-read.worker.ts(the other two are type-only), so it is registered inworkerModuleswith that caller evidence.Not established
mergeableisfalse/mergeable_state: dirtyagainst upstreammain(the first poll returnsnull/unknown; the value above is the second poll), so there is no merge ref and the heavypull_requestCI matrix does not dispatch on this head. That is a pre-existing condition; no merge, rebase or force-push was performed in this round.git merge-tree --write-tree --name-only upstream/main HEADreports the same eight-file conflict set before and after this round's commit, so round 25 added no conflict surface — including insubagent-session-reconciliation.ts, which upstream has itself edited since the fork's base.The acceptance of a nullable startup-additive column as the persisted host-boot identity is a maintainer decision and stays open. What is no longer open is the evidence: the upgrade and rollback contracts are measured above. Round 21b measures the released-binary rollback contract against the real
[email protected]package. What is still missing is annpm installof a packaged candidate build performing the upgrade; the candidate side of round 21b is this source tree.Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).