Skip to content

refactor(auth): prepare runtime profile reads asynchronously - #149309

Merged
steipete merged 35 commits into
mainfrom
codex/runtime-auth-async-read-publication
Sep 18, 2026
Merged

steipete merged 35 commits into
mainfrom
codex/runtime-auth-async-read-publication

Conversation

@steipete

@steipete steipete commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Runtime model preparation reads persisted authentication profiles synchronously, allowing SQLite work to block the Gateway's main event loop. Assigning those reads a separate broker backend also conflicts with memory publication when both use the same agent database.

User Impact

Model preparation now awaits isolated profile reads while preserving profile selection, configured transport, unavailable-model handling, and deferred provider preparation. Existing databases and configuration remain compatible; no operator migration is required.

Why This Change Was Made

Agent-local and legacy shared credentials use the existing isolated read-only child. The child runs the auth owner's fixed row query without competing for the agent's writer backend. Source-exclusion scopes supply their owned private snapshot. Captured agent/root admission remains live through cleanup, and the child independently retains source admission through native close. Existing bounded frames carry complete credential rows without an aggregate size limit.

Relocated shared credentials and selected personal accounts remain with the canonical shared-state actor. Credential mutations, FIFO ordering, postcommit publication, and synchronous SDK readers retain their existing owners. Selected-owner errors stay visible; inherited-owner refusal follows the existing decision. Final currentness and legacy-file checks run after cleanup using prepared persisted rows, so inherited or external profiles cannot conceal an unmigrated local source.

The read-only child and synchronous persistence reader share the same narrow table and JSON inspection kernel. The child no longer imports the writable auth runtime, and the extracted wrapper inventory includes its five required source dependencies.

The superseded auth broker entry is removed. Protocol types belong to their existing pure owners, and the unchanged duplicate-export guard passes without an exception. The earlier CI repair retains canonical fork routing and the image suite's equivalent asynchronous auth fixture.

Evidence

Final integration 667b9d54b534 carries canonical main cecf47a2d92e. The existing protocol owner handles main's new consolidated SQLite mode; no second parser is restored. Auth rows still use a dedicated child with the captured environment, complete framed transfer, current admission, and awaited native cleanup. Canonical catalog retention and shared-state operations remain intact.

All 153 selected Auth, readonly-worker, consolidated-state/preflight, and catalog-performance cases pass, together with core types, formatting, and fresh independent P0–P2 review. The normal build passed on the final source tree in 6 minutes 38 seconds. Fresh compiled Node and Bun probes each returned the exact 10,800,214-byte envelope, preserved source database bytes, and exited naturally.

Two inherited test expectations surfaced during integration. The planner correction was absorbed by canonical #151427, preserving its exact file and expanded host coverage. The catalog SQL assertion expected 20 reads per resident list, while identical query traces on baseline main and the executed PR merge showed 18: three bindings each perform one freshness read, four schema-admission reads, and one authority read. The test now requires exactly 18 and retains every functional, CPU, authority, and zero-I/O assertion. Its full real-store flow, selected changed checks, and independent P0–P2 review pass. This is not an Auth performance claim.

Predecessor CI 35331313677 passed on 9d950dd94a30. CI 35343981196 failed only the planner shard and aggregate gate. CI 35349142581 passed 141 jobs and skipped 14; only the catalog-count shard and aggregate gate failed. Final-head CI 35353298957 passed on 667b9d54b534: 142 successful jobs and 14 skipped, including the required openclaw/ci-gate. Native review, preparation, merge verification, and cleanup completed; landed as 1d4202ddbc05.

Post-merge performance comparison

Collected after the merge on September 18, 2026; these measurements were not available to the earlier merge decision. Compared the actual pre-merge parent 29e0ca0509c5 with reviewed head 667b9d54b534, using clean pinned checkouts, the same compiled runtime build profile, and Node 24.21.0 on a shared Apple M3 Ultra host (32 logical CPUs, 512 GiB RAM).

The real resolveModelAsync path read persisted synthetic profiles and called a local-only dynamic-provider hook. No auth reader was mocked and no live credentials/provider requests were used. Initial imports and separate fixture writes were outside timing; scoped preparation, child acquisition, transfer, and awaited cleanup were included. Each revision/size used three fresh processes with one first preparation and four warmed calls each. All 60 complete normalized model outputs and profile/mode assertions agreed. Every measurement process exited naturally with no remaining descendants.

