Skip to content

fix: start Gateway while slow agent database checks finish - #150677

Closed
steipete wants to merge 1 commit into
mainfrom
upd/sqlite-startup-integrity-budget
Closed

steipete wants to merge 1 commit into
mainfrom
upd/sqlite-startup-integrity-budget

Conversation

@steipete

@steipete steipete commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #150574.
Related: #141918, #142179, #150444, #150564.

What Problem This Solves

Fixes Gateway startup aborting when an agent database inspection exceeds its wait budget without finding corruption.

Thanks to @desksk for the report and offline integrity timings that distinguished slow storage contention from database damage.

User Impact

The Gateway starts and serves healthy agents while an unfinished agent remains degraded with its reason and Doctor guidance. Its inspection continues in the background. The agent becomes available only after its credentials, sessions, and models are prepared. Genuine corruption leaves that agent degraded; shutdown cancels and joins retained work.

Shared-state database failures retain their existing behavior. There are no new configuration options, CLI flags, environment variables, dependencies, or SQLite schema changes.

Why This Change Was Made

At this PR's baseline, two fleet-preflight slots and a 635-second allowance for a 267.5 MiB database without sidecars are already on main but unreleased. The reporter's installed 2026.9.4 still has the older budget and concurrency. This PR fixes the remaining fatal timeout path; it preserves that scheduler, budget formula, and supervisor policy.

The existing inspection scheduler now separates its foreground wait from native worker cancellation. Startup transfers unfinished inspections to the Gateway lifetime and records agent admission refusals. Recovery uses the existing secrets, session, and model owners under current file, roster, configuration, and publication authority before clearing a refusal. Caller cancellation still cancels the native readers, and failed inspections remain foreground errors until their background handoff succeeds.

The Gateway startup owner composes this admission lifetime with the Linux spawn broker from #150564. Broker readiness precedes core startup. Admission remains registered in the existing Gateway lifetime-sidecar registry; the outer broker cleanup also joins that same admission if core cleanup fails before reaching its sidecars. Deferred preparation re-enters only the captured broker context, preserving its private database-preparation authority.

Evidence

  • Before the fix, a healthy 628 KiB fixture passed ordinary integrity checks but the existing 1 ms budget seam produced Gateway failed to start: SQLite schema inspection timed out after 0.001 seconds. The original database bytes were unchanged.
  • Differential regressions failed against the original owners for timeout recovery, corruption isolation, shutdown, targeted session preparation, and revoked write authority; the fast path passed.
  • Gateway boundary tests use real SQLite children and HTTP /healthz: healthy agents serve while a slow agent is refused, preparation completes before recovery, corruption stays agent-local, queued peers recover independently, and shutdown joins native work.
  • Review regressions failed before their fixes: caller abort left both native readers alive; an expired inspection failure was silently accepted before handoff; shared credential snapshots came from the ambient state instead of the selected state.
  • The original 120 focused tests passed in their existing order, followed by 20 broker startup, shutdown, fallback, and callback-context tests. Three new held-cleanup cases prove that broker extinction waits for admission drainage on failure before adoption, after adoption, and before sidecar shutdown.
  • Fresh boundary proof: healthz=200 while the slow agent is agent-database-inspection-pending; readmission clears only after credential/session/model preparation, and a command spawned during preparation has the broker as its parent. Removing the broker-context capture fails this parent-process assertion.
  • pnpm install --frozen-lockfile, pnpm check:changed, and pnpm build passed on the composed candidate. No lint substitute or baseline edit was needed.
  • Fresh Codex autoreview with --mode branch --base origin/main --max-priority P1 returned scoped-clean on the committed head.

Proof uses isolated state directories and free ports with deterministic native-child pauses and the existing budget seam. It does not claim a physical slow-volume benchmark or a shipped-driver respawn reproduction.

Ownership and line-count tradeoff

Production: +1,092 / −198 (net +894, 26 files). Tests: +1,113 / −18 (net +1,095, 9 changed files). Docs: net +37. Generated Swift protocol: +2 / −2 (net 0).

Production growth owns the previously missing transfer from CLI preflight to Gateway lifetime, agent-specific pending admission and cancellation, and guarded recovery through existing credential/session/model preparation. It also prevents an unavailable inherited auth store from taking healthy agents down. The existing scheduler remains the concurrency owner. The broker composition adds 10 net production lines, reuses the same idempotent admission stop operation, and removes the reused-scope early return that skipped failure cleanup; it adds no parallel work registry.

@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review blocked

Automated review did not run, so no review verdict was produced.

Reason: The input-safety check could not safely complete for this revision.

ClawSweeper will not retry this unchanged revision.

Next step: No contributor action is requested. Maintainers should inspect the linked workflow run.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 17, 2026
Retain unfinished agent inspections under the Gateway lifetime instead of
turning a foreground timeout into a fatal startup error. Keep the agent
degraded until inspection and guarded credential, session, and model
preparation complete; cancel and join that work during shutdown.

