Skip to content

fix(sessions): scope transcript byte stats to the active reset window - #120059

Closed
ayaangazali wants to merge 2 commits into
openclaw:mainfrom
ayaangazali:fix/transcript-byte-fuse-reset-window
Closed

ayaangazali wants to merge 2 commits into
openclaw:mainfrom
ayaangazali:fix/transcript-byte-fuse-reset-window

Conversation

@ayaangazali

@ayaangazali ayaangazali commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #119984.

After /new, a fresh session can fail on every single turn with:

Context is too large and auto-compaction could not recover this turn. Try again, use /compact, or use /new to start a fresh session.

The advice in that message is the thing that does not work. /new is exactly what the user already did.

The cause is that /new does not shrink what the byte fuse measures. A reset writes a boundary event into the transcript, but it does not delete the events before it; the projection keeps them and readers are expected to apply the reset window at read time. That is how the message readers behave: resolveVisibleMessagePositions and readVisibleMessageRange in src/config/sessions/session-accessor.sqlite-reset-window.ts both honor the latest reset boundary.

readSessionTranscriptActiveStats was the one reader that skipped that step. It summed LENGTH(event_json) over every row in the active projection with no boundary filter, so the bytes dropped by /new kept counting. Everything downstream inherits that number: it is the only source of snapshot.byteSize, which becomes transcriptByteSize, which drives both shouldCompactByTranscriptBytes and the force flush check in src/auto-reply/reply/agent-runner-memory.ts. Once the total sits above maxActiveTranscriptBytes it stays there, so preflight compaction fires on a session that has nothing left to compact, fails, and prints the message above. Next turn, same thing.

Why This Change Was Made

The fix belongs in the reader, not in the fuse. The fuse is asking a reasonable question, "how many bytes is this session carrying," and it was being handed the wrong answer. Guarding at the call site would have left the same wrong number available to the force flush path next to it.

Rather than add a second boundary-aware reader, I moved the aggregate into session-accessor.sqlite-reset-window.ts, which already owns boundary discovery and already caches the resolved window per generation. The consumer in session-accessor.sqlite-active-events.ts collapses to a single delegation and its duplicate copy of the query is deleted, so there is one byte-stats path instead of two.

The retained pre-boundary span is counted using the window's own keptMessagePositions rather than a contiguous active-position range. That matters because a reset retains only the user and assistant messages named by the window; an intervening toolResult is dropped from the next turn. Counting the whole span would have kept discarded tool-result bytes on the fuse, which is the exact latch this PR is trying to remove. Thanks to ClawSweeper for catching that on the first revision.

Scope is narrow by construction. Boundary discovery returns no window unless the latest boundary is a reset, so sessions with no reset, and sessions whose latest boundary is a compaction, sum the whole projection exactly as before. This only changes the case the issue is about.

I did not touch the projection writer. Keeping dropped events on disk and windowing at read time is the existing design, the message readers depend on it, and changing it would be a much larger change than this bug needs.

User Impact

/new now actually clears the byte fuse. A fresh session starts from the bytes it really carries instead of inheriting the ones the reset dropped, so the "Context is too large" loop ends and the advice in that error message works.

No config, schema, or default surface changes. readSessionTranscriptActiveStats keeps its name, signature, and return shape.

Evidence

Two regression tests in src/config/sessions/session-accessor.sqlite-active-events.test.ts:

  1. a large turn, a reset with no retained history, then a short turn, asserting the reader reports one visible event and drops back under a kilobyte;
  2. a reset carrying firstKeptEntryId with a 20 KB toolResult sitting between the retained user and assistant messages, asserting the reader reports two events and stays under a kilobyte. The test also asserts readSessionTranscriptMessageEventById(scope, "kept-tool") is undefined, so the fixture is pinned to the same visibility rule the message readers use.

Both were confirmed to pin the fix by breaking the code and rerunning against the final shape:

× stops counting pre-reset bytes once /new drops the earlier transcript
AssertionError: expected 3 to be 1

× excludes discarded tool results from the retained pre-reset window
AssertionError: expected 4 to be 2

then restored for 13/13.

Surrounding surfaces stay green on current main: src/config/sessions 57 files / 771 tests, and the fuse owner src/auto-reply/reply/agent-runner-memory 2 files / 67 tests. tsgo -p tsconfig.core.json and tsgo -p test/tsconfig/tsconfig.core.test.json are both clean, oxlint is clean on the changed files, and git diff --check is clean.

One gap stated plainly rather than buried: I proved this at the reader and through the suites above, not by driving a live provider into the compaction loop and watching a post-/new turn succeed. The reader is the single source of every byte number both fuses use, which is why I am confident in the mechanism, but I have not produced a runtime session trace. If that trace is required before merge, say so and I will set up a gateway and capture it rather than guess at what it would show.

AI-assisted: written with AI assistance. I read the reset-window module, the active-events reader, and the fuse call sites myself, traced every consumer of the byte number, and ran the tests and gates locally.

@ayaangazali
ayaangazali marked this pull request as ready for review August 6, 2026 23:02
Copilot AI lite review requested due to automatic review settings August 6, 2026 23:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@ayaangazali
ayaangazali force-pushed the fix/transcript-byte-fuse-reset-window branch from 48a899e to bccd904 Compare August 6, 2026 23:46
@ayaangazali

Copy link
Copy Markdown
Contributor Author

CI status on this branch, since the red marks are not from this change.

check-test-types was real and is now green. It failed on ui/src/e2e/appearance-settings-defaults.e2e.test.ts with TS2304: Cannot find name 'browser'/'server'. That breakage came from #119978 at 14:46, my original base a73910dfba8 was cut at 15:57, and the fix dc0b9958999 (browser to suite.browser, server to suite.server) landed at 16:09, twelve minutes after I branched. I rebased onto 7c9596b0077 to pick that fix up rather than writing my own. It now reports SUCCESS.

checks-node-compact-large-1 and -3 are pre-existing. Both reproduce on a clean checkout of current main at 7c9596b0077 with none of this PR's changes:

checks-node-compact-large-6 is caused by the base, not the diff. This is the cleanest signal of the four. The commit is patch-identical before and after the rebase (git patch-id --stable gives 2d6016302b63 for both 48a899ee2b4 and bccd9049d62), and the shard flipped:

  • run 31130654982, base a73910dfba8: checks-node-compact-large-6 SUCCESS
  • run 31132294115, base 7c9596b0077: checks-node-compact-large-6 FAILURE

Same patch, different base, different result, so the cause is in a73910dfba8..7c9596b0077. The failure is chat-responsive.browser.test.ts > keeps the native gateway picker as compact as sidebar menus, where the computed styles come back as empty strings instead of 8px/13px/30px. I did not narrow it to a single commit, because this browser test also fails on my macOS checkout at every commit I tried including well before this range, so my local runs are not a trustworthy oracle for it and I would rather say that than guess.

check-dependencies is repo-wide. pnpm deadcode:full reports Unused files (1): ui/src/pages/chat/chat-host.test-fixture.ts, added by #120055. It fails the same way on #120069, #120068, #120067, #120052, and #120051.

This PR touches three files under src/config/sessions and none of them are in those module graphs. I do not have rerun rights on this repo, so I could not re-trigger the jobs myself. Happy to rebase again once main is green.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 7, 2026
@clawsweeper

clawsweeper Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 6, 2026, 10:39 PM ET / August 7, 2026, 02:39 UTC.

ClawSweeper review

What this changes

The PR makes session transcript byte statistics count only the logical messages visible after /new, including only retained pre-reset user and assistant messages.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 4 items remain

Keep this PR open: current main still counts the whole reset-retained projection, while the patch fixes that at the canonical visibility owner and resolves the prior retained-tool-result finding. It still needs an after-fix runtime trace, and the repository’s required direct Codex-source inspection was unavailable in this checkout.

