Skip to content

RubyLLM2 W2-06: Report stream events the parsers skip - #48

Merged
samuelboland merged 2 commits into
supernova-2-0from
dux-rubyllm2-w2-06-skipped-stream-events
Nov 30, 2026
Merged

samuelboland merged 2 commits into
supernova-2-0from
dux-rubyllm2-w2-06-skipped-stream-events

Conversation

@staging-supernova-dx-appf-io

@staging-supernova-dx-appf-io staging-supernova-dx-appf-io Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

What this does

Ports the 1.16 "report skipped stream events" feature (fork PR #45, which merges into main on the 1.16 line) onto the 2.0 base. This PR targets supernova-2-0, not main or upstream. It keeps the 1.16 interface exactly. Nothing in Supernova changes here.

Why: Supernova's initializer sets config.on_stream_parse_error = ->(event) { Llm::StreamEventSkipped.record(event) } and reads message.skipped_stream_events when it saves a reply. supernova-2-0 has neither, so the wave 3 gem bump would fail at boot with a NoMethodError on on_stream_parse_error=. Before this change, a stream event a parser could not decode was dropped silently.

New interface

  • config.on_stream_parse_error (default nil) in configuration.rb.
  • Message#skipped_stream_events. It is 0 when nothing was dropped or the reply was not streamed.
  • RubyLLM::SkippedStreamEvent (new file lib/ruby_llm/skipped_stream_event.rb) is a frozen Struct with keyword fields provider, model, site, event_type, byte_size and error_class.
    • site is one of sse_data, event_payload, event_type_header, exception_type_header, content_block_delta.
    • event_type is the SSE event: name or the Bedrock :event-type header, or nil.
    • error_class is nil when the payload decoded but was not a JSON object.
    • The payload is never kept, only its byte size.
    • log_fields renders key=value pairs joined by spaces, with nil shown as -.
  • SkippedStreamEvent.report(event, config) logs a warning (RubyLLM skipped a stream event it could not parse: <fields>) and then calls the hook. An exception raised by the hook is rescued and logged at warn, so it never ends the stream.
  • A Reporting mixin provides a private skip_stream_event. It builds and freezes the event, bumps the current stream accumulator's count and reports using @config || RubyLLM.config.

Counting

  • StreamAccumulator gains skipped_events and skip_event, and to_message passes skipped_stream_events: to Message.
  • merge_turn_segments in the Anthropic protocol sums the count across segments, so merging pause-turn segments does not lose it.

Report sites

  • Protocol::Streaming#handle_data reports :sse_data for a JSON::ParserError (with error_class) and for a payload that parses to a non-Hash (error_class nil). It now takes an event_type: argument, which handle_sse passes from the SSE event name. stream_response sets @stream_accumulator and clears it in an ensure.
  • Bedrock EventStream includes Reporting. decode_event_payload(payload, event_type:) reports :event_payload for a parse error (the outer payload or its base64 bytes) and for a non-Hash result. The InvokeAnthropic stream path goes through this same method.
  • Converse normalized_delta is rewritten to cache the decoded delta per event, so a bad delta is reported once even though several extractors read it. A string delta that fails to parse, or is not an object, is reported as :content_block_delta and becomes {}.

Crash fixes in code the new path exposed

  • ThinkingStream now reads the delta only when it is a Hash. A string delta with a block index raised TypeError and ended the stream.
  • tool_call_delta_event? now goes through normalized_delta instead of reading the raw event.dig('delta', 'toolUse').

Docs: docs/_core_features/streaming.md, docs/_getting_started/configuration-connection.md and docs/_getting_started/configuration.md are updated. models.json and aliases.json were not touched.

Review notes

  • The event_type_header and exception_type_header sites are in SITES for interface parity with 1.16, but nothing reports them yet. The current event_header has no rescue that drops an event. I did not confirm whether the base ever had one.
  • Behaviour change in Converse: a string delta that is not valid JSON, or not an object, now reports and returns {}. The ThinkingStream and tool_call_delta_event? edits are small robustness fixes beyond the literal scope.
  • The Converse spec 'returns nil for an undecodable payload' used to assert the old silent debug log. It now stubs warn.

Testing

  • New specs: spec/ruby_llm/skipped_stream_event_spec.rb, a skipped events block in the Converse streaming spec, and SSE site specs in protocol/streaming_spec.rb. invoke_anthropic_spec.rb gains end-to-end stream specs, including a bad base64 bytes frame.
  • RuboCop and the streaming, Converse and InvokeAnthropic specs were run locally: 389 examples pass.
  • The remaining non-live protocol and provider specs were also run. One spec file failed to load because of a json_schemer/regexp_parser gem incompatibility in the environment, so it was excluded. 47 failures remain (an instance_double(Configuration) problem in connection setup, plus a pricing spec). The same 47 fail on the base commit, so there are no new failures.
  • After review (a5330b4): spec/ruby_llm/protocols/invoke_anthropic_spec.rb ran with LANG=C.UTF-8, 41 examples, 0 failures, including the new pause_turn skipped-events spec, which fails with the summing line in merge_turn_segments removed.
  • No CI runs on PRs into supernova-2-0, so these local runs are the only test runs.
  • I did not confirm that the overcommit hooks were run.

Type of change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation
  • Performance improvement

Scope check

  • I read the Contributing Guide
  • This aligns with RubyLLM's focus on LLM communication
  • This isn't application-specific logic that belongs in user code
  • This benefits most users, not just my specific use case

Required for new features

Quality check

  • I ran overcommit --install and all hooks pass
  • I tested my changes thoroughly
    • For provider changes: Re-recorded VCR cassettes with bundle exec rake vcr:record[provider_name]
    • All tests pass: bundle exec rspec
  • I updated documentation if needed
  • I didn't modify auto-generated files manually (models.json, aliases.json)

AI-generated code

  • I used AI tools to help write this code
  • I have reviewed and understand all generated code (required if above is checked)

API changes

  • Breaking change
  • New public methods/classes
  • Changed method signatures
  • No API changes

Fork PR #45 on the 1.16 line reports every stream event a parser
cannot decode instead of dropping it silently, and Supernova relies on
config.on_stream_parse_error and Message#skipped_stream_events. Bring
the same interface to the 2.0 base so the wave 3 gem bump boots.

Each dropped event is logged at warn, passed to the hook as a frozen
SkippedStreamEvent, and counted on the streamed message. SSE data,
Bedrock eventstream payloads and Converse string deltas report; a bad
delta is decoded and reported once per event.

Co-authored-by: Sam Boland <sam.boland@appfolio.com>
@samuelboland

Copy link
Copy Markdown

Review of 30d2178. Three changes requested; everything else checked out (list below).

  1. docs/_core_features/streaming.md, the sites table: the :event_type_header and :exception_type_header rows say a Bedrock event or exception "whose header could not be read" is dropped. Nothing on this branch reports either site: Bedrock::EventStream#event_header (lib/ruby_llm/protocols/bedrock/event_stream.rb, headers[name] then .value) has no rescue, so no header read drops an event. Change both rows to say the site is kept in SITES for compatibility with 1.16 and is not reported on 2.0. Keep the symbols in SITES unchanged.

  2. Same file, the on_stream_parse_error example calls StreamEventSkipped.record(event.to_h), which is the Supernova class name. Use a generic hook instead, the same one the configuration docs use: ->(event) { Rails.logger.info(event.to_h) }.

  3. Protocols::Anthropic#merge_turn_segments now sums skipped_stream_events across segments (lib/ruby_llm/protocols/anthropic.rb:85), but no spec covers it. Add one to the existing provider_data across pause_turn segments block in spec/ruby_llm/protocols/invoke_anthropic_spec.rb: a streamed pause_turn segment with one bad bytes frame followed by a final segment with one bad frame, asserting message.skipped_stream_events == 2. Run that spec file and say in the PR description that it ran.

Verified and fine:

  • The interface matches 1.16 PR feat: report stream events the parsers skip (DUX-14977) #45: option :on_stream_parse_error, nil, the frozen keyword Struct and its six fields, SITES, log_fields, the warn text for a skip and for a raising hook, Reporting#skip_stream_event, the accumulator's skip_event/skipped_events, and Message#skipped_stream_events defaulting to 0.
  • @provider, @model and @config are set by Protocol#initialize (lib/ruby_llm/protocol.rb:85-89). Provider#complete builds a new protocol per call (provider.rb:136), so @stream_accumulator and the Converse delta cache cannot be shared between streams.
  • The InvokeAnthropic stream goes through Bedrock::EventStream#decode_event_payload, so its non-object payloads are reported as :event_payload.
  • The exception-frame path in decode_event still rewraps a non-JSON message and is not reported, and the spec asserts that.
  • tool_call_delta_event? and ThinkingStream#add previously raised TypeError on a String delta. Both fixes are in scope.
  • The specs cover the brief's list: each site, a frozen event, a hook that raises, two bad events counted with good chunks kept, [DONE] not reported, one bad Converse delta reported once, and 0 on a non-streamed reply. The global hook is reset in after.

@staging-supernova-dx-appf-io

Copy link
Copy Markdown
Author

@samuelboland

Review of 30d2178. Three changes requested; everything else checked out (list below).

  1. docs/_core_features/streaming.md, the sites table: the :event_type_header and :exception_type_header rows say a Bedrock event or exception "whose header could not be read" is dropped. Nothing on this branch reports either site: Bedrock::EventStream#event_header (lib/ruby_llm/protocols/bedrock/event_stream.rb, headers[name] then .value) has no rescue, so no header read drops an event. Change both rows to say the site is kept in SITES for compatibility with 1.16 and is not reported on 2.0. Keep the symbols in SITES unchanged.

  2. Same file, the on_stream_parse_error example calls StreamEventSkipped.record(event.to_h), which is the Supernova class name. Use a generic hook instead, the same one the configuration docs use: ->(event) { Rails.logger.info(event.to_h) }.

  3. Protocols::Anthropic#merge_turn_segments now sums skipped_stream_events across segments (lib/ruby_llm/protocols/anthropic.rb:85), but no spec covers it. Add one to the existing provider_data across pause_turn segments block in spec/ruby_llm/protocols/invoke_anthropic_spec.rb: a streamed pause_turn segment with one bad bytes frame followed by a final segment with one bad frame, asserting message.skipped_stream_events == 2. Run that spec file and say in the PR description that it ran.

Verified and fine:

  • The interface matches 1.16 PR feat: report stream events the parsers skip (DUX-14977) #45: option :on_stream_parse_error, nil, the frozen keyword Struct and its six fields, SITES, log_fields, the warn text for a skip and for a raising hook, Reporting#skip_stream_event, the accumulator's skip_event/skipped_events, and Message#skipped_stream_events defaulting to 0.
  • @provider, @model and @config are set by Protocol#initialize (lib/ruby_llm/protocol.rb:85-89). Provider#complete builds a new protocol per call (provider.rb:136), so @stream_accumulator and the Converse delta cache cannot be shared between streams.
  • The InvokeAnthropic stream goes through Bedrock::EventStream#decode_event_payload, so its non-object payloads are reported as :event_payload.
  • The exception-frame path in decode_event still rewraps a non-JSON message and is not reported, and the spec asserts that.
  • tool_call_delta_event? and ThinkingStream#add previously raised TypeError on a String delta. Both fixes are in scope.
  • The specs cover the brief's list: each site, a frozen event, a hook that raises, two bad events counted with good chunks kept, [DONE] not reported, one bad Converse delta reported once, and 0 on a non-streamed reply. The global hook is reset in after.

I've queued all three changes, and the coding agent is working on them now.

  1. Docs table: The :event_type_header and :exception_type_header rows in docs/_core_features/streaming.md will say the site is kept in SITES for compatibility with 1.16 and is not reported on 2.0. The symbols in SITES stay unchanged.
  2. Docs example: The on_stream_parse_error example will use ->(event) { Rails.logger.info(event.to_h) } in place of the StreamEventSkipped.record call.
  3. Spec: A new spec in spec/ruby_llm/protocols/invoke_anthropic_spec.rb, inside the provider_data across pause_turn segments block. It streams a pause_turn segment with one bad bytes frame, then a final segment with one bad frame, and asserts message.skipped_stream_events == 2. I'll run only that spec file under a UTF-8 locale and note in the PR description that it ran.

🔍 View trace

The two header sites stay in SITES for 1.16 compatibility but nothing
on 2.0 reports them, so the docs say so. The hook example now uses a
generic logger call, and a spec covers summing skipped events across
streamed pause_turn segments.
@staging-supernova-dx-appf-io

Copy link
Copy Markdown
Author

@samuelboland

Review of 30d2178. Three changes requested; everything else checked out (list below).

  1. docs/_core_features/streaming.md, the sites table: the :event_type_header and :exception_type_header rows say a Bedrock event or exception "whose header could not be read" is dropped. Nothing on this branch reports either site: Bedrock::EventStream#event_header (lib/ruby_llm/protocols/bedrock/event_stream.rb, headers[name] then .value) has no rescue, so no header read drops an event. Change both rows to say the site is kept in SITES for compatibility with 1.16 and is not reported on 2.0. Keep the symbols in SITES unchanged.

  2. Same file, the on_stream_parse_error example calls StreamEventSkipped.record(event.to_h), which is the Supernova class name. Use a generic hook instead, the same one the configuration docs use: ->(event) { Rails.logger.info(event.to_h) }.

  3. Protocols::Anthropic#merge_turn_segments now sums skipped_stream_events across segments (`lib/ruby_ll...

Pushed a5330b4.

Changed 2 files (+18 −3): docs/_core_features/streaming.md, spec/ruby_llm/protocols/invoke_anthropic_spec.rb


— via Coder session (view)

@samuelboland samuelboland changed the title feat: report stream events the parsers skip RubyLLM2 W2-06: Report stream events the parsers skip Nov 30, 2026
@samuelboland
samuelboland marked this pull request as ready for review November 30, 2026 18:26

@samuelboland samuelboland 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.

Interface matches 1.16 PR #45; every 2.0 site reports and counts; review fixes verified at a5330b4; specs run locally (no CI on this base).

@samuelboland
samuelboland merged commit 22aab1d into supernova-2-0 Nov 30, 2026
1 check failed
@staging-supernova-dx-appf-io

Copy link
Copy Markdown
Author

🤖 Supernova Code Review — View trace

🔁 Re-run this review

— via automation "Code Review Opus 5.5 Medium" (run), installed by Sam Boland (sam.boland@appfolio.com)

@staging-supernova-dx-appf-io staging-supernova-dx-appf-io Bot left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I reviewed the skipped-stream-event port: the SSE, Bedrock eventstream, Converse delta and InvokeAnthropic paths, the accumulator counting, the pause_turn merge, the config option and the docs. I left one inline finding.

  • lib/ruby_llm/protocols/converse/thinking_stream.rb:21: string-encoded reasoning deltas are decoded for the chunk's thinking, but ThinkingStream ignores them. Their text and signature are silently left out of raw_reasoning, which is used to replay the turn.

The rest looked correct to me: reporting, counting, the hook's rescue, the ensure cleanup of @stream_accumulator, and handling of exception frames.

🔁 Re-run this review

— via automation "Code Review Opus 5.5 Medium" (run), installed by Sam Boland (sam.boland@appfolio.com)

start = part.dig('start', 'reasoningContent')
@blocks[index] = Support::Utils.deep_dup(start) if start
delta = part.dig('delta', 'reasoningContent')
delta = part['delta']['reasoningContent'] if part['delta'].is_a?(Hash)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

ThinkingStream now skips string-encoded deltas, while the chunk extractors decode them. That means reasoning text and signatures sent this way get dropped from raw_reasoning.

Converse::Streaming#normalized_delta JSON-decodes a string delta, so extract_thinking_delta and extract_signature_from_delta still put that reasoning into the chunk's thinking. This line only reads part['delta'] when it is already a Hash. For a valid string delta like '{"reasoningContent":{"reasoningText":{"text":"…","signature":"…"}}}', the text and signature never reach @blocks. The final raw_reasoning then loses that block or its signature. That is the data used to replay the turn verbatim, and Bedrock rejects a thinking block that is missing its signature on the next request.

Before this PR the same input raised TypeError. Now it fails silently, which is harder to notice. Decode the delta the same way the extractors do, for example by passing the already-normalized delta into ThinkingStream#add, or by having it parse a string delta itself, so both paths see the same reasoning.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants