Repository navigation
fix: let Doctor check device identities without locking the credential store - #206513
Conversation
Doctor's legacy device identity detection reads each identity through read-only credential custody, which still opened the local credential store read-write, switched it to exclusive locking and began an IMMEDIATE transaction. Three such opens ran on every healthy doctor --fix, and while another client held the store's write lock each waited the full busy timeout and then reported no invalid identity. Inspection now opens the store read-only and reads committed rows in a deferred transaction with the same schema, integrity and receipt checks. A hot rollback journal still goes through custody, which can roll it back.
…ntity-read-only-inspection
|
🦞👀 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: passed. What this changesThis PR lets device-identity inspection use read-only SQLite transactions while preserving existing credential repair and journal-recovery custody. Example: An invalid primary identity is committed in client/credentials.sqlite while another connection holds BEGIN IMMEDIATE without creating a journal.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR: it addresses a current credential-inspection bug, has maintainer-approved direction, and introduces no definite code defect found in this review. Reviewed head: Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherDoctor and synchronous identity loaders call the local credential owner, which admits the credential database, reads identity rows, and returns validated identity material or a storage error; repairs retain the existing write owner. flowchart TD
A[Doctor detection] --> C[Device identity reader]
B[Existing identity loader] --> C
C --> D[Credential owner]
D --> E[Read-only inspection]
D --> F[Existing recovery custody]
E --> G[Credential SQLite store]
F --> G
Technical reviewBest possible solution: Keep inspection inside the existing credential owner, preserve write custody for repairs and journal recovery, and complete the outstanding validation before landing. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the writable inspection and swallowed lock-error path, supported by the author's reported red-on-main contention test; this review executed no target code. Is this the best way to solve the issue? The change repairs the owning credential operation with existing read-only connection and deferred-transaction primitives, preserves admission checks, and adds one distinct contention regression without unnecessary machinery. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3dfac409e3ce. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +30, Tests +24. Total +54 across 3 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 27, 2026, 3:57 AM ET / 08:57 UTC. |
Inherited CI failure on head
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…ock (#206513) Doctor's legacy device identity detection reads each identity through read-only credential custody, which still opened the local credential store read-write, switched it to exclusive locking and began an IMMEDIATE transaction. Three such opens ran on every healthy doctor --fix, and while another client held the store's write lock each waited the full busy timeout and then reported no invalid identity. Inspection now opens the store read-only and reads committed rows in a deferred transaction with the same schema, integrity and receipt checks. A hot rollback journal still goes through custody, which can roll it back. (cherry picked from commit 372e89d)
…ock (openclaw#206513) Doctor's legacy device identity detection reads each identity through read-only credential custody, which still opened the local credential store read-write, switched it to exclusive locking and began an IMMEDIATE transaction. Three such opens ran on every healthy doctor --fix, and while another client held the store's write lock each waited the full busy timeout and then reported no invalid identity. Inspection now opens the store read-only and reads committed rows in a deferred transaction with the same schema, integrity and receipt checks. A hot rollback journal still goes through custody, which can roll it back.
…ock (#206513) Doctor's legacy device identity detection reads each identity through read-only credential custody, which still opened the local credential store read-write, switched it to exclusive locking and began an IMMEDIATE transaction. Three such opens ran on every healthy doctor --fix, and while another client held the store's write lock each waited the full busy timeout and then reported no invalid identity. Inspection now opens the store read-only and reads committed rows in a deferred transaction with the same schema, integrity and receipt checks. A hot rollback journal still goes through custody, which can roll it back. (cherry picked from commit 372e89d) Follow-up audit: e2e0974 independently skips no-op state schema repair. Keep the identity-store fix limited to the existing read-only snapshot behavior. Co-authored-by: RomneyDa <[email protected]>
Related: #204775
What Problem This Solves
Every
openclaw doctor --fixchecks whether the stored device identities are damaged. That check is meant to be read-only, but it opened the local credential store for writing three times, switched it to exclusive locking and began a write transaction each time. On a healthy install it changed nothing, yet it took the store's write lock. When another client held that lock, each read waited the 5 s busy timeout and then reported "no damaged identity", so Doctor could skip a repair it should have made.User Impact
The damaged-identity check no longer locks the credential store or waits on another client's write. A damaged identity is detected while a write is open, and Doctor still replaces it as before. Commands that only load an existing device identity (
loadDeviceIdentityIfPresent, used by the CLI, node host, TUI and plugin SDK Gateway runtime) read the same way. Nothing changes in what any repair writes, and there is no config, schema or permission change.Why This Change Was Made
readStoredDeviceIdentityReadOnlyasked credential custody forreadOnly, but custody still used a read-write connection,PRAGMA locking_mode=EXCLUSIVEandBEGIN IMMEDIATE. The custody owner now has aninspectmode: a read-only connection and a deferred read transaction, with the same version, schema, integrity and receipt checks (admitClientCredentialStorein read-only mode writes nothing). The store uses DELETE journal mode, so a read-only open creates no files. If a-journalfile exists, a hot rollback may be needed, so inspection falls back to the existing custody path, which can roll it back. Gateway worker reads keep their current custody.This is the first read-first change from the
config-flowplan in #204775. The other pieces are not in this PR (see "What is not done"), sodoctor.pending.config-flowstill answerswork check=default.Evidence
Tested commit:
ed9b9df03ca(pack built from it). The pushed head merges currentmaininto it. Nothing in the merged range touches the credential store, device identity or Doctor. After the merge, the focused tests were rerun and pass.Root cause, unit level (red on unmodified
main, green on head). New case insrc/infra/state-migrations.device-identity.test.ts: it seeds an invalid primary identity, holds the store's write lock from a second connection (BEGIN IMMEDIATE), runs detection, and checks that the store file is unchanged.main67145de5d94: the case fails after 16.1 s. Detection waited the busy timeout three times and returnedhasInvalidCanonical: false.hasInvalidCanonical: true. Without the competing lock, the existing case "replaces an invalid canonical row without legacy JSON only under Doctor authority" passes on both, which rules out other causes.Real CLI cells. Linux, systemd user Gateway, npm install of a locally packed build. Unpublished versions:
2026.11.27ismain67145de5d94,2026.11.28is the PR parent33fa6a84cec,2026.11.29is the head. Config: Telegram plus the bundled memory-core, browser, active-memory and llm-task plugins. Two healthydoctor --fixruns ran understrace -fwith an io trace of every write-intentfscall and everynode:sqliteopen, write andBEGIN IMMEDIATE, limited to thedoctor.config-flowspan.doctor.config-flow, healthy runmain(doctor1 / doctor2)client/credentials.sqliteread-write opensclient/credentials.sqliteBEGIN IMMEDIATEclient/credentials.sqliteread-only opensstate/openclaw.sqliterw opens /BEGIN IMMEDIATE/ row writesBEGIN IMMEDIATEdoctor.pending.config-flowwork check=defaultwork check=defaultThe one remaining credential-store read-write open on head comes from the state schema repair's credential custody (
prepareClientCredentialMigrationCustody), not from detection. Store snapshots after a healthy run change the same rows on both builds (Gateway boot rows,agent_databases.last_seen_at, leases), andcredentials.sqliteis byte-identical on both.Guards. Same fixture with Telegram disabled and
/readyzprobed every 250 ms, PR parent vs head. While the Gateway served, the cell seeded an invalid primary identity row and a retirednode-device.json.doctorworkprinted "Replaced invalid primary device identity in SQLite." and "Retained legacy identity JSON is already consumed". The primary row afterwards had valid key material.doctorcleanand the healthy runs made no replacement./readyznot ready): parent 27.0, 23.2, 26.5 and 29.0 s; head 24.7, 24.9, 27.7 and 28.5 s. This is within noise on this host. The legacy-state step took 1.7 to 2.3 s on parent and 1.8 to 2.1 s on head.Red (
main67145de5d94, raw cell logs replayed):red-base.mp4
Green (head
ed9b9df03caplus the parent vs head guard cells):green-head.mp4
Raw red evidence (main 67145de)
Raw green and guard evidence (head ed9b9df, parent 33fa6a8)
CI on head
21a0d90ad65. 68 checks pass. One check fails:checks-node-changed-6, intest/e2e/qa-lab/runtime/gateway-provider-review-product-proof.e2e.test.ts("dispatches the exact acknowledged steer and preserves session and device authority", line 572: expectedstatus: "error"after the device is removed mid-run, got"ok"). This PR does not cause it:mainparent of the CI merge,91d491238b1. It also fails with this PR's product change reverted (2 of 2 runs) and on head (3 of 3 runs).84cab039664and fails on08eaf404075(refactor(gateway): drop mid-request authority re-checks in server methods (R6b part 1) #203991, "drop mid-request authority re-checks in server methods"). The test still expects the mid-run revocation check that refactor(gateway): drop mid-request authority re-checks in server methods (R6b part 1) #203991 removed.loadOrCreateDeviceIdentity(read-write custody), which this PR does not change.unknown("No matching job on main"), because scheduledmaindoes not run this e2e file.Commands and results
node scripts/run-vitest.mjs src/infra/state-migrations.device-identity.test.ts(red onmain, green on head, as above). Every test file undersrc/that touches the credential store or device identities (156 files, PostgreSQL excluded), run per directory: infra 550 passed, commands 210, cli 78, tui 44, agents 28, state 22, plugin-sdk 1, node-host 2 files, gateway 72 of 73 files. The one gateway failure (server.mentions-committed.test.ts, a 120 s deadline under host load) passes alone on head and on the parent.node scripts/check-changed.mjs --base origin/main: typecheck (core and tests), lint, import cycles and the repository guards all pass. The dead-export scan reports two exports inextensions/nextcloud-talkfrommain(refactor(nextcloud-talk): separate webhook decoding from queue lifecycle #203172), not from this diff.gpt-6.1-sol) at--max-priority P2, branch mode againstorigin/main. Result: scoped-clean, no P0 to P2 findings.Files audited:
src/infra/state-migrations.device-identity.test.ts, in full. All helpers and imports are used. No case was removed; one was added.What is not done (config-flow plan, #204775)
Measured on the same
maincells. These keepconfig-flowfromnone:prepareOpenClawStateDatabaseSchema(…, "doctor")): explicit Doctor repairs the shared schema every time. That is 14BEGIN IMMEDIATE, the schema lease, the quarantine store opened read-write, and the custody open above. The existingneedsOpenClawStateDatabaseSchemaRepair(…, "doctor")predicate does not cover what this repair can change on a current schema. Missing are: permission drift, recorded damage,user_versionor content-row drift, legacy tables, the session watch and publication draft migrations, indexes on lazy tables, additive backfills (ACP, cron jobs, delivery queue, subagent runs, operator approvals), and the credential receipt. Two of these have no read-only predicate today (delivery queue compaction, cron job backfill)..sealinvalidation, the integrity and ensure transactions, and the registry upsert all run unconditionally. Missing read-only predicates: the schema metadata no-op,entry_validrows, archive verification receipt drift, and planner statistics.r+probe: it is kept on purpose. It is the only check that proves the state database can be written (immutable flag, read-only mount, fix(doctor): diagnose immutable state without pending writes #199509). A read-only open cannot prove that, and it writes, locks and leases nothing.deferred-plugin-migration:discord. In the measured cell itsfinished_atchanged every run. The reopen as pending is load-bearing: file-era session migrations read pending rows from the database during the run and preserve sources while any obligation is pending (deferred-plugin-session-sources.ts). Skipping the reopen would change what those migrations do. Not querying the registry needs a stored "last failed attempt" fact or a retry policy, so both are left for a decision.