Skip to content

fix(gateway): settle sessions whose runs a cut-short restart aborted - #165188

Closed
steipete wants to merge 1 commit into
mainfrom
steipete/restart-settle-stale-running
Closed

steipete wants to merge 1 commit into
mainfrom
steipete/restart-settle-stale-running

Conversation

@steipete

@steipete steipete commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes child sessions that remain status: "running" with no active run after a cut-short Gateway restart drain, including dashboard-created children.

This narrow fix is superseded by #165733 (#165733), which makes persisted session status outcome-only and derives liveness from the run registry and queue. Keep this PR open until that cutover lands; the cutover removes the need for this narrower fix.

Solution

The lifecycle writer now records restart cancellation as the existing interrupted state for sessions excluded from main-session automatic resume. Session events carry the same state. Eligible main sessions keep their recovery cycle and can still resume and complete.

Before readiness, the existing recovery scan also repairs an ownerless child's older restart-only marker through the session store writer. It preserves native subagent recovery, pending delivery, live execution, and session admission owners, rechecking ownership at commit. The repair is idempotent and retains the recorded interruption timestamp. No schema, sidecar, configuration, or protocol changes.

User Impact

Affected child sessions stop showing an indefinite Working badge in the sidebar and Workboard. Restart recovery and parent-owned continuation remain available. Existing affected rows are repaired on startup when their saved restart marker and lack of another owner establish that repair is safe.

Why This Change Was Made

Restart cancellation previously kept every session running to preserve main-session recovery. However, that recovery excludes children by spawnDepth/subagentRole, while the separate startup orphan repair recognizes :subagent: keys. A dashboard child can therefore be excluded by both owners and remain running indefinitely.

The local regression proves this dashboard-child path. The supplied Team evidence does not include the affected rows' child/recovery metadata, so it does not establish that every reported Team row has this exact cause. Pending eligible main-session recovery is deliberately preserved.

Evidence

Supplied Team evidence (read-only, 2026-10-04)

Journal:

20:27:38 [gateway] received SIGTERM; restarting
20:27:39 [gateway] draining active work before external-restart with timeout 44597ms: queueSize=14 pendingReplies=4 embeddedRuns=6 agentRuns=7 sessionAdmissions=14 …
20:28:23 [gateway] restart drain budget 44597ms exhausted; cutting short queueSize=12 pendingReplies=4 embeddedRuns=6 backgroundExecSessions=1 agentRuns=6 …
20:28:23 [openai-transport] [responses] error … name=AbortError code=OPENCLAW_RESTART_ABORT (×2)

Ninety minutes later sessions.list still reported, for several agent: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.

Regression

The test starts registered runs through lifecycle events, invokes the real prepareGatewayRunShutdown with an exhausted drain budget, observes OPENCLAW_RESTART_ABORT, and persists the real Gateway lifecycle handler's events to SQLite. It checks the row immediately and after the startup recovery boundary, including hasActiveRun: false. It also proves main-session recovery admission and successful completion, startup idempotency, retained native ownership, and execution/admission acquisition before commit. This is an isolated owner-boundary test, not a live Team restart or a full Gateway process reboot.

Failing-before output on the original production code:

FAIL ... settles a restart-aborted dashboard child while preserving eligible main-session recovery
  {
    "abortedLastRun": true,
-   "status": "interrupted",
+   "status": "running",
  }
FAIL ... repairs the prior restart writer's ownerless dashboard child once during startup
-   "status": "interrupted",
+   "status": "running",
Test Files  1 failed (1)
Tests       2 failed (2)
real 91.43

The initial cold run included 43.14 seconds compiling the worker generation. The final fixture shares one SQLite state owner across its cases; it adds no real sleeps, polling, per-test Gateway boots, or worker pins.

Local proof

  • pnpm install --frozen-lockfile: passed, 27.9 s.

  • node scripts/run-vitest.mjs src/gateway/server-run-shutdown.recovery.test.ts --maxWorkers=1: 5 passed, 100.46 s wall; individual test bodies totaled 15.44 s. This exceeds the 5 s target because the shutdown-to-SQLite case initializes the real runtime/store and proves persistence across recovery ownership; mocking those writers would omit the defect. The three commit-ownership cases took 0.204 s total. No case uses a real sleep or polling.

  • Gateway lifecycle persistence, recovery projection, and event payload siblings plus recovery marking: 93 passed across six files in 316.97 s. After the final admission guard and fixture changes, the new regression and recovery-marking sibling were rerun: 16 passed in 187.11 s. Unchanged lifecycle proof was reused.

  • pnpm tsgo:core: passed, 5.84 s.

  • pnpm tsgo:core:test: passed all shards, 436.38 s. The first attempt found two newly authored fixture literals widened to boolean; explicit session-entry types fixed them.

  • oxfmt --check on all six changed files: passed. oxlint through scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json on all five TypeScript files: passed, 450.76 s including waiting for generated SDK artifacts.

  • pnpm check:deprecated-api-usage: passed, 72.30 s.

  • pnpm check:madge-import-cycles: 0 cycles, 100.05 s; subsequent changes added no dependency edges.

  • SQLite worker, line-cap, and max-lines ratchets: passed. git diff --check: passed.

  • pnpm changed:lanes --json: core, coreTests, docs; no UI, extension, or live-service lane.

  • git merge-tree --write-tree origin/main HEAD: clean (exit 0).

  • Pre-commit direct Codex review and the requested committed-branch direct Codex review: scoped-clean, no accepted/actionable P0/P1 findings.

  • Reviewed head: d1f85931f1994e05b940290d3b10731b237987af.

Branch autoreview status:

{
  "schema_version": 1,
  "status": "scoped-clean",
  "exit_code": 0,
  "engine": "codex",
  "report_produced": true,
  "reason": null,
  "reviewer_exit_code": null,
  "timed_out": false
}

CI seconds are not yet available; CI has not been dispatched manually. No live Team state was changed.

@clawsweeper

clawsweeper Bot commented Oct 4, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 2:55 PM ET / 18:55 UTC (Revision 2).

ClawSweeper review

What this changes

The PR records restart-aborted child sessions as interrupted, aligns session events with that outcome, and repairs older ownerless restart markers during startup.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this intentionally held fallback open. Current main retains the restart-terminal writer defect, and the proposed replacement remains open and conflicted; no introduced correctness defect was identified.

Priority: P2
Reviewed head: d1f85931f1994e05b940290d3b10731b237987af

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused fallback with meaningful persistence and ownership regressions and no identified blocking code defect.
Proof confidence 🌊 off-meta tidepool Not applicable: The verified trusted author is exempt from ordinary contributor runtime proof. Reported owner-boundary regressions exercise real shutdown, lifecycle persistence, and startup repair with synthetic runs; they are not a live Team restart. Existing-state compatibility is supported by the legacy SQLite fixture, idempotency, retained-owner controls, and unchanged storage shape.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The verified trusted author is exempt from ordinary contributor runtime proof. Reported owner-boundary regressions exercise real shutdown, lifecycle persistence, and startup repair with synthetic runs; they are not a live Team restart. Existing-state compatibility is supported by the legacy SQLite fixture, idempotency, retained-owner controls, and unchanged storage shape.
Evidence reviewed 9 items Pinned introduced change: Reviewed the merge-base-to-head production hunks and the complete new shutdown/recovery test. Base-branch drift was excluded from PR ownership.
Current main still needs writer settlement: Current main maps restart cancellation to running without the child eligibility distinction. The PR's lifecycle writer change therefore remains meaningful.
Latest release retains the same terminal behavior: The v2026.9.8 source likewise maps restart cancellation to running. This check does not establish that every observed stale Team row shares the dashboard-child mechanism.
Findings None None.
Security None None.

How this fits together

Gateway shutdown cancels unfinished agent runs, and lifecycle writers persist their session outcomes. Startup recovery and session projections consume those records to resume eligible work and display activity.

flowchart TD
  A[Restart drain expires] --> B[Cancel active runs]
  B --> C[Session lifecycle writer]
  C --> D{Eligible main session?}
  D -->|Yes| E[Retain restart recovery]
  D -->|No| F[Record interruption]
  G[Older restart markers] --> F
  F --> H[Session events and activity display]
Loading

Before merge

  • Resolve merge risk (P2) - The fallback head conflicts with main; landing it would require conflict resolution and review of the resulting integration.
  • Complete next step (P2) - Keep this fallback unmerged until the approved cutover lands; if fallback landing becomes necessary, resolve current conflicts and validate the resulting integration.
Agent review details

Security

None.

PR surface

Source +91, Tests +359, Docs +1. Total +451 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 105 14 +91
Tests 1 359 0 +359
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 465 14 +451

Review metrics

Metric Value Why it matters
Production versus regression growth production +91 net lines; tests +359 Production growth implements child settlement and guarded historical repair; the regression spans shutdown, persistence, and recovery ownership.
New regression cost 100.46 s reported wall time; 15.44 s test bodies The body explains the real runtime and SQLite initialization cost and distinguishes it from case execution.

Root-cause cluster

Relationship: partial_overlap
Canonical: #165733
Summary: The broader cutover owns the intended permanent repair, while this PR remains an explicitly retained fallback.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Use the approved outcome-only cutover to give run liveness one owner while preserving recovery custody, retaining this narrow repair until that implementation lands.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Use the approved outcome-only cutover to give run liveness one owner while preserving recovery custody, retaining this narrow repair until that implementation lands.

Do we have a high-confidence way to reproduce the issue?

Yes: source establishes that restart cancellation persists running while child metadata excludes main-session recovery. The captured failing-before regression exercises shutdown and SQLite persistence; this read-only review did not rerun it.

Is this the best way to solve the issue?

Yes as a bounded fallback, though the approved outcome-only cutover is the better permanent solution because it removes competing durable liveness state.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against f0d34cbd05b8.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs stale child-session activity after an exhausted restart drain, with bounded impact and an active replacement implementation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The verified trusted author is exempt from ordinary contributor runtime proof. Reported owner-boundary regressions exercise real shutdown, lifecycle persistence, and startup repair with synthetic runs; they are not a live Team restart. Existing-state compatibility is supported by the legacy SQLite fixture, idempotency, retained-owner controls, and unchanged storage shape.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-04T23:27:25.724Z sha d1f8593 :: needs maintainer review before merge. :: none

@steipete

steipete commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Holding this PR unmerged as a fallback. Peter approved the broader cutover this fix pointed at: persisted session status becomes outcome-only (done | failed | killed | timeout | interrupted), running/queued are never persisted, liveness comes from the run registry and the queue owner, and the restart-recovery claim lives on the recovery-owned fields instead of being inferred from status === "running". That removes the exclusion list this change extends. The cutover lands as its own PR from the same lane and supersedes this one; if it stalls, this PR is the immediate repair for Team and lands instead.

@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #165733, which removes the persisted running marker this fix worked around: session status becomes outcome-only, liveness comes from the run registry, and restart-aborted runs are recorded as interrupted at the lifecycle owner with a Doctor-only normalization for legacy rows. The failing-before reproduction from this PR lives on in #165733's recovery suite.

@steipete steipete closed this Oct 6, 2026
@steipete
steipete deleted the steipete/restart-settle-stale-running branch October 6, 2026 05:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant