Repository navigation
improve: reduce SQLite work during chat turns - #167965
Conversation
…odules Merge current main while preserving shared physical admission, cancellation, reader validation birthtime, and live deletion authority. Split worker usage, pool construction, failure settlement, and schema owner types to keep the existing line caps.
Checkpoint the single-owner cutover, cache invalidation regressions, and request-owned read transactions. Keep explicit migration verification. Paired measurement and final validation are still in progress.
Route retained existing-state writer coverage through the host-owned worker project, preserve first-admission incompatibility refusal, and match the final deletion-authority contract. Keep the gateway test under its inherited line count by moving existing pure fixture helpers. Regenerate assertion allowances without adding production assertions.
Include the thirteen transitive admission modules required by the native wrapper import-closure proof. Carry the existing birthtime through the worker validation fixture to preserve its physical-file identity.
Merge current main and preserve its optional settlement-only receipt delivery through the extracted owner. Keep the worker refusal error with the leaf contract to stay within the existing admission line cap. End the marker-free read-only fixture transaction normally; dedicated rollback and explicit revocation coverage remains unchanged.
Preserve snapshot-local reuse without freshness queries, publish dedicated archive writes, and remove Workboard polling. Retain native authority and settlement boundaries. Checkpoint reviewed corrections and focused regression repairs; final integrated proof remains in progress.
|
🦞👀 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. |
|
Landed as 1d76f57, verified on The final push only resolved the test-file conflict while merging main: it kept the incognito-placement case and the receipt-aware writer. All 55 focused tests across three files passed (234.53s wrapper time), and the conflict resolution received a clean P0/P1 review. The published-driver update cell remains valid and was reused for this test-only integration. Final-head CI finished with 124 successful jobs, 21 skipped jobs, four independently inherited failures, and the downstream aggregate failure. It was not green:
The relevant failing inputs are unchanged by the PR; security-fast, Security High checks and security-sensitive review succeeded. No failed job was rerun. Used the explicitly approved inherited-CI exception and head-pinned REST squash fallback after native merge returned HTTP 405 and native recovery rejected its preserved historical capture. The squash preserves the native title/body and human attribution, with no agent trailers. |
Stacked on #167739 (
dbasync/checkonce); this PR must land after it.What Problem This Solves
Chat turns repeatedly query SQLite freshness even though the Gateway owns the databases and their writes.
User Impact
Reduces warmed-turn all-thread SQLite statements from 1,074.6 to 867.9 (−206.7, −19.2%) and named worker requests from 386.9 to 366.5. Stored schemas, durability, retention, permissions, and live effect-boundary checks are preserved. The lane meets its ≥200-statement reduction target; the broader under-500 budget remains unfinished. Outside processes must route writes through the Gateway or run while it is stopped; remaining built-in direct writers are listed below as follow-ups.
Why This Change Was Made
The existing physical-database admission owner now publishes a shared write revision before releasing native write custody. Cached rows consume those in-process publications; an unsettled or unknown writer disables reuse. This replaces runtime
data_versionqueries without adding a second broadcaster, persistent state, or another worker request per read. Schema admission remains once per physical database per process; migrations and explicit repair retain their checks.Session, ACP, profile, pairing, voice, auth, and transcript-index caches retain their owning invalidation boundaries. Multi-statement reads keep consistent snapshots, single-statement reads use autocommit, and request-owned nested work reuses its existing transaction. Native/SDK nested rollback behavior remains.
Workboard can have multiple same-process stores through private runtime registries. Its retained lists and board revisions now consume the existing physical writer token through one narrow
sqlite-runtimere-export. That Workboard host-facade observation adds no SQL or worker request. Reads check the token before reuse and publication; an unsettled or changed token leaves an ordinary read uncached at its original revision, without replaying a mutation, reporting a new read failure, or polling. The one-second foreign-change timer and private data-version request are removed. There is no new SDK subpath or invalidation owner.TEMP-table DDL revokes connection-local facts while preserving physical MAIN schema admission. The classifier only treats explicit TEMP creation/qualified table deletion as local; ambiguous or mixed DDL remains conservative. This prevents local staging-table cleanup from triggering another MAIN validation while preserving rollback and custom-trigger invalidation.
Cache and statement ownership
The complete task inventory combines core, sessions, ancillary state, envelope, Workboard and outside-writer audits. It distinguishes same-process writer completeness from unsupported concurrent outside-process SQLite edits.
Evidence
Three alternating pairs passed all normal workload assertions and complete SQL/thread conservation. Every phase’s SQL median decreased, and all candidate/base median duration ratios are ≤1.017. No tolerance or combined-window exception is required. Measurement base:
cdb5143a0e03ac94ca9fb04982165bc792aba8a7; candidate runtime:4f4b116ec9c8a8ce053192895af2d83297ecd90f. The laterfc4469873e50commit only annotates the Workboard promise with its existing return type; type-erased JavaScript is identical after normalizing whitespace and optional trailing commas. The shared workload is unchanged, with the same host/runtime and alternating M,C,M,C,M,C order. Earlier diagnostic runs are not used as the median gate. Runtime data_version statements are zero in every candidate phase. The workload has no independent maintenance phase; the tables identify an overlapping maintenance subset from affirmative stack provenance.Published-driver × candidate update cell: pending (lander), per lane proof split. No persisted schema or version change.
Statement, request, envelope, maintenance, and attribution tables
Cells are base → candidate, median [min–max]. Warmed rows are medians of each run’s ten-turn mean. MAIN is Gateway thread 0. Canonical requests include resource-close; all named sends add admission metadata, stage handshakes and legacy admission requests, and do not claim to count every IPC message.
Statements
Requests
Admission requests
Probes and transaction statements (all threads)
Maintenance subset (existing phase placement)
The unchanged harness has no standalone maintenance phase. This subset counts only affirmative native/request stack provenance for scheduler, timer, checkpoint, recovery, pairing, retention, plugin cleanup, memory sync, idle close, or a named maintenance command. It excludes generic unbound/background and unassigned work. SQL-linked IDs are a lower bound on related canonical requests: zero-SQL sends are absent, and IDs are deduplicated within each window. This subset overlaps the phase totals above.
The following unambiguous maintenance commands also have complete canonical-send counts, including zero-SQL sends, across the full workload:
Adjacent combined windows
These per-run sums are retained for timing-dependent phase movement; no combined window replaces the warmed-turn gate.
Exact warmed-turn delta reconciliation
For each metric, this decomposition uses the actual middle run on each side (or the two middle runs for an even count). Independent component medians cannot be added to reconstruct the median total. The full ledger identifies every normalized SQL statement and every request type; the grouped table below sums exactly to the reported delta.
Canonical request components
Metadata request components
Admission-stage components
Validity and scope
Every run retains normal harness assertions and complete phase/thread SQL conservation. All six runs use the same observed admission census hash. The full
phase-summary.mdremains the authoritative expanded table, including individual warmed turns, all MAIN transport components, and rollback statements.median-delta-reconciliation.csvprovides the exact component ledger;statement-site-summary.jsonretains native source stacks;maintenance-subset.jsonrecords the subset arithmetic.Positive request phases
First-turn canonical requests rise 353→367 while all named sends fall 748→716; retained memory publication/lease work shifts into that window, with lower whole-workload counts. Cron all named sends rise365→368: eight PR-caused shared-admission metadata sends replace one database.prepareWrite request and four associated stage sends. Shutdown rises17→19 from two new archive-worker admission exchanges. These are required process-authority transport, not claimed as timing noise or request savings. Every all-thread SQL phase median falls, so no non-turn SQL tolerance or combined-window exception is invoked. See positive-request-attribution.md for source paths, exact middle observations and complete component ledgers.
Remaining outside-writer follow-ups
Direct device-pairing bootstrap fallback, credential/auth commands, updater/backup coordination, Memory and Matrix CLI, native companion stores, and Workboard CLI registration/fallback need routing or exclusive offline custody. Workboard registration may prepare its database before selecting even a read subcommand. The inventory records exact call sites and preserves the task's bounded follow-up scope; no broad low-level refusal or parallel routing mechanism was added. These paths do not justify keeping runtime probes.
The remote Windows workspace lease database is a separate host lock primitive, not a writer to the Gateway's shared/agent database. The managed update helper's restart-sentinel writer does target installation shared state and remains explicitly covered by the updater follow-up and published-driver contract.
Recorded correctness proof
[]after sibling worker created a card: 1 failed, 5 skippedworkboard-sibling-red.log,workboard-sibling-green.logtemp-drop-red.log,temp-drop-green.logPost-review state verification passed all 18 metadata tests and 49/50 validation-cache tests. The remaining fixture incorrectly expected an empty BEGIN/COMMIT to expire admitted schema facts. After correcting that expectation, the exact test passed (0.588s test; 23.19s Vitest; 58.16s wrapper; 59.57s shell wall), preserving its explicit revocation assertions. Evidence:
postreview-state-tests.log,postreview-admission-fixture.log. The initial combined run is not presented as fully passing, and no full-suite rerun is inferred from the focused correction.The third/final P2 review's Workboard finding was accepted as a wrong-result correctness repair and resolved with the red/green proof above. No fourth autoreview round was started, per review convergence. Its promise type inference error was subsequently fixed with an explicit existing return type, with no runtime change. These scoped results do not substitute for the final all-thread statement/request gate or exact-head aggregate checks.
Additional owner proof: all seven legacy migration race tests passed (37.64s Vitest, 48.59s wrapper). The deferred-integrity and coalesced async-admission cases also passed. The open-timing suite's canonical-index case failed because it expects 10ms of simulated registration time but observes 80ms (total 1150ms versus 1220ms); the exact failure reproduces on the pinned
cdb5143base. The inherited ingress-listing and WAL row-decoding failures are recorded separately. None is counted as a passing suite. Local test costs are recorded; CI seconds are unmeasured.Madge: zero cycles. Knip files/dependencies: passed. After the Workboard type correction, the full changed check passed every preceding guard and typecheck, including T1 no-growth, production core and extensions, and both test graphs. Its final production dead-export scan reports the untouched
src/infra/sqlite-worker-broker-reply.ts: settleFailedSqliteWorkerJobs; the same scan fails with the same single export on the pinnedcdb5143parent. That parent-only failure is recorded under the stacked-base/inherited-failure policy; the lane does not change the file or its callers. Public SDK diff passed with digest0add8078: zero entrypoint or top-level export/signature changes, 148 reachable-only changes. The new helper re-export belongs to the private first-party SQLite facade; no released public freshness API was removed.Change size and remaining proof
Relative to the integrated check-once base
cdb5143a0e03, candidatefc4469873e50changes:The production growth keeps receipt publication, active-writer custody, corruption revocation and accepted-work settlement with the existing admission lifecycle. It removes the old foreign-observation implementation instead of adding a parallel owner. Test growth mainly proves worker-to-reader invalidation and the native settlement/cleanup boundaries; retained compatibility and authority cases remain covered.
P2 follow-up: SDK documentation currently describes the write-token helper as request-free broadly. That statement is proven for Workboard's host facade; arbitrary worker contexts may use the helper's existing metadata exchange. Scope the wording in a follow-up; no runtime behavior or proof assertion depends on the broader wording.
The paired SQL proof, source/request attribution, inventory, focused test costs and static evidence are complete. Two unmatched startup target sends per run remain included in the request counts on both sides; their target attribution is unknown and they contribute no claimed saving. CI seconds are unmeasured. The full local check result is the inherited dead-export failure described above, not an unqualified green result. The published-driver update cell passed on the final candidate; see the landing verification below.
Focused test groups and measured local wall time
focused-7-worker-protocolfocused-7-schema-policyfocused-7-archivefocused-7-subagent-storefocused-3-corrected-corefocused-5-authfocused-5-canonical-readinessfocused-4-workboardintegrated-coreintegrated-sessionsintegrated-archiveintegrated-state-fixedtest-extractionsworkboard-sibling-greentemp-drop-greenpostreview-admission-fixtureEarlier groups are reused proof for unchanged behavior, not relabeled as final-head whole-suite runs. Successful owner files within failed aggregates and every original failure remain recorded in the local proof ledger. CI seconds are unmeasured; no combined grand total is claimed across overlapping suites.
Landing verification (reviewed head b67d735)
Merged main without conflicts and repaired its new migration-witness caller to use the existing read-snapshot owner after removal of the old pinned helper. The two-line repair received a clean focused P0/P1 review. Final-candidate Testbox proof: migration preservation and canonical validation passed (43.83s), and the formerly timing-out stale-geometry E2E passed (19.39s) after incorporating main's session metadata fixture repair.
The published-driver update cell passed on Testbox run 38047927911: published 2026.9.9 → candidate 2026.9.9, update exit 0, readiness 200, running version, durable state and incognito checks passed. Candidate package SHA256:
e9345b4ef2a1cc59d285e4d7303b33855ca9d6ef9488701000764c6b1a507cd9. The source receipt binds the tested tree to this head.CI for b67d735fd606, run 38048756808 completed with seven inherited failing test jobs; it is not green. The concurrent main run 38048680925, at
b0e5f302dd8d, independently shows the same cold-recall error (job 114203388563), scoped-discovery call count (114203388137), worker-placement evidence mismatch (114203388385), collaborator scroll (114203387187), position rail in both themes (114203387147), and native navigation geometry (114203387133). All failing test inputs are unchanged; the entire UI tree matches the tested main baseline.The seventh failure,
package-openclaw-for-docker/ “loads from a trusted harness checkout without installed dependencies,” independently reproduces on current mainc03681e7460c7: the copied fixture omitsscripts/lib/managed-cleanup-handoff.mts, producing the sameERR_MODULE_NOT_FOUNDbefore argument validation or database code. Command:pnpm test test/e2e/qa-lab/runtime/package-openclaw-for-docker.e2e.test.ts --maxWorkers=1 -t 'loads from a trusted harness checkout without installed dependencies'(66.50s Vitest / 73.41s wrapper). The fixture and direct script inputs match the CI baseline. No jobs were cancelled. These failures use the explicitly authorized native inherited-failure admin exception; required security and review gates remain enforced.Main integration (head 6ac9f28)
Merged main
e3415ea8c554by merge commitfaa09b825b293, resolving the admission-relay extraction without restoring freshness probes. The five-file integration passed focused P0/P1 review. Blacksmith Testbox leasetbx_01m4jv5kbxjtgh573e98z54kcjverified source tree0745a5c648a4a42516812b002097c06f463847ad: 88 tests across six admission, timeout, attachment, lease-heartbeat, and archive files passed in 81.13s across two shards. The lease is stopped. The earlier published-driver update pass is reused for this conflict-only integration.Commit
6ac9f2841de4applies the formatter-required import order in the archive worker; the single-file format check and focused P0/P1 review passed. CI run 38051402056 completed with 123 successful jobs, 21 skipped jobs, six failing test jobs and the downstream aggregate failure; no jobs were cancelled. The six failures are the cold-recall error, scoped-discovery call count, worker-placement evidence mismatch, collaborator scroll, position rail and native navigation geometry independently observed in main run 38048680925. The failing test inputs match the tested main baseline. The prior packaging-fixture failure is fixed by the incorporated main changes and absent from this run. Current-head CI remains red under the explicitly authorized inherited-failure exception.Native admin admission accepted the recorded CI attribution and enforced review/security evidence, then GitHub rejected the squash request with HTTP 405: “Base branch was modified. Review and try the merge again.” The documented same-head recovery is currently blocked by
Prior-CI admin admission: provider rejection requires exactly the expected captures: the preserved capture from the retired auto-merge attempt is not included in the validator's expected set. Both captures and the retained outcome are preserved; no direct merge or capture removal was used. GitHub now also reports a conflict insrc/gateway/server-worker-placement-session-target.test.ts. The PR remains open at6ac9f2841de4; no further branch changes have been made while native recovery is blocked.Final landing (head 379de23)
Landed as 1d76f57, verified on
origin/main, from head379de23edd800bb6bbf19d298aa6965852c174df.The final push only resolved the test-file conflict while merging main: it kept the incognito-placement case and the receipt-aware writer. All 55 focused tests across three files passed (234.53s wrapper time), and the conflict resolution received a clean P0/P1 review. The published-driver update cell remains valid and was reused for this test-only integration.
Final-head CI finished with 124 successful jobs, 21 skipped jobs, four independently inherited failures, and the downstream aggregate failure. It was not green:
7b125134f3860743c55696b3f273ed82abe535dc, usingOPENCLAW_VITEST_RUNTIME=bun node scripts/run-vitest.mjs src/agents/sandbox/sdk-state-owner.process.test.ts --maxWorkers=1. It failed on new.pilecompiler-cache entries; macOS usesLibrary/Caches/bun, while Linux uses.bun/install/cache. Test 3.251s; wrapper 45.21s.SessionTranscriptColdErrorunknowninstead ofunknown/current/absentThe relevant failing inputs are unchanged by the PR; security-fast, Security High checks and security-sensitive review succeeded. No failed job was rerun. Used the explicitly approved inherited-CI exception and head-pinned REST squash fallback after native merge returned HTTP 405 and native recovery rejected its preserved historical capture. The squash preserves the native title/body and human attribution, with no agent trailers.