Repository navigation
fix(auth): self-heal stale shared auth store ownership - #152111
xydigitLybnnnn wants to merge 4 commits into
Conversation
A long-lived process pinned the shared auth store owner (`legacy-main`) for its entire lifetime. When a sibling process ran `models auth login` and relocated the store into the state DB, the pinned process kept resolving the old, empty legacy database, so every `openai/*` route failed with "Explicit auth order for openai has no usable profiles." while the CLI still listed the saved profile. Only `state-db` is a one-way terminal state. Re-read `auth.sharedStore` while a root is still `legacy-main` so a process observes an out-of-process relocation without a restart. Keep the cached object identity while the legacy owner is unchanged so downstream legacy inspection stays memoized. Fixes openclaw#151620
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed October 6, 2026, 9:30 AM ET / 13:30 UTC (Revision 6). ClawSweeper reviewWhat this changesThe PR lets running processes discover relocated shared credentials while keeping each credential load and write tied to one consistent database owner. Warning SQLite table change This PR modifies persisted SQLite tables in Merge readiness⛔ Blocked before merge - 2 items remain Keep open: current main and v2026.9.8 still retain the stale ownership pin. The prior race findings are resolved, the runtime evidence supports the repair, and no new actionable defect was found. Priority: P1 Review scores
Verification
How this fits togetherOpenClaw’s auth store combines shared and agent-local credentials with account selection state. CLI credential writes feed this store, which supplies credentials to running model routes. flowchart TD
A[CLI saves credentials] --> B[Shared SQLite store]
B --> C[Resolve shared owner]
D[Agent local credentials] --> E[Capture database targets]
C --> E
E --> F[Read and combine credentials]
F --> G[Model route selection]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +48, Tests +580. Total +628 across 18 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Retain automatic relocation discovery and consistent per-load ownership within current main’s auth worker architecture, preserving existing credentials, account order, and refusal checks. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the stale-cache path: resolve legacy ownership, relocate the store in another process, then reload credentials without explicit invalidation. Supplied before/after traces corroborate it; this read-only review did not execute current main. Is this the best way to solve the issue? Yes, refreshing nonterminal ownership between loads and carrying the captured target through each load is a focused owner-level repair. Integration must preserve the newer worker architecture. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c78c2638ec74. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
resolveSharedAuthStoreOwnershipAsync() kept returning a cached legacy-main owner while the synchronous shared path resolver had already self-healed to the state database. runtime-read.ts pairs the two to choose a reader, so the relocated path resolved to a reader that was never prepared and the read threw. Re-read the non-terminal owner off-thread exactly like the synchronous resolver, keep the one-way state-db pin, preserve the process-stable legacy object, and add an async-resolver regression that fails against the pinned legacy cache.
|
@clawsweeper re-review The async reader finding is fixed in
The 8 failing checks on this head are not from this PR. They come from upstream |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Carry the prepared database path through async reader selection, row decoding, refusal diagnostics and final credential composition. Preserve relocation discovery on subsequent loads and add runtime/interleaving regression coverage. Co-authored-by: xydigitLybnnnn <[email protected]>
Capture synchronous owner and adapter identity, keep prepared reads stable across relocation, and match inherited refusals to the failed legacy database. Preserve contributor ancestry and strengthen race regressions.
|
Closing: this branch targets the pre-rewrite A narrow re-implementation of just The problem from #151620 is still present on |
Related: #151620
What Problem This Solves
Fixes saved model credentials remaining unavailable to a running process after another process relocates the shared auth store.
User Impact
Running readers discover the new store without a Gateway restart. Healthy local credentials remain usable when an inherited legacy store has a matching recorded refusal. No new configuration, migration, or provider-authentication behavior is introduced.
Why This Change Was Made
Refresh nonterminal legacy ownership between loads, then keep one database identity throughout each load. Synchronous reads, metadata, and write adapters use the captured owner or acquired connection; asynchronous reads retain their prepared owner across awaits; inherited refusals match the failed legacy database path without re-reading mutable ownership. A later load observes relocation without mixing credential rows, runtime state, provenance, or refusal diagnostics.
Preserves xydigitLybnnnn's resolver repair and contributor ancestry. Maintainer follow-up addresses independently reproduced asynchronous and synchronous interleavings.
Evidence
The original contributor evidence below is historical. Resolver-only async sufficiency claims and its runtime-proof gap are superseded by the additional runtime consistency repair and regression coverage described above.
Original contributor investigation and proof (historical)
What Problem This Solves
Issue #151620 —
openclaw models auth login --provider openaireported the credential as saved,openclaw models auth listshowed the new OAuth profile, but the gateway's model routes still saw zero usable openai profiles and rejected the model with:The failure survived repeated
doctor --fixruns and only cleared after the gateway process was restarted — the classic "CLI sees it, the gateway does not" split.Root cause
resolveSharedAuthStoreOwnership()insrc/agents/auth-profiles/path-resolve.tspinned the resolved owner of the shared auth store for the life of the process:with the comment "Pin each root once so later row changes require an owner-controlled restart".
Relocating
config_machine_state.auth.sharedStoreis inherently cross-process:openclaw models auth loginruns in its own process and writes{"location":"state-db"}while moving the credential into<stateDir>/state/openclaw.sqlite(prepareFreshSharedAuthStoreWrite()→initializeFreshSharedAuthStore()). A long-lived Gateway/TUI process that booted before that login keeps its cachedlegacy-mainowner and therefore keeps reading the now-empty<stateDir>/agents/main/agent/openclaw-agent.sqlite.The only existing invalidation is in-process (
reloadSharedAuthStoreOwnership(), driven by the login'smodels.authRefreshgateway notification). When that notification is not delivered or is rejected — gateway unreachable, different state root, or a warning that is simply printed and skipped — the stale pin survives until a real restart.state-dbis a one-way terminal state: production code (shared-store-bootstrap.ts,state-migrations.shared-auth-store.ts) only ever writes it, never back tolegacy-main.legacy-main(including an absent row) is not terminal, so it must not be pinned.The fix
src/agents/auth-profiles/path-resolve.ts— pin only the terminal state and re-read the non-terminal one:state-dbowner is returned as-is: terminal, so steady state keeps zero extra reads;legacy-mainowner re-readsconfig_machine_state.auth.sharedStoreand self-heals tostate-dbwhen another process relocated the store;legacy-main, the same ownership object is returned, so the legacy-inspection memoization inshared-store-bootstrap.ts(aWeakSetkeyed on object identity) keeps working; the stale comments in both files were rewritten to describe what is actually pinned.The same rule now applies to the off-thread owner read.
resolveSharedAuthStoreOwnershipAsync()returned any cached owner — including a non-terminallegacy-main— while the synchronousresolveSharedAuthStorePath()had already self-healed to the state database.runtime-read.tspairs the two to choose between the shared reader and the prepared per-database readers, so the relocated path resolved to a reader that was never prepared (agentReads.get(databasePath)isundefined) and the read threw. The asynchronous resolver now re-reads the non-terminal owner through the same worker operation, keeps thestate-dbpin, preserves the process-stable legacy object, and still lets an explicit commit/reload that lands while the read is in flight win.Tests in
src/agents/auth-profiles/path-resolve.shared-store.test.ts:legacy-mainafter an out-of-process write — now asserts the relocation is observed;legacy-mainand then observes an out-of-process relocation, for both the plain and the aliased state root;state-dbowner stays pinned after the ownership row disappears (no fallback);legacy-main.Evidence
1. Cross-process relocation — BEFORE (exit 1) vs AFTER (exit 0)
Harness:
logs/real_behavior/issue-151620-evidence/harness/cross-process-repro.mtswithlogin-write.mts. A long-lived process resolves the shared-store owner before any login exists; a separate process then performs a real login write; the long-lived process resolves again, loads the runtime auth snapshot and runs the real route-auth selection.The login write uses the product write path —
upsertAuthProfile()→saveAuthProfileStore({ sharedStoreWrite: true })→prepareFreshSharedAuthStoreWrite()→initializeFreshSharedAuthStore()— i.e. exactly the migrationopenclaw models auth loginperforms.The rejected route in the BEFORE run is the issue's exact error string; the AFTER run selects the openai subscription route instead.
Transcripts:
harness/before-fix.txt,harness/after-fix.txt.2. Real CLI login process against the running process (product entry)
Harness:
harness/cli-login-cross-process.mts. Same shape, but the relocating process is the real CLI —openclaw models auth paste-token, the automation entry thatmodels auth loginitself points users at. Note the warning the CLI prints in both runs: it saved the credentials and could not refresh the running gateway, which is exactly the silent failure the issue describes.The CLI keeps printing the same "could not refresh" warning in both runs — the fix removes the need for that refresh: the running process now self-heals from the ownership row the CLI wrote.
Transcripts:
harness/cli-before.txt,harness/cli-after.txt.3. Target suites
4. Project gates
The single failure is
src/process/spawn-broker/relay.test.ts > brokered process lifecycle owners > retains relay control and lineage through root exit and tree cancellationwith
service child cleanup did not complete before its hard deadline. It is unrelated to this change (different subsystem, not in the diff) and is specific to the local repro container, which runs as PID 1sleep infinitywith ~1.4k zombie processes and a full swap file. The same file passes on the host checkout of this branch:The changed-file suites themselves are green in both environments (evidence §3).
pnpm run check:changedwas re-run on the async-reader follow-up head and is still exit 0.5. Async owner / synchronous path agreement (async reader follow-up)
resolveSharedAuthStoreOwnershipAsync()carried the same non-terminal pin, andruntime-read.tspairs it with the synchronous shared path to pick a reader. The new regression fails against the pinned legacy cache and passes with the fix:Transcripts:
harness/async-owner-test-prefix.txt(failing),harness/async-owner-test.txtandharness/auth-suites-after-async-fix.txt(passing).Linked context
Fixes #151620.
Tests and validation
src/agents/auth-profiles/path-resolve.shared-store.test.ts+shared-store-bootstrap.runtime.test.ts+store.async-read.test.ts+oauth-refresh-fence.async.test.ts— 23 passedpnpm run check:changed— exit 0 (ratchets, targeted oxlint, tsgo core, tsgo core test shards, dead-code scan, guards)pnpm test:changed— 11216 passed, 1 failed insrc/process/spawn-broker/relay.test.ts(container-only process-cleanup deadline; the same file passes 2/2 on the host, see evidence §4). This run predates the async-reader follow-up commit; the changed-file suites were re-run on that commit (23 passed, evidence §5) and CI re-runs the full matrix on the pushed head.pnpm build(triggered lazily by the CLI in evidence §2) — exit 0path-resolve.ts— exit 1 with the issue's exact error messageRisk checklist
legacy-main; a root already onstate-dbkeeps the previous zero-read behaviour (terminal pin).legacy-mainstays object-identical while unchanged, so theWeakSet-based legacy inspection inshared-store-bootstrap.tsis not re-run per call.legacy-mainpay the extra read, andstate-dbroots still short-circuit without touching the worker.state-dbback tolegacy-main, so the terminal pin cannot go stale; if such a path were ever added, the pin would lag until the process restarts (unchanged from today's behaviour).Declared gaps
runtime-read.ts: the host state-worker context is unavailable in the unit environment (SqliteWorkerError: unavailable), so the async/sync agreement is locked at the resolver boundary instead.🤖 AI-assisted: This PR was developed with AI assistance.