Skip to content

fix: streamed messages pushed into scrollback twice — commit finalize via upsert - #74

Merged
saucam merged 3 commits into
mainfrom
fix/daemon-scrollback-double-push
Jul 2, 2026
Merged

fix: streamed messages pushed into scrollback twice — commit finalize via upsert#74
saucam merged 3 commits into
mainfrom
fix/daemon-scrollback-double-push

Conversation

@saucam

@saucam saucam commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Problem

The #50 fix covered only #artificiallyStreamText. The main streaming path still pushed every streamed message into scrollback twice — once when text_delta creates the message, again at text_done — and the same double-push lived in #flushActiveAssistant (interrupt/turn-boundary flush) and #finalizeActiveThinking (every thinking block).

Consequences (all verified in code):

  1. Duplicate rows / overlapping messages on re-attachscrollback.replay carried two entries per streamed messageId; the web virtualizer's ${sid}:${messageId}-keyed size/element caches collided → the residual cause of the intermittent overlap fix: O(N) session switch and intermittent message overlap in web UI #73 partially fixed.
  2. Memory episode fragmentation — the chunker received the stream-start push with empty content, splitting every plain turn into a prompt-only user_turn + a promptless assistant_turn.
  3. Scrollback byte cap disabled — push Memory/sqlite vec retrieval #1 accounted ~200 bytes, eviction subtracted the grown size for both entries → #bytes drifted negative and the 20MB cap never fired.

Fix

  • ScrollbackBuffer records the accounted size per entry and upserts by messageId: re-pushing a buffered id re-accounts the existing entry in place (keeping replay position) instead of appending a duplicate. Eviction subtracts exactly what was added — negative drift is structurally impossible. updateMessage is now O(1) via the id index (was a front-to-back scan on every tool state transition).
  • Stream-start sites push to scrollback only; the new #commitStreamed emits the durable transcript row + chunker event exactly once, at finalize, with final content. #artificiallyStreamText drops its bespoke reset-and-updateMessage dance for the same helper.
  • #seq seeds past the persisted transcript tail on resume (was reset to 0), making seq usable as a monotonic replay cursor for future attach pagination.

Tests

New session-stream-commit.test.ts (12 tests) pins:

  • one-scrollback-entry-per-messageId across all four finalize paths (text_done / thinking_done / batch-reply artificial streaming / turn-boundary flush)
  • buffer upsert + byte-cap enforcement under by-reference growth (the negative-drift regression)
  • chunker episode pairing — one combined user+assistant episode per turn, plus a test documenting the pre-fix fragmentation
  • seq continuation after resume

Full suite: 640 pass / 3 pre-existing failures (optional openai/@google/generative-ai packages not installed locally). Lint clean.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Prevented duplicate scrollback/transcript entries during streamed assistant/thinking flows by ensuring finalized content is committed exactly once across all finalize/flush paths.
    • Fixed session resume so new messages continue with the correct monotonic sequence value.
    • Improved scrollback reliability: message-id based upserts, accurate UTF-8 byte accounting on updates, and proper eviction that forgets updated items.
  • Tests
    • Added a regression test suite covering streamed commit “exactly once”, scrollback upsert/byte/eviction behavior, and resume sequence continuity.

… via upsert, not a second push

The #50 fix covered only #artificiallyStreamText. The main streaming path
still called #persistAndBuffer at BOTH stream start (text_delta creates the
message) and finalize (text_done), and the same double-push lived in
#flushActiveAssistant (interrupt/turn-boundary flush) and
#finalizeActiveThinking (every thinking block). Consequences:

