Skip to content

fix(gateway): preserve graceful shutdown when restart intent stalls - #188047

Merged
steipete merged 2 commits into
mainfrom
codex/sigterm-signal-settlement
Oct 30, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/sigterm-signal-settlement

Conversation

@steipete

@steipete steipete commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A stalled restart-intent operation could keep SIGTERM in signal settlement until the supervisor cleanup deadline. The settlement timeout then forced exit before ordinary shutdown could persist restart markers or abort active runs. A reversible suspend lease does not seal restart-intent storage; signal storage is sealed by the run loop's close/reset paths.

User Impact

SIGTERM now reaches ordinary graceful shutdown after at most one second waiting for earlier signals, a sealed store, or intent consumption. The shutdown owner can persist resume markers, abort active runs, and perform bounded cleanup. An unavailable intent can lose its optional restart metadata; stopping still proceeds.

Why This Change Was Made

The signal owner bounds its own wait and cancels intent admission. The existing database worker still owns settlement of dispatched native writes, and late results cannot revive a retired signal. SIGINT also keeps its stop request if it times out behind another signal. Existing restart authorization and committed handoff handling remain in their owners.

Worker inspections already cancel on committed drain or service shutdown. The regression extends the existing inspection test through suspend, reopen, and shutdown, including a provider that ignores cancellation. Write-capable provider operations retain their existing settlement owner.

Evidence

The two blocked-intent signal regressions fail on the base (close was never called), then pass with the fix. A real Gateway process, synthetic model stream, real suspend/resume RPCs, and an isolated SQLite writer lock reproduce the stalled consumption. On the base the short-bound fallback never occurs; with the fix the marker is persisted and the process exits successfully in 1.294 seconds on commit 12361a66a6e0262e24fd157101623f9bf8c267e5, below the ten-second acceptance bound.

Focused signal ordering, restart-intent, and worker lifetime tests pass. Targeted production, CLI-test, Gateway-test, and e2e typechecks, lint, format, diff whitespace, and both line ratchets pass. Test LOC decreases by one line overall; production changes are net +9 lines, documentation +7. No budgets or baselines change. Fresh isolated review found no actionable P0/P1 defects.

Broader local evidence remains red and is not reported as passing:

  • Full run-loop coverage: 154 pass, seven fail, one unhandled error. The same seven failures reproduce with base production: six managed-update setup failures (No safe OpenClaw temp root, group-writable volume ancestor), followed by a 120-second timeout and A process signal exit owner is already registered. The update-during-close test passes in isolation with the fix.
  • The unchanged base restart/resume e2e fails before SIGTERM: concurrent session setup reports Session entry changed during read, then the expected background reply is absent. The exact-head full file has one pass (new acceptance) and one failure in the same session-setup boundary (expected idle reply absent). This prevents broad replacement/resume acceptance on this host. An exploratory continuation after the new stop case also timed out awaiting the resumed provider request; the new acceptance parameter ends at the requested durable-marker/exit boundary.

Full exact-head CI and the merge decision belong to the coordinator; this PR must not auto-merge.

Local commands
node scripts/run-vitest.mjs src/cli/gateway-cli/run-loop.test.ts --maxWorkers=1 -t 'continues graceful shutdown after blocked'
# Base: two failures (close was never called); fixed: two pass.
node scripts/run-vitest.mjs run --config test/vitest/vitest.e2e.config.ts test/gateway-restart-resume.e2e.test.ts --maxWorkers=1 -t 'blocked store: true'
# Base: one failure (no one-second fallback). Fixed exact-head full file: new case passes, marker persisted, exit 0 in 1.294 s; legacy case fails at inherited setup boundary.
node scripts/run-vitest.mjs run --config test/vitest/vitest.e2e.config.ts test/gateway-restart-resume.e2e.test.ts --maxWorkers=1
# Exact-head full-file run described above.
node scripts/run-vitest.mjs src/cli/gateway-cli/run-loop.test.ts --maxWorkers=1 -t 'fences root admission|keeps admission fenced|joins FIFO signal|settles a queued Stop|captured pre-park Stop|upgrades an accepted restart|continues graceful shutdown after blocked'
# Ten pass on commit 12361a66a6e0262e24fd157101623f9bf8c267e5.
node scripts/run-vitest.mjs src/infra/restart-intent.test.ts src/gateway/worker-environments/service-lifetime.test.ts --maxWorkers=1
# Twelve intent and 39 worker lifetime tests pass.
node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo
node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.config-cli.json --incremental
node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.gateway-other.json --incremental
node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.test.root.e2e.json --incremental
# All pass, plus targeted oxlint, format, git diff --check, check:max-lines-ratchet and check:test-lines-ratchet.