Profiles Revision First preparation, seconds (median [range]) Warm preparation, seconds (median [range]) Parent observed RSS, MiB Summed parent/child observed RSS, MiB
1 baseline 0.311 [0.281–0.426] 0.014 [0.013–0.029] 395.6 395.6
1 candidate 0.603 [0.474–0.969] 0.179 [0.167–0.260] 394.8 472.3
2,000 baseline 0.331 [0.274–0.361] 0.022 [0.021–0.081] 391.7 391.7
2,000 candidate 0.458 [0.455–0.721] 0.191 [0.182–0.225] 395.9 481.5

The serialized stores were 158 bytes and 683,601 bytes. RSS values are medians of per-process observed preparation peaks, using parent endpoint readings and process-group samples at roughly 30–33 ms median intervals. Summed RSS double-counts shared pages and can miss short transient peaks; it is not unique memory/PSS. First preparation means after entry-module imports, not process startup or cold OS caches. These are small, shared-host synthetic samples, not a full Gateway benchmark.

Child isolation adds preparation time and approximately 77–90 MiB of observed summed RSS in these fixtures. A 1 ms timer made progress during candidate preparations (warm median 129/134 ticks versus zero for baseline), showing yielding during child waits; this does not establish an end-to-end latency or throughput improvement. No latency or memory reduction is claimed.

Storage compatibility: the table/schema versions, keys, and serialized credential formats are unchanged; the inspection kernel was extracted and reused. No database migration is introduced.

This evidence does not claim live provider/sign-in testing or that every SQLite operation in runtime preparation has moved off the parent thread.

Keep runtime discovery read-only through the canonical SQLite worker owners. Preserve captured profile paths and environment, host selection and migration diagnostics, cleanup failures, and caller authority across model preparation. Retain the public synchronous SDK reader for compatibility.
@clawsweeper

clawsweeper Bot commented Sep 15, 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 15, 2026
@steipete
steipete marked this pull request as ready for review September 15, 2026 17:57
@steipete
steipete requested a review from a team as a code owner September 15, 2026 17:57
@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 Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 18, 2026, 10:30 AM ET / 14:30 UTC (Revision 16).

ClawSweeper review

What this changes

Moves persisted authentication-profile reads during model preparation into asynchronous SQLite readers while preserving credential selection and synchronous SDK access.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/agents/auth-profiles/sqlite.ts. Prefer a design that avoids changing persisted SQLite tables. If the change is necessary, verify migration and upgrade compatibility against an existing database before merge.

Merge readiness

⛔ Blocked before merge - 3 items remain

This remains useful work: current main still reads authentication profiles synchronously during dynamic model resolution. No actionable correctness defect was found, but the required comparative performance evidence remains outstanding.

Priority: P2
Reviewed head: 667b9d54b534d9ecab38193db6d7f26e8382bd56

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The implementation has coherent ownership and useful regression coverage, with no concrete correctness finding; performance validation remains incomplete.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository state identifies this as maintainer-authored, so the external-contributor proof gate does not apply. Reported Node/Bun probes exercise the production read-only child and demonstrate complete transfer and clean exit; comparative model-preparation performance remains a separate scoped-policy requirement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies this as maintainer-authored, so the external-contributor proof gate does not apply. Reported Node/Bun probes exercise the production read-only child and demonstrate complete transfer and clean exit; comparative model-preparation performance remains a separate scoped-policy requirement.
Evidence reviewed 9 items Current main still needs the central change: The fetched main revision calls synchronous loadAuthProfileStoreForRuntime during dynamic model authentication selection.
Latest release also uses synchronous selection: The v2026.9.4 source uses synchronous ensureAuthProfileStore in resolveDynamicModelAuthProfile; the requested asynchronous path is not already supplied by that release.
Ownership and cleanup remain explicit: The runtime reader captures paths and environment, preserves selected versus inherited failure handling, joins reader disposal, and revalidates before returning. Agent readers retain lifecycle registration and source identity; shared and personal reads use the canonical shared-state worker.
Findings None None.
Security None None.

How this fits together

Model preparation combines configured model choices with stored authentication profiles before invoking provider hooks. This change moves database reads into isolated readers and returns prepared credential facts to the existing selection owner.

flowchart TD
  A[Model preparation request] --> B[Capture credential scope]
  B --> C{Credential owner}
  C --> D[Agent database read-only child]
  C --> E[Shared-state worker]
  D --> F[Join cleanup and recheck authority]
  E --> F
  F --> G[Apply overlays and select profile]
  G --> H[Prepare provider model]
Loading