Preserve caller cancellation, propagate failures until background handoff,
and keep inherited auth snapshots within their selected state directory.
Thanks to @desksk for the report and offline integrity timings.

Refs #150574, #141918, #142179, #150444.
@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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 17, 2026, 2:51 AM ET / 06:51 UTC (Revision 2).

ClawSweeper review

What this changes

Let Gateway serve healthy agents while slow database checks continue, then restore deferred agents after credential, session, and model preparation.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 5 items remain

The fix remains necessary on current main, but the previously reported custom-store startup failure is still present. The branch contains useful, coherent work and should remain open for correction.

Priority: P1
Reviewed head: f0b5c562dbebab9ada680423033da3b5d3a93bfc

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The design and boundary coverage are useful, but the unresolved startup blocker prevents merge readiness.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary contributor-proof gate is exempt for this member-authored PR. Its reported SQLite-child and HTTP-health boundary runs match the changed startup owner, with source coverage for shutdown and revoked write admission; published-updater compatibility remains a separate required gap.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary contributor-proof gate is exempt for this member-authored PR. Its reported SQLite-child and HTTP-health boundary runs match the changed startup owner, with source coverage for shutdown and revoked write admission; published-updater compatibility remains a separate required gap.
Evidence reviewed 9 items Current main still lacks background handoff: At fetched main, preflight awaits all scheduler workers and propagates inspection failures. The startup admission module is absent; the earlier merged budget and reader-reuse improvements do not implement this PR's recovery behavior.
Prior blocker remains reachable: When both active inspections expire, the scheduler defers every queued candidate before claimAgentTarget performs deduplication. Preflight still appends custom-path candidates with no inferred agent ID, while defer rejects any ownerless candidate. Registry-row ordering does not reconcile those duplicates.
Custom-path ownership contract: Preflight lines 546–552 obtain candidate ownership from the path-only resolver. That resolver deliberately does not read ownership state; an arbitrary custom SQLite filename therefore remains ownerless even when registeredDatabases already supplies its owner.
Findings 1 actionable finding [P1] Deduplicate registered custom stores before deferring the queue
Security None None.

How this fits together

Gateway startup checks configured and registered agent databases before admitting their sessions. This change transfers unfinished checks to the Gateway lifetime while keeping affected agents unavailable until preparation succeeds.

flowchart TD
  A[Configured and registered databases] --> B[Two inspection slots]
  B --> C{Foreground deadline exceeded}
  C -->|No| D[Healthy agents serve]
  C -->|Yes| E[Agent remains degraded]
  E --> F[Background inspection and guarded preparation]
  F -->|Success| G[Agent becomes available]
  F -->|Failure or shutdown| E
Loading

Before merge

  • Deduplicate registered custom stores before deferring the queue (P1) - The prior blocker remains. When both active inspections expire, this loop defers every queued candidate before claimAgentTarget can suppress duplicates. Preflight still appends custom SQLite paths with agentId: undefined even when the registry already identifies their owner, so AgentDatabaseStartupAdmission.defer() throws Cannot defer a database without an agent owner and aborts startup. Reconcile these duplicates using registered ownership before handoff, while retaining refusal for genuinely unknown owners; the new queue test covers only canonical paths.
  • Resolve merge risk (P1) - Registered custom-store installations can still abort startup when both inspection slots expire before queued duplicates are reconciled.
  • Resolve merge risk (P1) - Published-updater behavior with retained data, deferred migrations, and managed restart remains unverified; the supplied Gateway fixtures use current database owners.
  • Complete next step (P2) - Repair queued custom-store ownership with a Gateway regression, and provide published-updater upgrade evidence or an explicit item-specific maintainer waiver.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P1] Deduplicate registered custom stores before deferring the queue — src/state/openclaw-database-preflight-agent-scheduler.ts:75-78
Agent review details

Security

None.

PR surface

Source +884, Tests +910, Docs +37, Other 0. Total +1831 across 36 files.

View PR surface stats
Area Files Added Removed Net
Source 25 1077 193 +884
Tests 8 926 16 +910
Docs 2 40 3 +37
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 36 2045 214 +1831

Review metrics

Metric Value Why it matters
Production versus test growth Production net +884 lines; tests net +910 lines The PR explicitly justifies production growth as lifetime transfer and guarded agent recovery through existing owners.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/config/sessions/startup-migration.ts, migration/backfill/repair: src/gateway/server-agent-database-startup.ts, migration/backfill/repair: src/gateway/server-startup-session-migration.ts, migration/backfill/repair: src/state/agent-database-admission.ts, serialized state: src/agents/auth-profiles/inherited-store.ts, serialized state: src/gateway/server-startup-session-migration.ts, and 2 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #150574
Summary: This PR is the candidate fix for the remaining fatal timeout behavior; earlier merged work improved budgets and inspection overhead.

Members:

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

Merge-risk options

Maintainer options:

  1. Repair queued custom-store ownership (recommended)
    Reconcile duplicate custom paths against existing registered ownership and add a failing-before, passing-after Gateway timeout regression.
  2. Verify retained-state upgrades
    Provide published-updater × candidate evidence covering deferred admission, migration handling, and managed restart before landing.

Technical review

Best possible solution:

Keep the existing scheduler and guarded recovery owners, reconcile queued paths with registered ownership before handoff, and establish retained-state upgrade safety.

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

Yes, from source: configure a registered custom SQLite store and let both active inspections exceed their foreground deadlines while its ownerless duplicate remains queued. The handoff throws before Gateway starts; this review did not execute that scenario.

Is this the best way to solve the issue?

Not yet. Retaining work under the existing Gateway lifetime is a suitable approach, but queued ownership must be reconciled before deferral and the changed upgrade path still needs evidence.

Full review comments:

  • [P1] Deduplicate registered custom stores before deferring the queue — src/state/openclaw-database-preflight-agent-scheduler.ts:75-78
    The prior blocker remains. When both active inspections expire, this loop defers every queued candidate before claimAgentTarget can suppress duplicates. Preflight still appends custom SQLite paths with agentId: undefined even when the registry already identifies their owner, so AgentDatabaseStartupAdmission.defer() throws Cannot defer a database without an agent owner and aborts startup. Reconcile these duplicates using registered ownership before handoff, while retaining refusal for genuinely unknown owners; the new queue test covers only canonical paths.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: This addresses an observed Gateway startup failure on healthy databases, and a related startup-blocking case remains in the patch.
  • merge-risk: 🚨 availability: The introduced queue handoff can abort Gateway startup for registered custom stores.
  • merge-risk: 🚨 compatibility: Startup migration and admission behavior changes without published-updater proof for retained installations.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The ordinary contributor-proof gate is exempt for this member-authored PR. Its reported SQLite-child and HTTP-health boundary runs match the changed startup owner, with source coverage for shutdown and revoked write admission; published-updater compatibility remains a separate required gap.

Evidence

What I checked:

  • Current main still lacks background handoff: At fetched main, preflight awaits all scheduler workers and propagates inspection failures. The startup admission module is absent; the earlier merged budget and reader-reuse improvements do not implement this PR's recovery behavior. (src/state/openclaw-database-preflight-agent-scheduler.ts:86, 14ff4df9dfca)
  • Prior blocker remains reachable: When both active inspections expire, the scheduler defers every queued candidate before claimAgentTarget performs deduplication. Preflight still appends custom-path candidates with no inferred agent ID, while defer rejects any ownerless candidate. Registry-row ordering does not reconcile those duplicates. (src/state/openclaw-database-preflight-agent-scheduler.ts:75, f0b5c562dbeb)
  • Custom-path ownership contract: Preflight lines 546–552 obtain candidate ownership from the path-only resolver. That resolver deliberately does not read ownership state; an arbitrary custom SQLite filename therefore remains ownerless even when registeredDatabases already supplies its owner. (src/state/openclaw-database-preflight.ts:546, f0b5c562dbeb)
  • Gateway regression coverage: The queued-agent test creates canonical databases for a, b, and main, verifies HTTP health, and releases queued inspections independently. It does not configure a registered custom session-store path, so it does not cover the prior blocker. Other cases exercise corruption isolation, retained transcripts, credential preparation, superseded model publication, and shutdown. (src/gateway/server-agent-database-startup.test.ts:358, f0b5c562dbeb)
  • Authority and cancellation safeguards: Pending preparation is scoped to the exact state and agent refusal. Recovery checks shutdown, deletion, file identity, configuration, and snapshot revision; canonical validation adds the current-owner assertion to worker write admission. The added regression revokes authority at admission-request and verifies pending validation remains. (src/config/sessions/session-canonical-validation-readiness.ts:87, f0b5c562dbeb)
  • Proof scope and upgrade gap: The complete supplied PR body reports real SQLite children and HTTP health checks in isolated state, plus passing focused checks and builds, while explicitly disclaiming a shipped-driver respawn reproduction. Root policy requires published-driver × candidate evidence for startup/Doctor lifecycle changes. The waiver recorded at fix(gateway): reduce fleet bootstrap inspection overhead #150444 applies to that earlier optimization, not this PR. (AGENTS.md, f0b5c562dbeb)

Likely related people:

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

Rank-up moves

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

  • Fix queued custom-store duplicate handling and establish a failing-before, passing-after Gateway regression.
  • Add published-driver upgrade evidence for retained state, deferred migration, and managed restart recovery.

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-09-17T06:30:10.525Z sha f77c274 :: blocked before merge. :: [P1] Deduplicate registered custom stores before deferring the queue

@steipete

Copy link
Copy Markdown
Contributor Author

Superseded by #150755. GitHub did not refresh this PR's recorded head after the branch force-push, and reopening failed because the recorded head commit was no longer on the branch. The replacement PR was created from the same branch at 5d86a071da553c627ce39ab693191bab5bd8c635, preserving this PR's title, body, reporter credit, and 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 app: web-ui App: web-ui cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hard-coded 30s SQLite startup integrity/snapshot budget kills gateway on slow disks under concurrent multi-agent preflight (no timeout override)

1 participant