Repository navigation
perf(sessions): move target lookups and callers to workers - #169757
Conversation
Route ordinary session target and entry preparation through the existing worker owner. Migrate bundled callers, preserve native SDK transaction semantics and final tool authority, and remove duplicate bookkeeping reads and the obsolete sharing snapshot cache.
…t1cut-s8-encoding # Conflicts: # src/gateway/managed-image-attachments.sqlite-visibility.test.ts
|
🦞👀 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. |
Preserve worker publication and post-commit mention scheduling while keeping session target preparation asynchronous.
|
Carry selected stores, preserve progress bindings, and keep sharing types out of the Gateway policy graph.
Keep retired standalone-memory tests removed and preserve async preparation with current owner authorization.
Keep existing file and current authorization guards while allowing the owning writer to create an initially absent database. Preserve mock module contracts and projection-backed event fixtures.
…169757) Route durable Gateway target discovery, entry preparation, and combined-store lineage reads through the existing session worker. Migrate bundled callers to async APIs and keep prepared facts current through owner write receipts. Retain live authorization at real effects and documented deprecated SDK compatibility. Remove redundant internal bookkeeping checks and preserve SQL-side retained-payload projections. Fix asynchronous fixture assumptions, the monotonic fake test clock, and the extracted wrapper source inventory. Warmed causal median stays 170 statements / 41 requests / 0 MAIN; the lane removes six source-audited T1 sites across the three-PR series. Integrated Phase E independently removes six more; 15 conservative mixed SDK/worker/maintenance sites remain documented in the PR. Join targeted recovery to an existing recovery receipt before acknowledging final placement state, while preserving active-operation progress. Integrate the memory-only incognito owner without restoring native fallbacks; share captured memory rows during async lineage assembly.
|
Update: the focused test-only repair is now #171789, head The original source-only report below is historical; its then-unexecuted repair and baseline statements are superseded by the proof above. A concrete fixture follow-up from #151242 CI, head b51ae3f:
The fixture calls synchronous The fixture and three inspected authorization/preparation modules are byte-identical between #151242 and its pinned base Could this join the existing worker-migration follow-ups? The candidate repair is to await the native preparation owner and retain/release its authority through the test effect, preserving the tombstone and no-model-work assertions. That repair is not yet executed or proved. No production authority fallback or relaxed assertion is requested. Reusing this owner thread rather than opening a duplicate issue or folding session changes into the streaming PR. |
… source (#172579) sessions.files list/get for managed-worktree sessions re-reads the session entry during settlement to detect a reset or worktree change. Since #169757 that re-read passed the logical store path to readRetainedSessionEntryFacts, which only knows the physical SQLite path, so it always returned undefined and every request failed with "Session workspace changed during file read". Use the captured read source path, matching the other retained-facts callers. Co-authored-by: Patrick-Erichsen <[email protected]>
… source (openclaw#172579) sessions.files list/get for managed-worktree sessions re-reads the session entry during settlement to detect a reset or worktree change. Since openclaw#169757 that re-read passed the logical store path to readRetainedSessionEntryFacts, which only knows the physical SQLite path, so it always returned undefined and every request failed with "Session workspace changed during file read". Use the captured read source path, matching the other retained-facts callers. Co-authored-by: Patrick-Erichsen <[email protected]>
What Problem This Solves
Gateway target discovery and entry preparation could still open SQLite through synchronous lookup APIs during turn preparation, session selection, and later action checks. Durable callers now use the existing session read worker. Bundled callers await the replacement APIs, and mutations receive the selected canonical target instead of rediscovering it.
There is no new configuration or user-facing feature. Deprecated synchronous SDK methods retain their documented compatibility window; bundled callers use their async replacements.
Design and ownership
Prepared facts stay alive through the action they authorize and are updated by the existing writer receipts. File, media, sharing, publication, Talk, and tool effects consume those facts. Real execution, revocation, replacement, and disclosure boundaries retain their current authority check. The actor entry replica does not certify live authority.
The cutover preserves full entry snapshots by default, list-only child discovery, qualified-address selection, configured-store initialization, physical source identity, and SQL-side copies of opaque retained payloads. It removes the superseded synchronous Gateway loader exports, the sharing snapshot cache, ordinary steering/cron bookkeeping rereads, and projection rebuild per-chunk ownership reads. Rebuild publication uses its final conditional UPDATE result.
Both async combined-store merge callers prepare missing-owner lineage facts through the existing async reader, including explicit parents, spawn parents, and implicit thread parents. Captured absence remains absent for that selection; merging cannot reopen a native store. The synchronous durable compatibility loader retains its named native resolver. Incognito rows come from the memory actor and are captured once before lineage preparation, so the same rows are used during final assembly.
T1 accounting
Against integrated main
44d880a42258d0, this PR reduces conservative T1 sites 16→15 (raw primitive sites 19→18). Across the three lane PRs the independently attributable reduction remains 27→21. Main's separately landed Phase E removes three native-incognito sites and makes three search sites worker-only; the combined current tree has 15 conservative T1 sites. These are source-audited counts, not 15 ordinary Gateway-main-thread executions. No ordinary durable host path was found after the combined-lineage repair.session-transcript-match.tssession-transcript-projection-rebuild.tssession-transcript-projection-writer.tssession-transcript-read-fence.tssession-transcript-reconcile-memory.tssession-transcript-reconcile-readiness.tssession-transcript-retained-data.tssession-transcript-search.tstargets.tstranscript-payload.tstargets-discovery.native.tsThe current PR removes
projectionClaimIsOwned, one SQL site used by deletion, append, and finalization. It does not claim Phase E's independent six-site T1 reduction. Remaining mixed native kernels serve deprecated synchronous SDK compatibility or offline Doctor/migration; ordinary durable Gateway consumers use workers. Incognito now uses main's memory actor, with no native fallback.The retained effect-authority chain is
followup-turn-execution→prepareGatewaySessionEntryReadOnlyInWorker→reply-tool-authority, with final uses in host-private capabilities and question access. The actor entry replica does not replace this live authority. Deprecated SessionManager methods warn and name their Async replacements; they will be removed in a later release after the deprecation has shipped in a stable release.Live measurement (prior-head frozen pair)
Base
e78a253059eb07d70ea3f7140e1c4e9b9fadc383→ candidate7f33ab94d1d553280bc17a7646e3ea25488774c9.One alternating harness 2.1.0 pair, 10 warmed turns per run. Successful native executions are counted using the shared harness splitter; prepare calls and failed executions are excluded. Turn scopes follow originating trace, not wall-clock windows. Family SQL counts include descendants of the named SQL owner; requests_with_family_sql count unique logical requests containing that family SQL and overlap across families. Operation statements join SQL to logical requestId; rows are disjoint by origin operation. All foreground cache/retry work remains included. No latency claims.
Both runs: exit 0; evidence.ok; 13/13 top-level turns; native child OK; 39/39 RPCs; cron completed; compaction completed; clean shutdown; complete warmed causal coverage. Neither wrapper is partial. Candidate records one failed worker BEGIN IMMEDIATE (database is locked) in shutdown; the harness completes successfully and excludes that failed attempt from successful-statement counts.
Background SQL/min during warmed windows: 659.02 → 773.92. Loaded host; this is an observed maintenance rate, not a latency or per-turn saving.
Family rows overlap and must not be summed. Entry-cache counts include participant rows called by loadSessionEntrySnapshot. Row-facts SQL includes its transaction and descendant watermark reads. All five causal warmed families are unchanged. Whole exact-entry facts are 79→83: turn-caused 60→61 (the extra one is in second-session), background 19→22. The extra cold foreground read remains counted; it is not classified as timer noise. Whole turn-caused SQL is 2911→2927 (+16), requests 671→671; all-cause workload SQL falls 6645→6482.
The only causal warmed source delta is readAuthProfileRows: 11→10 SQL over ten turns, accounting for the complete −0.1 SQL/turn and −0.1 requests/turn. The lane does not claim this incidental auth-read difference as an optimization saving. Matched lane-owned SQL footprints are unchanged: read-fence 47→47 whole (36 turn-caused), targets 11→11 whole (background), transcript-payload 100→100 whole and 50→50 across warm turns; other listed lane-owned files have no successful SQL execution stack in this workload. Those zeroes are coverage limits, not a claim that the harness proves those flows.
The JSON retains all source and operation counts, exact warmed arrays, owner-file counts, originating phase totals, and observed host load. No warmer family increase or MAIN increase is hidden as background. Whole/window changes include differing counts of timer-driven memory indexing and registry maintenance.
Cold causal attribution
Cold first-turn +26 SQL includes the identical 32-SQL existing first-open admission batch moving from background into first-turn scope. The associated prepare operation stays 3 requests/63 SQL over the whole workload. A target-resource request also moves background→first-turn, with whole9 requests/8SQL unchanged. There is one genuine extra deletion-status read/request from assertAgentIngressOpen during first turn; attribute that cold reload to candidate until proven otherwise. Seven other cold reads are removed in this phase. No warm SQL/request/MAIN family increases. Count changes are retained; this report makes no latency or unconditional landing claim.
The structural first-turn delta is −6 SQL / 0 requests after excluding only the identical once-per-open admission batch and the two whole-count-neutral request moves. The raw result remains +26 SQL / +2 requests; the real deletion-status reload +1 SQL / +1 request stays charged to this lane. This decomposition does not replace the reported causal counts. The T1 MOVE exception applies: whole turn-caused SQL rises 0.55%, requests are unchanged, warmed medians do not rise, and the cold increase is attributed to admission routing. The deletion-status check stays because it guards admission of a real agent turn after deletion.
The 32-SQL batches are equal by normalized SQL/method multiset hash. Base dispatches it through session-entry-read-writable.ts:157; candidate dispatches it through withSessionEntryWorker in session-accessor.sqlite-replacement-worker.ts:252. Candidate admission source wraps the write queue in runWithSqliteDatabaseAdmissionTurn; the changed ordering makes this cold admission count against the foreground turn. It is not an extra whole-workload schema validation.
The extra deletion-status request follows assertAgentIngressOpen → loadAgentDeletionJournalStatus → readAgentDeletionJournalStatusInWorker. The earlier background sessions.create read occurs on both sides; candidate additionally reloads for chat-send admission. This is real foreground work, despite the status-loader sources being unchanged.
First-turn +2 requests are +1 preparation dispatch, +1 target-resource dispatch, +1 deletion-status reload, and −1 readExactEntries request. Only the first two are whole-workload count-neutral moves. Second-session −9 SQL is −2 entry-query, −2 participant reads, −4 cohort transaction statements, and +1 exact-entry facts; it removes one exact-entry worker request.
packages/memory-host-sdk/src/host/memory-schema-recall.ts:readMemoryChunkColumnssrc/config/sessions/session-accessor.sqlite-entry-query.ts:<anonymous>src/config/sessions/session-accessor.sqlite-participant-projection.ts:<anonymous>src/config/sessions/session-actor-hydration.worker.ts:hydrateSessionActorStatesrc/config/sessions/session-entry-cohort.worker.ts:snapshotsrc/config/sessions/session-sharing-store.kernel.ts:listSessionMembersInDatabasesrc/state/agent-deletion-journal.read.ts:readAgentDeletionJournalStatusInDatabasesrc/state/openclaw-agent-db-metadata.ts:readExistingAgentSchemaMetasrc/state/openclaw-agent-db-schema-helpers.ts:assertOpenClawAgentSchemaContainssrc/state/openclaw-agent-db-schema-helpers.ts:hasLegacyMemoryChunkProvenanceTriggersrc/state/openclaw-agent-db-schema-helpers.ts:hasRetiredAgentStateLeaseSchemasrc/state/openclaw-agent-db-schema.ts:agentDatabaseIntegrityBeforeMutationStepssrc/state/openclaw-agent-db-schema.ts:refreshOpenClawAgentDatabaseSchemasrc/state/openclaw-agent-db-session-migrations.ts:readSqliteTableColumnssrc/state/openclaw-quarantine-store.ts:readQuarantineSchemaVersionThe earlier pre-repair legacy-window pair was not an aggregate reduction: SQL mean360.1→480.2 and requests114.0→119.2. It identified 15 removed discovery/close requests per turn and an unrelated usage-cache write receipt invalidating shared session replicas. Commit
8feea29d435b1scopes those four cache kernels to no changed session keys; the final pair above is after that repair, against an updated main baseline. No subtraction or speculative counterfactual saving is claimed.Removed checks and accepted edges
agent.waitmay occupy an observer until completion/timeout; the one current check before returning data prevents disclosure.updatedAt-only change does not revoke an otherwise valid selected effect; real identity, sharing, and execution authority remain checked.The cold admission correction reserves the existing admission turn before entering the writer FIFO (all batch paths together), preventing a usage refresh/prune ↔ history deadlock found in CI. Cancellation races only admission waiting; accepted writes retain settlement and cancelled reservations preserve predecessor order. Media delivery joins the existing pending publication before its effect check. Shared terminal publication receipts keep session/security authority while tolerating workspace changes; pending/latest receipts still compare receipt-updated workspace metadata.
The final integration repairs preserve caller authority after accepted sends, reuse prepared Talk profile policy, and retain the worker-owned read-admission facts for cold publication reads. Detached placement setup retains the existing session authorization alongside its device hold; workspace and archive effects consume receipt-updated metadata rather than optional cache presence. Cold source capture now runs after the existing read admission and before snapshot dispatch, without another query. Recovery notice authority is captured after recovery admission and retained until dispatch settles, including runtimes without a typing adapter.
Evidence and integration
Candidate
b8ae4f2ad4d58a3e94b0a1fcac48348ed5921cb8includes main44d880a42258d0and Phase E's memory-only incognito cutover. Conflict resolution preserves main's transcript-pool idle policy alongside read-only database ownership, and main's wire-fixture cleanup alongside serial Git setup, concurrent transfers, and actual terminal waits. Changed-file oxfmt, oxlint, andgit diff --checkpass.b8ae4f2ad4d58a3e94b0a1fcac48348ed5921cb8, includingopenclaw/ci-gate, all production/test types, lint, Madge, source contracts, boundaries, T1/dialect/worker ratchets, security, and all ordinary behavioral jobs. 186 successful, 43 skipped, one neutral, zero failed checks.6cd0789ff8d04cd4374275b05b82ab3ee233b421, all types, lint, Madge, source contracts, boundaries, and T1/dialect/worker ratchets pass. Two behavioral jobs fail and one UI job times out; disposition is below. The subsequent repair changes only the MCP test watchdog; final integration also adopts main's scoped API-key test diagnostics, preserving its assertion.authorizedandreasonproperties. Lane changes are deprecation documentation/removal metadata, with no public signature change. This is explicitly prior-head evidence, not a final-artifact API comparison.Final-head Knip's five production findings are
bindSessionEntryPublicationSource,invalidateSessionEntryPublication, andpublishSessionSharingFieldChangeinsession-accessor.sqlite-entry-cache-publication.ts;withSqliteCommittedPublicationsinsqlite-post-commit.ts; andsqliteDatabaseSealSchemaForinopenclaw-database-seal-schema.ts. All-exports reports the same three entry-cache publication names. The frozen main run above emits identical findings. Current maind08d23228ab2624820e0548a641465d6aa40bfa9has no later edits to those declaration files. The earlier three memory/bootstrap findings were separately fixed by integrated main; they are not final-head findings.The prior integration CI's bootstrap-token reconcile and node-reconnect expectations reproduce on integrated main
5b742a7c787e11a606418e5bb78e4364eb3454f1: the new connection contract returns structuredUNAVAILABLErather than rejecting, and close text isgateway closed (1011): gateway hello delivery failed. Focused base evidence: two failed, 44 skipped; Vitest 135.85s, command 148.90s. Both failing tests and their connection owner are unchanged from that base through the latest integration. The exact prior-head failure appears in job 115559015985 and also in scheduled main job 115550039641.The MCP cancellation case in job 115559015572 exposed an overbroad test watchdog: it stayed armed after the native request settled, so unrelated full Gateway teardown could set
emergencyUsed. The final two-line test repair clears the watchdog on actual request settlement. The five-second cancellation deadline and settlement-before-close assertion are unchanged. A focused base run failed earlier atsessions.create(23.886s case, 119.51s command), so it is not claimed as inherited evidence. On final head, the exact corrected case passes: 1 passed/1 skipped, 15.248s case, 51.03s Vitest, 56.34s command. This fixes the overbroad watchdog; it does not claim the differently failing baseline proved inheritance. The earlier chat-settings timeout did not reproduce on base or candidate; passing replay is not called a fix. Its obsolete diagnostic mock was removed, leaving the test byte-identical to the integrated base. Prior-head job 115559015797 passes that case (10.005s) and all 34 tests in its file.CI-driven repairs include using the actual worker for usage write/prune regression setup; retaining the memory namespace in incognito creation; detaching App-file metadata from the opening RPC while preserving per-effect authority; and consuming an already-queued auth mutation before settling its publication. Focused regressions pass: usage 1/1 (case 3.3s, command 218.9s), Goal custody 3/3 (command 186.3s), App-file lifetime 1/1 (case 51ms, command 332.4s), incognito creation 1/1 (case 1.5s, command 325.3s), and auth publication (case 1.569s, command 59.66s; original failure reproduced before the fix). Command times include cold worker compilation. Forced termination continues to invalidate receipts; clean worker exit preserves admitted facts.
The live pair above exercises successful turns, child execution, RPCs, cron, compaction, and shutdown; it does not cover every denied filesystem/publication effect. No extra SQL pair was run after integration, and no local latency claim is made.
Codex autoreview completed two rounds across 19 partitions: five P2 findings, zero P0/P1; three fixed, two bookkeeping-reread requests declined under the accepted edges above. Later integration and CI repairs received focused source inspection. Cold media/App-file facts and logical-versus-physical worktree guard behavior remain documented follow-ups under the review cap; neither establishes an authorization bypass.
The prior-head UI 3/3 job reached its 20-minute job limit while still reporting passing tests; the annotations say the job exceeded its maximum execution time, with no failed assertion. This is a CI execution-time cancellation, not a passing UI claim.
Size and compatibility
Parent #169624 is merged. Against integrated main: 479 files, +8180/−5237 lines; production 182 files, +3518/−2935 (net +583); tests/support 292 files, +4644/−2274; docs 3 files, +16/−13; configuration/tooling 2 files, +2/−15. Direct lane kernels are +265/−265. Test classification includes paths and helper filenames containing
test, plus.spec.files.No lane schema/storage-format change or new configuration. Synchronous public SDK compatibility is deprecated with named async replacements and a later-release removal path. Native maintenance/Doctor and mixed compatibility kernels remain explicitly counted above. The Phase E hold is lifted and its memory-only incognito owner is integrated.