Follow-up: daemon CLI restart-intent fixtures

The six lifecycle.restart-intent.test.ts failures reproduce on both 12361a66 and the complete unchanged base 5f3afbe. They are caused by the fixture's default installed command returning environment: {} after #187901 deliberately stopped inheriting caller state selectors. The tests created their serving owner only in caller-selected state, so intent recording inspected a different isolated database.

The fixture now explicitly declares its owned state directory in the installed service command. All 15 daemon restart-intent tests pass with this fixture on both base production and the bounded-signal implementation. Production CLI recording, owner refusals, and SIGTERM cancellation are unchanged by this follow-up. Fresh isolated review found no actionable P0/P1 issues. Total test LOC for this PR is net zero.

Final local validation on 88a8558ac928272768a317bd6abf82fe5457bcef includes every test file under src/cli/daemon-cli/, src/cli/gateway-cli/, and src/infra/restart-intent* (68 explicit files). The real-process acceptance passes: marker persisted, exit code 0, shutdownMs=1325. All three targeted test typechecks, lint, format, whitespace and both ratchets pass. Across the exact-head invocations, all 68 requested files were exercised: 67 files passed; run-loop.test.ts retained the same seven baseline failures. Unique per-file case results are 992 passed, seven failed, one skipped. This is an aggregate across invocations, not a passing full-batch result.

The shared batch was stopped after its baseline fixture failures leaked the process signal exit owner into later process-owning runtime/timeline tests. The CLI runner shares that process singleton between files; fixture startup waits after registration has already rejected. The remaining six files completed in a fresh process (24 tests passed), and all three runtime-recovery cases also passed together in a separate focused run. The downstream timeouts were not independently rerun on the base; their attribution rests on the baseline-proven owner leak, the matching ownership path, and fresh-process passing results. Timeouts, production custody guards, budgets, and baselines are unchanged.

Follow-up proof artifacts remain in the task worktree: j1-followup-test-files.txt enumerates all 68 paths; j1-followup-all-tests.command.txt records the exact wrapper arguments; the shared-batch, remaining-file, and acceptance logs preserve the results. Full CI remains coordinator-owned.

Accepted edge cases and limits

Timed-out restart metadata may be discarded. Already dispatched native writes still settle with the database owner. No new config, schema, retention policy, compatibility path, dependency, or live Gateway mutation is introduced. Historical logs identify the unbounded intent-consumption boundary but cannot identify the exact database job responsible for the incident's long wait.

CI handoff timeout: inherited session-read failure

The checks-node-changed-7 handoff timeout on exact head 88a8558ac928272768a317bd6abf82fe5457bcef reproduces on fetched main e04fd211c732b5f3d3e800556bcef1b94ac0864f. Both standard-wrapper Linux arm64 runs used nice -n 5, --maxWorkers=1, separate worker caches, and successful runtime builds. Both finished with one failure at the unchanged 180000 ms timeout (Vitest durations 210.01s and 208.21s).

In both runs all six agent turns failed with SessionEntryChangedDuringReadError: Session entry changed during read before SIGTERM. The test waits at provider.ready for six held model requests and two exec sessions; restart-intent writing and signaling occur only afterward. The first SIGTERM came from timeout teardown, followed by clean-close receipts within 35ms of the signal fence on head and 30ms on main. This is the same session-read failure signature as the separate restart/resume setup failure, and supplies no evidence of a branch-specific signal/handoff regression.

Exact-head CI remains completed red; this is inherited-failure attribution, not a passing handoff proof. The underlying history-read defect and the five-second handoff assertion remain unresolved by these runs. No source change, timeout increase, CI retry, or additional push was made. Full logs and timestamps are preserved in the task's j1-handoff-classification.md report.

Bound restart signal settlement to one second and fall back to normal SIGTERM shutdown so active runs retain resume markers. Cancel late intent admission without detaching native write settlement. Prove suspend/reopen shutdown with an isolated blocked state store and retain worker inspection cancellation coverage. Timed-out optional restart metadata may be lost.
@clawsweeper

clawsweeper Bot commented Oct 30, 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 cli CLI command changes size: M labels Oct 30, 2026
@steipete
steipete marked this pull request as ready for review October 30, 2026 02:35
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T02:38:10.882111Z 12361a6 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 30, 2026
The service environment merge deliberately excludes caller-only state selectors. Declare the fixture-owned state directory in the installed command environment so intent recording and serving-owner refusals exercise the intended database. The same six failures reproduce on the complete base; the corrected fixture passes on base and the bounded-signal implementation. Keep production CLI and SIGTERM behavior unchanged.
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 30, 2026
@clawsweeper

clawsweeper Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Bounds restart-intent signal settlement so stalled storage cannot prevent graceful Gateway shutdown.

Example: SIGTERM arrives while a SQLite writer blocks restart-intent consumption.

  • Before: Signal settlement waits until the supervisor deadline and can bypass resume-marker persistence.
  • After: After at most 1,000 ms, graceful shutdown proceeds and late intent results are ignored.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-supported repair with reported subprocess acceptance; broad validation remains red and its CI failures are not yet attributed.
Proof confidence 🦐 gold shrimp (3/6) The host identifies this as maintainer-authored, so the ordinary contributor proof gate does not apply; supplied evidence exercises a real Gateway subprocess with synthetic model streaming, suspend/resume RPCs, and SQLite contention through successful marker persistence and exit.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A stop can exhaust its cleanup budget before active sessions receive durable resume markers.
Reason: The maintainer-authored direction restores the existing graceful-shutdown contract and explicitly accepts losing optional timed-out intent metadata.

Regression provenance

Regression provenance — verified: source commit 40d57f8dc8f5 by Peter Steinberger; canonical PR #167572 (blame-to-merge-commit).

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a current shutdown failure using the existing lifecycle owners; no actionable introduced defect was found.

Priority: P2
Reviewed head: 12361a66a6e0262e24fd157101623f9bf8c267e5

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported blocked-store subprocess acceptance covers durable-marker persistence and exit; successful post-replacement continuation remains unproven.
Agent review details

How this fits together

Gateway process signals enter the run-loop signal owner, which consumes optional restart metadata through the shared SQLite worker before requesting shutdown or restart.

flowchart TD
  A[Process signal] --> B[Run-loop signal owner]
  B --> C[Bounded intent consumption]
  C --> D[Shared SQLite worker]
  C --> E[Shutdown request]
  E --> F[Persist markers and abort runs]
  F --> G[Resource cleanup and exit]
Loading

Technical review

Best possible solution:

Keep signal waiting bounded in the existing signal owner while the database owner retains dispatched writes and ordinary shutdown persists resume markers.

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

Current-main source shows stalled intent settlement reaching force-exit before the shutdown request; the author additionally reports matching base-red/head-green runs, which this read-only review did not execute.

Is this the best way to solve the issue?

The patch is a focused fix: it bounds optional metadata observation, cancels late admission, and delegates shutdown and native write settlement to their existing owners.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Ordered worker-backed restart-intent settlement changes intended behavior with a stated reason (40d57f8: Move consumption off the signal thread, consume atomically, preserve ordering, and join accepted native writes.)
  • Natural shutdown and retired signal results keeps the original intent (98813c2: Finish owned cleanup before natural exit and prevent retired continuations from reviving lifecycle work.)
  • Graceful restart markers and acceptance coverage keeps the original intent (9344233: Persist running-root markers before aborting work and resume through ordinary session admission.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 40d57f8 adds src/cli/gateway-cli/run-loop-signals.ts:115 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 40d57f8dc8f5; files: src/cli/gateway-cli/run-loop-signals.ts)

PR surface

Source +9, Tests -1, Docs +7. Total +15 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 47 38 +9
Tests 3 114 115 -1
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 168 153 +15

Review metrics

Metric Value Why it matters
Production versus test LOC Production +47/-38; tests/support +114/-115 The small production increase carries cancellation through existing owners, and regression coverage reuses existing fixtures.

Labels

Label changes:

  • add P2: Repairs graceful shutdown under stalled restart-intent storage without changing normal configuration or adding a new capability.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Repairs graceful shutdown under stalled restart-intent storage without changing normal configuration or adding a new capability.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Establish whether the exact-head daemon assertions and restart timeouts reproduce on the base before selecting repairs or accepting inherited failures.

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.

Reviewed October 29, 2026, 10:52 PM ET / October 30, 2026, 02:52 UTC.

@clawsweeper

clawsweeper Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: applying reviewed decision.

I am applying the reviewed decision for this pull request: fix(gateway): preserve graceful shutdown when restart intent stalls This is item 1/1 in the current shard. Shard 1/1.

This transient lease prevents a newer review from overlapping label, comment, or close mutations.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@clawsweeper clawsweeper Bot removed the rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. label Oct 30, 2026
@steipete
steipete merged commit 315380c into main Oct 30, 2026
134 of 138 checks passed
@steipete
steipete deleted the codex/sigterm-signal-settlement branch October 30, 2026 03:45
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 30, 2026
…ls (openclaw#188047)

The first Team stop on the restart redesign (2026-10-29 20:43Z, release a8ef6aa) closed admission and then logged nothing for 85 s while SIGTERM waited on restart-intent settlement in run-loop-signals.ts. It force-exited before shutdown persisted any resume markers, and systemd SIGKILLed it. After restart there were zero resume inputs, so every running session was lost.

- SIGTERM now falls back to ordinary graceful shutdown after 1 s of stalled restart-intent settlement (marker persistence, abort, bounded cleanup) instead of forceExit, and it refuses late intent results.
- Shutdown releases worker-environment inspections whose provider ignores cancellation. On Team, 5 crabbox reconcile ops had been retained for 3.6 h.
- The CLI daemon lifecycle restart-intent test fixture now supplies the installed service's isolated state directory. Its six failures reproduce on unchanged main; production CLI behavior is unchanged.

Proof at exact head 88a8558:
- Locally: the run-loop regressions are red on base and green here. A new real-process acceptance case (suspend lease reopened, then SIGTERM) persists the marker and exits 0 in 1.3 s. 992 tests pass across the daemon-cli/gateway-cli/restart-intent suites; targeted typechecks, lint and format pass.
- Exact-head CI: 64 jobs succeeded. The only failure, test/gateway-restart-handoff.e2e.test.ts (180 s timeout), is inherited. It times out identically on main fe4fa70, with six SessionEntryChangedDuringReadError before SIGTERM. That is the separate main regression lane K1 is bisecting.
Production +9 LOC.
RomneyDa added a commit that referenced this pull request Oct 30, 2026
…ls (#188047)

The first Team stop on the restart redesign (2026-10-29 20:43Z, release bbde2b8) closed admission and then logged nothing for 85 s while SIGTERM waited on restart-intent settlement in run-loop-signals.ts. It force-exited before shutdown persisted any resume markers, and systemd SIGKILLed it. After restart there were zero resume inputs, so every running session was lost.

- SIGTERM now falls back to ordinary graceful shutdown after 1 s of stalled restart-intent settlement (marker persistence, abort, bounded cleanup) instead of forceExit, and it refuses late intent results.
- Shutdown releases worker-environment inspections whose provider ignores cancellation. On Team, 5 crabbox reconcile ops had been retained for 3.6 h.
- The CLI daemon lifecycle restart-intent test fixture now supplies the installed service's isolated state directory. Its six failures reproduce on unchanged main; production CLI behavior is unchanged.

Proof at exact head 88a8558:
- Locally: the run-loop regressions are red on base and green here. A new real-process acceptance case (suspend lease reopened, then SIGTERM) persists the marker and exits 0 in 1.3 s. 992 tests pass across the daemon-cli/gateway-cli/restart-intent suites; targeted typechecks, lint and format pass.
- Exact-head CI: 64 jobs succeeded. The only failure, test/gateway-restart-handoff.e2e.test.ts (180 s timeout), is inherited. It times out identically on main e04fd21, with six SessionEntryChangedDuringReadError before SIGTERM. That is the separate main regression lane K1 is bisecting.
Production +9 LOC.

(cherry picked from commit 315380c)
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. 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