Skip to content

fix(gateway): prevent startup failures during temporary state contention - #166111

Merged
steipete merged 3 commits into
openclaw:mainfrom
NianJiuZst:codex/fix-startup-state-admission
Oct 7, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
NianJiuZst:codex/fix-startup-state-admission

Conversation

@NianJiuZst

@NianJiuZst NianJiuZst commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway startup can exit before opening its listener when another OpenClaw process temporarily owns the shared-state schema. The reported lock lasted about nine seconds; a five-second SQLite busy budget is too short for that startup race.

User Impact

Startup waits up to five minutes for temporary schema custody, matching the existing startup migration lease budget and accommodating slow cold starts. Explicit offline maintenance still refuses access immediately. Exhausted contention retains the operational read-failure path (exit 1); configuration errors and required offline migrations retain their existing classification. No configuration, schema, stored-data, permission, or update-migration contract changes.

Why This Change Was Made

The existing snapshot owner retries only StateDatabaseAdmissionPendingError for its selected database. Startup supplies the wait budget; other snapshot callers still default to immediate refusal. Every attempt checks cancellation and fresh ownership. Snapshot preparation, callbacks, and cleanup remain outside the retry loop, and admission is revalidated before the callback.

Maintainer cleanup preserves synchronous error mapping and retained read settlement while removing a single-use forwarding function and duplicate positional arguments. It also simplifies error construction and empty registry diagnostics. The existing raw-SQLite test fixtures now await worker-backed database closure before opening a connection.

Permanent controlled-time tests cover recovery after nine simulated seconds, default immediate refusal, genuine maintenance, another database, the five-minute deadline, caller cancellation, and shutdown. A startup-entry regression exercises readAdmittedConfigSnapshot with a synthetic foreign schema-owner record and verifies one config callback and unchanged source bytes. No real retry sleeps were added.

Evidence

Main refresh: merged current main into 3c983c19e6c03aa60e84dc4a811f14d49cfb7e50 because CI run 37555942032 tested a stale merge ref predating shared paired-worker fixture fix 98567acd6060; all five PR files are byte-identical to f02c10837760ee328c55bb7f70c0833cfe835b68, so the recorded review and isolated proof are reused without a new lease.

Proven implementation head: f02c10837760ee328c55bb7f70c0833cfe835b68. The defect was still present on fetched main f97c85590ad9a68e36c231117aecc6c424fce6de; history inspection confirmed that cold snapshot admission still checked ownership once and rethrew before snapshot preparation.

  • Static checks passed: targeted oxfmt --check, node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json on the four changed TypeScript files, and git diff --check.
  • Independent Codex autoreview of the complete candidate tree: scoped-clean, no actionable P0–P2 findings. The committed tree matches the reviewed tree.
  • Exact-head isolated AWS proof: lease cbx_f83db7d0f253 (stopped; verified released in crabbox list --provider aws), Node 24.21.0, pinned pnpm 12.5.1. Trusted-main bootstrap verified the full SHA and IMDS no-role boundary; no hydration or Tailscale was used. No contributor code executed on the maintainer host.

Passing command:

pnpm tsgo:core && pnpm test \
  src/state/openclaw-state-db-readonly.snapshot-admission.test.ts \
  src/commands/config-preflight-snapshot.test.ts \
  src/state/openclaw-state-db-readonly.signal-custody.test.ts \
  src/state/openclaw-state-db-readonly.retained.test.ts --maxWorkers=1

Core typecheck passed in 15.23 s. All 48 tests across four files passed in 78.48 s command wall time, including worker preparation and both test projects.

On the same lease and unchanged Git HEAD, only the two production files were restored to merge-base 83908d3f49ee8a8049eb90a0fe649824994e79ff:

git checkout 83908d3f49ee8a8049eb90a0fe649824994e79ff -- \
  src/state/openclaw-state-db-readonly.ts src/commands/config-preflight-snapshot.ts
pnpm test src/state/openclaw-state-db-readonly.snapshot-admission.test.ts \
  src/commands/config-preflight-snapshot.test.ts --maxWorkers=1 \
  -t 'waits (for|through) temporary schema custody'

The owner regression failed as expected in 27.72 s. The wrapper stopped after the failed unit shard, so the startup regression was then exercised separately, with the same production-only revert:

pnpm test src/commands/config-preflight-snapshot.test.ts --maxWorkers=1 \
  -t 'waits through temporary schema custody'

That control failed as expected in 30.52 s, through readAdmittedConfigSnapshot. Sanitized excerpts:

Owner assertion: expect(await outcome).toEqual({ value: "admitted" })
Expected: { value: "admitted" }
Received: { error: Error("Cannot read shared state for discovery: <synthetic path>.
  Retry after the current state operation completes. Error: temporary schema custody") }

Startup control: Cannot read shared state for discovery: <synthetic path>.
  Error: OpenClaw state at <synthetic path> is undergoing offline maintenance;
  retry when it finishes.
NEGATIVE_CONTROL_EXIT=1
STARTUP_NEGATIVE_CONTROL_EXIT=1

Test cost: separate exact-head pnpm test <file> --maxWorkers=1 measurements were 29.00 s wall / 0.149 test seconds / 14 passing cases for snapshot admission, and 54.47 s wall / 36.476 test seconds / 19 passing cases for config preflight. Admission wall time includes 21.085 s of compiled-worker preparation. The existing startup integration suite exceeds 30 s because it exercises real configuration parsing, isolated SQLite snapshot/worker lifecycles, source-byte preservation, and operational-versus-terminal failure classification. The added startup case protects the caller's budget selection and production ownership classification, which the cheaper mocked admission suite cannot prove. Retry budgets use controlled time, with no real retry sleeps. File-specific CI seconds are unavailable: exact-head CI run 37554683431 was skipped; this is not a claim of green CI.

LOC against origin/main...HEAD: production +47/−54 (net −7); tests +169/−4 (net +165); docs +1/−0. Exact numstat:

1   0   docs/cli/gateway/running.md
59  3   src/commands/config-preflight-snapshot.test.ts
5   7   src/commands/config-preflight-snapshot.ts
110 1   src/state/openclaw-state-db-readonly.snapshot-admission.test.ts
42  47  src/state/openclaw-state-db-readonly.ts

ClawSweeper's outstanding P2 request to retain recovery, default-refusal, deadline, and cancellation coverage is addressed in the existing admission suite. No review finding was rejected. This phase stops after branch repair, proof, and this body update; no merge or sibling closure was performed.

This proof covers startup snapshot admission and retained-read lifecycle behavior. It does not establish a complete Windows Scheduled Task or Gateway + Node Host boot. The broader launcher status and service-supervision symptoms are outside this change.

Credit

Original fix by @NianJiuZst; maintainer cleanup and permanent regression coverage build on that startup-specific implementation. Controlled-time admission regressions adapted from @ericcaiwx-star's #166108, with both contributors credited in the maintainer commit. The startup-only five-minute budget is why this PR was selected as the base. The other PR remains open for coordinator disposition after landing.

Fixes #166088

Co-authored-by: Eric Cai [email protected]

@clawsweeper

clawsweeper Bot commented Oct 6, 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 commands Command implementations size: XS labels Oct 6, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 9:39 PM ET / October 7, 2026, 01:39 UTC (Revision 6).

ClawSweeper review

What this changes

Gateway startup gains bounded waiting for temporary shared-state contention, with cancellation and refusal regressions and documented startup behavior.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary on current main and the latest release. Recorded production-boundary proof remains applicable, prior follow-up is resolved, and no blocking introduced defect was found.

Priority: P1
Reviewed head: 3c983c19e6c03aa60e84dc4a811f14d49cfb7e50

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with preserved boundary proof, meaningful regressions, and no blocking introduced finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Recorded macOS two-process proof exercises the production schema lease and startup snapshot reader, showing recovery after release with one callback and unchanged source bytes. Source inspection preserves that evidence through cleanup and the byte-identical main refresh; isolated regressions supplement it. Complete Windows service boot is outside the claim, and no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Recorded macOS two-process proof exercises the production schema lease and startup snapshot reader, showing recovery after release with one callback and unchanged source bytes. Source inspection preserves that evidence through cleanup and the byte-identical main refresh; isolated regressions supplement it. Complete Windows service boot is outside the claim, and no stored-data contract changes.
Evidence reviewed 9 items Introduced behavior: The pinned introduction delta retries only same-database StateDatabaseAdmissionPendingError before capturing snapshot bytes. Caller cancellation is checked after awaited admission; preparation, callbacks, and cleanup remain outside the retry loop.
Current main still needs the repair: Fetched main checks cold snapshot admission once and throws before preparation during temporary schema custody. Its startup caller supplies no admission timeout.
Latest release: The v2026.9.8 snapshot reader has a single admission check and no admissionTimeoutMs option. Local release-blob inspection failed with HTTP 403; the read-only GitHub contents API supplied the release source.
Findings None None.
Security None None.

How this fits together

Gateway startup validates configuration using a private snapshot of shared SQLite state. Database ownership admission controls when that snapshot can be prepared and consumed by startup validation.

flowchart TD
 A[Gateway startup] --> B[Configuration preflight]
 B --> C[Database ownership admission]
 C --> D{Admission outcome}
 D -->|Temporary contention within budget| C
 D -->|Allowed| E[Private SQLite snapshot]
 E --> F[Startup validation]
 D -->|Maintenance or deadline| G[Reported startup failure]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -7, Tests +165, Docs +1. Total +159 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 47 54 -7
Tests 2 169 4 +165
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 217 58 +159

Review metrics

Metric Value Why it matters
Startup admission budget Startup: 0 → 300,000 ms; other callers: 0 ms The longer wait is confined to startup while other snapshot callers preserve immediate refusal.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #166088
Summary: This PR targets temporary schema contention in the startup report; broader Windows launcher and supervision symptoms remain outside its scope.

Members:

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

Technical review

Best possible solution:

Keep bounded startup waiting in the existing snapshot admission owner, preserving immediate refusal elsewhere and single execution of prepared work.

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

Yes: a foreign schema lease makes current main's cold startup snapshot admission throw before preparation. Source inspection and recorded two-process before/after proof establish the trigger; this read-only review executed no target code.

Is this the best way to solve the issue?

Yes: retrying typed temporary contention before snapshot preparation repairs the existing owner without replaying callbacks or relaxing maintenance admission.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Temporary schema contention can abort Gateway startup and leave channel workflows unavailable until operator recovery.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Recorded macOS two-process proof exercises the production schema lease and startup snapshot reader, showing recovery after release with one callback and unchanged source bytes. Source inspection preserves that evidence through cleanup and the byte-identical main refresh; isolated regressions supplement it. Complete Windows service boot is outside the claim, and no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded macOS two-process proof exercises the production schema lease and startup snapshot reader, showing recovery after release with one callback and unchanged source bytes. Source inspection preserves that evidence through cleanup and the byte-identical main refresh; isolated regressions supplement it. Complete Windows service boot is outside the claim, and no stored-data contract changes.

Evidence

What I checked:

  • Introduced behavior: The pinned introduction delta retries only same-database StateDatabaseAdmissionPendingError before capturing snapshot bytes. Caller cancellation is checked after awaited admission; preparation, callbacks, and cleanup remain outside the retry loop. (src/state/openclaw-state-db-readonly.ts:126, 3c983c19e6c0)
  • Current main still needs the repair: Fetched main checks cold snapshot admission once and throws before preparation during temporary schema custody. Its startup caller supplies no admission timeout. (src/state/openclaw-state-db-readonly.ts:121, f0c9bcfbe30f)
  • Latest release: The v2026.9.8 snapshot reader has a single admission check and no admissionTimeoutMs option. Local release-blob inspection failed with HTTP 403; the read-only GitHub contents API supplied the release source. (src/state/openclaw-state-db-readonly.ts:105, fc23bc864e45)
  • Re-review continuity: All five introduced files are byte-identical to the previous reviewed implementation head. The main refresh therefore introduces no new changes to the reviewed behavior or regression coverage. (3c983c19e6c0)
  • Preserved production-boundary proof: The completed review at fix(gateway): prevent startup failures during temporary state contention #166111 (comment) records inspection of earlier body SHA-256 f9bc09d515f690e10c839ae9d8bf87a5ee64d0199d4f67aa486bab7f010dbd29 and macOS two-process proof using the production schema lease and snapshot reader: default refusal, startup pending for 1.108 seconds, then recovery after release with one callback and unchanged source bytes. Inspection of the earlier production source confirms the same retry algorithm and startup budget; subsequent cleanup strengthens cancellation without changing recovery. This review reuses that recorded verification rather than claiming a new execution. (src/state/openclaw-state-db-readonly.ts:126, 3c983c19e6c0)
  • Regression coverage and cost: The admission suite protects nine-second recovery, default refusal, genuine maintenance, another database, deadline exhaustion, cancellation, and shutdown using controlled time. The startup-entry regression exercises real configuration and snapshot owners with a synthetic foreign ownership record, checking one callback and unchanged source bytes. The supplied body reports 48 passing cases, failing production-only negative controls, separate file timings, and the reason the existing integration suite exceeds 30 seconds; unavailable CI timing is explicitly disclosed. (src/commands/config-preflight-snapshot.test.ts:195, 3c983c19e6c0)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • victor-gurbani: 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 (5 earlier review cycles)
  • reviewed 2026-10-06T12:22:42.468Z sha 4202806 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-06T12:39:10.948Z sha 4202806 :: needs changes before merge. :: none
  • reviewed 2026-10-06T13:09:51.024Z sha 4202806 :: needs changes before merge. :: none
  • reviewed 2026-10-07T01:02:00.830Z sha f02c108 :: needs changes before merge. :: none
  • reviewed 2026-10-07T01:19:39.215Z sha f02c108 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 6, 2026
…atch

Keep startup's five-minute schema admission budget and preserve immediate
refusal for other snapshot callers. Check caller cancellation after awaited
admission, before preparing snapshot bytes. Preserve recovery, refusal,
exhaustion, and cancellation coverage, including the startup entry point.

Adapt the controlled-time admission regressions from Eric Cai's openclaw#166108.
Remove a single-use read forwarding layer without changing retained work
settlement, error mapping, or current/live read scopes. Await worker-backed
database closure before existing raw SQLite fixture access.

Fixes openclaw#166088

Co-authored-by: NianJiuZst <[email protected]>
Co-authored-by: Eric Cai <[email protected]>
@steipete
steipete merged commit af716af into openclaw:main Oct 7, 2026
135 of 136 checks passed
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
…ion (openclaw#166111)

* fix(gateway): retry temporary startup state contention

* fix(state): retain startup contention coverage and simplify read dispatch

Keep startup's five-minute schema admission budget and preserve immediate
refusal for other snapshot callers. Check caller cancellation after awaited
admission, before preparing snapshot bytes. Preserve recovery, refusal,
exhaustion, and cancellation coverage, including the startup entry point.

Adapt the controlled-time admission regressions from Eric Cai's openclaw#166108.
Remove a single-use read forwarding layer without changing retained work
settlement, error mapping, or current/live read scopes. Await worker-backed
database closure before existing raw SQLite fixture access.

Fixes openclaw#166088

Co-authored-by: NianJiuZst <[email protected]>
Co-authored-by: Eric Cai <[email protected]>

---------

Co-authored-by: NianJiuZst <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Eric Cai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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

2 participants