Skip to content

fix(subagents): attribute crash-orphaned runs and notify requesters - #136476

Closed
zeroaltitude wants to merge 38 commits into
openclaw:mainfrom
zeroaltitude:fix/subagent-orphan-attribution
Closed

zeroaltitude wants to merge 38 commits into
openclaw:mainfrom
zeroaltitude:fix/subagent-orphan-attribution

Conversation

@zeroaltitude

@zeroaltitude zeroaltitude commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

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 resultText and fallbackResultText are 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 head b099c4fa5c3 the harness did not execute at all — it died on its first persistence call with TypeError: persistSubagentRunsToDisk is not a function, because the persistSubagentRunsToDisk / …OrThrow / …AsyncOrThrow family and loadSubagentRegistryFromSqlite's old module home were removed from origin/main (the lifecycle controller persists through mutateSubagentRuns now and no longer accepts persist* 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.ts exercises 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, expectedEntry guard and terminal-effect chain), the real mutateSubagentRuns publication path inside that controller, persistRegistryFixture / loadSubagentRegistryFromSqlite against a temp OPENCLAW_STATE_DIR, and recordGatewayBootStart / 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.:

  1. 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.

  2. 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.

  3. 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.

  4. resumed (new) — the same row acquires a live execution context while the completion is queued. expectedEntry still identifies its owner, so only the execution-authority fence can stop the terminal write, the notification and the cleanup.

  5. 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.

  6. 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 093609122f5 this 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 and assertReadCurrent retired the helper before loadGatewayBootSegmentsForAttribution ever ran. The window is now entered deterministically rather than by timing. The run's recorded child session key is blank — the missing-session-entry orphan, 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 from subagent-registry-sweeper-orphan.ts and nothing else changed, the repaired scenario fails — and only the counting assertion fails:

    96 assertions, 1 failed.
      - race: the helper re-checked its selection after the history read :: {"selectionChecks":2}
    

    Every other race assertion still passed in that condition, because the downstream expectedEntry identity guard and the recoveryCurrent fence 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 reported 94 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.ts and subagent-registry-sweeper.ts to b099c4fa5c3 and 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 and endedReason: 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 reads 0 on the reverted helper — it does not re-assert the selection before the history read at all:

96 assertions, 13 failed.
 - resumed: requester was NOT notified :: {"announce":1,"browserCleanup":1,"settleWake":1,"contextEngineEnded":1}
 - resumed: no browser cleanup dispatched / no requester settle wake /
   no context-engine end notification :: (same recorder)
 - resumed: durable row was never written to a terminal state ::
     {"status":"terminal","endedReason":"subagent-error",
      "outcome":{"status":"error","error":"gateway restarted at … ended without a clean stop …",
                 "startedAt":…,"endedAt":…,"elapsedMs":120000}}
 - resumed: durable row is byte-identical to its pre-recovery snapshot
 - queued: requester was NOT notified :: {"announce":1,"browserCleanup":1,"settleWake":1,"contextEngineEnded":1}
 - queued: no browser cleanup dispatched / no requester settle wake /
   no context-engine end notification :: (same recorder)
 - queued: durable row stayed queued and was never written to a terminal state ::
     {"status":"terminal","endedReason":"subagent-error", …}
 - queued: durable row is byte-identical to its pre-recovery snapshot
 - race: the helper consumed its session observation before the history read :: {"selectionChecks":0}

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:

gateway restarted at 2026-10-12T22:56:12.944Z (previous boot f0767e87-… ended without a clean stop
at an unrecorded earlier time); the host rebooted under it; run orphaned after at least 2m from the
run's last recorded activity, no output recorded in the run registry; the restart came 56m after the
run's last recorded activity

Regression coverage

Nine cases in subagent-registry-lifecycle-orphan-settlement.test-support.ts drive 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.ts run 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, whose vi.mock returns a reason string where production returns a deferred observation. Reverting only the two source files to b099c4fa5c3 fails all three:

× reconciles a raw child session key through its recorded owner
  → promise rejected "Error: Session key does not contain an agent id…" instead of resolving
× resolves the deferred orphan observation instead of formatting the observation itself
  → "subagent run orphaned: [object Object]"  (expected "…: missing-session-entry")
× carries execution authority that refuses a run which comes back to life
  → { admitted: undefined, … }                (no fence on the completion request at all)

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 a persistOrThrow option on SubagentLifecycleController that no longer exists on origin/main — terminal writes go through mutateSubagentRuns now — so the seam it injected a failure at cannot be reached and the case had never compiled since the base merge. A duplicate copy of does not apply a queued interrupted completion to a same-id successor, resurrected by that same base merge in its older pre-createDeferredCore form, 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: 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 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 recorded childAgentId scoping 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 for recoveryRuntime.waitForAgent. On head 093609122f5 it timed out at 120s — the row was never resumed, so the wait never happened. That file is byte-identical to origin/main on this branch, and origin/main does not contain the sweeper-ownership clause at all, so both the clause and the red were this branch's:

# head 093609122f5
 × subagent registry persistence resume > keeps restored recovery dormant until the
   Gateway lifecycle activates it  120027ms
   → Test timed out in 120000ms.
 Tests  1 failed | 70 passed (71)       # |agents-support| shard

# head cbce78e043a
 Tests  71 passed (71)

Eight new cases in subagent-restore-resume-ownership.test.ts pin the predicate directly against the real reconciliation module (the existing restore suite vi.mocks resolveSubagentRunOrphanReason to () => 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:

 × resumes a recent child whose session already finished
 × resumes a recent child whose session is still running
 ✓ hands a run with no child session entry to orphan recovery
 ✓ hands a child session with no session id to orphan recovery
 ✓ hands a stale unended run to orphan recovery
 ✓ hands an aborted child session to orphan recovery
 ✓ resumes a run whose retained obligation already names its owner
 ✓ resumes a queued or already-ended row without consulting the session
 Tests  2 failed | 6 passed (8)

Preserved positive trace

The parent-head isolated production proof used two real Gateway processes and one persisted state directory:

  1. Gateway 1 accepted a real parent agent turn, spawned a real child, and confirmed both the registry row and task row were still running while the child command was alive.
  2. Gateway 1 was killed abruptly.
  3. Gateway 2 started against the same state database and ran the production sweeper.
  4. The requester received the attributed terminal event in real session history; the registry row retired and the child session was deleted exactly once.
{"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_id is a bare nullable TEXT column registered as a lazy additive column. The upgrade and rollback contracts were measured against real SQLite (ad-hoc script, not a committed harness — a committed scripts/proof-*.ts would have to be registered in config/knip.config.ts):

A  fresh start (empty state dir, real assertOpenClawDatabasesReady + open + recordGatewayBootStart)
   -> gateway_boot_lifecycle has host_boot_id; the boot row carries kernel:<uuid>
B1 preflight of a POPULATED pre-column database (previous schema SQL, same schema version, 2 real boot rows)
   -> status=startup-repairable requiresWrite=true foundVersion=17
      issues=["missing-column:gateway_boot_lifecycle.host_boot_id"]
B2 current-binary startup against that database
   -> both populated legacy rows preserved field-for-field; host_boot_id NULL on both;
      the new boot row carries a populated host boot id
B3 readGatewayBootLifecycleSegments over the upgraded database
   -> 3 ordered segments (hostBootId null, null, populated); the crashed legacy segment
      is still readable as crashed (completedAtMs null)
C1a older-binary schema contract with NO compatibility policy
   -> 1 issue: unexpected-column:gateway_boot_lifecycle.host_boot_id
C1b older-binary schema contract with the PRODUCTION policy (the same two collections and the same
    two compatibility objects that collectOpenClawStateSchemaIssues uses; neither compatibility
    object is modified by this branch)
   -> 0 gateway_boot_lifecycle issues — tolerated by the pre-existing
      allowCompatibleAdditiveColumns rule
C2 older-binary INSERT (7 named columns, no host_boot_id) against the upgraded STRICT table
   -> succeeds; the new row's host_boot_id is NULL
C3 older-binary named-column SELECT after that write
   -> all 4 rows returned in order
C4 roll forward again over the rolled-back-and-written file
   -> 0 gateway_boot_lifecycle schema issues

All runtime assertions passed.

C1a is recorded deliberately: the naive schema comparison does report the extra column. It is tolerated only because STATE_PERSISTENT_SCHEMA_COMPATIBILITY and OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY set allowCompatibleAdditiveColumns: true, and host_boot_id TEXT satisfies isCompatibleAdditiveColumnDefinition (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 current latest dist-tag, same package version as this branch) was downloaded with npm pack, extracted, and its dependencies installed. Its own bundled collectSqliteSchemaIssues, OPENCLAW_STATE_SCHEMA_SQL, STATE_PERSISTENT_SCHEMA_COMPATIBILITY and OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY were loaded and executed — no modeling, no hand-edited schema.

R0 loaded [email protected]; its bundled collectSqliteSchemaIssues + 97761-char schema SQL are in hand
R1 the released gateway_boot_lifecycle DDL equals this branch's DDL minus exactly the
   `host_boot_id TEXT` line; `host_boot_id` appears in ZERO files of the released dist
R2 whole-schema comparison: released 97761 chars vs this branch minus the column 99162 chars ->
   DIFFERENT (main has moved since the 2026.9.5 cut; the delta is not only our column)
R3 a database built from the RELEASED binary's own schema SQL, populated with real boot rows,
   preflighted by THIS branch
   -> status=startup-repairable requiresWrite=true
      issues=["missing-column:gateway_boot_lifecycle.host_boot_id"]   (exactly one issue, ours)
R4 this branch's real assertOpenClawDatabasesReady + open + recordGatewayBootStart upgraded that
   released-shaped database and wrote a new boot row
R5 the RELEASED binary's own collectSqliteSchemaIssues, both compatibility policies, against the
   upgraded database
   -> persistent=0, maintenance=0 issues TOTAL (not merely zero for gateway_boot_lifecycle)
R6 a released-shaped INSERT (7 named columns, no host_boot_id) succeeded on the upgraded STRICT
   table, and a released-shaped SELECT returned all 4 rows in order
R7 the released schema check is still clean after that released-binary write

All runtime assertions passed.

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 install of 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 a17a91548b5 and named plugin boundaries as an inherited red lane. On head b099c4fa5c3 the branch did not type-check at all: tsgo:core exited 2 (subagent-registry.persistence.orphan.test-support.ts awaited nothing from the now-async getSubagentRunByChildSessionKey), tsgo:core:test exited 2 with seven more errors in subagent-registry-lifecycle.test.ts, and tsgo:scripts exited 2 on the proof harness. Those suites therefore had not executed on this branch since its last base merge. The plugin boundaries lane is green on this head.

At the round-25 head cbce78e043a the complete changed-file gate is green. check:changed prints no summary block on success, so the authoritative signal is the exit code plus the lane headers, read individually from the log:

exit[check:changed]=0          # 37 check lanes + 31 per-file classification lines
exit[db-worker-ratchet]=0      # SQLite worker ratchet OK: no T1 call-count growth
exit[deadcode:unused-files]=0  # production scan 0 entries; full-tree scan 0 entries
exit[git-diff-check]=0

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 markers and the per-file lint/format lanes. The ratchet lanes require git ≥ 2.35 for git cat-file --batch-check object streaming; on a host whose default git is 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.mjs across ten files: 143 passed, 0 failed (unit-fast 31, infra 41, agents-support 71), against 134 passed / 1 failed on head 093609122f5.

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):

  • Line-cap growth on subagent-registry-lifecycle.test.ts (5451 → 5644), subagent-registry-restore.ts (700 → 703) and openclaw-state-read.worker.ts (700 → 705). Resolved by four coherent sibling extractions — openclaw-state-read.update-runs.kernel.ts (the updateRuns.* 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) and subagent-registry-lifecycle-orphan-settlement.test-support.ts (the orphan-settlement cases). No coverage trimmed, no max-lines suppression added.
  • SQLite worker ratchet: gateway-boot-lifecycle-read.kernel.ts counted as a new main-thread T1 SQL caller. Its only value import is openclaw-state-read.worker.ts (the other two are type-only), so it is registered in workerModules with that caller evidence.

Not established

mergeable is false / mergeable_state: dirty against upstream main (the first poll returns null / unknown; the value above is the second poll), so there is no merge ref and the heavy pull_request CI 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 HEAD reports the same eight-file conflict set before and after this round's commit, so round 25 added no conflict surface — including in subagent-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 an npm install of 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).

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
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The 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.

  • Before: Reap-based timing suggests 40m35s of execution and can produce a misleading timeout diagnosis.
  • After: The diagnostic reports at least 5m36s through last recorded activity and distinguishes that bound from the restart interval.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Both prior findings are repaired and boundary evidence is useful; incomplete shipped-path coverage and unsettled storage direction cap readiness.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Crash-orphaned children can receive misleading lifetime or timeout diagnostics when recovery happens much later.
Reason: The diagnostic repair has demonstrated value and maintainer support, but its new persisted host identity remains an explicit storage decision.

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
Reviewed head: cbce78e043a1f03646257f9dddd9ebf9c0934260
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should Gateway boot lifecycle persist nullable host_boot_id to distinguish host reboot from Gateway process death?
  • Recommendation: Accept the additive lifecycle column: Record acceptance of the existing lifecycle store owning host identity, retaining nullable legacy rows and established additive compatibility.
  • Why: Maintainer support for retaining this work does not accept its new persisted representation, and repository storage policy requires that decision.

Before merge

  • Add real behavior proof - Current-head output and the inspected SQLite-backed harness support rejection of replacement, release, resumption, and requeue at queued completion, including the revised history-read scenario; transport edges are recorders, and the shipped two-Gateway trace predates material restoration changes, so supply current Gateway restoration and requester-delivery logs with IPs, API keys, phone numbers, and non-public endpoints redacted. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Complete next step - Resolve GitHub-confirmed conflicts against current main while preserving canonical completion, recorded child ownership, and recovery authority.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Provide current Gateway restoration and requester-history output, plus a latest-stable published-driver upgrade to a packaged candidate with existing settings and data preserved.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 49c1815 adds src/infra/gateway-boot-lifecycle.ts:209 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 49c18152c8bf; files: src/infra/gateway-boot-lifecycle.ts)
  • Vincent Koc: Raw commit f6e8748 adds src/infra/gateway-boot-lifecycle.ts:29 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: f6e874835c60; files: src/infra/gateway-boot-lifecycle.ts)
  • Ayaan Zaidi: Raw commit a18708c adds src/infra/gateway-boot-lifecycle.ts:21 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: a18708c5c12d; files: src/infra/gateway-boot-lifecycle.ts)

PR surface

Source +731, Tests +1429, Other +711. Total +2871 across 31 files. Added test files: 6.

View PR surface stats
Area Files Added Removed Net
Source 15 875 144 +731
Tests 13 1479 50 +1429
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 711 0 +711
Total 31 3065 194 +2871

Review metrics

Metric Value Why it matters
Persisted schema addition 1 nullable TEXT column; 0 new configuration options Host continuity becomes durable Gateway lifecycle metadata through the existing startup-additive owner.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Misleading diagnostics and requester settlement after crashes affect a bounded recovery workflow.
  • merge-risk: 🚨 compatibility: The new persisted column requires accepted storage semantics and packaged upgrade compatibility before landing.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (29 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-28T18:35:51.607Z sha ede1cd8 :: blocked before merge. :: [P2] Move attribution history reads to the read worker | [P2] Describe the successor timestamp as restart time
  • reviewed 2026-09-29T02:12:01.242Z sha e0530e3 :: blocked before merge. :: [P2] Move attribution history reads to the read worker | [P2] Label the successor timestamp as restart time
  • reviewed 2026-09-29T04:28:30.295Z sha 7c67aa0 :: blocked before merge. :: [P2] Move attribution history reads to the read worker | [P2] Describe the successor timestamp as restart time
  • reviewed 2026-09-30T01:38:12.297Z sha db3677d :: needs real behavior proof before merge. :: [P1] Recheck live execution after the history read
  • reviewed 2026-10-01T20:54:15.798Z sha 6ecdd97 :: needs real behavior proof before merge. :: [P1] Recheck live execution after the history read
  • reviewed 2026-10-02T00:13:40.560Z sha 6cc19a8 :: needs real behavior proof before merge. :: [P1] Recheck live execution through orphan completion
  • reviewed 2026-10-09T01:22:14.275Z sha b099c4f :: needs real behavior proof before merge. :: [P1] Carry current execution authority into orphan completion | [P1] Pass the recorded child owner to the session reader | [P2] Resolve the deferred orphan observation before formatting it
  • reviewed 2026-10-13T02:09:57.027Z sha 0936091 :: needs real behavior proof before merge. :: [P2] Resolve orphan classification before skipping restored resumption | [P2] Enter the history read before replacing its selected run

Reviewed October 13, 2026, 9:39 PM ET / October 14, 2026, 01:39 UTC (Revision 30).

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL labels Sep 2, 2026
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
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Addressed the two findings at exact head d80e1b9202e:

  • startup restoration now preserves eligible active unended crash-orphans for the sweeper's requester-visible completion owner, while queued orphans retain the existing prune path;
  • host boot identity is resolved before both immediate SQLite write transactions.

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, pnpm tsgo:core, git diff --check, and every branch-owned pnpm check:changed lane. The aggregate gate stops only on five plugin-boundary removals inherited unchanged from origin/main.

@clawsweeper re-review

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

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]>
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Fixed the retained-history P1 on signed head 9c213203025.

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 tsgo:core green.

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).

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Sep 2, 2026
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
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Exact-head persisted-Gateway proof is complete at signed 50dfe32c25c.

The proof starts a real isolated Gateway and provider, creates a parent agent turn that calls the real sessions_spawn, confirms the child registry/task rows are running with a live command, kills Gateway 1 abruptly, then starts Gateway 2 against the same existing state database. The production sweeper attributes the orphan, writes a requester-visible terminal result, retires the registry row, and deletes the child session exactly once:

{"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, pnpm tsgo:core, zero dead exports, full changed-file gate including core-test typecheck/lint, production build, and fresh autoreview with no P0-P2 finding.

@clawsweeper re-review

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 4, 2026
Keep uptime-derived restart diagnoses generic and resolve fresh persisted terminal child outcomes before applying crash attribution.

Co-Authored-By: Claude <[email protected]>
@clawsweeper clawsweeper Bot removed the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label Oct 13, 2026
…(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
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Round 25 — both revision-29 findings addressed

Head cbce78e043a1f03646257f9dddd9ebf9c0934260 (GPG verified: true), pushed 093609122f5..cbce78e043a. One commit. Both findings were real; both are fixed with a negative control measured per finding rather than one shared run.


[P2] Resolve orphan classification before skipping restored resumption — subagent-restore-resume-ownership.ts:23-25

The problem, as I read it. 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 handed the sweeper every active restored run, including recent children whose sessions had already finished cleanly, which leaves their requesters unsettled until a later sweep. Confirmed in source at the reviewed head before changing anything, and then by running it: the predicate returns true for a run whose session entry is { sessionId, status: "done", endedAt }.

Approach. The three session-entry conditions now live in one exported pure classifier, classifySubagentRunOrphanFromSessionEntry, in subagent-session-reconciliation.ts. 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 — your second suggestion, since the first (consuming the scoped observation) would duplicate a worker read the caller has in hand. The recorded childAgentId scoping of that read is untouched. This also closes the provenance before-merge item: 333e43cd52e's distinction — recover interrupted owners, let completed sessions resume normal settlement — is what the classifier restores.

Result. 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 and waits for recoveryRuntime.waitForAgent; at 093609122f5 it timed out at 120s, because the row was never resumed. That file is byte-identical to origin/main on this branch, and origin/main does not contain the sweeper-ownership clause at all — so both the clause and that red were this branch's, which is the sharper version of your "late finding" note.

# 093609122f5   × keeps restored recovery dormant …  120027ms → Test timed out in 120000ms.
#               Tests  1 failed | 70 passed (71)        (|agents-support| shard)
# cbce78e043a   Tests  71 passed (71)

Eight new cases in subagent-restore-resume-ownership.test.ts pin the predicate directly against the real reconciliation module. Worth recording why nothing caught this earlier: the existing restore suite vi.mocks resolveSubagentRunOrphanReason to () => null, so neither it nor the type checker could see the coercion. Reverting only the predicate, with the classifier extraction kept, fails exactly the two resumption cases and none of the six orphan-handoff cases:

 × resumes a recent child whose session already finished
 × resumes a recent child whose session is still running
 ✓ hands a run with no child session entry / no session id / stale unended / aborted session
   to orphan recovery          (4 cases)
 ✓ resumes a run whose retained obligation already names its owner
 ✓ resumes a queued or already-ended row without consulting the session
 Tests  2 failed | 6 passed (8)

[P2] Enter the history read before replacing its selected run — scripts/proof-136476-orphan-owner-binding.ts:604-608

You were right, and the scenario was worse than "may not" reach the boundary — it could not. The helper awaits the session observation first, so the synchronous replacement landed in that earlier read and assertReadCurrent retired the helper before loadGatewayBootSegmentsForAttribution ran. Instrumenting the selection callback showed the session read alone consults it eight times; the replacement was always caught by one of those.

Approach. The window is now entered deterministically rather than by timing. The run's recorded child session key is blank — the missing-session-entry orphan, 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; the helper's own 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 assertions count the selection checks (two before the read, exactly one after it), so the scenario cannot pass vacuously again.

Verified by deletion, as you asked. With the post-history isCurrent() check removed from subagent-registry-sweeper-orphan.ts and nothing else changed, the repaired scenario fails — and only the counting assertion fails:

96 assertions, 1 failed.
  - race: the helper re-checked its selection after the history read :: {"selectionChecks":2}

Every other race assertion still passed in that condition, because the downstream expectedEntry identity guard and the recoveryCurrent fence catch the replacement on their own. That is precisely why the old assertion set could not isolate this guard. And with the guard still deleted, the previous scenario reported 94 assertions, 0 failed. All runtime assertions passed. — it certified a guard that was not in the tree. The proof claim in the PR body is corrected rather than silently swapped.


Gate

check:changed prints no summary on success, so the signal is the exit code plus the lane headers, read individually. Run with PATH=/home/linuxbrew/.linuxbrew/bin (git 2.55) so the ratchet lanes actually evaluate instead of bailing under the host's default 2.34:

exit[check:changed]=0          # 37 check lanes + 31 per-file classification lines
exit[db-worker-ratchet]=0      # SQLite worker ratchet OK: no T1 call-count growth
exit[deadcode:unused-files]=0  # production scan 0 entries; full-tree scan 0 entries
exit[git-diff-check]=0

line-cap growth ratchet OK (30 changed source files, no new violations or over-cap growth), plugin boundaries eligibleForRemoval=0, max-lines suppression ratchet OK with no new suppression.

  • Focused suites via scripts/run-vitest.mjs, ten files: 143 passed, 0 failed (unit-fast 31, infra 41, agents-support 71) — against 134 passed / 1 failed at 093609122f5.
  • pnpm tsx scripts/proof-136476-orphan-owner-binding.ts → 96 assertions, 0 failed. Reverting both sweeper files to b099c4fa5c3 → 13 failed (12 are the P1; the 13th is the new pre-read selection count, which reads 0 on the reverted helper). The body's previous "94 assertions, 12 failed" was measured on the round-24 harness and is superseded with the re-measured numbers, not restated.

Mergeability

mergeable: false / mergeable_state: dirty on the second poll (the first returns null/unknown). git merge-tree --write-tree --name-only upstream/main HEAD reports the same eight-file conflict set before and after this commit, so this round added no conflict surface — including in subagent-session-reconciliation.ts, which upstream has itself edited since this fork's base. Nothing was merged, rebased or force-pushed; the fork sync is a separate parked decision.

Still open from my side, and why

  • The nullable startup-additive host_boot_id acceptance is the maintainer decision; it stays with you.
  • Current restoration output / a fresh Gateway restart trace needs a live Gateway, and the packaged-candidate upgrade cell needs an npm install of a packed candidate build. Neither is something a fork can stand up, and I would rather name that than attach a half-real capture. The shipped two-Gateway trace remains explicitly labelled as historical.

@clawsweeper re-review

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@clawsweeper

clawsweeper Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Oct 14, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 24, 2026
steipete added a commit that referenced this pull request Oct 25, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
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]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @zeroaltitude for the investigation and crash-attribution work. Closing as superseded by the restart redesign in #185730 (9344233e7a66).

Verified against current main 202e7b2b5a63: registry restoration now preserves history only, and the sweeper explicitly skips unended historical runs. Graceful shutdown settles children quietly and gives their root requester one ordinary resume input. Crashes/SIGKILL are explicitly accepted as lossy in the new restart contract. The old child/requester restart-recovery owner was intentionally removed.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants