Skip to content

fix: gateway startup waits for concurrent first-run migrations - #120959

Merged
steipete merged 1 commit into
mainfrom
steipete/startup-migration-lease-wait
Aug 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/startup-migration-lease-wait

Conversation

@steipete

@steipete steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where first-run macOS onboarding could dead-end with “The Gateway didn’t start” when the Mac app launched the gateway and mac-node worker nearly simultaneously. Both processes ran startup migrations against the fresh state directory, and the process that lost the migration lease exited immediately instead of waiting for its sibling to finish.

Observed repeatedly on a fresh state directory:

[openclaw] Reason: OpenClaw startup migrations are already running for this state directory; retry after the other OpenClaw process finishes or after 2026-08-09T05:41:54.451Z. (held by pid 55698)
Could not start the CLI.

Why This Change Was Made

The startup-migration lease owner now serializes expected same-host contenders with a bounded, asynchronous 250 ms poll. The wait is capped by the existing five-minute lease TTL, preserves dead-owner and PID-reuse reclamation, and retains the existing contention error on timeout. Cross-host or unprovable owners still fail immediately.

After every successful acquisition, doctor preflight refreshes the authoritative config, plugin-index, and checkpoint facts under the lease. This closes both contention races: if the prior owner completed before or during the wait—or just before the first acquisition attempt—the next process skips migrations already recorded by that owner.

No retry was added to the Mac app or gateway spawner, and no config or environment surface was added.

User Impact

Fresh macOS onboarding can start the gateway and mac-node worker concurrently without the lease loser crashing the CLI. Normal contention resolves within seconds when the first process finishes; genuinely stuck live owners still produce the existing actionable error after the bounded wait.

Evidence

  • node scripts/run-vitest.mjs src/infra/startup-migration-checkpoint.test.ts
    • Test Files 1 passed (1)
    • Tests 16 passed (16)
    • Covers release-then-acquire, winner checkpoint recording, timeout text, and dead-owner reclaim.
  • node scripts/run-vitest.mjs src/commands/doctor-config-preflight.state-migration.test.ts
    • Test Files 1 passed (1)
    • Tests 30 passed (30)
    • Covers the post-acquisition checkpoint fast path and verifies migrations/checkpoint writes are skipped.
  • Adjacent preflight/config guard proof:
    • Test Files 1 passed (1) / Tests 69 passed (69)
    • Test Files 2 passed (2) / Tests 20 passed (20)
  • node scripts/check-changed.mjs -- <changed files> on Blacksmith Testbox
    • exit 0; production and test typechecks, lint, formatting, import cycles, SQLite/database guards, and changed-file guards passed.
  • Structured autoreview: no accepted/actionable findings; “patch is correct” (0.93 confidence).

Production LOC: +155/-47 (net +108). Tests: +107/-37 (net +70). The production growth establishes the bounded async serialization owner boundary and authoritative post-acquisition refresh; the synchronous acquisition API remains available for existing synchronous callers.

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: M maintainer Maintainer-authored PR labels Aug 9, 2026
@steipete
steipete marked this pull request as ready for review August 9, 2026 06:35
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 9, 2026
@clawsweeper

clawsweeper Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 9, 2026, 2:44 AM ET / 06:44 UTC.

ClawSweeper review

What this changes

The PR makes same-host processes wait for a concurrent first-run migration lease and refreshes migration checkpoint facts after acquiring that lease.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open for normal maintainer handling. The patch is a coherent owner-boundary repair for the current first-run race; no blocking correctness or security defect was found, and the maintainer/protected label prevents automated cleanup.

Priority: P1
Reviewed head: 8867a20e7578e11e75ffbd3b6672b51806cf5fd5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-backed reliability repair with no actionable review finding; pending exact-head checks remain the normal merge gate.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR has focused SQLite/unit and Testbox evidence; an external-contributor real-behavior-proof gate does not apply.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR has focused SQLite/unit and Testbox evidence; an external-contributor real-behavior-proof gate does not apply.
Evidence reviewed 5 items Current failure path: Current main acquires the startup migration lease synchronously; a live lease conflict throws immediately, which matches the reported losing-process failure.
Owner-boundary repair: The branch waits only for typed, same-host contention and preserves immediate failure for cross-host or unprovable owners; preflight then rereads checkpoint inputs under the acquired lease.
Caller and regression coverage: Gateway startup requires the startup checkpoint through config guard, and focused tests cover release/reacquire, timeout, dead-owner reclaim, and post-acquisition checkpoint skipping.
Findings None None.
Security None None.

How this fits together

Gateway and worker startup enter doctor preflight against one state directory. Preflight uses a shared migration lease and recorded checkpoints to decide whether migrations must run before startup continues.

flowchart LR
  A[Gateway and worker startup] --> B[Doctor preflight]
  B --> C[Shared migration lease]
  C --> D{Same-host owner active?}
  D -->|yes| E[Bounded wait and retry]
  D -->|no| F[Refresh checkpoint facts]
  E --> F
  F --> G[Run or skip migrations]
  G --> H[Startup continues]
Loading

