Skip to content

improve(sessions): reduce repeated database reads during chat turns - #168316

Merged
steipete merged 42 commits into
mainfrom
dbasync/w11entrycache
Oct 10, 2026
Merged

steipete merged 42 commits into
mainfrom
dbasync/w11entrycache

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #167965

What Problem This Solves

Warmed chat turns repeatedly acquire the same session entry, participant projection, and membership through SQLite workers. This change removes repeated statements and worker requests while preserving the existing writer and authority owners.

User Impact

No schema, stored-data, permission, retention, or durability change. On an admitted database, a simple cold entry read uses one statement; an eligible warm read sends no worker request and executes no SQL. Effects retain their current live-authority checks, and writers reread authoritative rows inside their synchronous write transaction.

Why This Change Was Made

Standalone reads, admission/writable reads, and admitted cohorts share bounded physical-database facts in the entry reader. Every read still joins its existing writer FIFO. Pending invalidation preserves a non-readable slot so the committing writer can install its sealed postimage before observers; incomplete or superseded coverage falls back to a fused read. Native write revisions fence raw in-process changes without foreign-commit probing. Physical facts use the consuming actor's actual live generation, and partial snapshot reads cannot discard already known full snapshots at the same revision.

The fact set retains at most 128 keys and 8 MiB of serialized fact data per database, across at most 32 databases. Optional full receipt enrichment is also bounded at 8 MiB for the complete envelope and is shed without changing required receipts. Display projections do not retain saved prompts. The fused query validates case-folded guard rows, while selected listings retain internal-row filtering and pending-row validation. Transcript, lifecycle-header, parent-discovery, Board-related row facts, and other composite snapshots stay with their existing worker owners. Owner-column availability consumes admitted schema definitions instead of repeating table-info queries per handle.

Evidence

Three alternating base/candidate pairs reduce the warmed-turn median by 200.1 SQLite statements and 39.7 logical worker requests. The exact/actor/plain entry-reader families directly account for 176.5 statements and 33.5 requests of saving. The remaining workload difference includes background frequency and phase placement; it is not all credited to the entry cache. The measured candidate remains at 715.5 statements per warmed turn, so this change makes progress toward the broader under-500 target.

Measured base: 9a1a08d7f398f81358430caf28ccce615f567a7b. Measured candidate: 71a50c943078be6e48aedfe61e2ad7e4d864e5ee. The later 0951d33ead3cbceea4a49aeb54efaba441ea17f2 changes only storage documentation, and 67219158381ba splits the existing cohort lifecycle tests. c12504f65c82d replaces the worker’s private string validator with the shared readStringValue/expectDefined helpers; it preserves accepted values and submitted SQL, while naming the invalid field in errors. The final 713c5b0a95ce8 keeps query-builder methods bound to their receiver and makes an existing undefined return explicit; neither change alters SQL or public types. Runs used the same macOS arm64 host, Node 26.10.0 and SQLite 3.53.4 in the order base, candidate, base, candidate, base, candidate. Earlier exploratory runs are excluded.

The unchanged synthetic workload uses a local mock provider, isolated state, signed Gateway WebSocket pairing, 13 top-level turns plus a child, control-plane RPCs, scheduled cron, committed compaction and graceful shutdown. Each warmed observation is the mean of ten complete turns, including their settling windows. Tables show median [min–max] across three observations per side.

Counts include successful native exec/get/all/run/iterate executions on every thread and helper process, including transaction controls, repeated prepared-statement executions, schema work and background activity. Multi-statement exec calls are split into statements. Prepares and failed executions are reported separately; SQLite trigger/FTS internal instructions are not counted as extra submitted statements. Logical requests include zero-SQL resource cleanup; continuation/admission transport frames are separate.

Statements by phase

Phase Base all SQL Candidate all SQL Δ SQL Base MAIN SQL Candidate MAIN SQL Duration C/B
Startup 3,104 [3,103–3,104] 3,104 [3,073–3,105] 0 1,980 [1,980–1,980] 1,980 [1,955–1,980] 1.135
Connect / settle 248 [223–254] 394 [236–539] 146 44 [44–44] 69 [44–70] 1.426
First session + first turn 1,820 [1,811–1,872] 1,317 [1,240–1,690] -503 78 [73–79] 77 [60–79] 0.839
Warmed turn 915.6 [851.7–920] 715.5 [708.7–750.4] -200.1 18.1 [11–19.7] 14.7 [14–19.4] 0.905
Second session + tool parent + child 3,347 [3,318–3,501] 2,945 [2,861–3,149] -402 106 [106–127] 125 [104–159] 0.719
Control plane 20 [19–181] 22 [20–73] 2 0 [0–17] 0 [0–2] 1.014
Scheduled cron 1,321 [1,247–1,519] 857 [818–1,192] -464 166 [156–190] 24 [17–162] 1.001
Compaction 330 [328–342] 269 [269–273] -61 24 [24–25] 24 [24–24] 0.993
Shutdown 126 [121–132] 122 [115–122] -4 66 [63–69] 66 [66–66] 0.921
Entire workload 19,570 [18,986–19,708] 16,160 [16,047–17,344] -3,410 2,649 [2,601–2,679] 2,492 [2,431–2,735] 0.892

All median candidate/base duration ratios are below 1.5; the warmed ratio is 0.905. These instrumented durations on a busy host support the count comparison and are not an uninstrumented latency benchmark.

Logical requests by phase

Phase Base all requests Candidate all requests Δ requests Base MAIN requests Candidate MAIN requests
Startup 69 [69–70] 70 [69–70] 1 69 [69–70] 70 [69–70]
Connect / settle 42 [37–42] 44 [36–75] 2 42 [37–42] 44 [36–75]
First session + first turn 350 [338–353] 268 [239–320] -82 348 [336–351] 267 [238–319]
Warmed turn 218.5 [203.8–220.7] 178.8 [177.6–190.5] -39.7 218.5 [203.8–220.7] 178.8 [177.6–190.5]
Second session + tool parent + child 748 [732–784] 693 [665–743] -55 748 [732–784] 693 [665–743]
Control plane 6 [5–38] 8 [5–18] 2 6 [5–38] 8 [5–18]
Scheduled cron 273 [250–331] 180 [166–257] -93 273 [250–331] 180 [166–257]
Compaction 83 [82–86] 73 [72–74] -10 83 [82–86] 73 [72–74]
Shutdown 16 [15–20] 16 [15–18] 0 16 [15–20] 16 [15–18]
Entire workload 3,788 [3,653–3,828] 3,113 [3,109–3,441] -675 3,786 [3,651–3,826] 3,112 [3,108–3,440]

MAIN SQL means execution on Gateway thread 0; MAIN requests means requests sent from that thread. All-thread totals retain worker/helper activity.

Direct entry-read attribution

The three entry families combined fall from 220.4 [218.4–220.8] to 43.9 [43.7–44.6] SQL and 51.4 [51–51.6] to 17.9 [17.7–18.6] requests per warmed turn. These combined savings are computed from each run’s combined counts before taking medians. Independently calculated component medians need not sum to the combined median.

Request owner Base SQL Candidate SQL Base requests Candidate requests
session-exact-entries 133 [133–133.2] 23.4 [23.4–23.6] 26 [26–26] 9.4 [9.4–9.6]
session.entry.read 74.8 [73.4–75.3] 17.5 [17.1–17.9] 19.4 [19–19.6] 5.5 [5.1–5.9]
session-entry-read 12.1 [12–12.8] 3.2 [2.8–3.3] 6 [6–6] 3.2 [2.8–3.3]

Warm hits remove complete requests. Cold facts combine entry, participants and members in one statement. Within those three families, the native statement classes change as follows; retained composite reads still own their snapshots.

Statement class Base median / turn Candidate median / turn
BEGIN + COMMIT 80 12
Standalone participant SELECT 48 5
Other entry SELECT 51 8
Standalone membership SELECT 11 1
Canonical main-key SELECT 26.2 3
Fused entry/participants/members SELECT 0 12.9
Other retained reads/setup 4 2

These categories are mutually exclusive within the entry families. The main-key saving comes from removing entry-read requests that previously performed that lookup; it may overlap savings from independent optimizations measured against other bases.

Phase placement and retained work

Connect rises by 146 statements at the median. The largest contributor is deferred memory schema.admit: connect counts change from [0, 0, 0] to [129, 130, 0], while first-turn counts change from [130, 130, 130] to [1, 0, 130]. Prewarming and connection/lease/admission work also move with startup. The complete startup window decreases in every pair:

Pair Base startup + connect + first turn Candidate startup + connect + first turn
1 5,178 4,784
2 5,162 4,883
3 5,199 5,031

Control-plane SQL rises by 2 at the median, within the non-turn allowance. Control + cron decreases in all pairs (1,267→840; 1,538→877; 1,502→1,265), as does compaction + shutdown (468→391; 451→384; 460→395). First-turn, warmed-turn and whole-workload raw medians decrease.

Two candidate runs retain 33 and 32 additional preparation statements in the first warmed turn. The memory vector table’s real DROP/CREATE operates on the live agent database in that phase in those runs; in the base runs and the third candidate run it operates on a reindex staging database during first-turn. The writer prepares again only for missing/revoked schema proof, explicit readmission, a preparation journal or initial native admission. This is consistent with required validation after owned DDL, rather than an unconditional per-open check. Whole-workload database.prepareWrite counts are base [66, 66, 65] and candidate [98, 98, 66]; the additional work stays in all totals. Phase, physical-target and source-stack evidence supports this attribution; exact cross-thread ordering within a phase is not claimed.

The candidate also executes one additional foreground transcript-accounting history-page request and 11.2 [10–11.6] statements per warmed turn through readSessionLogSnapshot → readSessionTranscriptAccountingAsync. This cost is included in the net result. The retained stack ends at that shared reader, so the exact triggering caller branch and input difference are unresolved; it is not attributed to background variation or a proven loss of cached usage fields. Old and fused reads share parseReadableSessionEntryData and its decoder chain; full receipt postimages decode the persisted entry JSON and preserve usage fields. The tail query also serves turn-taint checks, so its presence cannot identify a usage fallback. Other median differences include memory-domain and plugin-state activity; the entire 200.1/39.7 reduction is not presented as a deterministic entry-cache saving.

Regression proof and limits

pnpm test src/config/sessions/session-entry-read-ordered.test.ts --maxWorkers=1 passes 6/6 tests on the candidate: 13.99 s wall time, including cached worker preparation; the six test bodies total 3.451 s. It covers zero-dispatch reuse and eviction across agent stores, pending-patch FIFO visibility, full snapshots surviving a partial refresh, native/worker participant and membership changes, and writer-ordering guards.

The new zero-dispatch regression was copied unchanged onto the pinned baseline and selected with --testNamePattern 'retains exact reads without dispatch'. It fails at the intended assertion: expected 0 worker requests, observed 3 after repeated reads. Exactly one test ran, with five skipped: 1.107 s test execution, 48.65 s wall time including cold worker compilation. The baseline test file was restored to its exact original bytes afterward. These differing compiler-cache states are not used for a test-speed claim. CI execution seconds have not been measured.

All 78 top-level turns, six child runs, six cron completions, six compactions and six graceful shutdowns passed. Calibration independently produced eight native calls, two prepares, seven successful statements and zero failures on MAIN and a worker in every run. Native SQL and request-linked accounting conserve exact phase/thread/SQL totals. No data_version probes, first-turn SQL failures or warmed SQL failures occurred.

Shutdown-only BEGIN IMMEDIATE: database is locked failures were retained separately: base [0, 1, 5], candidate [1, 0, 1]. They are excluded from successful-statement totals under the same counting contract on both sides. The fixture uses synthetic data and does not establish behavior for incognito, Talk, production-sized histories, arbitrary plugin/tool mixes, or uninstrumented latency. Statement counts also do not measure scanned rows, decoded bytes or write amplification.

The published-driver × candidate update cell is pending for the lander. The Knip production scan reports the same unused broker export on the exact baseline and candidate, with no candidate-only findings; details follow below. Compact summaries, exact statement/request stack counts and workload receipts were retained after verification; raw traces and synthetic fixture databases were removed under the campaign disk policy. No evidence archive is retained.

Review and source scope

Originally stacked on #167965; the parent has landed and this PR now targets main. The lander integrated main in 1d4f42e8 and updated the wrapper inventory in 7294e003. The measured baseline includes the initial integration of main and its retired-read-helper repair. Main has not been repeatedly merged during measurement. The parent branch has independently advanced; this proof is pinned to the baseline and candidate above, not the moving branch tip.

Three P2 Codex autoreview rounds completed, with the third reporting no actionable P0–P2 finding in its supplied scope. The third round reviewed f7b3e897d39a; subsequent changes include the worker-only filename, receipt/cache correctness fixes and regression updates, documentation, the test-only cohort lifecycle split, the shared string-validator replacement, and the final lint corrections. This is not an exact-final-head review claim. No fourth round was run under the requested three-round convergence rule.

Lane source delta: production +1,096/-147 lines; tests +1,083/-471; documentation +26/-0. Test counts include the intact cohort lifecycle test-file split. Most production growth is the bounded shared facts owner, the fused statement, and receipt completeness handling. There is no schema or dependency change.

Final validation

Focused owner coverage passes: 20 read-only worker tests, 3 cohort tests (including one-statement cold facts), 32 replacement-receipt tests, 24 entry-worker tests, schema-fact regressions, and the repaired logical-reader cases. The final complete ordered-reader suite passes 6/6 as detailed above. Early failures exposed a folded-sibling guard and stale fixtures for the new reply shape; the guard was preserved and those cases were rerun after correction. The Gateway-method mock typing failure was repaired and its targeted typecheck passed.

Test costs are measured wall times, including build/import overhead: the five-owner group took 201.59 s, the corrected entry-worker file took 105.63 s, and the focused logical/ordered follow-up took 170.01 s on the loaded host. Those group times are not presented as individual-file or CI costs. The final ordered-reader file took 13.99 s; CI execution seconds remain unmeasured.

Local validation ran through the campaign proof semaphore against 0951d33ead3c, then T1, Madge, and SDK checks were repeated on Linux Testbox at c12504f65c82d. SQLite T1 passes at 707 → 707, with no per-file increases. Madge passes with 0 cycles. The SDK diff completes with no entrypoints added or removed and 148 reachable-only affected exports (no direct export changes), acknowledgement digest e1fe07b5976435c85c84c79a31510dcce8118d47b6d335cdc737107672613b03. The final lint correction preserves dependencies and public types, so the Madge and SDK results are reused.

Knip's production scan reports src/infra/sqlite-worker-broker-reply.ts: settleFailedSqliteWorkerJobs on both the exact measured baseline and candidate. The file and its broker caller are untouched by this lane; the candidate has 0 new Knip findings, and full-tree and script export scans pass on both revisions. This is confirmed inheritance from the stacked baseline, not a claim that current main has the same finding. The temporary baseline worktree was removed after the comparison.

The final changed-file check exposed test-only line-cap growth in session-logical-entry-read.worker.test.ts. The admitted-cohort lifecycle tests were moved intact into session-entry-cohort-lifecycle.worker.test.ts, preserving their assertions and per-suite isolated state. Both split suites pass on Linux Testbox: 12/12 cohort lifecycle cases in 24.789 s wall time, and 29/29 logical-reader cases in 31.677 s. The complete changed-file check then passed the early guards, formatting, database ratchet, core types, and all 27 core test typecheck graphs, before rejecting the worker’s private readString declaration. That declaration has now been replaced with existing shared normalization helpers, preserving whitespace, empty strings, rejection of non-strings, and the exact SQL paths. At c12504f65c82d, the cohort worker suite passed 3/3 in 26.462 s, core production types passed in 49.585 s, and the remaining planner-selected guards passed except two lint issues and the inherited deprecated-import finding described below. The final lint corrections retain the query-builder receiver and change a bare return to explicit undefined; at final head 713c5b0a95ce8, lint passes across all 40 changed TypeScript files (22.701 s), the cohort/schema suites pass 63/63 (20.011 s wall time, 5.38 s Vitest duration), and core production types pass (43.220 s). The coercion guard, line-cap guard, and SQLite T1 ratchet also pass. All candidate files matched their pinned Git blobs before and after execution. The published-driver × candidate update cell passed during landing; see the landing validation below.

The deprecated-API guard reports src/gateway/server-methods/agents.ts:2 for its direct config mutation import. The exact same file and guard blobs are present on the measured baseline; running the guard collector on that baseline file reproduces the finding. The file is untouched by this lane. The corresponding current-main file at b883658c8178ce1ea5dced8ffb6da60a612d66e1 no longer triggers the guard. This is inherited stack drift, not a current-main failure.

The changed-file proof is assembled from the complete early checks and all 27 test typecheck graphs, the final-head production typecheck and affected regressions, and the remaining commands selected by the repository's own planner. No claim is made that a single uninterrupted check:changed invocation returned zero: the inherited Knip and deprecated-API findings remain documented exceptions. The remaining guards cover coercion helpers, schema version, database-first stores, media helpers, runtime sidecars and cycles, webhooks, and pairing boundaries. Remote proof used the gated Blacksmith Testbox lease tbx_01m4ja56n47kdaq5tvjwqbx8je after local slot contention, through scripts/crabbox-wrapper.mjs; Testbox run. Wrapper command results and pinned source-byte checks establish the result; lease cleanup may cancel the enclosing Actions run.

The Testbox lease was stopped and its campaign remote slot released after proof. Compact evidence is retained for the pending lander update cell.

Active-writer read repair (1e2996333bbb6, f80ae10ef3663)

The integrated head 7294e0030ede5 failed Gateway history and reset cleanup because an entry read tried to acquire a read batch while its call path already held writer admission. The exact correlated-mirror history case was reproduced locally with Session read batch cannot reenter an active SQLite writer admission; the new owner regression failed on the pre-fix code for the same reason.

The session writer now lends its existing native execution scope to nested entry reads. Reads join the existing transcript preparation/append queue when present, otherwise the writer's accepted-read settlement queue. The plain reader uses the captured database with its existing projection/error codec, and the native operation remains synchronous. Reads inside a native callback dispatch on that callback's worker, so native failure can unwind before cleanup; reads before a native callback use the same retained executor. The writer drains accepted reads before releasing FIFO. The admission reentrancy guard and synchronous write transactions are unchanged, and cached postimages do not authorize writes.

Local proof on this repair, through the campaign proof semaphore:

  • 130/130 tests across 9 files, including all 7 ordered-reader cases, the exact history and reset failures, read-only/cohort readers, retirement, transcript admission, and replacement/receipt settlement. Group wall time: 323.49 s; summed Vitest duration: 286.87 s. The new active-writer regression took 1.201 s within that run. CI execution seconds are not measured.
  • Production typecheck and all 27 test typecheck graphs pass. SQLite T1 has no call-count growth against 7294e0030ede5; Madge reports 0 cycles.
  • All seven changed TypeScript files pass lint. The remaining schema, coercion, deprecated-API, database-first, media, sidecar, import-cycle, webhook, pairing and documentation-format guards pass. Knip reports four unused exports in three unchanged files: POST_ACTIVATION_INSPECTIONS_STEP, resolveSessionConversationStub, resolveSessionTargetStub, and the default export in tools/solid-lint/index.mjs. The files and Knip configs match main 379da8e456922; no finding is in this repair.

The 130-test run, 27 test typecheck graphs, and Madge scan cover 1e2996333bbb6. Follow-up f80ae10ef3663 only renames shadowed callback variables and returns the same runtime-target object directly; lint and production types pass after that cleanup. No further behavior change is claimed.

The SDK comparison 7294e0030ede5 → 1e2996333bbb6 completes with 0 added/removed entrypoints and 0 direct export changes. Its 148 reachable-only affected exports come from the added internal session.entry.readResult operation and optional captured-database parameters; existing call signatures remain valid. Acknowledgement digest: 758db11d8db44fd2ec80c7c62cb1b514f50677e5a4fd675c479dfac242065c20. The final naming/return-expression cleanup does not alter those declarations.

check:changed --base 7294e0030ede5 passes its changed-file line and suppression limits, then stops at the inherited environment budget (456 vs 455). The same source census fails on the incoming head and main 379da8e456922. The broader branch check also reports the existing session-entry-read-runtime.ts line-cap increase (736 to 744, cap 700); this repair does not change that file. The existing typecheck-boundary advisory is 722 UI E2E roots vs 720. Remaining planner-selected commands were run separately, rather than claiming one uninterrupted green check:changed run.

This repair adds +179/-29 production lines, 54 test lines, and 6 documentation lines. The growth is the writer-scope adapter, accepted-read settlement, and the synchronous plain-reader operation; it does not add a parallel cache. Earlier SQL tables remain evidence for their named measured revisions; no new SQL savings are claimed for this correctness repair. The published-driver × candidate update cell passed during landing; see the landing validation below. No fourth P2 review round was run under the coordinator's review-convergence rule. These are additive commits; the actor-lane stack history is preserved.

Landing validation

Main was integrated with additive merge commits, without rebasing the actor-lane stack. The first integration exposed a metadata-postimage interaction: full entry facts must retain full snapshots instead of substituting the display-only writer postimage. Commit 8e4c029e4de4 fixes that distinction. The existing aggregate-snapshot receipt regression reproduced the issue; seven focused suites then passed 84/84 in 80.87 s wall time (79.27 s Vitest). A scoped independent review found no P0/P1 finding.

The published 2026.9.8 driver upgraded to the packaged candidate at tree 104b8141e63c5b141a2a816dfb069402d5fc24ab: update finished, readiness returned HTTP 200, the running candidate version was verified, and durable and incognito sessions survived. This ran on Blacksmith Testbox. The later merge commit d9f89b6b70e5 only resolves main's admission-record conflicts, preserving its host-snapshot revision checks in the shared merge owner. The update-cell pass is reused under the coordinator's conflict-only rule.

The conflict-only head d9f89b6b70e56d4aed142acdb3ad9419f7bad700 passed all five requested suites (schema facts, admission workers, session-turn planning, replacement receipts, and replacement workers) in 65.19 s wall time over two Vitest shards on Blacksmith Testbox. The configured pre-commit secret/content hook was independently run against the exact merge tree and passed. CI execution seconds remain unmeasured.

Landing validation findings (2026-10-10)

The lander stopped at d9f89b6b70e56d4aed142acdb3ad9419f7bad700. Final-head CI completed with 19 failed test jobs and a failed aggregate gate.

A same-host, same-runtime comparison of src/gateway/session-observer.worker.test.ts passed 14/14 tests on the exact merged-main parent 9c37dbf3e90b1717b7013b0a47c64e25300c5b55 (86.20 seconds), but failed 5/14 on this PR head (71.54 seconds), matching CI job 114266984319. Three companion-snapshot tests resolve instead of rejecting after the read owner changes; the dormant-read test reports Dormant read did not enter its retained worker; the worker-read count test receives 1 where at least 2 is expected. These five failures are resolved by the worker-fixture repair below; they were not treated as inherited failures. No assertions were weakened.

The plugin lifecycle-admission failure was independently reproduced on recent main in Testbox (18 passed, one identical failure); that finding does not exempt the PR-specific observer failures. The other failed jobs remain unclassified. No CI/admin override or REST merge was used. The focused postimage repair, conflict proof, and published-driver update cell recorded above remain valid.

Observer worker-fixture repair (79aee0b5f96f)

The unchanged 14-case observer worker suite reproduces the lander result at d9f89b6b70e56: 9 passed, 5 failed, with 93.94 s Vitest duration on local Node 26.11.1. These five failures come from test interception below the new cache boundary: three companion tests never perform their injected rewrite/close, the dormant test never enters its worker gate, and the dispatch-count test requires repeated worker requests that warm facts intentionally eliminate. They are not evidence of missing committed-entry notifications.

The existing publication owner already installs facts, prepares projections, and then sends each public notification. The repair leaves that owner and all production code unchanged. Worker-fault tests invalidate the exact physical-store/session key before arming their read hook. The off-main-thread dispatch test explicitly selects cache misses so it still exercises actual worker requests. Every existing assertion remains; the companion cases additionally assert that the injected hook ran exactly once. No new fence, handshake, cache bypass in production, or SQL is added.

Focused local proof ran through the campaign proof semaphore:

pnpm test src/gateway/session-observer.worker.test.ts src/config/sessions/session-entry-read-ordered.test.ts src/config/sessions/session-row-changes.test.ts --maxWorkers=1

27/27 pass: all 14 observer cases, all 7 ordered-reader cases, and all 6 committed-publication cases. Total runner wall time is 49.95 s; observer Vitest duration is 21.50 s, and the ordered/publication shard is 22.74 s. The ordered suite retains zero-dispatch warm hits, receipt visibility behind a pending patch, cross-agent isolation, eviction, membership/participant changes, and active-writer ordering. Publication cases retain commit/rollback, projection-before-public-notification, and exact-key delivery assertions. CI execution seconds are unmeasured.

An intermediate fixture attempt omitted physical store provenance from the invalidation and remained 10/14; the final fixture supplies the actual database path and passes all cases. Logs: observer-before.log, observer-focused.log, and observer-check-changed.log in the lane proof directory.

The repair changes one test file (+31/-11 test lines; 0 production lines). Production SQL, worker-request behavior, SDK surface, schema, durability, and retention are unchanged; prior measurements and update-cell evidence remain pinned to their documented revisions. No fourth P2 review round was run, following the coordinator's review-convergence rule. The other failed CI jobs in the landing record remain outside this focused repair and are not claimed green.

check:changed --base d9f89b6b70e56 passes its conflict, line-cap, suppression, assertion, SQLite T1, timeout, mock-export, format, wrapper, dependency, and plugin-boundary checks, then stops at the inherited UI E2E root budget (722/720). The root-budget owner/configuration match the exact main parent 9c37dbf3e90b; both trees contain 722 matching roots. Newer main fixes that split in 471035c7b7c8. The changed Gateway test graph was therefore checked directly with node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.gateway-root.json --incremental and passes (27.82 s). Coercion, deprecated-API, and changed-file Oxlint checks also pass.

The remaining dead-code scan has 0 production unused exports and reports three inherited script/test exports: tools/solid-lint/index.mjs: default, and resolveSessionConversationStub / resolveSessionTargetStub in src/agents/tools/sessions-channel-fixture.test-support.ts. These files and the relevant Knip configurations match the exact main parent; newer main addresses them in 61621f7b5941. They are outside this one-file repair. No additional main integration was performed. The complete check:changed command is not claimed green.

CI repair before landing (2026-10-10)

The red checks-node-changed shards on 3006bca95170 came from four causes:

  • Fixtures that observed worker reads (question/session access, chat metadata, session sharing, own-run, model-account, steering, binding authority, exec preparation, runtime agent). Warm entry receipts now answer repeat reads in memory, so these tests invalidate the session facts before the read they inject faults into. The foreign-connection session-sharing case is removed: under the single-owner rule (improve: reduce SQLite work during chat turns #167965), outside writers go through the Gateway.
  • Cold snapshot serialization in session-entry-patch (fixed in the entry-cache projection, 2063b0ba8545).
  • Cron revocation fixture: it closed the database from inside the read's dispatch hook, so the close inherited the read's writer context. It now runs the close outside it, the same way the existing session-sharing test does.
  • Product fix (a813d5c3ce3a): standalone cached reads took a foreground writer admission around the whole worker read. A warm read of one session then waited behind an unrelated session's in-flight write, and writers waited behind reads (subagent-control.warm-preparation caught it). Retained facts are keyed by the committed write token, a hit re-checks the token, and installs are skipped when a commit lands mid-read. So the admission added ordering main never had, and no correctness. Reads inside an active writer still borrow it.

The borrowed-reader tool-authority case now expects no extra exact read, because admission already warmed the entry facts.

Inherited failures, which also fail on current main and are not touched here:

  • src/gateway/server-worker-placement-session-evidence.test.ts: ordinary directory discovery failures.
  • src/auto-reply/reply/get-reply-native-slash-fast-path.test.ts: admitted catalog model selection.
  • src/agents/harness/context-engine-transcript-cursor.test.ts: reconstructed terminal anchor.
  • The duplicate UI e2e import that failed check-lint-core was fixed on main in 48588a652222.

…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.
@clawsweeper

clawsweeper Bot commented Oct 10, 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 docs Improvements or additions to documentation gateway Gateway runtime extensions: memory-core Extension: memory-core labels Oct 10, 2026
@clawsweeper clawsweeper Bot added the rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. label Oct 10, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 10, 2026
Resolve the replacement-receipts test import to main's transcript test-support owner while preserving entry-cache receipt coverage. Conflict-only integration; keep stacked branch ancestry intact.
Warm entry receipts now answer repeat reads in memory, so the revocation and
config-reload cases invalidate the session facts before the read they observe.
The foreign-connection case is removed: under the single-owner rule outside
writers go through the Gateway (#167965).
…eads

The cron revocation case closes the database from outside the read's writer
context, and the borrowed tool-authority case expects no extra exact read
because admission already warmed the entry facts.
Standalone read-only entry reads took a foreground writer admission around the
whole worker read, so a warm read for one session waited behind an unrelated
session's in-flight write (and writers waited behind reads). Retained facts are
keyed by the committed write token and installs are skipped when a commit lands
mid-read, so the FIFO adds ordering main never had without adding correctness.
Reads inside an active writer still borrow it.
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 10, 2026
# Conflicts:
#	src/infra/sqlite-database-admission-record.ts
#	src/infra/sqlite-database-admission.ts
…mission

After the main merge, durable sessions capture identity with a synchronous entry
read before the first await, so waiting on the worker read spy never resolved
and the case timed out at 120 s. Main's version of the test is correct as is.
@steipete
steipete merged commit ea4693e into main Oct 10, 2026
164 of 171 checks passed
@steipete
steipete deleted the dbasync/w11entrycache branch October 10, 2026 22:21
steipete added a commit that referenced this pull request Oct 11, 2026
#168316 made session-entry-read.worker.ts statically import
session-accessor.sqlite-exact-read.ts for the synchronous readSessionEntryResult,
which broke the lazy-reader import contract in
session-history-read.imports.test.ts. The synchronous reader now lives in
session-entry-read-result.worker.ts: native writer operations import it directly
and the worker's async request path loads it lazily, as before.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…penclaw#168316)

Warmed chat turns repeatedly re-read the same session entry, participant projection and membership through SQLite workers. The entry reader now keeps bounded per-database entry facts, keyed by the committed write token and refreshed by in-process write receipts (single Gateway owner). Warm reads are answered in memory; cold reads still use one worker statement.

Measured on the synthetic turn workload (3 alternating pairs): warmed turn -200.1 statements and -39.7 worker requests; entire workload 19,570 -> 16,160 statements. No schema, stored-data, permission, retention or durability change.

Standalone cached reads stay off the writer FIFO, as the plain reader did. Reads inside an active writer borrow it. Test fixtures that inject faults into worker reads now invalidate cached facts first; the foreign-connection session-sharing case is retired under the single-owner rule (openclaw#167965).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
openclaw#168316 made session-entry-read.worker.ts statically import
session-accessor.sqlite-exact-read.ts for the synchronous readSessionEntryResult,
which broke the lazy-reader import contract in
session-history-read.imports.test.ts. The synchronous reader now lives in
session-entry-read-result.worker.ts: native writer operations import it directly
and the worker's async request path loads it lazily, as before.
steipete added a commit that referenced this pull request Oct 19, 2026
Read fresh session snapshots when observing the child Gateway. Retained exact-row facts introduced in #168316 use in-process write receipts and can retain the initial absence of main after a forced monitor has written its transcript.

Use an automatic-reply heartbeat prompt for the openclaw runtime instead of invoking its disabled structured response tool. Preserve the main-session poll and reply assertions and the foreground transcript isolation check.
steipete added a commit that referenced this pull request Oct 19, 2026
…oll (#176715)

* test(heartbeat): fix empty forced-monitor transcript reads

Read fresh session snapshots when observing the child Gateway. Retained exact-row facts introduced in #168316 use in-process write receipts and can retain the initial absence of main after a forced monitor has written its transcript.

Use an automatic-reply heartbeat prompt for the openclaw runtime instead of invoking its disabled structured response tool. Preserve the main-session poll and reply assertions and the foreground transcript isolation check.

* test(heartbeat): wait for settled internal completion results

Internal dashboard sessions require a final result. NO_REPLY starts bounded required-result recovery, so observing that row alone can snapshot an unfinished continuation. Request the completion marker and wait for no active run before validating the last reply. Keep the exact post-monitor foreground transcript assertion.

Offline loopback proof reproduced seven-to-eight transcript growth with one exec-completion input and one admitted run ID: NO_REPLY followed by required-result recovery. Main monitoring left the held foreground transcript unchanged. Returning the result directly needed one response and preserved the settled transcript across monitoring. See docs/concepts/messages.md silent replies contract.

Validation: gated loopback cases passed; targeted oxlint, oxfmt, diff check, and independent review passed. The existing source-reply-retry test command stalled during module collection and was stopped without a test verdict. The reported different live run ID was not reproduced offline. No live credentials or operator Gateway used.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
…oll (openclaw#176715)

* test(heartbeat): fix empty forced-monitor transcript reads

Read fresh session snapshots when observing the child Gateway. Retained exact-row facts introduced in openclaw#168316 use in-process write receipts and can retain the initial absence of main after a forced monitor has written its transcript.

Use an automatic-reply heartbeat prompt for the openclaw runtime instead of invoking its disabled structured response tool. Preserve the main-session poll and reply assertions and the foreground transcript isolation check.

* test(heartbeat): wait for settled internal completion results

Internal dashboard sessions require a final result. NO_REPLY starts bounded required-result recovery, so observing that row alone can snapshot an unfinished continuation. Request the completion marker and wait for no active run before validating the last reply. Keep the exact post-monitor foreground transcript assertion.

Offline loopback proof reproduced seven-to-eight transcript growth with one exec-completion input and one admitted run ID: NO_REPLY followed by required-result recovery. Main monitoring left the held foreground transcript unchanged. Returning the result directly needed one response and preserved the settled transcript across monitoring. See docs/concepts/messages.md silent replies contract.

Validation: gated loopback cases passed; targeted oxlint, oxfmt, diff check, and independent review passed. The existing source-reply-retry test command stalled during module collection and was stopped without a test verdict. The reported different live run ID was not reproduced offline. No live credentials or operator Gateway used.
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 merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant