Skip to content

Conversation

@manstis
Copy link
Contributor

@manstis manstis commented Jul 17, 2025

Description

I've been testing with /streaming_query and a Pattern Fly "Chat Bot" UI enabled client.

I found that the event stream from lightspeed-stack was causing problems.

  • Python ASGI was timing out, killing the process and re-launching the async thread.
Django version 4.2.19, using settings 'main.settings.development'
Starting ASGI/Daphne version 4.1.2 development server at http://127.0.0.1:8000/
...
INFO 2025-07-18 08:15:20,777 runserver.py:log_action HTTP POST /api/v1/ai/streaming_chat/ 200 [28.74, 127.0.0.1:59802]
...
WARNING 2025-07-18 08:15:38,010 server.py:application_checker Application instance <Task pending name='Task-30' coro=<ASGIStaticFilesHandler.__call__() running at /home/manstis/workspaces/git/manstis/forks/ansible-ai-connect-service/venv/lib/python3.12/site-packages/django/contrib/staticfiles/handlers.py:101> wait_for=<Future pending cb=[Task.task_wakeup()]>> for connection <WebRequest at 0x786dcc0d88f0 method=POST uri=/api/v1/ai/streaming_chat/ clientproto=HTTP/1.1> took too long to shut down and was killed.
...
INFO 2025-07-18 08:16:11,777 runserver.py:log_action HTTP POST /api/v1/ai/streaming_chat/ 200 [28.74, 127.0.0.1:59802]

It looks like streaming is terminated/closed and re-started.

This manifested itself as inter-weaved responses, for example "Ansible is blah blah blah[asgi-timed-out]Ansible is blah blah blah". I suspect this was caused by lightspeed-stack only sending some selective llama-stack stream tokens back to the calling client. If there was a big delay, e.g. while the RAG/embedding database is loaded by llama-stack, lightspeed-stack wouldn't send any events for a while and ASGI killed the async process assuming it had died.

Screenshot from 2025-07-18 09-18-15

With the fix in this PR, to send more tokens, the issue seems to be resolved.

This leads to funny things in the UI:

  • Pattern Fly "Chat Boy" UI wants the events for "Tool calls" to be formatted

"Tool calls" were not being rendered correctly.

This PR fixes it:

image

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

  • Related Issue #
  • Closes #

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Improved streaming of server-sent events, allowing multiple, more detailed updates per chunk during query processing.
    • Enhanced event handling for errors, turns, shield calls, inference steps, tool executions, and heartbeat signals, providing clearer and more granular feedback during streaming queries.
  • Tests

    • Updated and expanded unit tests to cover new event types and streaming behavior, ensuring accurate and reliable event emission.

@manstis manstis requested a review from tisnik July 17, 2025 13:29
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

The stream_build_event function was refactored to become a generator yielding multiple Server-Sent Events (SSE) per chunk, with detailed handling for various event and step types including error, turn, shield call, inference, and tool execution events. Corresponding unit tests were updated to use concrete data structures instead of mocks and to verify the expanded, more granular event output including error and heartbeat events.

Changes

File(s) Change Summary
src/app/endpoints/streaming_query.py Refactored stream_build_event to yield multiple SSE messages per chunk with comprehensive event and step type handling, including error and heartbeat events.
tests/unit/app/endpoints/test_streaming_query.py Replaced mocks with concrete domain-specific instances; expanded tests to cover new event types, error and heartbeat events; updated expected streaming content counts and assertions; added multiple new test functions for detailed event scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant response_generator
    participant stream_build_event

    Client->>response_generator: Request streaming response
    loop For each chunk received
        response_generator->>stream_build_event: Process chunk
        loop For each event yielded by stream_build_event
            stream_build_event-->>response_generator: Yield SSE event string
            response_generator-->>Client: Send SSE event
        end
    end
Loading

Estimated code review effort

3 (~45 minutes)

Poem

In the meadow where events now stream,
A rabbit hops through a code refactor dream.
No more single notes—now a chorus of song,
Each chunk yields many, the flow grows strong!
With tests now real and heartbeats anew,
The stream hops forward—swift, robust, and true.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 24a8048 and 476d12d.

📒 Files selected for processing (2)
  • src/app/endpoints/streaming_query.py (5 hunks)
  • tests/unit/app/endpoints/test_streaming_query.py (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app/endpoints/streaming_query.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit/app/endpoints/test_streaming_query.py (1)
src/app/endpoints/streaming_query.py (1)
  • stream_build_event (134-169)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-pr
🔇 Additional comments (12)
tests/unit/app/endpoints/test_streaming_query.py (12)

3-3: LGTM! Appropriate imports for concrete type usage.

The addition of datetime and concrete llama_stack_client.types imports aligns well with the refactor to replace generic mocks with concrete data structures, improving test reliability.

Also applies to: 16-35


173-217: Excellent refactor to use concrete data structures.

The replacement of generic mocks with concrete AgentTurnResponseStreamChunk objects significantly improves test reliability. The detailed comment explaining why mocks fail with hasattr checks is particularly valuable for future maintainers.


264-264: Correct assertion update for expanded event emission.

The change from 4 to 5 expected streaming content chunks properly reflects the refactored stream_build_event function that now yields multiple events per chunk.


278-279: Updated assertion reflects enriched streaming content.

The expanded expected response text correctly captures the more detailed tool execution information now included in the streaming output.


644-665: Good test coverage for turn_start event handling.

The test properly uses concrete data structures and verifies the expected token event output for turn_start events. The structure and assertions are appropriate.


667-699: Comprehensive test for turn_awaiting_input event.

The test properly constructs a complete Turn object with all required fields and verifies the expected token event output. Good use of realistic data structures.


701-733: Thorough test for turn_complete event handling.

The test correctly verifies that turn_complete events yield the content from the turn's output message and use the proper event type. Well-structured with complete data objects.


735-801: Excellent coverage for shield call event handling.

Both tests (with and without violations) provide comprehensive coverage of shield call step completion. The use of concrete SafetyViolation objects and verification of different output formats based on violation presence is particularly thorough.


803-827: Good refactor of existing step_progress test.

The update to use concrete AgentTurnResponseStreamChunk and TextDelta objects instead of mocks improves test reliability while maintaining the same coverage.


829-887: Comprehensive coverage for tool call delta handling.

Both tests effectively cover the different representations of tool calls (string vs ToolCall object) in ToolCallDelta payloads. The verification of tool_call event type output is appropriate for this functionality.


889-939: Excellent refactor with comprehensive tool execution coverage.

The update to use concrete data structures and test multiple events from the iterator properly reflects the refactored stream_build_event behavior. The verification of both tool call arguments and summary events is thorough.


941-979: Good edge case coverage for error and heartbeat handling.

Both tests effectively cover important edge cases - error handling when chunks contain errors and heartbeat events for unrecognized step types. The use of a mock for the error scenario is appropriate since it's testing error handling behavior.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@manstis manstis requested a review from jrobertboos July 17, 2025 13:29
@manstis manstis force-pushed the streaming_improvements branch 3 times, most recently from 65d4cba to 627265f Compare July 18, 2025 10:11
@manstis manstis changed the title [DRAFT] Streaming improvements Streaming improvements Jul 18, 2025
@manstis manstis marked this pull request as ready for review July 18, 2025 11:12
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/app/endpoints/streaming_query.py (2)

189-218: Consider improving violation message formatting.

The violation message concatenates metadata and user_message with just a space separator, which might make parsing difficult.

Consider using a structured format:

-                            "token": f"{violation.metadata} {violation.user_message}",
+                            "token": f"Violation: {violation.user_message} (Metadata: {violation.metadata})",

295-295: Consider making the hard-coded role configurable.

The role is hard-coded as "inference" in multiple places to satisfy PatternFly UI requirements. This creates tight coupling with the UI implementation.

Consider making this configurable:

# At module level or in configuration
PATTERNFLY_TOOL_EXECUTION_ROLE = "inference"

# In the function
"role": PATTERNFLY_TOOL_EXECUTION_ROLE,  # chunk.event.payload.step_type,

Also applies to: 309-309, 324-324, 348-348, 361-361

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c873fb and 627265f.

📒 Files selected for processing (2)
  • src/app/endpoints/streaming_query.py (4 hunks)
  • tests/unit/app/endpoints/test_streaming_query.py (8 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit/app/endpoints/test_streaming_query.py (1)
src/app/endpoints/streaming_query.py (1)
  • stream_build_event (130-392)
🔇 Additional comments (13)
src/app/endpoints/streaming_query.py (7)

6-6: LGTM! Import changes align with the new functionality.

The addition of Iterator to the type imports is appropriate for the refactored generator function.


15-18: LGTM! New imports support the enhanced event handling.

The added imports for interleaved_content_as_str, ToolCall, and TextContentItem are necessary for the detailed event processing in the refactored function.


147-161: LGTM! Error handling is properly implemented.

The error event handling correctly checks for the error attribute and yields a properly formatted SSE error event.


162-188: LGTM! Turn event handling prevents ASGI timeouts.

The implementation correctly sends empty token events for turn_start and turn_awaiting_input, which helps prevent ASGI timeouts during periods of inactivity. The turn_complete event properly includes the full output message content.


219-283: LGTM! Comprehensive inference event handling.

The inference handling correctly processes all event types and properly distinguishes between text and tool call deltas, including handling both string and ToolCall object formats.


381-393: LGTM! Heartbeat events prevent timeout for unhandled cases.

The heartbeat event serves as an effective catch-all mechanism to keep the connection alive for unrecognized event types, which aligns with the PR's goal of preventing ASGI timeouts.


432-437: LGTM! Correctly handles multiple events per chunk.

The updated logic properly iterates over all events yielded by the refactored stream_build_event function and accumulates tokens from each event.

tests/unit/app/endpoints/test_streaming_query.py (6)

15-27: LGTM! Tests now use concrete types instead of mocks.

The transition from generic mocks to concrete llama_stack_client.types instances improves test reliability and ensures the tests accurately reflect real-world usage.


164-208: LGTM! Well-structured test data with clear documentation.

The test data properly constructs the streaming response using concrete types, and the comment explaining why mocks can't be used (due to hasattr behavior) is helpful for future maintainers.


255-256: LGTM! Test assertions correctly updated for new event structure.

The assertions properly reflect:

  1. Increased number of streaming chunks (4 → 6) due to multiple events per chunk
  2. Expanded response content including tool execution details

Also applies to: 269-270


571-595: LGTM! Comprehensive test for step_progress events.

The test properly verifies the token event generation for text deltas using concrete types and appropriate assertions.


597-647: LGTM! Thorough test for step_complete with multiple events.

The test correctly verifies that multiple events are yielded for tool execution, including tool calls and summaries. The use of an iterator and multiple next() calls properly tests the generator behavior.


649-669: LGTM! Important test for heartbeat fallback mechanism.

This test ensures that unrecognized event types generate heartbeat events rather than causing errors, which is crucial for maintaining connection stability.

@manstis manstis force-pushed the streaming_improvements branch 4 times, most recently from 87640f1 to 24a8048 Compare July 18, 2025 13:24
Copy link
Contributor

@umago umago left a comment

Choose a reason for hiding this comment

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

Code LGTM! Really good refactor, thanks!

elif step_type == "tool_execution":
yield from _handle_tool_execution_event(chunk, chunk_id, metadata_map)
else:
yield from _handle_heartbeat_event(chunk_id)
Copy link
Contributor

Choose a reason for hiding this comment

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

Love this! So much easier to follow the flow

Copy link
Contributor

@tisnik tisnik left a comment

Choose a reason for hiding this comment

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

LGTM, please rebase

@coderabbitai coderabbitai bot mentioned this pull request Nov 12, 2025
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.

3 participants