Repository navigation
perf(agents): reduce repeated SQLite work during agent preparation - #168992
Conversation
… facts Reuse admitted model and cancellation facts, batch auth reads, keep outbox SQL worker-only, and replace relay read-then-write checks with guarded mutations. Sandbox effects consume committed registry facts. Retain released synchronous SDK and destructive cleanup contracts.
|
🦞👀 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: needs real behavior proof before merge. What this changesThis PR batches auth reads, moves outbox SQL into its worker, and reuses prepared session, sandbox, and worktree facts. Example: Agent preparation reads both persisted auth rows.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 6 items remain Keep this PR open for its useful performance work, but block merge on the remaining reservation regression. Exact-head CI confirms the previously reported hydration defect; the relay test-ratchet finding is fixed. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherAgent preparation consumes admitted session and database state, uses SQLite workers for persistence, and supplies model ownership and sandbox authority to execution. flowchart TD
A[Agent preparation] --> B[Admitted session facts]
A --> C[SQLite worker operations]
C --> D[Agent and shared databases]
D --> E[Committed registry facts]
B --> F[Model and sandbox effects]
E --> F
Technical reviewBest possible solution: Keep the worker cutover while allowing unchanged persisted reservations to hydrate without weakening replacement or unknown-settlement rejection. Do we have a high-confidence way to reproduce the issue? Current-main source shows repeated preparation reads, and exact-head CI independently confirms the introduced reservation hydration failure; no target code was run during this review. Is this the best way to solve the issue? The existing workers and publication owners are appropriate places for these reductions, but the facts guard must preserve cold reservation hydration and current authority at final effects. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 1598547552d6. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: The sandbox authority cutover needs final-effect validation; inspection found no concrete authorization bypass or supply-chain regression. EvidenceSecurity concerns:
What I checked:
Likely related people:
PR surfaceSource -42, Tests +164, Docs +15, Other +44. Total +181 across 41 files. Added test files: 2. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (5 earlier review cycles)
Reviewed October 11, 2026, 6:48 AM ET / 10:48 UTC (Revision 6). |
…t1agents # Conflicts: # src/agents/embedded-agent-runner/run/model-setup.ownership.test.ts
…mission (#169101) #168992 (e63b5a0) reused the run-admission session snapshot for the first native ownership read. Admission runs in prepareEmbeddedRunSession, before the lane controller claims the session writer, so the snapshot never carries the claimed activeWriterRunId. Every pinned native harness run with a writer claim then failed with "Native model ownership changed during run preparation" (run.harness-auth-failover.test.ts, 5 tests). Reuse the admitted snapshot only when it already carries the expected writer; otherwise take the existing worker read.
The paired auth read introduced by e63b5a0 (#168992) no longer prepares the old single-cell query, so the corruption fixture never fired. Inject the same native corruption error into the paired query instead. Keep every unreadable, cacheability and shared-handle eviction assertion. No production behavior changes. Linux proof: focused file 20/20 (58.12s Vitest, 60.67s wrapper); original infra shard 57 files / 854 tests (578.34s). Disabling eviction in the isolated negative control fails at the retained-handle assertion. The original fixture fails at injected=false on the unchanged base. P2 review is clean. Core test types, lint and boundary checks pass. check-changed retains inherited duplicate-scan coverage and unrelated unused-export failures; no scanner configuration or baseline is changed. Use the original CI shard for this test-only matcher fix rather than the whole unsliced infra config; no shared helper or runtime owner changed.
…mpaction V2) (#168401) Closes #168088. Related: #168164. ## What Problem This Solves With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history. ## Fix - **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache. - **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt. - **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them. - **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up. - **Fixed during live testing** (each with a regression that fails on the defect): 1. V2 never ran: the compact request was checked before the async provider adapter dispatched it. 2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there. 3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped. ## User Impact ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off. ## Evidence Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds. | Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall | |---|---:|---:|---:|---:|---:| | Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 | | Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 | | Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 | Request parity, compaction request vs the preceding normal turn: | Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input | |---|---|---|---|---:| | Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% | | Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% | | Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% | The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests. **Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark. **Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover: - request parity; - failed, cancelled and incomplete terminal responses; - aborts; - duplicate or empty items; - multilingual retention; - two consecutive persisted compactions; - the async-dispatch case and replay normalization through the real `SessionManager`. Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes. ## Release-landing follow-ups (2026.10.2) - **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces: - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`. - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request. - Requests with no anchor keep the conservative estimate. - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now. - Production LOC: +45/-27. Most of that is the function split plus contract comments. - **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (#168843; same fix as #168961). - **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment). ### Unrelated failures that also happen on `main` (proof scoped to the tests involved) Both failures reproduce on a clean `origin/main` checkout at `ce5b795128e` with no PR code. Checking out commits around one change shows that both start at 5843d60 (#168539, "route transcript appends through the session actor"): | Test | `5843d60c^` | `5843d60c` | `origin/main` `ce5b795128e` | |---|---|---|---| | `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail | | `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail | - #168981 independently reports the prompt-cache failure on clean main. - #169006 (steering diagnostics) landed and did not fix the steer-fifo failures. - CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here. ### Local proof on the current head All runs below were local and focused on the touched files: - `chatgpt-v2-compaction`: 13/13. - The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`. - `agent-runner.runreplyagent.e2e`: 231/231. - The 3 repaired Gateway e2e files: all passed. - `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests. - Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`. ### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `ff6f58a8c32`) The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain: 1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`): - Fails the same way on a clean `origin/main` checkout at `ff6f58a8c32`, and passes at `bdcbb2d8870` (10/10). - `git bisect` names `e63b5a01cf26` as the first bad commit: #168992, "perf(agents): reduce repeated SQLite work during agent preparation". - This PR does not touch native harness auth. 2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout): - Also fails on the unrelated PR #169026 (CI run 38137511377). - Passes locally (2/2) on this head, on clean `origin/main` `ff6f58a8c32`, and on this branch merged with that main. - This PR touches no `extensions/codex` files. Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head. Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Dallin Romney <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
…penclaw#168992) Move context-engine outbox persistence to its existing execution worker and remove duplicate preparation reads. Batch auth store/state reads, use committed sandbox facts at effects, and retain credential, command, and destructive-cleanup authority checks. Agents T1 inventory: 33 to 12, with twelve documented synchronous-contract and destructive-cleanup exceptions. Five lock primitives are reclassified, not claimed as eliminated SQL. Three paired warmed measurements: 406.2 to 403.5 all-thread statements per turn; auth reads 6 to 3 statements at unchanged 3 requests. Aggregate requests 92.7 to 93.3 reflect existing session-operation variance. Includes focused regression coverage, two Codex review rounds, and the scoped static checks recorded in the PR. No schema or public API change. Keep no-op sandbox reservation receipts from invalidating returned row facts; existing database-reopen regressions pass.
…mission (openclaw#169101) openclaw#168992 (70e895e) reused the run-admission session snapshot for the first native ownership read. Admission runs in prepareEmbeddedRunSession, before the lane controller claims the session writer, so the snapshot never carries the claimed activeWriterRunId. Every pinned native harness run with a writer claim then failed with "Native model ownership changed during run preparation" (run.harness-auth-failover.test.ts, 5 tests). Reuse the admitted snapshot only when it already carries the expected writer; otherwise take the existing worker read.
The paired auth read introduced by 70e895e (openclaw#168992) no longer prepares the old single-cell query, so the corruption fixture never fired. Inject the same native corruption error into the paired query instead. Keep every unreadable, cacheability and shared-handle eviction assertion. No production behavior changes. Linux proof: focused file 20/20 (58.12s Vitest, 60.67s wrapper); original infra shard 57 files / 854 tests (578.34s). Disabling eviction in the isolated negative control fails at the retained-handle assertion. The original fixture fails at injected=false on the unchanged base. P2 review is clean. Core test types, lint and boundary checks pass. check-changed retains inherited duplicate-scan coverage and unrelated unused-export failures; no scanner configuration or baseline is changed. Use the original CI shard for this test-only matcher fix rather than the whole unsliced infra config; no shared helper or runtime owner changed.
…mpaction V2) (openclaw#168401) Closes openclaw#168088. Related: openclaw#168164. ## What Problem This Solves With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history. ## Fix - **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache. - **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt. - **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them. - **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up. - **Fixed during live testing** (each with a regression that fails on the defect): 1. V2 never ran: the compact request was checked before the async provider adapter dispatched it. 2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there. 3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped. ## User Impact ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off. ## Evidence Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds. | Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall | |---|---:|---:|---:|---:|---:| | Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 | | Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 | | Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 | Request parity, compaction request vs the preceding normal turn: | Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input | |---|---|---|---|---:| | Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% | | Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% | | Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% | The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests. **Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark. **Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover: - request parity; - failed, cancelled and incomplete terminal responses; - aborts; - duplicate or empty items; - multilingual retention; - two consecutive persisted compactions; - the async-dispatch case and replay normalization through the real `SessionManager`. Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes. ## Release-landing follow-ups (2026.10.2) - **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces: - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`. - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request. - Requests with no anchor keep the conservative estimate. - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now. - Production LOC: +45/-27. Most of that is the function split plus contract comments. - **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (openclaw#168843; same fix as openclaw#168961). - **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment). ### Unrelated failures that also happen on `main` (proof scoped to the tests involved) Both failures reproduce on a clean `origin/main` checkout at `02040ecbc92` with no PR code. Checking out commits around one change shows that both start at 9657a374 (openclaw#168539, "route transcript appends through the session actor"): | Test | `9657a374^` | `9657a374` | `origin/main` `02040ecbc92` | |---|---|---|---| | `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail | | `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail | - openclaw#168981 independently reports the prompt-cache failure on clean main. - openclaw#169006 (steering diagnostics) landed and did not fix the steer-fifo failures. - CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here. ### Local proof on the current head All runs below were local and focused on the touched files: - `chatgpt-v2-compaction`: 13/13. - The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`. - `agent-runner.runreplyagent.e2e`: 231/231. - The 3 repaired Gateway e2e files: all passed. - `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests. - Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`. ### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `3dc543d9ee8`) The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain: 1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`): - Fails the same way on a clean `origin/main` checkout at `3dc543d9ee8`, and passes at `596e31d1764` (10/10). - `git bisect` names `70e895e21606` as the first bad commit: openclaw#168992, "perf(agents): reduce repeated SQLite work during agent preparation". - This PR does not touch native harness auth. 2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout): - Also fails on the unrelated PR openclaw#169026 (CI run 38137511377). - Passes locally (2/2) on this head, on clean `origin/main` `3dc543d9ee8`, and on this branch merged with that main. - This PR touches no `extensions/codex` files. Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head. Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Dallin Romney <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
First-parent upstream 069a5b8..75df19c (17 commits, including openclaw#169043 entry lifecycle queries, openclaw#169034, openclaw#169058 memory index facts, openclaw#168950, openclaw#169019 telegram queued history replies, openclaw#168790/openclaw#168756/ openclaw#168759/openclaw#168739 Solid UI ports, openclaw#168813 codex metadata/startup lifecycles, openclaw#168981, openclaw#168992 agent preparation SQLite work). Only conflict: worker-access inventory, regenerated (631 files, 2436 calls). Auto-merged files carrying our overlay, reviewed: snapshot.ts (upstream's block-reply reconcile reads through index-1; our per-part continuation-marker strip in extractAssistantStreamSnapshot unchanged), codex side-question.ts (upstream's request-scoped client lease; our disableContinuationTools and the extracted dynamic-tool-call helper unaffected), subagent-registry-restore.ts, session-sharing-store.native.ts. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]>
What Problem This Solves
Agent preparation repeats SQLite reads and retains main-thread SQL even when its worker or committed owner facts already hold the answer. This reduces that work without changing persisted data or the public API.
Design and impact
Context-engine outbox SQL now runs exclusively in the existing execution worker, or in the incognito actor. The synchronous fallback is deleted. Recovery returns its pending result directly and publication does not reread state already supplied by the owner. Auth workers read credential and runtime-state cells with one statement. Relay renew/delete/prune use guarded mutations. Sandbox effect guards consume facts installed by worker reads and committed write receipts. Model preparation reuses its admitted session entry; cancellation preparation reuses the session-generation owner; worktree cleanup reuses its existing lease census.
Credential dispatch, tool/command launch, and destructive cleanup retain their real effect-boundary authority checks. No schema, migration, retention, update, Doctor, plugin-loading, service-lifecycle, or SDK surface change.
Main-thread SQLite
Agents T1 inventory: 33 → 12. Sixteen call sites are removed or moved into their worker owner; five retained removal/exit lock call sites are correctly classified as permitted lock primitives, not represented as eliminated SQL.
The twelve remaining T1 sites use the requested escape hatch:
ensureAuthProfileStore,upsertAuthProfile, andAuthStoragepaths must return credentials or finish atomic persistence synchronously. Async bundled paths use workers. Retire these adapters when those SDK contracts migrate.ModelRegistryconstruction/refresh consumes the catalog immediately. Prepared Gateway runtime already uses the worker-read catalog.Removed checks and accepted edges
Measurement
Exact base
7943ae59280f6ffd4bae07e4a877a361e79e654b; candidate1e94f14a611019ccced1c9e72535e6cbba4d2ef8. Three alternating base/candidate pairs on one isolated AWS host, with the shared harness and unchanged assertions. Values are median [min–max]; warmed rows are per turn. Both native main/worker calibrations must report 8 calls, 2 prepares, 7 SQL statements, and zero failures.auth-profile-rowsThe same auth read falls 10 → 5 statements on the first turn, at 5 unchanged requests. Outbox/relay/sandbox/cleanup behavior is covered by owner regressions; no workload saving is claimed for unexercised paths.
The warmed raw statement median falls 2.7 (0.66%); the first turn falls 6. Warmed requests rise 0.6 (0.65%), while the available entire-workload request median falls 1764 → 1763. Operation attribution shows that the warmed request difference comes from existing session-owner timing, not an added auth request: per-pair total request deltas are +0.3, +0.6, −0.1. These are existing session entry reads, actor completion/delivery, shared facts, corpus inventory, exact-entry, and tombstone operations. Auth stays exactly 3 requests in every warmed observation; separate operation medians are not additive.
All six first/warmed observations and twelve native calibration streams passed. No fourth pair was run; the full-workload comparison has the sampling limitation below. Later phases have two complete baseline workloads and three candidate workloads: M3 was interrupted after all warmed turns by the inherited settlement failure. Those later statistics are reported as n=2/3, not as three complete pairs. No full third baseline workload is claimed.
Final validation/landing head is
ca20afdebb1536d44bd16a476d7a0f893e3f5f5c, integrated with main parent30469f450063ebd23e6a731fcc95019a785d28ed. The final main integration conflicted only in generated inventory; it contains no lane runtime-code resolution. SQL measurements are retained at the exact revisions above under the campaign's proof-reuse rule. Integration combined main's model-preparation simplification with this lane's admitted-entry reuse; the final credential-dispatch read remains. Other integration conflicts were generated inventory. Subsequent changes align test-export ownership, remove an unused export, shrink the assertion baseline, format the resolved test, and prevent an empty sandbox reservation receipt from discarding the returned row. None adds SQL or worker requests.Validation and landing
Focused coverage: all 48 selected test files completed, including changed tests and consumers mocking changed exports. The first selected run took 880.48 s and exposed two obsolete initial-read race expectations; those were deleted, and the ownership suite passed. The remaining 27 files plus the changed relay test passed in 722.56 s (
node scripts/run-vitest.mjs ... --maxWorkers=2). After the final model-setup integration,node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/model-setup.ownership.test.ts --maxWorkers=1passed 31 tests, 115.18 s Vitest / 149.74 s command wall time. CI execution seconds are not separately profiled.The remote lease expired during the initial focused run. Completed SQL artifacts were recovered, the lease and slot were released, and focused/static proof continued locally through campaign proof slots. The incomplete remote test run is not counted as a pass.
The integrated 36-step
check:changedplan was executed through a continuation runner so inherited failures did not hide later checks. Core and all test type graphs, type-aware core/script lint, mock-export checks, import cycles, and both database ratchets passed. Madge passed in 152.74 s; final export-collision validation passed in 41.96 s. Final formatting and assertion-ratchet reruns passed after fixing a stale allowance and one blank line.Two static exceptions reproduce on untouched source at main
6e06137f85ef3262f47dae63626d97f14c2f1ca1: the max-lines suppression insrc/web-search/runtime.test.ts, and Knip findings forisCodeModeExecToolKind,readVoiceSessionFacts,renderSettingsSecretInput, andloadSubagentMaintenanceCandidatesInDatabase. Both full-tree and production Knip scans were run on main and candidate. All four reported source files and the Knip configuration are unchanged between the verified main revision and the final main parent. The old outbox test-only export declaration was moved to the new kernel filename, and the unused sandbox row-reader export was removed; no lane-specific Knip finding remains.Final-head CI exposed a real sandbox cache defect: a no-op reservation receipt advanced the cache revision despite carrying no changed rows, discarding the returned reservation after database reopen. The existing two reopen cases reproduced locally. Empty receipts now leave row facts unchanged; no additional query or request is introduced. All four sandbox verification files passed afterward (35 tests, 89.60 s command wall time), followed by scoped type-aware lint, core types, formatting, and both database ratchets. Other completed proof was reused.
Two Codex autoreview rounds completed with no actionable P0/P1 findings. The implementation was reviewed in the first round; the second round covered the lock-classification correction. Retained lock callers and the final conflict resolution were inspected separately. No third review round.
An earlier CI head found lint annotations and three stale FIFO-test observations; those were fixed in the final push. The queue tests now observe actual worker submission and verify the callback cannot enter or mutate durable state while blocked, then verify the committed result. No production retry or weakened assertion was added. Two further tests that intercepted the removed initial preparation read were deleted as requested; current-writer, cancellation, replacement, and final-dispatch tests remain.
One candidate attempt and two attempts of the third baseline measurement returned
agent.wait: errordespite a successful visible reply,executionSettled: true, and no session error. The same visible-reply/error-status signature is present on main in run 38122045725,sqlite-sessions-transcripts-flip-proof.built-cli.e2e.test.ts. The failed attempts were preserved and excluded from complete-workload statistics. The candidate replacement passed unchanged; the third baseline failed again, so its valid first/warmed windows are included and its incomplete downstream phases are excluded. This PR does not claim to fix that inherited intermittent settlement failure.Native review initialization stalled for over 20 minutes without completing. Its owned process was stopped and stale lock recovered. Landing uses the explicitly authorized head-pinned REST squash fallback under relaxed landing v4; static gates remain mandatory. Final-head CI and security status are recorded below rather than inferred from older runs.
At head
0aedb5671c69b2ab1a755784e210ae42fa73cd07, all security checks passed. Aggregate CI failed on the two sandbox-reopen cases now fixed and on the inherited built-CLIagent.waitfailure described above (run 38132298826). The final four-line sandbox fix is pushed asd518acde1fceda54ae482727d65b165067b94b89; focused proof and static checks passed. Relaxed landing v4 permits the head-pinned admin/REST route without waiting for another full CI cycle. The inherited Knip findings are recorded explicitly, not represented as passing checks. The final main integration includes the upstream max-lines repair; the final inventory, worker/dialect ratchets, max-lines ratchet, assertion ratchet, and generated-file formatting checks all pass. Prior runtime tests, type-aware lint, type graphs, export-collision, Madge, and Knip evidence are reused for the unchanged lane code.LOC against the final main parent: production +746 / −784 (net −38), tests +314 / −150, docs/config/tools +188 / −128. Most production churn is moving the outbox implementation into its worker kernel. No changelog edit: release-note context is in this PR.