Skip to content

fix(sessions): rewind and switch without copying the transcript - #198929

Merged
obviyus merged 28 commits into
mainfrom
openclaw/amber-shrimp
Nov 15, 2026
Merged

obviyus merged 28 commits into
mainfrom
openclaw/amber-shrimp

Conversation

@obviyus

@obviyus obviyus commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Rewind and branch switch copied the entire transcript into a new session id just to append one ~200-byte leaf control row. On a production session with ~57k events (~357 MB) this:

#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. transcriptWriteScopeIsCurrent compares sessionId for 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.

  • Rewind/switch run one write transaction: validate the target with index seeks only (identity rows, active-path rows, one event row), rotate the transcript generation, append the one leaf row to the existing transcript, and repoint the active-path projection incrementally through the projection owner's suffix replacement. The index is never left dirty.
  • Fences that replace the identity rotation: transcript generation (delta cursors, context version, SessionManager.transcriptVersion, prompt cache), transcript_updated_at (suffix CAS), and a rotated lifecycleRevision (owner-fenced writers and local workspace custody, which compared (sessionId, lifecycleRevision) only).
  • Fork still creates a new session from a prefix and uses fix(sessions): keep large rewinds from exhausting the shared database worker #198786's bounded streaming reader as the single prefix-copy owner.
  • The memory-actor install owner (incognito/unbound sessions) follows the same identity contract.
  • Usage: rewound turns were really billed. The in-place cut's leaf control carries billsDisplaced: true (carried through the persisted leaf codec; the public SDK leaf type is unchanged), and selectBilledTranscriptEvents (now the single owner for the three usage scans) bills the active path plus the branch each marked control displaced, minus inheritedThrough, 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.
  • Control UI: rewindChatHistory restores the composer as soon as sessions.rewind resolves, then reloads history and branches without blocking the refill.
  • Both catch blocks in sessions-rewind.ts now log the real failure cause through rejectSessionMessageCutFailure; client messages are unchanged, including fix(sessions): keep large rewinds from exhausting the shared database worker #198786's read-budget refusal.
  • The in-place install, its indexed reader and the projection repoint run inside the session database worker (session-message-cut-in-place.kernel.ts, session-transcript-active-path-repoint.ts); the pre-cut check is a session.messageCut.preflight worker operation, so main-thread SQLite calls do not grow.

Contract change. A rewind or branch switch keeps sessionId; previousSessionId is 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 via ocx base merge-base), synthetic transcript shaped like production (~6.25 KB average event, some ~250 KB events):

Events (raw JSON) main rewind Branch rewind, first in process Branch rewind, warm Bytes written main → branch First chat.history after rewind main → branch
1,000 (6.1 MB) 746 ms 528 ms 19 ms 1.53 MB → 144 KB rebuilding → 1 ms
10,000 (61.4 MB) 4,284 ms 443 ms 20 ms 14.2 MB → 177 KB rebuilding → 1 ms
57,144 (351 MB) 12,367 ms 1,034 ms 20 ms 96.3 MB → 173 KB rebuilding → 1 ms

main = merge base d98f18ff7c3d (includes #198786). Branch numbers are from d2d40112; 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 base 896cc0cc44d7; #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, first chat.history 17 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 (no inheritedThrough) 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 --dist on the exact head 069928a1 passes, including check-cli-bootstrap-imports (the earlier inherited budget failure is fixed on main, merged in at 72928ad6). 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):

  • Bounded branch repoint: the repoint refuses a selected branch whose retained bytes exceed SYNC_REBUILD_MAX_BYTES (the streaming reconcile owner publishes it instead) and streams the rows it does read with iterateSqliteQuerySync. Test: switches to an oversized branch without hydrating it in one transaction.
  • Canonical ancestry: the rewind predecessor comes from the canonical active projection, not the raw 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.
  • Validate before workspace retirement: a lagging projection is reconciled inside a write transaction before validation, so invalid selections never retire the workspace. Test: invalid lagging projection case in sessions-rewind.local-workspace.test.ts.
  • Stale-pane admission: worker-prepared activePathNavigationMoved lets chat admission accept an ancestor or empty-root view only when no leaf control 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.
  • Memory generation: memory-actor cuts rotate the transcript generation with the watermark, so a pre-cut raw-delta cursor gets generation_mismatch.

After these fixes, 57,144 events: warm rewind 13 ms, first chat.history 1 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):

  • Canonical navigation from one owner: the in-place cut no longer walks raw parent_id. It scans the navigation tree once per cut through the existing branch-listing scanner (scanSessionTranscriptTree), extracted as scanSessionTranscriptNavigationTree, 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).
  • Supersession billing: the usage projection keeps supersedesEntryId, and selectBilledTranscriptEvents collapses 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.history 1 ms, branch switch 175 ms (one canonical navigation scan, the same one sessions.branches.list runs; main's copying switch takes 11.4 s).

Review follow-ups (ClawSweeper on 94d9e0a)

Fixed in e88a17ae:

  • Resolve the planned control before publishing: the cut builds its leaf control 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.
  • Usage timing cursor: displaced paths are billed first and the active path last, so the continuation cursor (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.history 1 ms, branch switch 181 ms.

Review follow-ups (ClawSweeper on e88a17a)

Fixed in 88b33251:

  • Payload-free navigation reads: identity, predecessor and tip lookups read navigation and projection columns only. The one payload a rewind needs for editor text is read after validation, through fix(sessions): keep large rewinds from exhausting the shared database worker #198786's budget (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.
  • Timing cursor from the active branch: billing dedup decides which rows count; the continuation cursor and latency ancestry come separately from the canonical active path (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.history 1 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.

  • Billing: the scan records each leaf control's 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, minus inheritedThrough, with supersession chains collapsed. No raw parentId is read.
  • Timing: each reply's latency comes from its own canonical user ancestor, computed per row; the continuation cursor comes from the active path's latest user. The order-sensitive displaced-timestamp state is deleted. Histories without leaf controls keep base's file-order cursor (flat fallback).
  • Tests: bills and times every branch from canonical navigation (side cursor, sibling switch, rewind, rewind and continue, never rewound) and times 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:

  • Rollup cache version: USAGE_COST_ROLLUP_VERSION 11 → 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).
  • CI lint (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.txt records 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.

main was merged in (72928ad6) to resolve a conflict in the generated worker-access inventory, which was regenerated (db:worker-inventory:check current).

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 without inheritedThrough. 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 in bills each real turn once across rewrites, copies and displaced paths (fails with 30 on 720542a1).

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 missing inheritedThrough from 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 on 907a0a89).

CI server-startup-trace (both attempts): src/gateway/**/*server*.test.ts runs in one isolate: false fork 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 on main; CI's annotation is truncated, so this head's CI run is the confirmation. Fixed in fd03df1f: the memory case keeps rssMb/heapUsedMb pinned 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.ts caught 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 in 069928a1 by recording the fact at write time (billsDisplaced on 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 are
streamed through iterateSqliteQuerySync, one decoded payload at a time. A branch
of 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-tip and
already-active still refuse with the sandbox, the saved projection and the guest
worktree 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 leaf control itself: the worker-prepared active-path facts report
whether 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-changed and 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.ts bills 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 069928a1 on a separate Mac (artifacts kept with this task's proof): v2026.11.3 seeded rewound, switched and forked sessions plus a pending local workspace handoff through its own rewind/switch/fork code; openclaw doctor --fix ran the pre-existing agent 27→42 / state 22→40 migration (with backups); the head Gateway (ocx build --dist) then served real RPC.

Check Result
chat.history per seeded session 4/4 identical (ids, roles, text, per-message tokens)
Settings, pending workspace handoff, lifecycleRevision preserved
Pre-upgrade branches both listed, original still active
New in-place rewind / branch switch on upgraded copy-model data working (8–147 ms)
Usage per session, stable → head identical on all six sessions (total 55 → 55)
After the new rewind and switch (no new turns) 55, every row unchanged
One real model turn per copy, then rewind, switch and a Gateway restart 55 → 231 (+88 each), unchanged by the rewind, switch and restart
Stored leaf controls every control head wrote carries billsDisplaced: true (6), the 2 from v2026.11.3 stay unmarked; survives 2 Gateway restarts

Accepted, 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 inheritedThrough subtraction 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.

obviyus and others added 12 commits November 14, 2026 19:13
`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
@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: XL labels Nov 14, 2026
@obviyus obviyus changed the title Publish openclaw/amber-shrimp fix(sessions): rewind and switch without copying the transcript Nov 14, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 14, 2026
obviyus and others added 2 commits November 15, 2026 10:59
`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]>
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 15, 2026
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]>
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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]>
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override (approved by the lead: unrelated red CI may land once proven not caused by this PR).

Exact head 7ed472af38ace1610430ef43939ad02a15b3a5fd: ClawSweeper ready, no findings. Exact-head 57,144-event Gateway rewind E2E passes (rewind/history/switch). A v2026.11.3 → head upgrade with doctor --fix matches stable usage exactly (55 → 55; 231 after real turns, held through rewind, switch and a restart). The only commit since 069928a1 reverts a public type field (no runtime change).

Failing job:

  • checks-node-changed-compact-large-38-2: src/gateway/talk/handlers/client-native-control.test.ts (native Talk post-cancel consultation assertion). Inherited: the same signature is documented in fix(test): native Talk fixture retires prompt baselines between cases #198248 and failed on this PR's earlier heads before any Talk-adjacent change. This PR changes no Talk code (git diff origin/main...HEAD -- src/gateway/talk src/talk is empty).

@obviyus
obviyus merged commit d59fe05 into main Nov 15, 2026
177 of 180 checks passed
@obviyus
obviyus deleted the openclaw/amber-shrimp branch November 15, 2026 07:42
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in d59fe05 via the landpr maintainer override (native Talk red inherited, see #198248).

Exact head 7ed472af: ClawSweeper ready; 57k-event Gateway rewind E2E passes; v2026.11.3 → head upgrade keeps stable usage (55 → 55). Real-provider prompt cache after rewind/switch: Anthropic unchanged (full hit both sides); OpenAI with the native prompt_cache_key keeps ~21.6k cached tokens on head vs 0–6.5k on main, because the session id no longer rotates.

Follow-ups: mark in-session navigation controls billsDisplaced; append-time usage ledger (schema change, needs approval).

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant