Skip to content

fix: keep device identity reads lock-free - #124745

Merged
steipete merged 211 commits into
mainfrom
fix/doctor-readonly-device-identity
Aug 17, 2026
Merged

steipete merged 211 commits into
mainfrom
fix/doctor-readonly-device-identity

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where read-only device identity checks could create coordinator lock state and serialize behind identity writers. A concurrent first-time database creator could also expose an empty SQLite bootstrap snapshot that made the read fail before schema creation committed.

Why This Change Was Made

Read-only identity lookup now opens the state database without taking the identity coordinator. It treats only a truly empty bootstrap database with a missing device_identities table as a temporary miss; partial or corrupt schemas still fail closed. Identity creation and migration remain coordinator-owned, and no SQLite schema or version changes are included.

AI-assisted: yes.

User Impact

Doctor and other read-only device identity consumers no longer create lock files or wait behind identity creation. Concurrent first-start reads safely return no identity until the creator commits, then observe the authoritative identity.

Evidence

Node 24.15.0 focused validation:

  • src/infra/device-identity.test.ts: 23 passed, including no-write, bootstrap concurrency, authoritative winner, and corrupt-row behavior.
  • src/infra/state-migrations.device-identity.test.ts: 26 passed.
  • src/infra/startup-migration-checkpoint.test.ts: 17 passed.
  • src/node-host/startup-state-migrations.test.ts: 6 passed.
  • src/commands/doctor-device-pairing.test.ts: 9 passed.
  • Oxfmt check passed for all three changed files.
  • Oxlint passed with 0 warnings and 0 errors.
  • git diff --check passed.
  • TruffleHog filesystem scan of all changed files found 0 verified or unverified secrets.
  • Production LOC: +33/-9 (net +24); tests: +139/-1. The production growth narrowly distinguishes an empty creator bootstrap from malformed/partial schema state while preserving fail-closed behavior.

check:changed classification was attempted but its delegated Crabbox binary failed local sanity checks; the focused Node 24 tests and direct format/lint gates above were run instead. Codex autoreview was unavailable; a final diff review found no P0-P2 findings.

@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 16, 2026 18:42
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Aug 16, 2026
* refactor(imports): dedupe and hoist imports