Before merge

  • Resolve merge risk (P1) - Fresh child acquisition, credential transfer, and awaited teardown may increase model-preparation latency and aggregate memory use; comparative measurements remain unavailable.
  • Complete next step (P2) - Add before/after model-preparation elapsed time and aggregate parent/child RSS, including child acquisition, transfer, and cleanup, to the PR evidence.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +1237, Tests +710, Docs +12, Other +4. Total +1963 across 67 files.

View PR surface stats
Area Files Added Removed Net
Source 35 1890 653 +1237
Tests 29 827 117 +710
Docs 1 12 0 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 2 5 1 +4
Total 67 2734 771 +1963

Review metrics

Metric Value Why it matters
Production versus validation growth Production net +1,237 lines; tests and test support net +710 lines The production growth implements captured read lifetimes and complete framed transfer, with extracted synchronous code included in the net total.

Stored data model

Persistent data-model change detected: serialized state: src/agents/auth-profiles/runtime-read.ts, serialized state: src/agents/auth-profiles/sqlite-read.ts, unknown-data-model-change: src/agents/auth-profiles/runtime-read.ts, unknown-data-model-change: src/agents/auth-profiles/sqlite-read.ts, unknown-data-model-change: src/agents/auth-profiles/sqlite.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Measure the complete preparation cost (recommended)
    Provide comparative model-preparation timing and aggregate parent/child RSS that include child acquisition, transfer, and cleanup.

Technical review

Best possible solution:

Retain the existing credential and lifecycle owners while demonstrating that asynchronous reads improve responsiveness at an acceptable measured latency and memory cost.

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

Not applicable to a discrete bug report: this is a performance refactor, and source confirms the synchronous reads it replaces; no timed Gateway stall was reproduced during this read-only review.

Is this the best way to solve the issue?

Unclear overall: the design reuses the appropriate storage owners and preserves existing contracts, but its end-to-end performance benefit still needs comparative measurements.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded runtime responsiveness improvement without evidence of an urgent user-facing outage.
  • merge-risk: 🚨 other: Per-read child startup and teardown introduce latency and memory tradeoffs that green CI does not quantify.
  • 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: The supplied repository state identifies this as maintainer-authored, so the external-contributor proof gate does not apply. Reported Node/Bun probes exercise the production read-only child and demonstrate complete transfer and clean exit; comparative model-preparation performance remains a separate scoped-policy requirement.

Evidence

What I checked:

  • Current main still needs the central change: The fetched main revision calls synchronous loadAuthProfileStoreForRuntime during dynamic model authentication selection. (src/agents/embedded-agent-runner/model.registry-resolution.ts:181, 014d72f106f5)
  • Latest release also uses synchronous selection: The v2026.9.4 source uses synchronous ensureAuthProfileStore in resolveDynamicModelAuthProfile; the requested asynchronous path is not already supplied by that release. (src/agents/embedded-agent-runner/model.registry-resolution.ts:222, 3a9d69db306c)
  • Ownership and cleanup remain explicit: The runtime reader captures paths and environment, preserves selected versus inherited failure handling, joins reader disposal, and revalidates before returning. Agent readers retain lifecycle registration and source identity; shared and personal reads use the canonical shared-state worker. (src/agents/auth-profiles/runtime-read.ts:236, 667b9d54b534)
  • Concrete performance tradeoff: Each auth-profile-rows operation creates a child and awaits its shutdown before returning. This removes synchronous SQLite reads from the parent but introduces process acquisition, transfer, and teardown costs. (src/infra/sqlite-readonly-worker.ts:289, 667b9d54b534)
  • Performance evidence requirement and review continuity: The scoped agent policy requires before/after seconds and RSS. The previous completed review covered this same head, reported no findings, and requested those measurements. The supplied complete body reports transfer integrity, cleanup, build, and CI results but still provides no comparative model-preparation timing or RSS; its catalog query count is expressly not an auth performance claim. (src/agents/AGENTS.md:61, 667b9d54b534)
  • Validation evidence and its limits: The captured body reports final-source Node and Bun probes returning the complete 10,800,214-byte envelope, preserving database bytes, and exiting naturally. GitHub confirms CI run 35353298957 succeeded on the reviewed head. The added real-child regression checks transfer integrity and joined process closure; lifecycle tests cover replacement and retired authority. This review inspected source without executing tests. (src/infra/sqlite-readonly-worker.test.ts:85, 667b9d54b534)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Record before/after model-preparation elapsed time and aggregate parent/child RSS, including cold child acquisition and cleanup.

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 (15 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-18T09:21:13.686Z sha 69f3306 :: blocked before merge. :: none
  • reviewed 2026-09-18T09:57:57.077Z sha 9d950dd :: blocked before merge. :: none
  • reviewed 2026-09-18T10:19:18.025Z sha 9d950dd :: blocked before merge. :: none
  • reviewed 2026-09-18T11:55:01.238Z sha dfcb989 :: blocked before merge. :: none
  • reviewed 2026-09-18T12:30:03.671Z sha 4e1f69f :: blocked before merge. :: none
  • reviewed 2026-09-18T13:04:18.842Z sha 4e1f69f :: blocked before merge. :: none
  • reviewed 2026-09-18T13:25:48.708Z sha 0fa4fbe :: blocked before merge. :: none
  • reviewed 2026-09-18T14:07:29.307Z sha 667b9d5 :: blocked before merge. :: none

Keep runtime profile reads on the existing SQLite worker owners while retaining
current inherited-refusal, model transport, and lifecycle behavior. Recheck
captured legacy candidates after awaited reads using persisted prepared facts.

Keep the required worker ABI as a transparent export from the SQLite owner,
without changing the duplicate-export guard or adding an exception.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XL and removed size: L labels Sep 17, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Sep 17, 2026
Keep read payload and command types with the existing auth data contracts so
worker contracts do not depend on storage implementations. Preserve emitted
runtime behavior and the existing worker ABI.

Run real async-reader fixtures through the canonical fork owner, including
full-suite exclusions and watch/shuffle routing. Give the image fixture the
matching async auth entry backed by its existing profile data.
@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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 18, 2026
@steipete
steipete merged commit 1d4202d into main Sep 18, 2026
224 checks passed
@steipete
steipete deleted the codex/runtime-auth-async-read-publication branch September 18, 2026 14:56
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 19, 2026
…w#149309)

Runtime model preparation now awaits isolated authentication-profile reads, avoiding synchronous SQLite work on the Gateway event loop and competition with memory's agent-database writer. Relocated shared credentials and personal accounts retain the existing shared-state owner; synchronous SDK readers and credential writes remain compatible.

The readonly child and synchronous reader share a narrow JSON inspection kernel. Auth reads keep captured admission through native cleanup, carry complete rows in framed IPC, and preserve selected-owner errors and recorded inherited-source refusal. Canonical consolidated snapshots remain supported by one protocol parser.

Validation: 153 focused Auth, readonly-worker, consolidated-state/preflight and catalog tests; core types; independent P0–P2 review; normal build; compiled Node and Bun probes returning the complete 10.8 MB envelope without changing database bytes. Exact-head CI passed 142 jobs with 14 skips, including the required gate: https://github.com/openclaw/openclaw/actions/runs/35353298957.

Inherited planner and catalog-count assertions were reproduced and reconciled with canonical source. Live provider sign-in was not exercised. No operator migration is required.
steipete added a commit that referenced this pull request Sep 20, 2026
…52286)

* refactor(auth): prepare bounded shared auth scopes asynchronously

Read shared ownership and portable credentials through the existing state
worker before entering bounded CLI and provider-setup auth scopes. Resolve
paths before awaiting and recheck admission and ownership before entry.

Preserve local overrides, OAuth refresh ownership, and personal-account
isolation. Record the cold-worker latency and memory tradeoff in PR evidence.

Related: #149309

* fix(test): await scoped auth while staging live fixtures

Wait for the portable auth view and target persistence before fixture
installation continues. Drain the CLI's existing maintenance owner before
exit and run direct helper tests through the host database-worker lane.

* test(auth): include cacheability in scoped read fixtures

* test(auth): align cancellation fixture with current row metadata

* test(outbound): clean up ACK fixtures with their owner

(cherry picked from commit 4681239)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 21, 2026
…enclaw#152286)

* refactor(auth): prepare bounded shared auth scopes asynchronously

Read shared ownership and portable credentials through the existing state
worker before entering bounded CLI and provider-setup auth scopes. Resolve
paths before awaiting and recheck admission and ownership before entry.

Preserve local overrides, OAuth refresh ownership, and personal-account
isolation. Record the cold-worker latency and memory tradeoff in PR evidence.

Related: openclaw#149309

* fix(test): await scoped auth while staging live fixtures

Wait for the portable auth view and target persistence before fixture
installation continues. Drain the CLI's existing maintenance owner before
exit and run direct helper tests through the host database-worker lane.

* test(auth): include cacheability in scoped read fixtures

* test(auth): align cancellation fixture with current row metadata

* test(outbound): clean up ACK fixtures with their owner

(cherry picked from commit 4681239)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL 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