- scrollback.replay carried two entries per streamed messageId; clients
  rendered the message twice and the web virtualizer's messageId-keyed
  caches collided (the residual cause of the 'intermittent message
  overlap' that #73 partially fixed)
- the memory chunker received the stream-start push with empty content,
  emitting a prompt-only user_turn episode and then a promptless
  assistant_turn — every plain turn fragmented into two half-episodes
- byte accounting drifted negative (push #1 accounted the empty size,
  eviction subtracted the grown size twice), permanently disabling the
  20MB scrollback cap

Fixes:

- ScrollbackBuffer now records the accounted size per entry and upserts
  by messageId: re-pushing a buffered id re-accounts the existing entry
  in place (keeping its replay position) instead of appending a
  duplicate. Eviction subtracts exactly what was added — negative drift
  is structurally impossible. updateMessage is O(1) via the id index
  (was a front-to-back scan).
- Session stream-start sites push to scrollback only; the new
  #commitStreamed emits the durable transcript row and the chunker event
  exactly once, at finalize, with final content. #artificiallyStreamText
  drops its bespoke reset-and-updateMessage dance for the same helper.
- #seq now seeds past the persisted transcript tail on resume instead of
  restarting at 0, making seq usable as a monotonic replay cursor.

Tests: session-stream-commit.test.ts pins one-scrollback-entry-per-
messageId across all four finalize paths (text_done, thinking_done,
batch-reply artificial streaming, turn-boundary flush), buffer upsert +
byte-cap accounting under by-reference growth, chunker episode pairing
(including a test documenting the pre-fix fragmentation), and seq
continuation after resume.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9ac07c79-5489-4d66-b7ab-bf4b50714898

📥 Commits

Reviewing files that changed from the base of the PR and between b01879e and 3cf8204.

📒 Files selected for processing (1)
  • src/tests/session-stream-commit.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/session-stream-commit.test.ts

📝 Walkthrough

Walkthrough

ScrollbackBuffer now upserts entries by messageId with byte accounting, streaming session paths defer durable commits until finalization, resumed sessions restore the next sequence number, and new tests cover the updated behavior.

Changes

Streamed Commit Deduplication and Resume Sequencing

Layer / File(s) Summary
ScrollbackBuffer entry-based storage and upsert
src/daemon/scrollback.ts
Introduces Entry storage with tracked byte size, messageId indexing, upsert-by-id push behavior, and entry-based replay, mutation, eviction, and clear handling.
Session streamed commit deduplication
src/daemon/session.ts
Adds optional scrollback sequence restoration, defers streamed message persistence during deltas, and commits finalized streamed messages once through #commitStreamed.
Session resume sequence restoration
src/daemon/session-manager.ts
Derives the next scrollback sequence from persisted transcript rows and passes it into restoreScrollback during resume.
Regression test suite for streamed commit and resume behavior
src/tests/session-stream-commit.test.ts
Adds seven tests covering streamed commit singleացման, scrollback byte accounting and eviction, episode chunking, and resume sequence continuity.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
participant Provider
participant Session
participant ScrollbackBuffer
participant TranscriptStore
participant EpisodeChunker
Provider->>Session: text_delta / thinking_delta
Session->>ScrollbackBuffer: push (scrollback-only)
Provider->>Session: text_done / turn end
Session->>Session: `#commitStreamed`(msg)
Session->>ScrollbackBuffer: updateMessage(final content)
Session->>TranscriptStore: append once
Session->>EpisodeChunker: notify once
Loading
sequenceDiagram
participant SessionManager
participant TranscriptStore
participant Session
SessionManager->>TranscriptStore: read persisted transcript entries
SessionManager->>SessionManager: compute max seq
SessionManager->>Session: restoreScrollback(messages, maxSeq + 1)
Session->>Session: advance sequence cursor
Loading

Possibly related PRs

  • saucam/codeoid#50: Prior duplicate-scrollback fix for #artificiallyStreamText; this PR generalizes the same commit-once behavior and message update path.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main fix: preventing streamed messages from being duplicated in scrollback by committing finalized entries via upsert.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/daemon-scrollback-double-push

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.16129% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.63%. Comparing base (9233d9a) to head (3cf8204).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/daemon/session.ts 85.71% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #74      +/-   ##
==========================================
+ Coverage   80.72%   81.63%   +0.90%     
==========================================
  Files          56       56              
  Lines        7895     7899       +4     
==========================================
+ Hits         6373     6448      +75     
+ Misses       1522     1451      -71     
Flag Coverage Δ
daemon 81.63% <95.16%> (+0.90%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/daemon/scrollback.ts 100.00% <100.00%> (ø)
src/daemon/session.ts 73.85% <85.71%> (+3.53%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/tests/session-stream-commit.test.ts (2)

421-424: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

C7 bypasses the actual SessionManager.resumeSessions code path.

The test hand-computes maxSeq from loadTranscript and calls session.restoreScrollback directly instead of invoking SessionManager.resumeSessions. Per the PR stack, the real fix lives in SessionManager.resumeSessions (computing max persisted seq and passing maxSeq+1). If that method's logic ever diverges from this manual reimplementation (e.g. different reduce semantics, additional filtering, off-by-one), this test would still pass while the production resume path regresses.

Consider invoking SessionManager.resumeSessions (or its session-scanning helper) directly, if feasible with the existing daemon test scaffolding, so the test protects the actual code path rather than a parallel reimplementation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/session-stream-commit.test.ts` around lines 421 - 424, The test is
reimplementing the resume logic instead of exercising
SessionManager.resumeSessions, so it can miss regressions in the real production
path. Update the test to call SessionManager.resumeSessions directly, or the
same session-scanning helper it uses, and assert the resumed scrollback/seq
state through that path rather than manually loading transcript entries and
calling session.restoreScrollback. Keep the existing daemon scaffolding and use
the SessionManager and resumeSessions symbols to locate the change.

354-371: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

"Pre-fix fragmentation" test only exercises EpisodeChunker in isolation.

This test documents the historical bug by manually feeding EpisodeChunker.onMessage with a hand-crafted empty-then-full assistant sequence, but never verifies that the live Session actually calls the chunker exactly once with final content (the C1-C4 tests only check scrollback duplicates, not chunker call count/content). A regression where Session re-introduces a stray chunker.onMessage call at stream-start would not be caught by any test in this suite.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/session-stream-commit.test.ts` around lines 354 - 371, The
fragmentation regression test only covers EpisodeChunker in isolation and misses
the real Session behavior. Extend the session-stream commit coverage to assert
that Session invokes EpisodeChunker.onMessage only once for the streamed
assistant turn, with the final non-empty content, so a stray stream-start empty
call would fail. Use the existing Session and EpisodeChunker test setup around
the streamed-message flow to verify call count and payload, not just scrollback
contents.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/daemon/scrollback.ts`:
- Around line 69-77: The scrollback byte tracking in scrollback.ts is using
JSON.stringify(...).length, which counts characters instead of UTF-8 bytes and
can violate the 1MB cap for non-ASCII messages. Add a shared helper in
Scrollback to compute serialized size with real byte accounting
(Buffer.byteLength(..., "utf8") or TextEncoder) and use it everywhere size is
set or updated, including the existing entry update path and the Entry creation
path, so `#bytes` and eviction in `#evict` stay accurate.

---

Nitpick comments:
In `@src/tests/session-stream-commit.test.ts`:
- Around line 421-424: The test is reimplementing the resume logic instead of
exercising SessionManager.resumeSessions, so it can miss regressions in the real
production path. Update the test to call SessionManager.resumeSessions directly,
or the same session-scanning helper it uses, and assert the resumed
scrollback/seq state through that path rather than manually loading transcript
entries and calling session.restoreScrollback. Keep the existing daemon
scaffolding and use the SessionManager and resumeSessions symbols to locate the
change.
- Around line 354-371: The fragmentation regression test only covers
EpisodeChunker in isolation and misses the real Session behavior. Extend the
session-stream commit coverage to assert that Session invokes
EpisodeChunker.onMessage only once for the streamed assistant turn, with the
final non-empty content, so a stray stream-start empty call would fail. Use the
existing Session and EpisodeChunker test setup around the streamed-message flow
to verify call count and payload, not just scrollback contents.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7955792b-792f-4257-9fc0-1355e06bbb83

📥 Commits

Reviewing files that changed from the base of the PR and between 9233d9a and 5e5b05a.

📒 Files selected for processing (4)
  • src/daemon/scrollback.ts
  • src/daemon/session-manager.ts
  • src/daemon/session.ts
  • src/tests/session-stream-commit.test.ts

Comment thread src/daemon/scrollback.ts Outdated
…ession test

CodeRabbit review follow-ups on #74:
- String.length counts UTF-16 code units; use Buffer.byteLength so the
  20MB cap holds for non-ASCII payloads
- end-to-end test that a real Session + MemoryEngine ingests exactly one
  combined user+assistant episode per streamed turn (a stray stream-start
  chunker feed would fail it)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@saucam

saucam commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review in b01879e:

  • UTF-8 byte accounting: applied as suggested — serializedSizeOf helper using Buffer.byteLength(..., "utf8") at all three accounting sites, plus a regression test with multi-byte content asserting bytes matches real UTF-8 size.
  • Live-session chunker coverage (nitpick 2): added — a real Session wired to a real MemoryEngine now asserts exactly one combined user+assistant episode per streamed turn; a stray stream-start chunker feed fails it.
  • C7 via SessionManager.resumeSessions (nitpick 1): skipping for now — resumeSessions needs a fully-constructed SessionManager (identity manager, providers, config), which the current scaffolding doesn't support; the seeding logic itself lives in Session.restoreScrollback, which the test does exercise. The 3-line maxSeq mirror in session-manager.ts is the only untested piece.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant