Skip to content

fix(streaming): enforce strict index validation in event accumulator to prevent state corruption - #1782

Open
l1ve709 wants to merge 1 commit into
anthropics:mainfrom
l1ve709:fix-streaming-index-mismatch
Open

fix(streaming): enforce strict index validation in event accumulator to prevent state corruption#1782
l1ve709 wants to merge 1 commit into
anthropics:mainfrom
l1ve709:fix-streaming-index-mismatch

Conversation

@l1ve709

@l1ve709 l1ve709 commented Jul 27, 2026

Copy link
Copy Markdown

Summary

This PR resolves an unhandled edge case in the streaming parser where out-of-sequence or dropped content_block_start events could silently corrupt the internal accumulator state, leading to cryptic IndexError exceptions during downstream content_block_delta processing.

Root Cause Analysis

The accumulator previously appended content_block_start payloads blindly without asserting the sequence invariant (as noted by the legacy # TODO: check index comment). If an SSE event is dropped or misordered by the network layer, current_snapshot.content desynchronizes from the expected block sequence.

When a subsequent content_block_delta arrives, the parser relies on content = current_snapshot.content[event.index]. If the internal state length is misaligned with the incoming event.index, it triggers an obscure IndexError inside the delta router, making it extremely difficult for developers to debug the underlying network/API failure.

Changes Made

  • Introduced a strict sequence invariant check during content_block_start evaluation for both standard (_messages.py) and beta (_beta_messages.py) streams.
  • The parser now employs a fail-fast mechanism by explicitly raising a RuntimeError describing the index mismatch, guaranteeing stream integrity.

Validation

  • Adheres to existing ruff static analysis and formatting guidelines.
  • The state machine mathematically ensures event.index == len(current_snapshot.content) before allowing .append() mutations.

@l1ve709
l1ve709 requested a review from a team as a code owner July 27, 2026 17:42
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