Repository navigation
perf(auth): move auth saves to workers and publish incrementally - #165644
Conversation
|
🦞👀 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 5, 2026, 9:13 PM ET / October 6, 2026, 01:13 UTC (Revision 7). ClawSweeper reviewWhat this changesMoves asynchronous credential saves into SQLite workers, updates affected authentication snapshots incrementally, and waits for temporary database cleanup before deleting credential files. Warning SQLite table change This PR modifies persisted SQLite tables in Merge readiness⛔ Blocked before merge - 2 items remain The optimization remains useful on current main. Both previous findings are resolved, and no remaining actionable introduced defect was identified in the reviewed save, publication, authority, and cleanup paths. Priority: P2 Review scores
Verification
How this fits togetherAuthentication stores hold shared, agent-local, and personal provider credentials. Save operations commit durable state and then publish runtime snapshots used by model selection and credential resolution. flowchart TD
A[Credential update request] --> B[Capture store owner]
B --> C[SQLite worker transaction]
C --> D[Host update callback]
D --> E[Recheck live admission]
E --> F[Commit durable credentials]
F --> G[Publish affected auth snapshots]
G --> H[Model authentication]
Before merge
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep asynchronous saves with the existing worker owners while preserving callback-once semantics, live commit admission, canonical reconciliation, and safe temporary-store disposal. Do we have a high-confidence way to reproduce the issue? Yes: the reported fixed-cadence benchmark exercises the real asynchronous save/publication entry point, and current main still contains the synchronous work it targets. No benchmark or tests were executed during this read-only review. Is this the best way to solve the issue? Yes: extending the existing worker and snapshot owners preserves the established storage and SDK contracts without introducing another persistence owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against a7928ef49ad7. 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 (6 earlier review cycles)
|
|
13ece22 to
75e071b
Compare
Run async credential/state save transactions in the SQLite worker while preserving locked-row callbacks and live write admission. Publish affected auth snapshots from committed facts and transfer large cells in bounded field records, retaining native synchronous and Doctor custody contracts. The 50-agent, 1 MiB fixture improves median main-thread CPU per save from 800.755 ms to 5.293 ms; the requested 2 ms target remains unmet. Canonical auth/secrets tests and the full build pass on Blacksmith Testbox. Inherited dead-export and line-count failures remain disclosed in the PR evidence.
Create the timestamp-bearing base fixture once for the input and expected value so a millisecond boundary cannot change the expected OAuth expiry. Keep the independent metadata and clone-isolation assertions unchanged.
Keep catalog auth writes bound to their request and captured state root, and settle claimed OAuth work before closing that authority. Preserve env-only callback visibility, keep internal guards out of the public SDK parameter contract, and carry publication metadata through the same bounded field exchange as committed stores. Drain native and worker database owners before removing transient registration or deleting credential directories. Refuse ambiguous disposal and recheck file identity after registry publication. Remove private lifecycle barrel exports and migrate callers to their owning modules. Repair the affected worker-test routing and selection-race fixtures while preserving their behavior assertions.
Route generic personal-account updates through the canonical personal worker owner after its main-branch cutover. Preserve callback checks and forward live authority into transaction and commit admission. Keep the stronger OAuth claim guard that validates both cancellation and credential ownership. Extend the existing authority regression through callback and commit revocation; removing commit-time forwarding makes the intended negative control fail.
6ddc90a to
fa257bc
Compare
Auth saves moved into SQLite workers in #165644, but seven QA consumers still ran in Vitest threads without the host broker. The SDK nullable write contract masked the host-owner rejection as an isolated auth staging error. Route those consumers through existing isolated fork owners, and await worker/database drainage before deleting fixture state. Keep delivery-cache private-QA preparation under its infra owner and retain canonical job metadata for private-QA targets so its serial job contract survives selection. Preserve every test case, assertion and timeout. Production credential placement is unchanged. The isolated-store matrix covers invalid/future outer roots and concurrent explicit state roots; the real Gateway delivery proof retains one native session across three turns. Validation on Linux Testbox from 282f796 plus this patch: all 107 QA cases, the real three-turn delivery proof (18.8s test / 38.9s harness), routing/config/importer tests, 171 build-admission cases, registry checks, and full check-changed. The QA matrix took 62.5s CI wall time; its eight extracted cases and 21 assertions remain intact. Four real preflight checkout/event shapes and independent P2 review passed. The final portable compiler filename match also passed the complete build-admission file and lint on Linux, plus an isolated P2 delta review.
…nclaw#165644) * perf(auth): move auth saves to workers and publish incrementally Run async credential/state save transactions in the SQLite worker while preserving locked-row callbacks and live write admission. Publish affected auth snapshots from committed facts and transfer large cells in bounded field records, retaining native synchronous and Doctor custody contracts. The 50-agent, 1 MiB fixture improves median main-thread CPU per save from 800.755 ms to 5.293 ms; the requested 2 ms target remains unmet. Canonical auth/secrets tests and the full build pass on Blacksmith Testbox. Inherited dead-export and line-count failures remain disclosed in the PR evidence. * test(auth): remove clock skew from snapshot clone test Create the timestamp-bearing base fixture once for the input and expected value so a millisecond boundary cannot change the expected OAuth expiry. Keep the independent metadata and clone-isolation assertions unchanged. * fix(auth): settle worker saves and temporary database cleanup Keep catalog auth writes bound to their request and captured state root, and settle claimed OAuth work before closing that authority. Preserve env-only callback visibility, keep internal guards out of the public SDK parameter contract, and carry publication metadata through the same bounded field exchange as committed stores. Drain native and worker database owners before removing transient registration or deleting credential directories. Refuse ambiguous disposal and recheck file identity after registry publication. Remove private lifecycle barrel exports and migrate callers to their owning modules. Repair the affected worker-test routing and selection-race fixtures while preserving their behavior assertions. * fix(auth): preserve personal worker authority after integration Route generic personal-account updates through the canonical personal worker owner after its main-branch cutover. Preserve callback checks and forward live authority into transaction and commit admission. Keep the stronger OAuth claim guard that validates both cancellation and credential ownership. Extend the existing authority regression through callback and commit revocation; removing commit-time forwarding makes the intended negative control fail. * test(auth): repair worker routing and probe cleanup fixtures * test(auth): keep one admission test inventory entry
Auth saves moved into SQLite workers in openclaw#165644, but seven QA consumers still ran in Vitest threads without the host broker. The SDK nullable write contract masked the host-owner rejection as an isolated auth staging error. Route those consumers through existing isolated fork owners, and await worker/database drainage before deleting fixture state. Keep delivery-cache private-QA preparation under its infra owner and retain canonical job metadata for private-QA targets so its serial job contract survives selection. Preserve every test case, assertion and timeout. Production credential placement is unchanged. The isolated-store matrix covers invalid/future outer roots and concurrent explicit state roots; the real Gateway delivery proof retains one native session across three turns. Validation on Linux Testbox from 590c8eb plus this patch: all 107 QA cases, the real three-turn delivery proof (18.8s test / 38.9s harness), routing/config/importer tests, 171 build-admission cases, registry checks, and full check-changed. The QA matrix took 62.5s CI wall time; its eight extracted cases and 21 assertions remain intact. Four real preflight checkout/event shapes and independent P2 review passed. The final portable compiler filename match also passed the complete build-admission file and lint on Linux, plus an isolated P2 delta review.
persistAuthProfileBatch and upsertAuthProfileWithLock captured the pre-lock-wait OAuth authority snapshot with synchronous DatabaseSync reads on the main thread (8 host SQL statements for one profile save into an empty store). #165644 moved saves into workers but left this read behind. Read the snapshot through the existing worker-backed row readers inside a usage-preparation reservation taken synchronously at call time, so async writers admitted later stay ordered behind it; release it before the OAuth lock wait. Legacy synchronous main-thread commits cannot be ordered behind an async read, so native-commit watches captured at call time detect one landing first and make the snapshot unknown, which refuses conservatively. Delete the synchronous helpers. Co-authored-by: Peter Steinberger <[email protected]>
…72911) persistAuthProfileBatch and upsertAuthProfileWithLock captured the pre-lock-wait OAuth authority snapshot with synchronous DatabaseSync reads on the main thread (8 host SQL statements for one profile save into an empty store). openclaw#165644 moved saves into workers but left this read behind. Read the snapshot through the existing worker-backed row readers inside a usage-preparation reservation taken synchronously at call time, so async writers admitted later stay ordered behind it; release it before the OAuth lock wait. Legacy synchronous main-thread commits cannot be ordered behind an async read, so native-commit watches captured at call time detect one landing first and make the snapshot unknown, which refuses conservatively. Delete the synchronous helpers. Co-authored-by: Peter Steinberger <[email protected]>
What Problem This Solves
Shared and agent-local OAuth, credential, and auth configuration saves stall the Gateway while the host rereads and encodes SQLite JSON cells and rebuilds derived agent snapshots.
User Impact
Ordinary shared and agent-local updates perform their SQLite transaction in the existing worker and publish affected snapshots incrementally. Credentials, SecretRefs, inheritance, and auth state preserve their existing semantics. There is no schema, stored-format, configuration, migration, or update/rollback change and no operator action is required.
The requested ≤2 ms main-thread CPU/save target remains unmet: the latest rebased candidate measures 5.039 ms median. The original matched parent/candidate comparison measured 915.710 → 5.090 ms, a 99.44% reduction.
Why This Change Was Made
The worker owns the current-row read, merge, encoding, and commit. Host callbacks execute at most once against locked authoritative rows; live admission is checked again before commit. Generic shared/agent cells and their publication metadata share a field exchange bounded to 64 KiB per record, including oversized values and property names. The ordinary commit acknowledgment carries no store or publication blob.
Shared credential publication consumes committed facts and preserves unaffected snapshots and revisions. State/profile-set changes, OAuth reconciliation, and overtaken commits use canonical worker reads for affected snapshots. Unknown outcomes invalidate matching views without replaying durable writes. Local updates refuse observed inherited-source changes; this preserves in-process ordering, not cross-database atomicity.
The old async wrapper around a synchronous transaction and whole-row transfer fallback are removed. Released synchronous SDK saves, native compensation, and Doctor maintenance retain their contracts. Catalog workers bind native writes to their request and captured root and settle claimed OAuth work before closing. Temporary-store disposal drains native/worker owners and removes registration before deletion; failed or ambiguous disposal retains files. Env-only no-op callbacks receive no persisted credentials and do not decode stored bodies. The SDK adapter forwards only its established fields, keeping the new internal admission callback private.
Required non-test/non-doc diff: +2,579/−526, net +2,053 lines, including tooling/test-routing inventory. Production
src/alone is +2,553/−523, net +2,030 lines. Growth preserves the released arbitrary callback-once/locked-row contract, unrestricted credential-cell sizes, native custody, commit reconciliation, and safe async disposal. Functions cannot cross as ordinary worker commands. The change adds no credential-body cache or competing cleanup owner.Evidence
The isolated Linux rig compared parent
ac3830b776a3d361848c9b9a70aa1755e91dc6e2with the candidate using the same fixture and lockfile: 50 agents × 1 MiB cells, two warmups, then ten shared saves scheduled at fixed six-second start times.nice -n 10 ionice -c3 node --import ./scripts/tsx.mjs .rig/benchmark-cadence.mjsexercises the real async save API;process.threadCpuUsage()excludes worker CPU.Candidate wall latency was 8.55–61.18 ms, 24.89 ms median, versus parent 1,196.27 ms median / 10,702.62 ms maximum. Candidate save starts averaged 6,000.64 ms apart; the parent missed one scheduled slot and caught up, averaging 6,001.46 ms. Sampled RSS was 1.14 GB versus 1.06 GB; this allocation-heavy sample is not steady-state memory proof. All 50 effective snapshots matched parent digests. An independent read-only comparison also matched all 51 raw auth cells, 52,433,140 bytes, including the shared cell. The audit's 78–233 ms figures measured cell-read fanout; this fixture measures the complete save/publication flow. This measurement uses candidate
75e071be82b4a803d81fe66c261b0f263854c092, including the final SDK correction and both auth integrations. Earlier six-second-idle runs are superseded by this fixed-cadence measurement.After rebasing onto
8313f565a2e77d90ccb983ef68acd72eb732f4e3, the same rig fixture measured final candidatefa257bcfb33d(treee43efb0c64ca) again: main-thread CPU 3.246 / 5.039 / 18.259 ms (minimum/median/maximum), wall latency 14.061 ms median / 86.318 ms maximum, and 6,000.219 ms average start interval. All 50 stored/snapshot digests and all 51 raw cells still match the older parent exactly. This is a fresh candidate measurement, not a matched comparison against the new base; the table above remains the historical causal comparison. Upstream worker-diagnostic classification changed, which is why the candidate was remeasured. Sampled RSS was 1.157 GB and is not steady-state memory proof.All Testbox proof used blacksmith-testbox / openclaw-check, with exact base/head, source hashes, and full candidate trees verified. All listed leases are stopped and verified absent.
tbx_01m47bq9yxzk6r43g496vf8nnhscripts/ci-build-manifest.mjs, duplicate control, routing/planner contracts, admission, and ten affected auth/secrets/catalog/session/probe filestbx_01m479d8vgejytjkh4fc1q5jnxpnpm test <file> --maxWorkers=1for admission, Codex refresh authority and model probe; cleanup/resource siblings; routing-owner tests; affected type graphs; native changed-check guardstbx_01m475q8t4h3gkstka939zebkf75e071be82b4:node scripts/run-vitest.mjsover auth/secrets; core and affected auth test types; 15 native-plan-selected guards;pnpm buildtbx_01m4733621dw6d7ywvm2s7g1fhtbx_01m46vnq82fhc1qq1zff0b2qj6pnpm buildtbx_01m46yj67xey76t323mdwg9f2gpnpm buildThe hosted Build Artifacts run for
fa257bcfb33dpassed on its PR merge checkout. The cache-misspnpm build:ci-artifactsstep ran the runtime compiler, runtime postbuild, SDK declarations and UI/metadata pipeline in 164s; artifact verification passed. This covers the rebased runtime build inputs.The final rebase incorporates the upstream fixes for worktree preparation's line limit and heartbeat-test shadowing. The pinned base also had two full-lint failures:
src/state/openclaw-agent-execution-incognito.compute.test.ts(1,027 > 1,000 lines) andextensions/amazon-bedrock/stream.runtime.test.ts(1,015 > 1,000). File/config/tool identity attributed both to the baseline. Currentmainfixes them in #165851, and the lane merges cleanly with that base. The historical full-lint runs remain recorded as failed.Standalone test-cost proof:
pnpm test src/agents/auth-profiles/store-update.test.ts --maxWorkers=1passed 22 cases in 32s; the equivalent disposal-owner command passed eight cases in 24s; the equivalent SDK compatibility command passed five cases in 26s on the earlier SDK validation lease; the corrected fallback-validation file passed two cases in 24s. These commands consumed 106 serial runner seconds, including startup. The final CI repair adds admission 13 cases / 35s, Codex authority 7 / 35s, and model probe 6 / 22s with the same standalone command form: 92 serial runner seconds. Its cleanup/resource selection passed 13 cases / 45s and routing owners 34 / 24s. Cases that also appear in broader selections are not counted twice.Six isolated counterfactuals confirmed the intended defects, then restored exact source bytes: omitted final disposal identity check (one failure), disabled env-only isolation (four failures), old unbounded publication result (two failures, 131,237 bytes versus 65,536), the old SDK adapter (one private-guard invocation failure), omitted personal commit authority (one failure), and omitted fallback credential validation (one failure). Coverage also protects changed-agent-only publication, callback refusal/at-most-once execution, native commit races, lost acknowledgments, throwing observers, oversized fields/keys, and Doctor custody.
The full rig
node scripts/check-changed.mjs --staged --base c55f16f142118c859691e177f119cb2834287e33run passed its guards, formatting, Doctor tests, production types and all 27 core test type graphs, then the extension typecheck terminated with exit 137 without a compiler diagnostic. Its cause is unconfirmed. The exact extension command subsequently passed on Testbox in 92s; the unfinished native-plan phases were all executed, with the inherited lint failures above preserved. Five affected core graphs were refreshed after integration, followed by the final auth graph and production types on the published candidate.The integrated auth run initially found two stale assertions requiring exactly two validator calls. Live admission correctly revalidates more often. The revised tests preserve accepted/refused fallback behavior and first/last credential validation; the final 1,718-case run and missing-validator counterfactual both confirm the correction. Earlier CI also exposed request custody, import-cycle/inventory, worker-test routing and premature temporary-file deletion defects; the owner repairs and replayed proof are included here.
Independent review completed clean for the full candidate, integration fixes, five-file fixture repair, and duplicate-routing correction (no actionable P0–P2 findings). The latest rebase onto
8313f565a2e7was conflict-free and preserved all five lane commits patch-identically.The hosted run on
75e071be82b4failed three jobs; final repair commit6ddc90a0bbd7addresses them: database-admission and Codex refresh tests were still routed through thread pools despite requiring host-owned database brokers, and the model probe asserted a retired snapshot-cleanup callback. The test-only repair routes the two files through the existing fork owners, settles database owners before fixture deletion, and asserts actual probe-directory removal. The changed-mock guard initially rejected its legacy closed mock; the final probe uses a partial auth-module mock and the canonical mock-factory ledger shrinks by one exact entry. The temp-directory report retains advisory warnings for explicit tracker ownership: async database settlement must finish before synchronous deletion. No warning suppression was added. Production guards, pool configuration, and timeouts are unchanged. The performance, auth/secrets, and build evidence above is reused because production source is unchanged.The next hosted run (
37396600599) stopped in preflight: the branch and advancing main had independently registered the admission test at different inventory positions. Newer main then acquired a second duplicate of its own. The lane rebased onto that main and commitfa257bcfb33dremoves both redundant occurrences, retaining one canonical fork owner. The focused rebase proof refreshes affected auth, secrets, catalog, session, and probe integration; prior broader tests and the full build remain earlier-head evidence, and the new head’s hosted artifact build passed. The planner duplicate guard remains unchanged. The actual manifest-builder counterfactual reproduces the exact hosted refusal; the corrected manifest schedules the admission file once. No upstream fixes were copied or cherry-picked.Final hosted CI run
37398275356onfa257bcfb33dcompleted with 102 successful jobs and 22 skipped jobs. All executed test/build/check jobs passed exceptsecurity-fast, whose production dependency audit reports HIGH[email protected], GHSA-68fv-2mgg-jv7q (affected range>=1.0.0 <1.2.2). The aggregate CI gate consequently failed. This branch does not changepackage.jsonorpnpm-lock.yaml, and current main retains the same dependency. The dependency blocker is not waived; no dependency override, audit suppression, or rerun was introduced.Live-provider and native Windows-device proof were not run; Windows-style environment cases ran on Linux.