Skip to content

fix: keep startup credential preparation off the main thread - #180154

Merged
steipete merged 1 commit into
mainfrom
dbasync/mainreg2
Oct 22, 2026
Merged

steipete merged 1 commit into
mainfrom
dbasync/mainreg2

Conversation

@steipete

@steipete steipete commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Startup credential preparation runs SQLite admission on the Gateway main thread. The recent workload census attributed 16 main-thread statements at boot and 15 at restart to this path, including an unnecessary receipt reread on each preparation.

User Impact

The Gateway keeps automatic credential migration and refusal behavior while performing normal credential preparation in its existing worker before serving.

Why This Change Was Made

The credential worker now handles startup preparation under the existing app/native custody and admission rules. Admission returns its receipt postimage, so preparation can decide whether metadata needs upgrading without reading the receipt again. A typed preparation result carries migration-required across the worker boundary; required migrations still run under maintenance ownership and finish before startup continues.

The synchronous normal-startup path is removed. Native schema, integrity, permissions, source binding, commit authority, and once-per-process admission remain owned by the existing credential implementation. No schema or public IPC protocol changes. The implementation adds 52 net production lines and 18 regression-test lines to preserve those ownership boundaries.

Builds on #178998; original author Jason (Json), @fuller-stack-dev, is credited in the commit.

Evidence

  • 36 focused startup, credential-worker, and device-identity tests pass, including fresh/migrated credentials, malformed-input refusal, remount recovery, and restart.
  • The new regression fails with all original production files restored: 12 main-thread prepare calls. The candidate records zero main-thread SQL during preparation and restart.
  • Two independent Codex review rounds completed without actionable P0–P2 findings. An implementation check between rounds caught and fixed the worker error-subclass transport issue.
  • Exact-candidate published-driver update passed: package acceptance run 39708483094, including package integrity, npm 12 install, and the published-driver update cell. Ordinary PR CI 39708475744 also passed.
  • Final-head PostgreSQL proof: All 37 selected cases pass on the exact candidate: 24 on native PostgreSQL 17 and 13 on Blacksmith Testbox with the pinned PostgreSQL 18 image below. Coverage includes migration/refusal/restart, public update and rollback, port/rebind/recovery, offline authentication, archive restore, backup, Matrix roots, CLI, Gateway ownership, and interactive setup. The original updater, Gateway, and interactive setup timeouts remain recorded; unchanged narrow replays passed. The same native PostgreSQL 17 setup case passed on base and head with the original limits. Authenticated readiness arrived 39.20s after PTY harness launch on base and 28.40s on head; this comparison shows no added delay, without making a general latency claim.
  • One frozen workload pair completed; measured counts and attribution are below.
  • Production and all 29 test type shards, changed-file type-aware lint, Madge (zero cycles), and source/export-name collision guard passed. T1 remains 170; dialect violations remain zero. Exact-base replay reproduces three max-lines suppressions and two test-root budgets in untouched files. Knip matches the exact base: scripts3/production2/full-tree6 (11 entries, 10 distinct findings), all unchanged; zero new findings.

Native proof encountered three timeout classes: updater recovery (200 seconds), Gateway bootstrap/restart (120 seconds), and interactive setup waiting for child authentication (60 seconds). A read-only sample showed filesystem rename waits; the runner had defaulted Bun's compiler cache to the external worktree. With explicit internal caches, the updater replay passed in 55.4 seconds; the isolated Gateway case passed in 24.2 seconds. Interactive setup passed on Testbox in 17.5 seconds. No source, assertions, or timeout limits changed. These passes do not prove a product fix or establish one cause for every failed attempt. The first Testbox filter accidentally skipped four interactive cases; a corrected filter ran exactly those four and passed.

Measured result

One frozen v3.1.4 M1/C1 pair completed on base b98018c4433de6a471c7b9376156193debd91af9 and candidate 172040713d8e3077f3b502243f5fc8125503752a. All 36 frozen hashes matched. Both real workloads completed all 14 turns, child and cron flows, compaction, shutdown and restart. Preflight load was 54.94 with 112.90 GiB internal free space; arm loads were 41.44/39.28. Temporary runtime state was on internal storage. These are counts, not latency measurements; candidate build packaging encountered substantial external-volume I/O waits.

Scope Base SQL / requests / MAIN Candidate SQL / requests / MAIN
Whole workload 2992 / 801 / 131 2986 / 806 / 101
Credential boot 38 / 2 / 16 28 / 3 / 0
Credential restart 36 / 2 / 15 26 / 3 / 0
Credential total 74 / 4 / 31 54 / 6 / 0

The credential owner removes 20 statements and all 31 MAIN statements, at the cost of two worker requests. Nine schema/integrity admission shapes occur twice rather than four times (18 statements removed); both post-admission receipt SELECTs disappear. The receipt UPSERT moves into the worker. Remaining MAIN includes one additional boot PRAGMA busy_timeout = 5000 in the existing desktop-pairing migration's cold-open path (openclaw-state-db.ts:430); it is outside credential preparation. The fenced cron MAIN read remains one in each arm.

Across ten causally attributed warm turns, SQL median/range is 45 [45–48] → 45 [45–52], requests 11 [11–12] → 11 [11–13], MAIN 0 [0–0] → 0 [0–0]. Means are 45.3 → 46 SQL and 11.1 → 11.3 requests. All seven extra warm statements and two requests are accounted for by an auth-profile helper read (four SQL/one request) and session-entry patch (three SQL/one request) occurring in warm turn 6 instead of the second-session phase. Whole-workload counts for those owners are identical: 8 SQL/2 requests and 168 SQL/39 requests.

Shared read families are counted using captured SELECT stacks across all operations, not only top-level owner labels. Exact-entry facts 19→19, actor hydration 10→10, entry-cache snapshot loads 7→7, row-facts SELECTs 15→15. SELECTs containing transcript rewrite watermarks are 49→50, from one additional background usage-cost read. Every shared family is 0→0 per causal warm turn. Automation jobs outside the cron phase are 52 SQL/13 requests/0 MAIN → 56/14/0; the difference is one background compaction poll (BEGIN, two config-machine-state reads, COMMIT). All other automation-job phases are identical, with no separate automation-runs operation observed. Outside the cron phase, statements touching cron_jobs are 17→17 and those touching cron_run_receipts are 5→5; their execution phases shift, but the work does not increase. These background increases are retained in the raw whole-workload totals, not subtracted from the result.

Exact serial PostgreSQL command and environment

Homebrew PostgreSQL 17; fresh UTF-8 en_US.UTF-8 cluster with vector, pg_trgm, and unaccent; throwaway HOME/TMPDIR on internal storage. Default pinned Bun runtime. The 37 selected cases comprise 14 credential migration/update/port cases and 23 related cases across the other nine files.

env HOME="$PG_TEST_HOME" TMPDIR="$PG_TEST_TMPDIR" BUN_RUNTIME_TRANSPILER_CACHE_PATH="$PG_BUN_CACHE" OPENCLAW_VITEST_FS_MODULE_CACHE_ROOT="$PG_VITEST_CACHE" LC_ALL=en_US.UTF-8 NODE_DISABLE_COMPILE_CACHE=1 node scripts/test-database-conformance.mjs --engine postgres --connection "$PG_TEST_DSN" -- \
  src/infra/client-credential-migration.postgres.test.ts \
  src/infra/client-credential-update.test.ts \
  src/infra/database-engine/port-command.credentials.integration.test.ts \
  src/gateway/server-database-engine.postgres.test.ts \
  src/infra/database-engine/offline-auth.postgres.test.ts \
  src/infra/database-engine/archive-restore.postgres.test.ts \
  src/infra/database-engine/update-preflight.conformance.test.ts \
  src/infra/database-engine/matrix-roots.postgres.test.ts \
  src/infra/database-engine/backup.test.ts \
  src/infra/database-engine/port-command.integration.test.ts \
  src/infra/database-engine/cli-oneshot.postgres.test.ts \
  src/infra/database-engine/interactive-setup.integration.test.ts \
  --maxWorkers=1 --bail=1 \
  --testNamePattern='PostgreSQL client credential cutover|client credential PostgreSQL public update custody|database port client credential continuity|Gateway PostgreSQL shared-state bootstrap|offline CLI on PostgreSQL|whole-archive PostgreSQL restore|captures a retained PostgreSQL agent and restores local credentials|Matrix declared account-root database portability|restores user and Git exports and exact updater state|privately adds the first-use deletion phase|PostgreSQL one-shot CLI|CLI with unresolved PostgreSQL credentials|^postgres interactive setup'

Remote remainder: Blacksmith Testbox tbx_01m5h16mshfqtcx38q46s868mr, Actions 39728047378, requested 16-class, observed 4 CPUs and 15,788 MiB total memory. Exact candidate tree 0b5ce786cb34a80240726a95e035cb9f5c6b2c4d was verified before execution. Image: pgvector/pgvector:pg18@sha256:2358fcba361ed2233a5ed81b5fe4ca779ccb304120ce531a3bf51c0ed7e2bc11; temporary HOME/TMPDIR and explicit Bun/Vitest caches; default pinned Bun, LC_ALL=en_US.UTF-8. The same conformance runner selected port credentials and offline authentication (9 passes), then only the omitted interactive cases (4 passes):

node scripts/test-database-conformance.mjs --engine postgres --connection "$PG_TEST_DSN" -- \
  src/infra/database-engine/interactive-setup.integration.test.ts \
  --maxWorkers=1 --bail=1 \
  --testNamePattern='postgres interactive setup.*(setup saves|crestodian saves|onboard recovers|bare root preserves)'

The native setup attribution used base b98018c4433de6a471c7b9376156193debd91af9 then candidate 172040713d8e3077f3b502243f5fc8125503752a, sequentially with fresh en_US.UTF-8 PostgreSQL 17 clusters, internal HOME/TMPDIR/Bun/Vitest caches, default pinned Bun, and unchanged assertions/timeouts. Identical temporary output-only observers recorded the following; the observers were removed after proof. Build/transform time is excluded from these timestamps.

Marker (elapsed from PTY harness launch) Base Candidate
Gateway runtime.early completed 34.582s 22.175s
Child process uptime at that marker 22.806s 15.156s
Authenticated readiness 39.195s 28.401s
Entire setup test 77.144s 42.496s

Both passed. This bounded comparison did not reproduce added startup latency; host/cache variation prevents treating the difference as a general speedup. The native filter was postgres interactive setup.*setup saves interactive setup and releases ownership for a Gateway. The remote lease is stopped, its Actions run completed/cancelled after successful commands, and its campaign slot released.

Use the existing credential worker for startup custody admission and return
its admitted receipt postimage instead of rereading the migration receipt.
Keep app custody authoritative and complete required migrations before serving.
Return migration-required as preparation data across the worker boundary.

The startup regression fails on the original path with 12 main-thread prepare
calls and passes with zero across preparation and restart. Preserve the
migration, refusal, remount, and identity continuity coverage from #178998.

Co-authored-by: Jason (Json) <[email protected]>
@clawsweeper

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T02:10:58.360574Z 1720407 PR opened
ℹ️ 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.

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 172040713d8e3077f3b502243f5fc8125503752a
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/infra/client-credential-async.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/infra/client-credential-readiness.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/infra/client-credential-store.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/infra/client-credential.worker.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations size: S labels Oct 22, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 22, 2026
@clawsweeper

clawsweeper Bot commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR moves normal startup credential preparation into the existing credential worker and reuses its admitted receipt.

Example: Gateway startup opens ~/.openclaw/client/credentials.sqlite.

  • Before: Credential admission runs SQLite statements on the main thread and rereads the receipt.
  • After: The credential worker performs admission and returns readiness from the admitted receipt.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused implementation with useful boundary coverage and no definite defect; production startup measurements, upgrade validation, and broad CI remain incomplete.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; reported SQLite/worker regressions support the change, but the body explicitly leaves final-head startup measurements and stable-upgrade compatibility validation pending, and predecessor media does not exercise this worker change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Gateway startup and restart perform credential SQLite admission on the main thread.
Reason: The maintainer-authored direction removes measured main-thread work and a redundant read without adding configuration or competing ownership.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this maintainer-authored PR addresses synchronous credential preparation still present on main, and no definite introduced defect was found.

Priority: P2
Reviewed head: 172040713d8e3077f3b502243f5fc8125503752a

Before merge

  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: The final-head Gateway startup/restart workload and fresh-install plus v2026.10.5 upgrade run preserving credentials and settings remain pending.
Agent review details

How this fits together

Startup checks credential readiness before serving; app IPC or exclusive local custody supplies readiness, and required recovery remains with Doctor maintenance.

flowchart TD
A[Gateway startup] --> B[Credential preparation]
B --> C[Existing app IPC]
B --> D[Credential worker]
D --> E[Local SQLite custody]
E --> F[Readiness result]
C --> F
F --> G[Doctor maintenance when required]
F --> H[Continue startup]
G --> H
Loading

Technical review

Best possible solution:

Use the existing credential worker for admission and receipt reuse while preserving app custody, automatic migration, and credential continuity.

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

Current main directly performs credential custody admission and a receipt read on the startup caller thread; the PR reports a failing baseline regression, but this read-only review executed no target code.

Is this the best way to solve the issue?

The change is a focused repair using existing execution and storage owners, with a justified typed result preserving migration-required behavior across worker error transport.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3c9cdb3 adds src/infra/client-credential.worker.ts:35 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3c9cdb3f493d; files: src/infra/client-credential.worker.ts)
  • Jason (Json): Raw commit 5f40d22 adds src/commands/startup-client-credentials.ts:113 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5f40d22a366d; files: src/commands/startup-client-credentials.ts)

PR surface

Source +52, Tests +18, Docs +8. Total +78 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 74 22 +52
Tests 1 18 0 +18
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 100 22 +78

Labels

Label changes:

  • add P2: This removes synchronous SQLite work from startup and restart without an established outage or urgent user-facing regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.

Label justifications:

  • P2: This removes synchronous SQLite work from startup and restart without an established outage or urgent user-facing regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.

Rank-up moves

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

  • Complete the pending startup/restart workload and stable-upgrade validation with existing credentials and settings preserved.

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 21, 2026, 10:09 PM ET / October 22, 2026, 02:09 UTC.

@steipete
steipete merged commit cca4a17 into main Oct 22, 2026
202 of 205 checks passed
@steipete
steipete deleted the dbasync/mainreg2 branch October 22, 2026 05:59
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 23, 2026
…aw#180154)

Run normal startup credential custody admission in the existing credential worker before serving, and reuse the admitted receipt postimage instead of reading it again. Preserve migration-required handling, app custody, port rebinding, security checks, and once-per-process admission.

The frozen workload removes 20 credential SQL statements and all 31 credential MAIN statements across boot/restart, with two additional worker requests. Warm SQL/request medians remain 45/11 and warm MAIN remains zero.

Builds on openclaw#178998.

Co-authored-by: Jason (Json) <[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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant