Repository navigation
perf(sessions): fuse prompt and lifecycle worker requests - #174098
Conversation
Capture model prompt projections and reduce lifecycle patches in their existing worker owners. Preserve committed failure/publication ordering and skip ACP joins when current parent fields cannot require child-delivery suppression.
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs changes before merge. What this changesThis PR combines prompt capture and lifecycle bookkeeping into worker commits and skips unnecessary ACP metadata reads. Example: An existing chat session records the enriched prompt "Summarize today's notes".
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 3 items remain Keep this PR open: the maintainer-directed optimization is useful, but three introduced test and wrapper defects block merge. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe session persistence layer receives transcript and run-lifecycle updates from the Gateway, commits them through durable workers or memory actors, and returns facts for runtime publication and failure reporting. flowchart LR
A[Gateway chat turn] --> B[Session operation adapter]
B --> C[Durable worker]
B --> D[Memory actor]
C --> E[Committed facts]
D --> E
E --> F[Runtime publication and failure transcript]
Technical reviewBest possible solution: Keep the worker consolidation and repair the cancellation import, runtime-config fixture, and wrapper dependency inventory. Do we have a high-confidence way to reproduce the issue? Source confirms the redundant baseline worker requests, and exact-head CI independently records the three introduced defects; no local execution was performed. Is this the best way to solve the issue? Using closed operations in the existing workers preserves one persistence owner and current-row reduction without adding configuration or a parallel storage path. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6385baea120a. Provenance checked
TestingProof path: none. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +235, Tests +249, Docs +14. Total +498 across 34 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel 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 Reviewed October 16, 2026, 6:33 AM ET / 10:33 UTC. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: beabffd44d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| contextClaimId: params.event.contextClaimId, | ||
| data: params.event.data, | ||
| }, | ||
| currentLifecycleGeneration: getAgentEventLifecycleGeneration(), |
There was a problem hiding this comment.
Revalidate lifecycle generation inside the queued commit
When this write waits behind an earlier SQLite operation while the Gateway lifecycle rotates, currentLifecycleGeneration retains the pre-wait value. The worker can consequently treat a restart-cancelled or recovery-fenced event from the retired generation as current and settle stale status/recovery state; the previous callback-based path read the generation after reaching the write FIFO. Resolve it at commit time or enforce the live generation in the synchronous pre-commit guard.
AGENTS.md reference: src/gateway/AGENTS.md:L29-L30
Useful? React with 👍 / 👎.
| options: { | ||
| currentMetadata?: true; | ||
| /** Skip the join when the consuming projection cannot use ACP metadata. */ | ||
| includeMetadata?: (entry: SessionEntry | undefined) => boolean; |
There was a problem hiding this comment.
Honor the metadata filter for memory sessions
When delivery handles a parentless incognito session, the new predicate returns false, but this function enters the memory branch before evaluating it. prepareMemoryAcpSessionEntryRead then unconditionally calls readAcpSessionMetaForEntries, so these deliveries still incur the shared-state worker/SQLite metadata join that this optimization removes for durable sessions; apply the predicate to the actor snapshot before performing that join.
AGENTS.md reference: AGENTS.md:L72-L74
Useful? React with 👍 / 👎.
|
Reviewed the two automatic inline findings against the actual ownership paths at ad315b3. The lifecycle-generation finding does not establish a reachable restart regression. The only production rotation is in The memory-session metadata filter finding is a valid bounded optimization follow-up. This PR skips the join for durable parentless sessions; memory-session reads preserve their existing metadata behavior. Applying the predicate to the memory actor snapshot can remove that remaining join in separate work. No incognito saving is claimed. This is deferred under the task's two-review-round cap, which limits subsequent fixes to real P0/P1 issues. The focused repaired lifecycle worker cases pass (2/2), and the previously failing abandoned-recovery cleanup case passes on both recent main and this candidate. That cleanup failure is recorded as intermittent, not proven inherited or fixed. The unrelated transcript NO_REPLY expectation fails identically on recent main and remains separately documented. |
…74098) Capture immutable model-prompt projections in one transcript-worker command and apply lifecycle reductions against the owner's current session entry without the host prepare round trip. Return committed failure and recovery facts on the existing receipt, preserving runtime publication and failure-transcript ordering. Skip the ACP metadata join for current parentless sessions while retaining current parent and ACP checks for child delivery. Keep terminal lifecycle persistence separate from completeTurn because admission closure and reply accounting follow its durable commit. No schema, public SDK, retention, or service lifecycle change. Release-note context: fewer session bookkeeping worker requests for ordinary chat turns, with durable and memory-session behavior preserved.
83e5309) Fleet-gap CARRY cluster "superseded-turn tombstone" (group B: 83e5309). 🌻 ruled (room msg 1563128144884662273) that D3a's yield is ported with it. A turn superseded by a newer session writer was persisted with abortedLastRun: true. With its delivery claim still on the row, the successor's admission opened a restart-recovery cycle, and a message-tool-only room was tombstoned with no restart (#1462). The superseded run keeps status "killed" but is no longer marked as an aborted last run. Re-ported onto this tree's projection owner, src/config/sessions/session-run-lifecycle-projection.ts; upstream 5b1d81e (openclaw#174098) moved the line there from the fleet's gateway/session-lifecycle-state.ts. The fleet's test-harness moves (410de31, 39dd408) only hosted its integration case, and the P0 fossil now covers that. Proof: - session-lifecycle-state.test.ts 50/50, with the new "superseded by a newer session writer" row (status "killed", abortedLastRun false). - main-session-restart-recovery.live-stop.test.ts P0 ("superseded end event (#1463 fossil shape) leaves the live session safe") goes RED at 8fd1fa9 to GREEN here. - P1/P2 stay RED; they belong to the D3b port. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]>
What Problem This Solves
Warm chat turns make separate worker round trips for pure session bookkeeping. Capture the immutable model-prompt projection inside the transcript worker, reduce Gateway lifecycle events directly against the current session row, and skip ACP metadata joins when the current session has no parent and therefore cannot require child-delivery suppression.
The lifecycle commit returns its failure/recovery facts on the existing receipt. Runtime publication and failure-transcript appends keep their existing order. Goal resumes and recovery-owner changes are merged from the current stored entry. Error rendering stays on the host so its redaction registry remains authoritative. Memory sessions retain equivalent receipt behavior.
Generic transcript/entry callbacks remain supported for nonserializable caller work. The normal model-prompt and lifecycle paths no longer use those prepare/commit round trips. No schema, retention, public SDK, update, service lifecycle, placement, audit timing, or cross-store commit changes.
Removed work and accepted edges
The final lifecycle/observer patches are not folded into
completeTurn: terminal persistence drains before its admission closes and before reply accounting starts. Changing that ownership/publication boundary needs separate work. Observer-digest attribution for the remaining entry-only request is not claimed as measured proof.Evidence
Three alternating baseline/candidate harness-v3 pairs completed against
dc43a7e79cc3571b89663970a496c10bd60ef99band reviewed headad315b3e014ad7fee7f62aa108eff52a0981ea90(the merged production/test blobs were verified equal). All six accepted workloads passed all 14 top-level turns, spawn, control RPCs, cron, compaction, 300-second connected idle, restart readiness, post-restart chat, and both clean shutdowns. Native SQL/prepare errors and missing causal coverage are zero; every fixture child exited. The frozen v3 harness was unchanged. Node 24.22.0 and the loaded SQLite 3.54.0 libraries were pinned and attested before/after every arm; compile caching was disabled. Fixture account provisioning is unmeasured, not zero SQL. Host load varied substantially: counts only, no latency claim.Counts below are median [min–max]. Warm rows pool 30 turns per side; whole-workload rows contain three runs.
The warmed saving is two requests per turn (8%), with unchanged SQL. The 21-request target is not reached. The harness creates a parented durable session, so its two ACP metadata requests correctly remain; the parentless optimization is covered by focused owner tests and is not counted as a harness saving.
Shared-read families are overlapping classifications. Per-warm medians are unchanged: exact-entry, actor hydration, entry-cache snapshot and watermark reads are zero; row facts are 2 SQL / 2 requests. Whole-workload medians and ranges are disclosed below (SQL / family-attributed requests / MAIN).
Entry-cache snapshot work rises by 3 SQL / 2 requests at the whole-workload median, while total workload falls by 33 SQL / 22 requests. The first candidate warm turn can perform a real 5-SQL/1-request initialization reload. Traces show background memory-index DDL invalidation moving from before initialization caching on the first baseline to after caching on both initial candidate attempts. That is a supported timing explanation; the exact missed key is inferred because cache tokens/miss reasons were not traced. The fusion retains the final publication path. This work remains counted, and candidate scheduling effects are not ruled out.
Causal warm run-mean medians are also unchanged at 72.6 SQL, with requests 25.2 → 23.2. Raw warm run-mean medians are 74.8 → 76.1 SQL and 25.4 → 23.7 requests; their additional background work remains included. Pooled raw warm medians do not rise. Causal first-turn SQL medians are 223 → 223 (requests 64 → 62); causal post-restart SQL is 149 → 149 (requests 49 → 47).
Startup background work shifts between connect and first-turn windows. Combined windows below include every statement/request and show their distribution across adjacent phases. Boot/connect/first rises 3 SQL / 3 requests (0.16% / 1.16%); compaction/idle/shutdown falls, as does the whole workload. No extra pair was needed: all three pairs agree on the warm saving.
One initial candidate attempt is excluded because restart
chat.sendtimed out after a roughly 95-second main-thread stall correlated with a native file-watcher registration error. An unrelated standing-intent worker spent that interval waiting for host admission (2 ms of SQL). Relevant watcher/admission/shutdown owners are byte-identical to base, but the original cause remains unproven and is not called inherited or fixed. Its evidence is retained. One unchanged candidate retry passed, followed by the remaining alternating pairs; none of the three accepted candidates repeated that failure. A bounded external sample in the retry began after the turn succeeded and had no usable call graph.Focused tests cover stored-message metadata preservation and immutable replay; queued goal resumes and recovery-owner updates; memory failure receipts; lifecycle restart/reopen and failure publication; current parent/ACP metadata changes during delivery. Two Codex review rounds are scoped-clean through P2. Formatting, type-aware lint for the repairs, and diff checks pass. The first focused Gateway run passed 127 cases. Its fixture repairs and the previously unrun files completed with 383 passing cases; the two remaining lifecycle fixture failures were traced to test-pool routing and import order, repaired, and both pass in the real database-worker pool. A separate fixture type now uses InternalSessionEntry for internal lifecycle fields.
Initial CI exposed a widened lifecycle status type, one static import cycle through the broad session barrel, missing wrapper inventory modules, and test-fixture typing/setup issues. The repair commit addresses these, shrinks the obsolete assertion baseline entry, and keeps the actual owner behavior unchanged. Final CI on ad315b3 (run 38892235838) passes production/test types, lint, source contracts, architecture/Madge, baseline/T1/dialect ratchets, PostgreSQL conformance, and all test jobs except the inherited transcript expectation below. Its aggregate CI gate is red solely for that inherited failure. The abandoned-recovery cleanup case also passes in final CI. The unrelated transcript catalog NO_REPLY assertion fails identically on pinned main 28f8cab. A separate abandoned-recovery cleanup failure passed its focused main reproduction; the candidate replay also passes. This is recorded as intermittent and is not classified as inherited or fixed.
Knip production and script scans pass with zero findings. The final full-tree rescan confirms its sole finding (
ui/src/pages/chat/components/chat-message-group.test-support.ts: renderActivityGroup) is identical on main run 38881317413; the source, scan configs, runner, and lockfile match. Exact-base inventory and final CI confirm global T1 222 → 222 and dialect counts 0 → 0. The remaining changed-file T1 lookup serves the public deprecatedresolveTranscriptSessionKeyBySessionIdSDK contract through 2026-12-31; it is outside the fused worker operations. No SDK surface change or published-driver update cell applies.Diff versus the pinned base: +1,163 / −606 total; production +802 / −567 (net +235). Most lifecycle projection code is moved from the Gateway into the shared pure reducer; production growth carries its committed failure/recovery facts through the existing durable and memory receipts.
Automatic review disposition: the proposed extra lifecycle-generation check is not added because Gateway close drains accepted lifecycle persistence before the sole production generation rotation; the existing source/terminal authority remains at commit. The parentless memory-session metadata join is a bounded follow-up under the two-round cap; this PR claims the skip only for durable sessions.