Priority: P1
Reviewed head: 120ccb7ca2b1dd3f28a925bdddd9ef03fd8a593a

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The owner-layer patch and regressions are strong, but real behavior proof remains a merge gate.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: Focused regression tests and exact-head CI are useful, but no after-fix runtime trace shows /new unblocks the next turn; please attach redacted terminal or gateway output. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: Focused regression tests and exact-head CI are useful, but no after-fix runtime trace shows /new unblocks the next turn; please attach redacted terminal or gateway output. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main defect: The active-stat reader sums every active transcript row without applying the existing reset window.
Canonical owner boundary: Reset-window discovery already defines retained pre-reset message positions and post-boundary visibility; the patch moves byte accounting to that owner instead of adding a fuse-side exception.
Both byte consumers: The active statistic becomes the snapshot byte size used by both preflight compaction and forced memory flushing.
Findings None None.
Security None None.

How this fits together

SQLite transcript storage retains historical events across reset boundaries, while reset-window readers determine the logical transcript visible to the next agent turn. The byte statistic feeds compaction and memory-flush safeguards before an agent runs.

flowchart LR
  A[Stored transcript events] --> B[Reset boundary]
  B --> C[Visible message window]
  C --> D[Transcript byte statistics]
  D --> E[Compaction safeguards]
  E --> F[Next agent turn]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: Focused regression tests and exact-head CI are useful, but no after-fix runtime trace shows /new unblocks the next turn; please attach redacted terminal or gateway output. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - Merging changes byte accounting for existing reset transcripts; attach runtime evidence that a reset drops below the fuse and permits the following turn.
  • Resolve merge risk (P1) - A final Codex-runtime merge recommendation remains blocked because the required sibling Codex source is unavailable for direct inspection.
  • Complete next step (P2) - No mechanical repair remains; contributor runtime proof and the unavailable Codex contract check are the merge blockers.
Agent review details

Security

None.

PR surface

Source +36, Tests +76. Total +112 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 61 25 +36
Tests 1 76 0 +76
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 137 25 +112

Review metrics

Metric Value Why it matters
Production versus regression coverage production +61/-25; tests +76/-0 The net production growth is justified by consolidating byte accounting at the existing reset-window ownership boundary and deleting the duplicate aggregate.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.sqlite-active-events.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-active-events.ts, serialized state: src/config/sessions/session-accessor.sqlite-reset-window.ts, unknown-data-model-change: src/config/sessions/session-accessor.sqlite-active-events.test.ts, unknown-data-model-change: src/config/sessions/session-accessor.sqlite-reset-window.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #119984
Summary: This PR is the candidate owner-layer repair for the linked reset-window byte-accounting failure.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Capture reset recovery proof (recommended)
    Before merge, attach redacted runtime output showing an over-limit session resets below the byte fuse and its next turn completes.
  2. Pause until contract review is possible
    Keep the PR open until a reviewer can inspect the required Codex runtime source alongside the runtime trace.

Technical review

Best possible solution:

Keep one reset-window-owned byte-stat path, then attach a redacted after-fix gateway trace proving /new clears the fuse and the next turn succeeds.

Do we have a high-confidence way to reproduce the issue?

Yes in source: current main retains pre-reset rows but its byte aggregate ignores the reset window, and the resulting byte value reaches both compaction safeguards. The contributor has not supplied an after-fix runtime trace.

Is this the best way to solve the issue?

Yes for the OpenClaw-owned defect: the reset-window reader owns logical transcript visibility, so correcting its shared statistic repairs both consumers without a fuse-side workaround. Direct Codex contract inspection is still required before a final merge recommendation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 21e9634f1084.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P1: The reported condition can repeatedly prevent an affected agent session from completing any subsequent turn.
  • merge-risk: 🚨 session-state: The PR intentionally changes which persisted transcript events count toward reset-session compaction safeguards.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Focused regression tests and exact-head CI are useful, but no after-fix runtime trace shows /new unblocks the next turn; please attach redacted terminal or gateway output. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • steipete: Reset cursor preservation and the SQLite transcript refactor are central predecessors to this reset-window behavior. (role: session architecture lineage owner; confidence: high; commits: 9ae9fcb1cdd2, 4273ca9dbd9b; files: src/config/sessions/session-reset-boundary-event.ts, src/config/sessions/session-accessor.sqlite-reset-window.ts)
  • Shakker: Blame attributes the current whole-projection stats implementation and adjacent current session path to this contribution. (role: current session-accessor contributor; confidence: medium; commits: e118e607bc68; files: src/config/sessions/session-accessor.sqlite-active-events.ts, src/auto-reply/reply/agent-runner-memory.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach a redacted trace of an over-limit session, /new, the reduced byte accounting, and a successful next turn.
  • After updating the PR body with that proof, request a fresh ClawSweeper review if one is not triggered automatically.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-07T00:32:08.678Z sha bccd9049d621d5f2ae4a14e0dcadf709c6543cf1 :: needs real behavior proof before merge. :: [P1] Count only retained pre-reset messages

@ayaangazali
ayaangazali force-pushed the fix/transcript-byte-fuse-reset-window branch from bccd904 to 120ccb7 Compare August 7, 2026 01:51
@ayaangazali

Copy link
Copy Markdown
Contributor Author

Thanks, the P1 was right and I have fixed it at 120ccb7ca2b.

The retained-tail predicate did use the contiguous active-position range from firstKeptEntryId to the boundary, so an oversized toolResult sitting between the retained user and assistant messages still counted against the fuse. That is the same latch the PR is meant to remove, just narrower.

It now counts the window's own keptMessagePositions instead:

eb.and([
  eb("active.active_position", "<", window.boundaryActivePosition),
  eb("active.message_position", "in", keptMessagePositions),
])

Those positions are already filtered to user and assistant roles by findLatestResetMessageWindow, so the byte reader and the message readers now apply the same visibility rule instead of two similar ones. That also made keptFromActivePosition unnecessary, so it is gone from the window type.

New regression covers exactly your case: a reset carrying firstKeptEntryId with a 20 KB toolResult between the retained messages. It asserts two visible events and under a kilobyte, and it asserts readSessionTranscriptMessageEventById(scope, "kept-tool") is undefined so the fixture stays pinned to the visibility contract rather than to my predicate. Reverting the predicate fails it with expected 4 to be 2.

src/config/sessions is 57 files / 771 tests green on current main, both tsgo lanes and oxlint are clean.

On the real-behavior proof: I have not produced one and I am not going to claim otherwise. The tests above are reader-level. If a runtime session trace showing a post-/new turn staying under the fuse is required before merge, I will set up a gateway and capture it rather than describe what it would probably show.

The remaining red checks are not from this branch. checks-node-compact-large-1, -3 and check-dependencies were inherited breakage that #120080 has since fixed on main, and this push is rebased onto that, so they should clear on the next run.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 7, 2026
@clawsweeper

clawsweeper Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix(sessions): scope transcript byte stats to the active reset window This is item 1/1 in the current shard. Shard 21/44.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@fuller-stack-dev

Copy link
Copy Markdown
Member

Thank you, @ayaangazali — this PR identified the canonical reset-window owner and established the right repair direction. Since this head was authored, current main added valid paired tool-result retention to reset model context. Merging this unchanged would therefore undercount model-visible retained bytes. I opened fresh-base successor #124126, which carries the reset-window fix forward with exact paired-result accounting, hot-path cache coverage, and explicit credit to you. I am leaving your contributor history untouched and closing this in favor of that replacement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /new does not reset the maxActiveTranscriptBytes fuse — fresh session at 0% context fails every turn with "Context is too large"

3 participants