* feat(lint): enforce import/no-duplicates and import/first
…n session (#124708)

* feat(voice-call): add sessionScope "main" for main-session call routing

Inbound and outbound calls can now share the configured agent's main
session instead of a dedicated voice session. The new scope resolves
through the existing explicit-key canonicalization path, honoring core
session.mainKey and global-scope aliasing. The inbound webhook path now
forwards coreSession like every other resolver call site.

* style: format events.test.ts

* test(voice-call): split events.test.ts under the max-lines cap
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

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

ClawSweeper review

What this changes

This PR changes persisted device-identity reads so read-only consumers do not create coordinator locks and can treat a genuinely empty concurrent SQLite bootstrap as temporarily identity-less.

Regression provenance

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

Merge readiness

⚠️ Ready for maintainer review - 6 items remain

Keep open for maintainer review. Current main proves the lock-creating read path, but the exact PR head and merge result could not be inspected because its promised Git objects are absent locally and GitHub DNS was unavailable; the protected maintainer and security labels also require human handling.

Likely related people

  • @steipete — high confidence; current owner-history and blame point to this device-identity path.

Priority: P2
Reviewed head: 05196f456c9a9752d284f7115d0f7571caa05ca9
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The source-level diagnosis is credible, but exact-head patch, merge-surface, dependency, and runtime proof could not be independently checked.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its reported focused tests still need exact-head verification before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its reported focused tests still need exact-head verification before merge.
Evidence reviewed 7 items Current defect location: The standard persisted-identity read enters the device-identity coordinator before performing its otherwise read-only lookup, so it can serialize behind creation and create coordinator state.
Coordinator side effect: Coordinator acquisition ensures its private directory before taking the SQLite coordinator, confirming that the standard read is not lock-free.
Owner boundary and caller: The artifact-preserving read-only state helper is the shared owner for non-mutating database reads, while Doctor currently calls the coordinator-taking identity reader.
Findings None None.
Security Needs attention Resolve the unreviewed dependency graph delta: The supplied dependency guard lists package manifests and pnpm-lock.yaml although the PR describes a three-file identity repair; inspect the exact merge result before landing.

How this fits together

Device identity lets CLI, Doctor, Gateway probes, and node tooling authenticate or inspect pairing state. These consumers read the shared SQLite state database and then either attach an existing identity or report that none is available.

flowchart LR
  Consumer[CLI, Doctor, or Gateway probe] --> Lookup[Device identity lookup]
  Lookup --> ReadOnly[Read-only state database access]
  ReadOnly --> Check{Identity table available?}
  Check -->|identity row| Identity[Return validated identity]
  Check -->|empty bootstrap| Miss[Return temporary absence]
  Check -->|partial or corrupt state| Fail[Fail closed]
  Identity --> Client[Authentication or diagnostics]
  Miss --> Client
Loading

Decision needed

Question Recommendation
Can the intended three-file device-identity repair be isolated and its exact merge result, dependency delta, and focused bootstrap proof reviewed before this branch lands? Refresh a clean merge result: Rebase or otherwise provide an exact merge result containing the identity repair, then review its focused tests and any surviving dependency changes.

Why: The available metadata conflicts sharply on scope, and read-only SQLite behavior affects authentication-adjacent consumers; automated review cannot establish the actual merge surface without the unavailable PR head.

Before merge

  • Resolve security concern: Resolve the unreviewed dependency graph delta - The supplied dependency guard lists package manifests and pnpm-lock.yaml although the PR describes a three-file identity repair; inspect the exact merge result before landing.
  • Resolve merge risk (P1) - The branch reports a three-file repair but its supplied base-to-head metadata includes 2,039 changed files plus dependency manifests and pnpm-lock.yaml; without the exact merge result, unrelated runtime, workflow, or dependency changes cannot be ruled out.
  • Resolve merge risk (P1) - The declared repair grows production code by 24 net lines; keep the empty-bootstrap classification at the shared read-only SQLite owner rather than duplicating database-state policy in identity consumers.
  • Resolve merge risk (P1) - The Node SQLite read-only/bootstrap contract is directly relevant to the claimed empty-snapshot behavior, but the upstream runtime contract and exact-head tests could not be inspected while network access was unavailable.
  • Complete next step (P2) - Protected maintainer/security labels and the unavailable exact merge surface require owner review rather than automated repair.

Findings

  • [medium] Resolve the unreviewed dependency graph delta
Agent review details

Security

Needs attention: The dependency guard reports package-manifest and lockfile changes outside the stated repair, and the unavailable exact merge result prevents a supply-chain clearance.

Review metrics

Metric Value Why it matters
Declared repair LOC production +33/-9 (net +24); tests +139/-1 The PR body reports this intended repair delta; the positive production growth needs exact-merge confirmation and owner-boundary justification.

Stored data model

Persistent data-model change detected: migration/backfill/repair: ui/src/styles/chat/sidebar.css, persistent cache schema: .agents/skills/openclaw-ci-limits/SKILL.md, persistent cache schema: .github/actions/setup-node-env/action.yml, persistent cache schema: .github/workflows/openclaw-live-and-e2e-checks-reusable.yml, serialized state: ui/src/pages/new-session/cloud-recovery-state.test.ts, serialized state: ui/src/pages/sessions/route.test.ts, and 13 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Inspect a refreshed merge result (recommended)
    Confirm that only the intended SQLite identity-read changes and reviewed dependency deltas survive before merge.
  2. Pause the stacked branch
    Recreate the repair narrowly if unrelated runtime, workflow, or dependency changes remain in the merge result.

Technical review

Best possible solution:

Produce a current merge-result diff containing only the intended identity/read-only-storage repair, keep empty-bootstrap classification in the shared read-only SQLite boundary, and prove exact-head behavior for missing, concurrent-empty, valid, and corrupt database states.

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

Yes, from source: loadDeviceIdentityIfPresent acquires the coordinator before an otherwise read-only lookup, and the coordinator ensures its lock directory. Exact concurrent-bootstrap execution against the PR head was unavailable.

Is this the best way to solve the issue?

Unclear: moving this behavior to the shared artifact-preserving read-only SQLite boundary is the right architectural direction, but the exact PR implementation and its one-snapshot bootstrap classification could not be inspected.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The source-proven defect affects device-identity diagnostics and startup-adjacent reads with limited, non-emergency blast radius.
  • merge-risk: 🚨 other: The supplied branch metadata includes a large unexpected surface and dependency graph changes that cannot be resolved against the actual merge result.
  • 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: This maintainer-authored PR is exempt from the external-contributor proof gate; its reported focused tests still need exact-head verification before merge.

Evidence

Security concerns:

  • [medium] Resolve the unreviewed dependency graph delta
    The supplied dependency guard lists package manifests and pnpm-lock.yaml although the PR describes a three-file identity repair; inspect the exact merge result before landing.
    Confidence: 0.92

What I checked:

  • Current defect location: The standard persisted-identity read enters the device-identity coordinator before performing its otherwise read-only lookup, so it can serialize behind creation and create coordinator state. (src/infra/device-identity.ts:168, b097d64574be)
  • Coordinator side effect: Coordinator acquisition ensures its private directory before taking the SQLite coordinator, confirming that the standard read is not lock-free. (src/infra/device-identity-coordinator.ts:86, b097d64574be)
  • Owner boundary and caller: The artifact-preserving read-only state helper is the shared owner for non-mutating database reads, while Doctor currently calls the coordinator-taking identity reader. (src/state/openclaw-state-db-readonly.ts:138, b097d64574be)
  • Existing regression coverage: Current tests distinguish the standard reader from the artifact-free reader: only the latter is asserted not to create coordinator artifacts, leaving the reported standard-reader behavior source-reproducible. (src/infra/device-identity.test.ts:274, b097d64574be)
  • History provenance: The coordinator behavior dates to the identity-race repair, and current history identifies a subsequent bootstrap-ownership repair in the same subsystem. (src/infra/device-identity.ts:165, 21a9428a8a53)
  • Exact-head inspection gap: The advertised PR head was not present in the partial local clone, and GitHub/Git promisor access failed on DNS resolution; therefore the three intended-file diff and resulting merge tree could not be verified.

Likely related people:

  • steipete: Current blame for the coordinator-taking reader and Doctor caller names Peter Steinberger, and history shows the identity-race and bootstrap-ownership repairs under this area. (role: feature owner and recent area contributor; confidence: high; commits: 21a9428a8a53, 2132c15bd65b, dd1ee7b3750a; files: src/infra/device-identity.ts, src/infra/device-identity-coordinator.ts, src/commands/doctor-device-pairing.ts)

Rank-up moves

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

  • Provide an inspectable exact merge result or clean rebase.
  • Attach exact-head focused bootstrap and corrupt-state test output after the scope is resolved.

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 (4 earlier review cycles)
  • reviewed 2026-08-16T18:48:54.354Z sha 96c29f3 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-16T19:37:15.298Z sha 5634bc0 :: needs changes before merge. :: [P1] Keep the bootstrap classification in one SQLite snapshot
  • reviewed 2026-08-17T03:03:14.929Z sha 5634bc0 :: found issues before merge. :: [P1] Keep bootstrap classification in one SQLite snapshot
  • reviewed 2026-08-17T05:22:03.469Z sha b5ffcc3 :: needs maintainer review before merge. :: none

steipete and others added 19 commits August 16, 2026 11:51
* feat(codex): register additional session homes

* fix(codex): preserve automatic session homes

* docs(codex): explain automatic home discovery around sessionCatalog.homes

---------

Co-authored-by: IWhatsskill <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
#124724)

* fix(ui): keep Control UI device identity working on plain-HTTP origins

@noble/ed25519 defaults its SHA-512 provider to crypto.subtle, which
browsers gate to secure contexts, so device identity silently vanished
on http:// LAN dashboards and connects fell back to shared-credential
auth with no pairing. Wire a lazy pure-JS @noble/hashes fallback for
SHA-512 and the fingerprint SHA-256, and drop the isSecureContext gate
in the connect path. Secure contexts keep the platform digests and pay
no startup bytes: the fallback loads as its own lazy chunk, kept out of
the gateway-runtime startup chunk on purpose.

* test(ui): cover device identity minting and signing without crypto.subtle

New jsdom regression suite fails on pre-fix code (subtle-less crypto stub
with getRandomValues, which real insecure contexts keep). Rewrites the
gateway connect tests that previously asserted the device-less insecure
fallback: an insecure context now attaches a device identity.

* docs(web): plain-HTTP dashboards now pair with a device identity

The signing key never crosses the wire, so HTTP+pairing is strictly
stronger than the old HTTP token-only fallback; HTTPS (Tailscale Serve)
stays the recommendation for transport privacy.

* fix(ui): drop unnecessary boolean literal compare in secure-context timing meta

* test(ui): declare device.id on the connect-frame test shape

* test(ui): split the subtle-less scope-upgrade e2e into the two real invariants

Without crypto.subtle the browser can now sign, so the banner offers the
explicit admin upgrade; manual-only guidance is reserved for browsers that
cannot mint an identity at all (no WebCrypto RNG). Also corrects the
connect-path comment: blocked storage yields an ephemeral identity, only a
failed mint degrades device-less.

* fix(ui): address review findings on the HTTP device-identity path

- Storage-blocked pages keep one stable in-memory identity per page
  lifetime instead of minting a fresh unpaired key on every reconnect,
  and a write-rejecting store no longer fails the mint (regression tests
  bite pre-fix).
- Connect timing now reports the real browser secure-context fact via a
  shared browserSecureContext() helper instead of inferring it from
  device-identity presence.
- Docs state the accepted trusted-proxy contract: browsers attach a
  device identity on every origin, so first connects follow the standard
  pairing flow (deviceAutoApprove or a one-time approval); device-less
  admission remains only for browsers that cannot mint an identity.

* refactor(ui): trim the connect-path additions under the max-lines cap
…24464)

A LINE push made exactly one attempt, so a transient provider or transport
failure dropped the reply even though retrying was safe to do. Retrying alone
would have duplicated a send LINE already accepted, so every push now carries an
X-Line-Retry-Key and reuses it across attempts: LINE answers a replayed key with
409 and the accepted request's sent messages, which resolves to the original
delivery instead of a second message.

Retries follow LINE's documented policy - server errors and transport failures
only, never 2xx, 409 or any 4xx - and run through the shared channel API retry
runner in strict mode. Replies stay single-attempt because LINE offers no retry
key for them.
… abort (#124756)

* fix(outbound): record queue-write loss and fail every payload on prep abort

Two silent-observer gaps in the outbound queue admission path:

1. Best-effort staging/queue-write failures were swallowed with a bare
   'return null'. The send proceeded live-only, so a crash mid-send lost
   the message with zero forensic trace of why the write-ahead row was
   missing. Every sibling degradation on this boundary logs
   (persistQueuedPreSendState, the dispatch-refresh fallback); this one
   now warns with channel/target and the error.

2. Batch preparation failure emitted message_sent for only the first
   payload while audit emitted per-payload terminals, so plugins with
   message_sent hooks saw 1 failure for an N-payload batch. The failure
   path now emits one hook failure per logical payload, matching the
   audit terminals and the recovery sibling's
   queuedTerminalFailureEvents. The unused error.payload pick and its
   OutboundPayloadPreparationError import went with it.

Regressions: queue-write warn asserted in the existing best-effort
fallback test; new multi-payload prep-failure test asserts 2 hook
failures. Both fail pre-fix.

* chore(outbound): keep OutboundPayloadPreparationError module-local

Last external consumer went away with the per-payload emit; the
deadcode:exports gate rejects unused exports.
…4754)

* refactor(gateway): drop dead session-subscriber registry surface

getForConnection and both registry clear() methods had no production
callers — only server-chat-state.test.ts consumed them (verified by
repo-wide grep incl. plugin-sdk). The recency-sorted connToSessionKeys
index existed solely so getForConnection returned keys in subscription
order, an ordering nothing read, rebuilt via toSorted() on every
subscribe/unsubscribe/settle — including the provisional-replay settle
path.

unsubscribeAll now reads the reverse index directly from
connToSessionRecency's keys (same contents, no ordering), removing the
per-call O(k log k) rebuild and the duplicate map. Tests assert through
get()/getApprovals(), the production read paths, per test-audit norms.

Behavior-neutral: subscription state transitions and event-visible
delivery unchanged; chat-state, broadcast, node-subscription,
instance-runtime, agent-events, session-events suites pass.

* test(gateway): fix ETXTBSY flake in workspace-sync candidate bounding

The test rewrote its mock git script between two createGitTransferList
calls. On Linux CI the second spawn can race a lingering fork of the
first child still holding the script's write fd, failing exec with
ETXTBSY. Write the script once; vary the entry count through a data file
the script reads instead.
)

* test(runners): cover paired-node lifecycle wire

* fix(runners): preserve retryable device lifecycle

* test(runners): keep wire fixture internals local

* fix(runners): stop fallback on device capacity
* fix(openai): centralize setup auth metadata

* refactor(openai): overlay auth hooks in place

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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: android App: android app: ios App: ios app: linux app: macos App: macos app: web-ui App: web-ui channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: raft Channel integration: Raft channel: signal Channel integration: signal channel: slack Channel integration: slack channel: synology-chat channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: twitch Channel integration: twitch channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser cli CLI command changes commands Command implementations dependencies-changed PR changes dependency-related files docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: acpx extensions: baseten Extension: baseten extensions: browser extensions: byteplus extensions: canvas extensions: chutes extensions: clickclack extensions: codex extensions: copilot extensions: crabbox extensions: device-pair extensions: diagnostics-prometheus extensions: diffs extensions: elevenlabs extensions: firecrawl extensions: fish-audio Extension: fish-audio extensions: google extensions: lmstudio extensions: memory-core Extension: memory-core extensions: memory-wiki extensions: minimax extensions: mistral extensions: nvidia extensions: oc-path extensions: ollama extensions: onepassword 1Password plugin extensions: openai extensions: opencode extensions: opencode-go extensions: openrouter extensions: openshell extensions: perplexity extensions: policy extensions: qa-lab extensions: tavily extensions: volcengine extensions: xai fleet gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. plugin: cua-computer plugin: google-meet plugin: logbook Logbook automatic work journal plugin plugin: mxc plugin: teams-meetings Teams Meetings plugin plugin: workboard rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security Security documentation 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.