Repository navigation
Conversation
`sessions.rewind`, `sessions.fork` and `sessions.branches.switch` answered UNAVAILABLE with a generic retry message and discarded the thrown error, so a failing history mutation left no diagnosable trace. A production session with ~57k transcript events / ~357 MB could only be diagnosed by reading the SQLite worker's own crash output. Record the raw cause at both refusal points (upstream presence preparation and the local mutation) and keep the client-facing message unchanged. The helper lives in its own module because `sessions-rewind.ts` is already at the 700-line oxlint ceiling. Co-authored-by: obviyus <[email protected]>
Rewind and branch switch created a new session id and copied the whole transcript tree into it, appending one ~200-byte `leaf` control. The copy also required hydrating every event into the SQLite worker, so a session with ~57k events / ~357 MB exhausted the worker heap and the RPC failed with UNAVAILABLE. Rewind and switch now append the `leaf` control to the existing transcript in one write transaction and keep their session id. Validation reads only what the cut needs through index seeks: the target identity row, its active-path row, one event payload for the role and editor text, and the active leaf. Cost no longer depends on transcript size. The session id was the only unconditional fence against writers holding pre-cut state, so it is replaced by two fences every consumer already checks: `transcript_rewrite_watermarks.generation` rotates, and the append bumps `session_windows.transcript_updated_at` strictly, which fails the compare-and-swap in `replaceTranscriptSuffixEventsSync`. The lifecycle revision now rotates for in-place cuts too, which retires live local-workspace custody and owner-fenced transcript writers. Local workspace custody therefore transfers on the (session id, lifecycle revision) pair instead of the session id alone. Fork is unchanged: it legitimately creates a session from a prefix. Existing assertions that required a new session id or `previousSessionId` encoded the copy's identity rotation, not rewind behavior, and are updated to the generation/lifecycle contract. Incomplete: the in-memory session actor is a second message-cut install owner and still rotates the session id, and the local-workspace tests still encode session-id custody transfer. See ~/Developer/.agents/handoffs/rewind-constant-cost/REPORT.md. Co-authored-by: obviyus <[email protected]>
Rewind and branch switch created a new session id and copied the whole transcript tree into it to append one ~200-byte `leaf` control. The copy needed every event in the SQLite worker, so a session with ~57k events / ~351 MB exhausted the worker heap and the RPC answered UNAVAILABLE. Smaller sessions succeeded but held the write transaction for seconds and then left the active path projection dirty, so the next `chat.history` was refused while it rebuilt. Both message-cut install owners, the SQLite accessor and the in-memory session actor, now append the `leaf` control to the existing transcript and keep the session id. Validation reads only the target identity row, its active-path row, one event payload for the role and editor text, and the active leaf, all through existing indexes. The active-path projection is repointed incrementally in the same transaction: the removed suffix after the common ancestor plus the selected branch back to it, through the projection owner's existing suffix replacement. A lagging projection still falls back to its reconcile owner. The session id was the only unconditional fence against writers holding pre-cut state, so it is replaced by fences the same writers already check: the transcript generation rotates, the append bumps `session_windows.transcript_updated_at` strictly, which fails the compare-and-swap in `replaceTranscriptSuffixEventsSync`, and the lifecycle revision rotates, which retires owner-fenced transcript writers and live local-workspace custody. Custody therefore transfers on the (session id, lifecycle revision) pair instead of the session id alone. The Control UI needed no detection change: `windowReset`, the decreased message total and the ordinary entry publication are all content-derived. It now refills the composer as soon as `sessions.rewind` resolves instead of after the history and branch reloads. Fork is unchanged: it legitimately creates a session from a prefix. Measured with ocx test, base via ocx base merge-base, rewinding the newest user message. Warm rewind 23/20/20 ms at 1k/10k/57k events and 144/177/173 KB written, against 677/2358/11416 ms and 1.5/14.2/96.3 MB on the base commit; the first history read after the cut is 1 ms here and refused as "rebuilding" on the base. Gateway RPC end to end at 57k: rewind 190 ms, first `chat.history` 17 ms, second rewind 43 ms, branch switch 40 ms. Assertions that required a new session id, `previousSessionId` or a deferred projection encoded the copy, not rewind behavior, and move to the generation, lifecycle and incremental-repoint contract. Known open decision: usage now reports a rewound session without the rewound turns' tokens, because the usage scan follows the active path and no retired window remains. `usage.sessions-usage-owner-attribution.integration.test.ts` retains the previous contract and stays red to mark it. Co-authored-by: obviyus <[email protected]>
An in-place rewind or branch switch leaves a completed turn off the active path, and the usage scan counted only that path, so tokens that were really spent disappeared from Usage. Before in-place cuts the same total came from the retired copy, which kept counting the path that was active when it was retired. `selectBilledTranscriptEvents` now owns that selection for every usage scan: the active path plus every path a leaf control selected or displaced, minus paths an upstream transcript already counted. A sibling branch that was never active is not reachable that way and stays unbilled, matching the retired-copy accounting. The three usage scans that each repeated `dropInheritedTranscriptEvents(records, selectVisibleTranscriptEvents(records))` now call that one owner. Parity against the merge base, same rewind / branch switch / fork scenarios under `ocx test` on `ocx base merge-base` and here: every reported token total matches exactly (16 / 16 / 39 / 55 across the four scan points). `planSessionMessageCut` becomes fork-only, since both install owners now reach it only for a fork. Its rewind/switch whole-tree arms, `validateBranchTip`, `uniqueEntryId` and the `copyPrefix` parameter are removed. `session-cost-usage-worker-refresh.test.ts` keeps its assertions and is red in five cases: it specifies the copy accounting model at unit level, which this change replaces. See the handoff report for each case and its numbers. Co-authored-by: obviyus <[email protected]>
Folds the read-only message-cut preflight into the reader module that owns the indexed reads, and drops the speculative active-path predecessor fallback: an append chains onto the active tip, so a target on the active path has its stored parent on that path. Returns the projection facts columns to the rebuild module that already owned them, instead of a separate extraction. Adds the legacy upgrade test for the billing rule. Rows captured by running switch-then-rewind on the merge base through ocx base merge-base, where each cut copied the whole tree: the family reports 70 tokens there and 70 here, so billing historically active paths does not recount a turn a copied window already billed. Verified end to end first by replaying the dumped rows through `sessions.usage` on both sides. Co-authored-by: obviyus <[email protected]>
Rewind and branch switch append one leaf control to the existing transcript, so the usage fixtures that encoded the retired copy no longer describe any real history. Each rebuilt fixture is an in-place transcript, and every expected total is what the base commit reports for the same user history through the real rewind/switch path. - worker-refresh: switch fixtures now use planInPlaceSessionMessageCut with the memory cut reader; the leaf-control rows bill the displaced branch (206, 15, 35, 75, 75). - worker-refresh: drop the test that counted a switch-created copy transcript. - rollup-scan: rows carry the id and parent link a real appender writes, and the side append is the custom audit row the real writer appends without a parentId. Co-authored-by: obviyus <[email protected]>
selectBilledTranscriptEvents replaced selectVisibleTranscriptEvents in the usage scanners but dropped its flat fallback, so a transcript whose canonical rows carry no id billed nothing: no path reaches an id-less row. Restore the same rule the visible-event owner applies, which bills the whole transcript when no path exists and no leaf control claims one. Base reports 72 tokens for eight such rows; the new test asserts that number and passes on 896cc0c. Co-authored-by: obviyus <[email protected]>
Both delayed-receipt cases asserted that the stored row carried a new sessionId once C3's transaction committed. Rewind and switch no longer rotate the session id, so the same checkpoint now asserts the new incarnation the in-place cut installs: the session id is unchanged, and the lifecycle revision and the transcript generation are rotated, which are the fences that retire pre-cut readers and writers. The settlement subject is untouched: the binding, the identity publication and the native subscription are still asserted to be unreleased at the gate and released only after the receipt arrives. Co-authored-by: obviyus <[email protected]>
#198786 bounded the shared worker's heap during history cuts by reading the navigation projection and streaming retained events one at a time. Rewind and branch switch no longer copy anything, so only fork still needs that reader. - fork keeps the bounded reader and all three budgets (8 MiB per event, 8 MiB retained, 100k events); its prefix copy is the single remaining prefix-copy owner, so no second implementation exists. - the oversized-history regression now forks, which is the cut that reads payloads, and additionally asserts that an in-place rewind of the same oversized transcript succeeds. - drop the reader's payloadBytes total: its only consumer was the non-fork synchronous-rebuild decision, which the in-place path replaced with a projection repoint. - drop the per-event budget on the retired whole-transcript rewind preflight, which the indexed validator replaced. - the memory benchmark verifies the in-place contract it now exercises: the session id is unchanged, one leaf control row was appended, and every pre-cut row still holds its payload. - docs: rewind and branch switch keep the conversation and only move its active branch; the copy budget documents fork. Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: 78055507-b9bf-869d-95f7-fabd1c672bd6
|
🦞👀 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: blocked before merge. What this changesThis PR makes rewind and branch switching update the existing transcript instead of copying it into a new session. Example: Rewind a conversation containing 57,144 events and about 351 MB of transcript data.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 8 items remain Keep open: this useful performance repair has introduced memory, navigation, and workspace-preflight defects that block merge. Priority: P2 Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherControl UI history actions call Gateway session RPCs, which coordinate workspace settlement and session storage mutations; transcript projections feed history and model context, while usage scanners retain billed turns. flowchart TD
A[Control UI history action] --> B[Gateway session RPC]
B --> C[Workspace settlement]
B --> D[Session cut planner]
D --> E[SQLite or memory actor]
E --> F[History and model context]
E --> G[Usage accounting]
Technical reviewBest possible solution: Keep the in-place design while preserving canonical navigation, bounded payload processing, memory-generation invalidation, and worker-owned preflight. Do we have a high-confidence way to reproduce the issue? Current main visibly copies the transcript for rewind and switch, matching the supplied large-history report; review findings follow reachable source paths, without executing target code. Is this the best way to solve the issue? Removing the copy addresses the expensive operation directly, but the replacement must preserve the existing navigation and lifecycle owners rather than assuming raw identities provide equivalent semantics. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b27440329b4c. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +643, Tests +235, Docs +2, Other +12. Total +892 across 34 files. Added test files: 2. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. 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 November 14, 2026, 9:30 AM ET / 14:30 UTC. |
|
Superseded by #198929 (same change plus the CI fixes; the publisher could not extend this branch). |
What Problem This Solves
Rewind and branch switch copied the entire transcript into a new session id just to append one ~200-byte
leafcontrol row. On a production session with ~57k events (~357 MB) this:ERR_WORKER_OUT_OF_MEMORY, 512 MiB cap) before fix(sessions): keep large rewinds from exhausting the shared database worker #198786, failing unrelated requests that shared it;chat.historyfailed withsession history is rebuilding; retry shortlyuntil a background rebuild finished;#198786 bounded the worker memory of that copy. This change removes the copy for rewind and branch switch.
Why This Change Was Made
Why it copied. #110660 rotated the transcript identity so a stale live writer could not erase the leaf repoint with a snapshot replace.
transcriptWriteScopeIsCurrentcomparessessionIdfor every writer, while owner/lifecycle/writer-run fences are optional, so rotation was the only unconditional fence. Full snapshot replace is now test-support only; production writers append or use the suffix compare-and-swap.New design.
leafrow to the existing transcript, and repoint the active-path projection incrementally through the projection owner's suffix replacement. The index is never left dirty.SessionManager.transcriptVersion, prompt cache),transcript_updated_at(suffix CAS), and a rotatedlifecycleRevision(owner-fenced writers and local workspace custody, which compared(sessionId, lifecycleRevision)only).selectBilledTranscriptEvents(now the single owner for the three usage scans) bills the active path plus the selected and displaced path of every leaf control, minusinheritedThrough, and keeps the flat-transcript fallback.rewindChatHistoryrestores the composer as soon assessions.rewindresolves, then reloads history and branches without blocking the refill.sessions-rewind.tsnow log the real failure cause; the client message is unchanged.Contract change. A rewind or branch switch keeps
sessionId;previousSessionIdis no longer set by them. The Control UI already detects the cut from content (windowReset, decreased totals, entry publication), so no UI detection change was needed.Evidence
Benchmark (
ocx test, vitest from source; base side viaocx base merge-base), synthetic transcript shaped like production (~6.25 KB average event, some ~250 KB events):mainrewindmain→ branchchat.historyafter rewindmain→ branchrebuilding→ 1 msrebuilding→ 1 msrebuilding→ 1 msmain= merge based98f18ff7c3d(includes #198786). The branch's first-in-process time is flat across sizes: it is worker start (entry read, cold-restore check and commit round trips), the same cost a session-entry control write pays. Warm rewinds are the steady state.main's first read after the cut was measured on the pre-rebase base896cc0cc44d7; #198786 does not change index rebuild.End to end (
ocx test, real Gateway RPC on an isolated throwaway gateway, 57,144 events, mock provider): rewind 190 ms, firstchat.history17 ms (no retry), second rewind 43 ms, branch switch 40 ms; the next model turn contains the new prompt and none of the rewound messages.Stale-writer race test (
session-accessor.sqlite-message-cut-fence.test.ts,ocx test): fails with the new fence removed (the stale append is admitted onto the pre-cut tail), passes with it.Usage parity, base vs branch on the same histories via the real rewind/switch/fork path (
ocx base merge-base/ocx test): identical for every scenario (16 / 16 / 39 / 55 cumulative; 206, 15, 75, 75, 35, 72 for the rebuilt fixtures). A legacy copied pair produced by base's own rewind reports 70 tokens on both sides, so sessions rewound before this change are not double counted.Tests (
ocx test): message-cut (incl. fence, native, native-binding, content, branches), sessions-rewind (incl. local-workspace, handoff, incognito, image-context), server-close rewind, usage (worker-refresh, rollup-scan, owner-attribution, legacy-copy-upgrade), #198786's oversized-history regression (now exercised through fork, plus an in-place rewind of the same transcript that succeeds), and the Control UI chat-history suites. Assertions that encoded the copy mechanism were rewritten to assert the same behavior through the new contract; every changed usage expectation was taken from a base measurement.tsgo:core, oxfmt, oxlint clean.Packaging:
ocx build --dtsandpnpm test:install:smokeare blocked on this head by an inheritedmainfailure incheck-cli-bootstrap-imports(agents/identity-file.worker.js: 240 evaluated modules exceeds budget 220). The identical failure reproduces on the unmodified merge based98f18ff7c3d; this PR does not touch that worker's import graph.Follow-ups (not in this PR): other whole-transcript loads remain in parent fork, reset boundary, transcript mirror, session-manager reload, cost reporting and memory capture.