Repository navigation
refactor(sessions): persist run outcomes only; liveness comes from the run registry - #165733
Conversation
|
🦞👀 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: blocked before merge. Reviewed October 6, 2026, 1:42 PM ET / 17:42 UTC (Revision 16). ClawSweeper reviewWhat this changesThe branch stores completed run outcomes, derives session activity from runtime registries, and updates recovery, maintenance, CLI selection, and regression coverage. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 9 items remain Keep open: the two prior compatibility blockers remain, and the legacy-yield migration introduces an additional continuation-admission failure. Current main and the merged Workboard fix do not replace the remaining cutover. Priority: P2 Review scores
Verification
How this fits togetherSession metadata preserves outcomes and recovery custody across Gateway restarts. Runtime run and queue owners supply current activity to session lists, while recovery owners decide whether interrupted work may resume. flowchart TD
A[Incoming agent turn] --> B[Admission and recovery owner]
B --> C[Live run registry and queue]
B --> D[Durable session metadata]
C --> E[Gateway session presentation]
D --> E
D --> F[Restart recovery]
F --> B
Decision needed
Why: The coordinator decisions cover internal behavior but do not establish permission to break released SDK writes or reinterpret recovery state for older schema-24 readers. Before merge
Findings
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep registry-derived liveness behind a compatible SDK transition, preserve rollback custody, and avoid creating recovery ownership for completed yields. Do we have a high-confidence way to reproduce the issue? Yes, the three blockers have explicit source paths: a previously valid plugin status write, a migrated unfinished row reopened by v2026.9.8, and a migrated yielded parent entering foreground admission. These paths were inspected, not executed. Is this the best way to solve the issue? No, the owner consolidation is sound in direction, but the current implementation breaks released compatibility and creates recovery residue for a completed yield. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against cca16bed6373. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (15 earlier review cycles; latest 8 shown)
|
ca37244 to
98684e4
Compare
47a7637 to
5fe118a
Compare
Use live reply ownership when admitting turns with durable execution fences, and release an unclaimed recovery route only with its delivered pending intent. Preserve explicit message-tool-only policy when early run IDs make fallback execution and finalization share options. Migrate current-main fixtures away from persisted liveness and retired event fields without relaxing their behavior assertions. Refresh worker inventory. Validation: production and core test types, formatting, lint, import cycles, worker inventory, focused owner suites, and direct-route review passed. Progress presentation passed all 16 cases with a canonical macOS fixture root. Broader proof identified inherited database-admission and rotation-spy failures on main 6d94780; those remain unchanged. Final integration proof continues on the rebased head before publication. Refs #165733
Move unchanged fence normalization and recording into the existing persisted recovery utility owner. Update every caller and remove the old exports so the consolidated transition module stays below its lint budget without splitting its authority decisions. Validation: core and extension types, all 27 core test-type shards, formatting, type-aware lint, both import-cycle checks, worker inventory, and independent review passed. The 13-file integration packet passed 244 tests in 277.03s; the preceding 22-file packet passed 708 tests in 757.78s. The E2E packet passed 243 tests, including 16 progress-presentation cases and real SIGKILL recovery, in 1549.79s including the runtime build. Linux-only restart handoff stayed platform-skipped on macOS. Temporary canonical temp-root fixture overrides were removed after proof. Refs #165733
A database close refusal left queued input intact and the drain's finally block immediately rescheduled it. With debounce disabled this starved the event loop and flooded shutdown logs. This owner defect is inherited from main b2fab20, where the new deterministic regression also fails with "expected 2 to be 1" before its safety stop. Classify the refusal with the existing shared admission-closed error and park the queue without completing or discarding its input. Release detached work; a fresh drain signal or durable restart recovery owns continuation. Move the singleton error to a leaf module and migrate all consumers so this admission boundary introduces no runtime or type-inclusive import cycle. Retain explicit requests received while a refused attempt unwinds on that exact drain owner. One successor consumes the request and parks again if admission still refuses it; no automatic retry loop is restored. Persisted session outcomes and durable recovery contracts are unchanged. The fake-clock regression proves one attempt while closing, retained input, released root work, and successful draining after admission reopens. The final standalone drain suite passes 23 tests in 12.04 seconds wall; the new cases use only fake-clock advancement. The queue/recovery sweep passes 1,063 tests across 60 files. This is a separate production fix for the shutdown hot loop exposed by #165733's RPC fixture.
6b1cd9f to
f0e950c
Compare
Use live reply ownership when admitting turns with durable execution fences, and release an unclaimed recovery route only with its delivered pending intent. Preserve explicit message-tool-only policy when early run IDs make fallback execution and finalization share options. Migrate current-main fixtures away from persisted liveness and retired event fields without relaxing their behavior assertions. Refresh worker inventory. Validation: production and core test types, formatting, lint, import cycles, worker inventory, focused owner suites, and direct-route review passed. Progress presentation passed all 16 cases with a canonical macOS fixture root. Broader proof identified inherited database-admission and rotation-spy failures on main 6d94780; those remain unchanged. Final integration proof continues on the rebased head before publication. Refs #165733
Frozen upstream: 10334ec (previous base 14fe10d). Nine conflicts, resolved hunk by hunk: - config-baseline.counts.json, worker-access-inventory.md: upstream's copy; regenerated in follow-up commits. - agent-runner-run.ts: keep the feature's bindVisiblePartialReplyObserver; re-apply upstream's always-present runId (openclaw#165733). - agent-runner-result-payloads.ts: drop upstream-removed stale "drain" comment; keep queued-delegate counts. - session-accessor.sqlite-lifecycle.ts: add upstream's captureIncognitoSessionOperation import; history maintenance stays in the feature's sibling module; drop upstream-removed jsdoc. - openclaw-agent-db-lifecycle.ts: upstream's validation-cache imports (get/invalidate) replace hasRevoked. - doctor-health.migration-refusal.test.ts: both sides added the same maintenance facts; keep the typed one. - get-reply-run.media-only.test.ts: helpers stay in the continuation test-support; upstream's expectDefined form re-homed there. - subagent-announce.format.e2e.test.ts: upstream's call.params form + feature continuationTrigger assertion and omitted-trigger case; matrix stays in the feature's nested-matrix test-support; drop redundant embedded-run mock resets (upstream consolidation openclaw#166052). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
* commit 'c39d9b0692dbaafa5b1bfe02514c9f6411ab5546': (30 commits) fix(ci): clear MCP audit and service-worker test blockers (#166217) test(gateway): wait for steering admission in FIFO fixtures fix(llama-cpp): managed setup crashes and loops on macOS below 13.3 (#163358) perf(worktrees): avoid full session parsing during GC (#166072) fix(update): recover stopped legacy managed services (#166232) perf(gateway): stream bounded link preview metadata (#166195) perf(diagnostics): release completed Git operation state (#166214) chore(deps): update fs-safe to 0.24.1 and clone plugin source captures (#166189) feat(clients): adopt worker-local inference placement (#163647) test: serialize PowerShell completion process suites (#166229) test: stabilize release timing boundaries (#166218) refactor(sessions): persist run outcomes only; liveness comes from the run registry (#165733) test(gateway): prove mention refresh after config retargeting fix(team-reports): keep the missed closed day when catch-up runs after midnight (#165780) test(gateway): join WebChat queue admission and drain completion fix(logging): reject blank diagnostic stability query fields (#145532) fix(agents): report unparseable serialized edit arguments (#163577) improve(anthropic): log Claude Code version probe failures (#157697) fix(agents): clarify prompt-size provider failures (#159712) fix(memory): re-throw non-ENOENT/ENOTDIR errors in root memory file lookup (#107921) ...
…e run registry (openclaw#165733) Persisted session status now records only run outcomes (done, failed, killed, timeout, interrupted). Running and queued are derived from the live run registry and queue, so a cut-short restart drain can no longer leave a session showing "Working" forever. - Restart-aborted runs record `interrupted` with a reason and end time while keeping recovery claims; the startup orphan reconciler is removed. - Startup runs the Doctor transform once to normalize legacy persisted running/queued values to interrupted (verified legacy yields keep ownership). - Turn admission, chat restart recovery, sessions tail, and session cleanup read liveness from the live owners. - Follow-up queue drains park instead of retrying in a hot loop when agent database admission is closing. - agent.wait wakes when queued chat admission publishes after the wait began. - Explicit message-tool-only delivery policy survives model fallback. Net production LOC is reduced. CI: all test shards green on 85a4f42; security-fast fails on the same two MCP SDK advisories that fail on main (run 37501461189), not caused by this change.
What Problem This Solves
A cut-short restart could leave a persisted session marked
runninglong after its run disappeared. The sidebar Working badge and Workboard then disagreed with the live run registry.This PR supersedes #165188, the narrow restart-settlement fix. Keep that PR open until this cutover lands. The plugin facts work overlapped #165189, which landed first; this branch preserves its registry/queue derivation and shared pull-request owner improvements.
Solution
Persist only run outcomes:
done,failed,killed,timeout, andinterrupted. Starts clear the previous outcome and retain run identity/timing. Gateway rows derive running and queued activity from the run registry and queue owner. Restart-aborted runs persist interruption, reason, and end time; eligible work retains the recovery owner's existing claims.Coordinator-decided contracts:
sessions tail: select running sessions throughsessions.listwhen reachable, matching session identities. Offline selection uses activity order and printsGateway unreachable: showing the most recently active session; explicit--storeuses activity order and printsexplicit store: ordered by activity. Authorization and policy errors do not silently fall back.sessions cleanup --enforcerefuses while a Gateway owns the store, names the owner, and directs the operator to Gateway-delegated cleanup or to stop the Gateway. Delegation and dry-run previews retain their existing behavior.running|queued → interruptedtransform leaves the outcome unset for verified yielded-parent ownership, guarded against an active writer, a recovery fence, or terminal evidence. Other legacy liveness values settle tointerrupted. Liveness always remains registry-derived.Startup invokes the existing Doctor transform before admitting each store. The transform is idempotent, logs its count, preserves timestamps/history and claims, and arms existing recovery fields for eligible legacy running entries that lacked claims. Recovery discovers work through
mainRestartRecovery,restartRecoveryRuns, before-reply, and delivery fields. Storage workers receive explicit live-session-key snapshots and revalidate before destructive writes. No new schema version or sidecar store is introduced.Terminal cleanup retires only the execution or delivery claim it owns. Accepted terminal writes drain first; unrelated claims, successor generations, and source reservations survive. The CI follow-up also removes remaining persisted-liveness fixtures, updates the canonical Gateway test inventory, and prunes the obsolete assertion-safety allowance.
User Impact
Sessions no longer display indefinite Working badges because of stale saved liveness. Eligible interrupted work can resume, including turns without a channel delivery route. Verified yielded parents retain continuation ownership without a spurious recovery turn. Local cleanup cannot prune a store owned by a live Gateway.
Why This Change Was Made
Run liveness already has an authoritative registry and queue. Persisting another liveness flag let restart settlement, recovery discovery, readers, and maintenance disagree. Durable session metadata now records outcomes, while runtime owners supply activity.
The coordinator accepted the −418 production-line reduction; −476 was a target, not a publication gate. The coordinator also authorized publishing the rebased head while hosted CI runs the full changed plan. No merge or auto-merge is requested.
Evidence
Team evidence supplied read-only for 2026-10-04:
Ninety minutes later
sessions.liststill reported, for severalagent:roboclaw:dashboard:…sessions:status: "running", hasActiveRun: false,updatedAt: 2026-10-04T20:28:24Z(five rows share that second), last activity hours earlier. Nothing is running for them (no live run in the registry), yet every surface that reads the persisted status (sidebar "Working" badge, Workboard) shows them as running. The run registry is right; the persisted session status is stale.Baseline reproduction on
382c987dbe1c7ee08634ef72e752085ed7639d2efailed through the real restart-shutdown and startup entry points (34.69 s wall):Rebase and publication
Published head:
bc60cd6c9122555b81db318f54794c84bb331018, rebased ontoc20c6e5822d741c03831cac8ad805aace1735de3.98684e45ec2dwas pushed as authorized; subsequent pushes resolved verified conflicts as main advanced. GitHub reported MERGEABLE immediately after this publication. Merge-tree against the fetched main is clean. These were conflict-resolution pushes, not attempts to rerun CI for green.src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.tsagent-runner.runreplyagent.steering-receipts.cases.ts. Retain the cutover's session-key alignment, the retained follow-up/ownership assertions, and main's structured steering diagnostics.src/infra/gateway-lock.test.tssessions cleanup --enforce.src/auto-reply/reply/agent-runner-result-accounting.fallback.test.tsdisposeOpenClawAgentDatabaseByPathintoopenclaw-agent-db-disposal.ts; retain async database-close cleanup.src/gateway/server-plugins.session-facts.test.tsThe generated worker inventory was refreshed after integration. Main's per-agent inbound-admission wait and exact terminal-dispatch cleanup remain intact. The temporary-error allowance from
98684e45ec2dwas dropped because main's admission wait supersedes it; the hard-kill test again rejects every failure reply.Proven checks and limits
src/infra/gateway-lock.test.tsandsrc/channels/turn/run-channel-turn.startup-admission.test.ts, throughnode scripts/run-vitest.mjs ... --maxWorkers=1src/gateway/server-plugins.session-facts.test.ts, through the native Vitest wrappersrc/auto-reply/reply/agent-runner-result-accounting.fallback.test.ts, through the native Vitest wrapperThe local command-error regression failed before the owner fix (2 expected failures, 43.05 s), then passed its focused cases (61.61 s). It exercises actual
agentCommandadmission and preserves sibling recovery claims. The real drain/startup regressions require their existing Gateway lifecycle composition; the hard-kill case requires a real process restart. Their process/build overhead is included in wall times and is not replaced with helper-only proof.The complete changed-plan packet at
128bf7545380412578e71a5fd67623fa936ba00cselected 152 units, including 42 changed-check commands and 80 canonical Node rows, plus required supplemental owners. 14 units executed: 12 passed, 2 failed; 138 remained unrun. No full green result is claimed.128bf7545380checks-node-changed-compact-large-16-1Type/storage Testbox run: native command 1,321.931 s, successful settled wrapper receipt. Runtime Testbox run: native command 2,743.315 s, including a 691.79 s runtime prerequisite; failed receipt preserved. Lease cleanup status is separate from command success. All task leases were released.
The two failed units
checks-node-changed-1— 293.68 s. Its sole failure wasextensions/qa-lab/src/gateway-kill-restart-send.e2e.test.ts, “reconciles an orphaned run and replies to a new inbound send after SIGKILL.” The original unacknowledged inbound was replayed while agent database preparation was pending, producing an error reply before recovery could be observed. The empty-transcript checkpoint race had already been corrected withallowEmpty: true, while still requiring an unfinished tool call. Main subsequently added the actual abortable per-agent wait in8e3c6beb8f65, insrc/channels/turn/execution.tsbefore metadata writes/dispatch; this rebase includes it. Its four focused startup-admission tests pass locally. The full hard-kill E2E awaits hosted CI; no post-fix E2E pass is claimed.checks-node-changed-4— 485.00 s. Its sole failure wastest/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts, “records suppressed Slack announcements without claiming delivery.” The child was terminal but delivery remained pending because embedded cleanup stalled atopenclaw-trajectory-flush,timeoutMs=10000,pendingRows=7,queuedBytes=30062,activeOperation=sqlite-append. The stall is in the trajectory append/flush path (src/trajectory/runtime-store-writer.ts,src/agents/embedded-agent-runner/run/attempt-trajectory-flush.ts), before command-level claim cleanup. Fifteen other tests in that file passed; the originally reported usage/memory test also passed. A prior Testbox packet passed this same Slack case (76.874 s), and the trajectory/attempt cleanup owners were unchanged by this PR. These facts suggest timing or admission contention rather than a stale-status assertion, but attribution is unproven. Pending delivery is the correct unresolved state; it was not relabeled to manufacture success.Hosted CI owns the remaining full plan
Per coordinator decision, the remaining compact Node rows, test-type stripes, ratchets, lint/guard, build, SDK, and recovery coverage are delegated to hosted CI on the published head. Historical local/Testbox passes above are labeled with their scope; they do not establish full-plan success on this head. The coordinator is watching CI; this task does not rerun workflows or re-push merely for green.
Baseline attribution attempts never executed a test: Testbox admission remained queued for 15 minutes, then AWS sync stalled for 10 minutes twice, including a fresh full resync. Both AWS receipts recorded zero command time. A local hard-kill diagnostic reached its 600.15 s host budget during runtime prerequisites, before test execution. An earlier rebase's E2E selection again requested that full build and was stopped before tests (131.27 s); the separate core packet above passed. No build-skip flag, longer test timeout, or passing-baseline claim was used.
Final branch autoreview
Direct-route Codex full-branch review completed on
bc60cd6c9122555b81db318f54794c84bb331018, againstorigin/main(captured basec20c6e5822d741c03831cac8ad805aace1735de3), at P1 with a 3,600-second engine timeout. All four passes completed with zero findings; final source verification passed. The complete selected branch diff and supplied committed owner context were reviewed. Runtime proof limits remain as recorded above.{ "schema_version": 1, "status": "scoped-clean", "exit_code": 0, "engine": "codex", "report_produced": true, "reason": null, "reviewer_exit_code": null, "timed_out": false, "usage": { "attempts": 4, "reported_attempts": 4, "unknown_attempts": 0, "partial_attempts": 0, "complete": true, "tokens": { "input_tokens": 408769, "cached_input_tokens": 0, "output_tokens": 12531, "reasoning_output_tokens": 11928 } } }Production LOC
Physical lines in the same touched production files, compared with base
c20c6e5822d741c03831cac8ad805aace1735de3. Tests, test support, docs, and tooling are excluded. The coordinator accepted −418.Production LOC by file
src/agents/agent-command-restart-recovery.tssrc/agents/agent-command.tssrc/agents/agent-harness-completion-delivery.tssrc/agents/command/cleanup.tssrc/agents/command/post-run.tssrc/agents/command/session-preparation.tssrc/agents/embedded-agent-runner/runs.tssrc/agents/main-session-recovery/main-session-recovery-admitted-interruption.tssrc/agents/main-session-recovery/main-session-recovery-lifecycle.tssrc/agents/main-session-recovery/main-session-recovery-state.tssrc/agents/main-session-recovery/main-session-recovery-store.tssrc/agents/main-session-recovery/main-session-recovery-types.tssrc/agents/main-session-recovery/main-session-restart-dispatch.tssrc/agents/main-session-recovery/main-session-restart-recovery-checkpoint.tssrc/agents/main-session-recovery/main-session-restart-recovery-delivery.tssrc/agents/main-session-recovery/main-session-restart-recovery-failure.tssrc/agents/main-session-recovery/main-session-restart-recovery-marking.tssrc/agents/main-session-recovery/main-session-restart-recovery-runtime.tssrc/agents/main-session-recovery/main-session-restart-recovery-shared.tssrc/agents/main-session-recovery/main-session-restart-recovery-store.tssrc/agents/main-session-recovery/main-session-restart-recovery-target.tssrc/agents/subagents/registry/subagent-delivery-state.tssrc/agents/subagents/registry/subagent-registry-helpers.tssrc/agents/subagents/registry/subagent-registry-restart-recovery-helpers.tssrc/agents/subagents/registry/subagent-registry.store.sqlite.tssrc/agents/subagents/registry/subagent-session-reconciliation.tssrc/auto-reply/reply/agent-runner-execute.tssrc/auto-reply/reply/agent-runner-run.tssrc/auto-reply/reply/reply-turn-admission.tssrc/auto-reply/reply/restart-recovery-claim.tssrc/cli/program/register.status-health-sessions.tssrc/commands/doctor-session-delivery-state.tssrc/commands/doctor-session-title-repair.tssrc/commands/doctor/shared/session-entry-rewrite.tssrc/commands/doctor/shared/session-entry-shape.tssrc/commands/sessions-cleanup.runtime.tssrc/commands/sessions-tail.tssrc/config/sessions/disk-budget-files.tssrc/config/sessions/disk-budget.types.tssrc/config/sessions/lifecycle.tssrc/config/sessions/restart-recovery-receipt.tssrc/config/sessions/restart-recovery-state.tssrc/config/sessions/session-accessor.entry.tssrc/config/sessions/session-accessor.sqlite-contract.tssrc/config/sessions/session-accessor.sqlite-maintenance-candidates.tssrc/config/sessions/session-accessor.sqlite-replacement-projection.tssrc/config/sessions/session-accessor.sqlite-replacement-read.tssrc/config/sessions/session-accessor.sqlite-status.tssrc/config/sessions/session-accessor.sqlite-transcript-reports.kernel.tssrc/config/sessions/session-accessor.sqlite-transcript-reports.tssrc/config/sessions/session-accessor.sqlite-transcript-reports.types.tssrc/config/sessions/session-accessor.sqlite-transcript-reports.worker.tssrc/config/sessions/session-accessor.tssrc/config/sessions/session-cold-storage-eligibility.tssrc/config/sessions/session-cold-storage-selection.tssrc/config/sessions/session-cold-storage-worker.tssrc/config/sessions/session-cold-storage.tssrc/config/sessions/session-entry-read.types.tssrc/config/sessions/session-entry-read.worker.tssrc/config/sessions/session-entry-state-format.tssrc/config/sessions/session-entry-status-read.tssrc/config/sessions/session-history-eviction-candidates.tssrc/config/sessions/session-history-eviction.tssrc/config/sessions/session-history.tssrc/config/sessions/startup-migration.tssrc/config/sessions/store-maintenance-preserve.tssrc/config/sessions/store-maintenance.tssrc/config/sessions/terminal-status.tssrc/config/sessions/types.tssrc/gateway/agent-turn/agent-session-persist.tssrc/gateway/server-chat-event-admission.tssrc/gateway/server-methods/agent-session-patch.tssrc/gateway/server-methods/chat-restart-recovery.tssrc/gateway/server-methods/chat-send-admission.tssrc/gateway/server-methods/chat-send-handler.tssrc/gateway/server-startup-session-migration.tssrc/gateway/session-lifecycle-state.tssrc/gateway/session-row-projection-record.tssrc/gateway/session-utils-core.tssrc/gateway/session-utils-display.tssrc/gateway/session-utils-row.tssrc/gateway/sessions-patch-lifecycle-flags.tssrc/infra/gateway-lock.tssrc/infra/outbound/delivery-completion.tssrc/sessions/session-run-error.tssrc/status/status-text.ts