Before merge

  • Resolve merge risk (P1) - A live but stuck same-host lease owner can now hold the competing startup path for up to the existing five-minute lease TTL; the bound and retained terminal error make this an explicit availability tradeoff rather than an unbounded stall.
  • Complete next step (P2) - This maintainer-authored, maintainer-labeled PR has no mechanical repair task remaining; retain it for normal exact-head CI and maintainer merge handling.
Agent review details

Security

None.

PR surface

Source +108, Tests +70. Total +178 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 155 47 +108
Tests 2 107 37 +70
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 262 84 +178

Review metrics

Metric Value Why it matters
Production versus test delta production +155/-47 (net +108); tests +107/-37 (net +70) The production growth is justified by the new asynchronous lease-owner boundary and authoritative post-acquisition refresh, while focused tests cover the race outcomes.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-config-preflight-checkpoint.ts, migration/backfill/repair: src/commands/doctor-config-preflight.state-migration.test.ts, migration/backfill/repair: src/commands/doctor-config-preflight.ts, migration/backfill/repair: src/infra/startup-migration-checkpoint.test.ts, unknown-data-model-change: src/commands/doctor-config-preflight.state-migration.test.ts, unknown-data-model-change: src/commands/doctor-config-preflight.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the bounded startup wait (recommended)
    Accept the existing five-minute lease TTL as the upper bound for genuine same-host startup contention, while retaining the immediate error for non-local or unprovable owners.

Technical review

Best possible solution:

Keep lease policy centralized in the checkpoint owner, preserving fail-fast behavior for non-local or unprovable owners while serializing legitimate local first-run contenders.

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

Yes, from source: a gateway startup path reaches synchronous lease acquisition, and a live owner currently throws immediately; the branch directly covers that transition with focused regression tests.

Is this the best way to solve the issue?

Yes: placing serialization and the post-acquisition reread at the shared lease/checkpoint owner fixes every caller without duplicating retry policy in the Mac app or gateway spawner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against a3d2ac7dc887.

Labels

Label changes:

  • add P1: The current race can abort gateway startup during first-run onboarding.
  • add merge-risk: 🚨 availability: The PR deliberately changes gateway-startup contention from immediate failure to a bounded wait.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR has focused SQLite/unit and Testbox evidence; an external-contributor real-behavior-proof gate does not apply.

Label justifications:

  • P1: The current race can abort gateway startup during first-run onboarding.
  • merge-risk: 🚨 availability: The PR deliberately changes gateway-startup contention from immediate failure to a bounded wait.
  • 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: This maintainer-authored PR has focused SQLite/unit and Testbox evidence; an external-contributor real-behavior-proof gate does not apply.

Evidence

What I checked:

Likely related people:

  • steipete: Introduced the current checkpoint/preflight surface and the prior lease-reclamation repair, then authored this owner-boundary follow-up. (role: feature owner and recent area contributor; confidence: high; commits: c2e7c819f570, a1a507ddaf56, 8867a20e7578; files: src/infra/startup-migration-checkpoint.ts, src/commands/doctor-config-preflight.ts)
  • vincentkoc: Recent history connects this person to the config-guard caller that routes gateway startup into preflight. (role: recent adjacent caller contributor; confidence: medium; files: src/cli/program/config-guard.ts)

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.

@steipete
steipete merged commit 7dc4dc8 into main Aug 9, 2026
190 checks passed
@steipete
steipete deleted the steipete/startup-migration-lease-wait branch August 9, 2026 06:56
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 10, 2026
tomorrowflow pushed a commit to tomorrowflow/openclaw that referenced this pull request Aug 16, 2026
harjothkhara added a commit to harjothkhara/openclaw that referenced this pull request Aug 27, 2026
Rebase-onto-main fixups (main moved ~2544 commits since this branch was
last synced, largely via openclaw#120959's startup-migration-checkpoint rework):
- withTempDir -> withTestDir (helper renamed in src/test-helpers/temp-dir.ts).
- makeTempRoot -> makeDoctorStateDir (the actual tracked-tempdir helper this
  test file uses elsewhere; makeTempRoot never existed here).
- Mock ../config/io.js's readConfigFileSnapshotWithPluginMetadata and
  ../infra/startup-migration-checkpoint.js's needsStateMigrationCheckpoint /
  recordSuccessfulStateMigrations / acquireStartupMigrationLeaseWithWait,
  all added/renamed by openclaw#120959's checkpoint-identity rework.
- needsStateMigrationCheckpoint now mirrors needsStartupMigrationCheckpoint
  by default (openclaw#120959 decoupled the two), and the plugin migration
  fingerprint is pinned non-null so the pre/post-convergence identity
  check doesn't spuriously refuse readiness in this suite.

ClawSweeper P3 fix (confidence 0.98): the two "no-copy" fixtures in
doctor-config-preflight.legacy-config.test.ts never created a bare
.openclaw directory, so config/paths.ts's resolveStateDir fell through to
the legacy dir as the resolved state dir instead of ~/.openclaw. That made
targetsDefaultStateRoot false, so the canonical-root guard this PR added
was never actually exercised — the assertions passed vacuously because the
copy target itself became ~/.clawdbot. Creating a bare ~/.openclaw in both
fixtures makes it the resolved target and forces the guard to run.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. 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