Repository navigation
fix(sessions): rewind and switch without copying the transcript - #198929
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
CI on the PR head found five PR-caused failures. Each is fixed at its owner. - Import cycle: session-message-cut-target.ts called the planner while the planner imported its reader contract. The indexed SQLite reader and the in-place install now live in session-message-cut-in-place.kernel.ts, and the reader contract plus its memory implementation live with the policy owner in session-message-cut-plan.ts. session-message-cut-target.ts is gone, so the cycle has no edge left and no barrel was introduced. - Non-const assertion: the target row's payload went through `as TranscriptEvent` before `asOptionalRecord`, which already accepts unknown. The cast is removed, not annotated. - Main-thread SQLite: the kernel and session-transcript-active-path-repoint.ts run only inside the message-cut write transaction and are classified in the workerModules inventory with their callers as evidence. The read-only pre-cut precheck no longer opens a database on the Gateway thread: it is a session.messageCut.preflight worker operation, dispatched through the store's own worker the way the entry read above it already is. The native route without agent-database execution passes the handle it already opened. T1 call count returns to its base value of 167. - Eager import closure: session-actor-memory-fork.ts reached the memory reader through the retired module; it now imports the planner module that the PR wrapper inventory already lists, so the wrapper closure is unchanged. - Line cap: sessions-rewind.ts was at the 700-line cap. Its two history-mutation catch blocks now share rejectSessionMessageCutFailure in the existing session-rewind-failure-log.ts sibling, which keeps every verbatim refusal (locked model selection, workspace conflict, exceeded read budget) and the logged cause. Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: b6c6b181-53d9-8f32-9312-3ace7df109bd
|
🦞👀 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. |
`src/gateway/**/*server*.test.ts` runs in one fork with `isolate: false`, and this PR adds a Gateway-booting rewind test to that shard. The process-wide tracked worker count is therefore ambient: a neighbor's workers can still be retiring when the startup-trace memory case reads the line, which made CI report `workers=1` where the regex demanded `workers=0`, deterministically and in both parameter cases. The case owns the process memory fields; the case above it owns worker attribution, so it no longer pins a count it does not control. Co-authored-by: obviyus <[email protected]>
…trol v2026.11.3 rewinds and switches copied the whole transcript without inheritedThrough and appended one control displacing the source's active tip. That displaced path is exactly what the retained source bills, so treat it as the copy's inherited history; controls copied along with the history belong to older transcripts. A switch copy now keeps the sibling its source never billed, also after an in-place rewind (40, not 0), and a rewind copy no longer bills the prefix its source already counts. Co-authored-by: obviyus <[email protected]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Timestamp heuristics could not tell a v2026.11.3 whole-transcript copy from a normal session whose messages predate its lazily created header (CI: owner-attribution integration, 23 -> 0 after an in-place rewind). Record the fact at write time instead: the in-place cut's leaf control carries `billsDisplaced: true`, carried through the leaf codec and agent-core type. Usage bills the active path plus the branch each marked control displaced, minus inheritedThrough. Unmarked controls (pre-upgrade copies, in-session navigation) keep main/stable active-path accounting, so legacy data keeps stable's numbers and a later in-place cut never drops spend. Co-authored-by: obviyus <[email protected]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
The released SessionManager.appendLeafControl shape is a plugin SDK contract (test/type-contracts/session-persistence-compat.ts). The marker is a storage fact read by usage; it stays in the persisted leaf codec and the cut writer. Co-authored-by: obviyus <[email protected]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Maintainer override (approved by the lead: unrelated red CI may land once proven not caused by this PR). Exact head Failing job:
|
|
Landed in d59fe05 via the landpr maintainer override (native Talk red inherited, see #198248). Exact head Follow-ups: mark in-session navigation controls |
…claw#198929) Rewind and branch switch append one leaf control to the existing transcript instead of copying it into a new session, so a 57k-event (~357 MB) session rewinds in ~170 ms without exhausting the SQLite worker or leaving history rebuilding. In-place cut controls carry `billsDisplaced: true`; usage bills the active path plus branches displaced by marked controls, so upgraded v2026.11.3 sessions keep stable's totals. Co-authored-by: Ayaan Zaidi <[email protected]>
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).leafcontrol carriesbillsDisplaced: true(carried through the persisted leaf codec; the public SDK leaf type is unchanged), andselectBilledTranscriptEvents(now the single owner for the three usage scans) bills the active path plus the branch each marked control displaced, minusinheritedThrough, keeping the flat-transcript fallback. Unmarked controls (pre-upgrade copies, in-session navigation) keep main/stable active-path accounting, so legacy data keeps stable's numbers and no read-time inference is needed.rewindChatHistoryrestores the composer as soon assessions.rewindresolves, then reloads history and branches without blocking the refill.sessions-rewind.tsnow log the real failure cause throughrejectSessionMessageCutFailure; client messages are unchanged, including fix(sessions): keep large rewinds from exhausting the shared database worker #198786's read-budget refusal.session-message-cut-in-place.kernel.ts,session-transcript-active-path-repoint.ts); the pre-cut check is asession.messageCut.preflightworker operation, so main-thread SQLite calls do not grow.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). Branch numbers are fromd2d40112; the final head re-measured below. The branch's first-in-process time does not grow with transcript size (0.4–1.0 s run to run): 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 on the exact head
069928a1(ocx test, real Gateway RPC on an isolated throwaway gateway, 57,144 events with production-shaped messages and compaction entries, mock provider): rewind 173 ms, firstchat.history17 ms (no retry), second rewind 33 ms, branch switch 239 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. Pairs produced by v2026.11.3's rewind or switch (noinheritedThrough) count each turn once after upgrade (see Upgrade compatibility); stable counted the shared history in both the copy and its source.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 --diston the exact head069928a1passes, includingcheck-cli-bootstrap-imports(the earlier inherited budget failure is fixed onmain, merged in at72928ad6). The upgrade run below used that build.Review follow-ups (ClawSweeper on
e1c1b52)Fixed in
da5c4062, each with a regression test that fails without the fix (ocx test):SYNC_REBUILD_MAX_BYTES(the streaming reconcile owner publishes it instead) and streams the rows it does read withiterateSqliteQuerySync. Test:switches to an oversized branch without hydrating it in one transaction.parent_id; inactive-branch walks defer to the reconcile owner for leaf controls, resets and parentless continuations. Test:rewinds a parentless continuation to its canonical predecessor.invalid lagging projectioncase insessions-rewind.local-workspace.test.ts.activePathNavigationMovedlets chat admission accept an ancestor or empty-root view only when noleafcontrol landed after the client's anchor; absence fails closed. No protocol field. Test:rejects leaf {active-sibling,null} from before a branch switch, now using the real pre-switch identity.generation_mismatch.After these fixes, 57,144 events: warm rewind 13 ms, first
chat.history1 ms, 173 KB written. Ratchets unchanged (main-thread SQLite T1 167 → 167).Review follow-ups (ClawSweeper on
da5c406)Fixed in
94d9e0a9, with regressions that fail without the fix (ocx test):parent_id. It scans the navigation tree once per cut through the existing branch-listing scanner (scanSessionTranscriptTree), extracted asscanSessionTranscriptNavigationTree, and takes both ancestry (selectSessionTranscriptTreePathNodes) and tips (selectSessionTranscriptTreeTipNodes) from it. A published projection equals a full canonical rebuild by construction. Rewinds select an active predecessor and never build the tree. Test:keeps canonical ancestry and tips for a side-cursor history(side-cursor and parentless shapes; non-tip selections refuse before any workspace retirement).supersedesEntryId, andselectBilledTranscriptEventscollapses supersession chains. Two maintenance rewrites of one 10-token turn bill 10 (base 10/10/10, head 10/10/10); a real rewind and regenerate still bills both. Test:bills a rewritten turn once and a regenerated turn twice.57,144 events after this round: warm rewind 24 ms, first
chat.history1 ms, branch switch 175 ms (one canonical navigation scan, the same onesessions.branches.listruns; main's copying switch takes 11.4 s).Review follow-ups (ClawSweeper on
94d9e0a)Fixed in
e88a17ae:leafcontrol first and scans the navigation tree with that pending control included. The resolved leaf, the published path and the tips all come from that one tree. If the canonical owner would not select the requested target (for example a tip from before the latest reset), the request is refused in the preflight (not-branch-tip/off-active-path) before any workspace retirement, matching the memory reader and branch listing. No path is published that the scanner has not resolved with the control in place. A rewind whose predecessor is active, with no reset after it, still answers from the projection with index seeks only. Test:keeps canonical navigation for a reset-boundary history.lastUserTimestamp) stays on the active branch. Test:keeps the rewound branch's timing cursor on its active turn(latency matches a non-rewound control).57,144 events after this round: warm rewind 15 ms, first
chat.history1 ms, branch switch 181 ms.Review follow-ups (ClawSweeper on
e88a17a)Fixed in
88b33251:SESSION_MESSAGE_CUT_MAX_BYTES, checked on stored bytes before decoding); over-budget rewinds refuse with the typed read-budget error. A branch switch never decodes payloads. Test:repoints oversized history without hydrating it in one transaction.selectActivePathTranscriptEvents). Test:takes the continuation cursor from the active branch(new turn, no new turn, never rewound).57,144 events after this round: warm rewind 17 ms, first
chat.history1 ms, branch switch 188 ms.Review follow-ups (ClawSweeper on
88b3325)Fixed in
be636a6a: usage now resolves billing and timing through the same canonical navigation scan as the cut.displacedLeafId(the canonical active leaf immediately before it, after reset re-rooting). Billing covers the current active path plus, per control, the selected and displaced canonical paths, minusinheritedThrough, with supersession chains collapsed. No rawparentIdis read.bills and times every branch from canonical navigation(side cursor, sibling switch, rewind, rewind and continue, never rewound) andtimes an appended reply against a flat transcript's cursor.Usage vs base (
ocx base merge-base): identical for flat transcripts, supersession, rewind with and without a new turn, and never-rewound sessions. Two shapes intentionally differ: after a side-cursor rewind and a sibling switch, head keeps billing the displaced reply (and its latency sample), which base's probe dropped (side cursor: base 0 / head 10 tokens; sibling switch: base 10 / head 20 tokens).Control UI performance against CI's newer base
d6008485: chat boot JS gzip 1,314,167 B (base) → 1,313,829 B (head), −338 B. The remaining cap violations (request count, total CSS) are present on that base; this PR changes no CSS.Review follow-ups (ClawSweeper on
be636a6)Fixed in
24ae9b46:USAGE_COST_ROLLUP_VERSION11 → 12, so upgraded installs rebuild rollups whose accounting changed. Test:rebuilds a usage rollup published by an older accounting version(seeds a version-11 rollup that matches the transcript byte for byte; the refresh republishes 0 → 10 tokens; fails with the old version).consistent-return,no-unnecessary-type-parameters) fixed in code; four PR-only exports made module-private for the dead-export scan.Test-lines allocation: net test lines are +488 against the 400 allowance.
config/test-lines-allocations/198929-rewind-in-place-cut.txtrecords 88 lines: two irreducible harnesses (the cache-upgrade rebuild through the real usage worker, and the oversized in-place repoint), two comment lines on the startup-trace shard constraint, and fifteen lines pinning the upgrade cases (v2026.11.3 rewind copy 0, switch copy 40 before and after an in-place rewind; marked switch copy keeps the family at 70). Every other regression was folded into existing table-driven tests, and one superseded ordering test was deleted.mainwas merged in (72928ad6) to resolve a conflict in the generated worker-access inventory, which was regenerated (db:worker-inventory:checkcurrent).Review follow-ups (ClawSweeper on
720542a)Superseded by the write-time marker in
069928a1(see the CI follow-up below); kept for the review trail.Fixed in
907a0a89: the predates-header rule applies only to copies withoutinheritedThrough. Copies the merge base wrote carry the marker and a newer header; their inactive-sibling branch (never billed by the source) now survives an in-place rewind, keeping the family at 70. The worker-refresh fixture now gives those copies a realistically newer header. Test: the marked-switch-copy case inbills each real turn once across rewrites, copies and displaced paths(fails with 30 on720542a1).Review follow-ups (ClawSweeper on
907a0a8)Superseded by the write-time marker in
069928a1(see the CI follow-up below); kept for the review trail.Fixed in
c253b3df: a v2026.11.3 switch copy's selected sibling was never billed by its source, so skipping every pre-header branch lost it after an in-place rewind. The copy now infers its missinginheritedThroughfrom its own copy control (the source's displaced active tip) and ignores controls copied from older transcripts. Test:stableCopy("a1" | "a2b" | "a2b" + rewind)bills 0 / 40 / 40 (fails on907a0a89).CI
server-startup-trace(both attempts):src/gateway/**/*server*.test.tsruns in oneisolate: falsefork and this PR adds a Gateway-booting rewind test to it, so the process-wide tracked-worker count the memory case asserted (workers=0) is ambient there (same-process startups log 0–7). The test passes 3/3 in isolation on the merge ref and onmain; CI's annotation is truncated, so this head's CI run is the confirmation. Fixed infd03df1f: the memory case keepsrssMb/heapUsedMbpinned and no longer asserts the shared worker count; the case above it still owns worker attribution.Review follow-ups (CI on
c253b3d)usage.sessions-usage-owner-attribution.integration.test.tscaught the timestamp inference: a normal session whose messages predate its lazily created header looked like a v2026.11.3 copy and lost its spend after an in-place rewind (23 → 0). Fixed in069928a1by recording the fact at write time (billsDisplacedon the in-place control) and deleting all timestamp heuristics (720542a1,907a0a89,c253b3df).Provenance
Large-history payload bounds (b62210f)
That commit made the retained-history copy stream full events one at a time so a
valid large transcript could not exhaust the shared database worker. The in-place
repoint now keeps the same bound on its own payload read: the plan refuses any
selected branch whose retained bytes exceed the projection owner's existing
synchronous budget (
SYNC_REBUILD_MAX_BYTES), and the rows it does hydrate arestreamed through
iterateSqliteQuerySync, one decoded payload at a time. A branchof 1,000 one-MiB events no longer materializes in the worker; the streaming
reconcile owner publishes it instead.
Workspace validation before retirement (f833631)
That commit established that an invalid history selection leaves retained runtimes
and workspace edits untouched, by validating the cut before the local workspace is
retired. The in-place preflight keeps that invariant and no longer depends on a
clean projection to do it: when the active-path projection lags, the preflight
reconciles it through its owner inside a write transaction and then validates, so
missing-entry,not-user-message,off-active-path,not-branch-tipandalready-activestill refuse with the sandbox, the saved projection and the guestworktree edits intact.
Stale-pane chat admission (#113073)
That PR required that a message typed against one displayed branch never lands on
another branch after a different client switches it; the fence was the rotated
session id. Because an in-place cut keeps the session id, the fence is now the
appended
leafcontrol itself: the worker-prepared active-path facts reportwhether a navigation control landed after the client's displayed leaf, and chat
admission accepts an ancestor view — including the pinned empty root that shared
first sends rely on — only when none did. A pane that still shows the pre-switch
branch, or claims the empty root after a navigation, is refused with
active-leaf-changedand the transcript is untouched.Upgrade compatibility
This PR adds no schema change or migration: agent/state schema versions are byte-identical to the merge base. It adds one optional field to leaf-control events (
billsDisplaced: true), written only by the in-place cut. Existing copy-model transcripts stay readable as-is and keep their usage:session-cost-usage.legacy-copy-upgrade.test.tsbills rows produced by base's own rewind identically on both sides (70 tokens), and the worker-refresh suite pins v2026.11.3 copies at stable's bill (rewind copy 10, switch copy 50), also after a later in-place rewind (50).Full latest-stable → head upgrade, run on the exact head
069928a1on a separate Mac (artifacts kept with this task's proof):v2026.11.3seeded rewound, switched and forked sessions plus a pending local workspace handoff through its own rewind/switch/fork code;openclaw doctor --fixran the pre-existing agent 27→42 / state 22→40 migration (with backups); the head Gateway (ocx build --dist) then served real RPC.chat.historyper seeded sessionlifecycleRevisionbillsDisplaced: true(6), the 2 from v2026.11.3 stay unmarked; survives 2 Gateway restartsAccepted, unchanged from stable/main: v2026.11.3 copies keep stable's double count of the history they share with their retained source; in-session navigation controls (SessionManager) stay unmarked and keep active-path accounting; downgrading to an older binary ignores the mark and undercounts branches displaced after the upgrade. Retired sources must stay in the session family, as today.
Follow-ups (design review): mark in-session navigation controls too; then replace transcript-derived billing with an append-time usage ledger (one row per usage-bearing append, written in the same transaction, idempotent on session and entry id), backfilled once by Doctor with this rule, so reporting becomes a sum and the path walk, marker and
inheritedThroughsubtraction leave the runtime.Supersedes #198903 (same change; the publisher could not extend that branch).
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.