Skip to content

LCORE-4724: project a streaming-query agent run onto the SSE contract - #3376

Open
max-svistunov wants to merge 1 commit into
lightspeed-core:mainfrom
max-svistunov:lcore-4724-streaming-query-adapter
Open

max-svistunov wants to merge 1 commit into
lightspeed-core:mainfrom
max-svistunov:lcore-4724-streaming-query-adapter

Conversation

@max-svistunov

@max-svistunov max-svistunov commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

LCORE-4724, part 1 of 3: StreamingQueryEventStream, the projector that turns the native pydantic-ai events of a /v1/streaming_query run into today's SSE contract, built on pydantic-ai's UIEventStream with one hook per event kind (design pai-responses-lcore-rewrite.md; ticket LCORE-4724). It is what replaces the dispatch_stream_event chain of utils.agents.streaming once the endpoint switches over (LCORE-4728); nothing calls it yet and the dispatcher keeps serving production.

This part covers the text of a turn: before_stream opens with the start event; text starts and deltas become token events with the chunk counter the accumulator keeps; a text end folds the part into the turn's response text; the run result closes with turn_complete, with the refusal text when the model refused, exactly as the dispatcher does. The media type is a field of the stream, so plain-text clients still get the token text alone. The end event stays with the endpoint, which needs the persisted turn and the quota balances the projector cannot see; the endpoint reads this stream's accumulator and run result after the stream.

Parts 2 and 3 (tools; compaction, error and interruption) follow as one PR on top of this one, so each stays under 400 lines. Layout: src/query/projector/, mirroring the Responses projector package.

One commit, 319 lines, no API or configuration change; wire names and payload models are unchanged.

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library [pyproject.toml + uv.lock]
  • Bump-up dependent library [requirements.*.txt for Konflux]
  • 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
  • Benchmarks improvement

Tools used to create PR

Identify any AI code assistants used in this PR (for transparency and review context)

  • Assisted-by: Claude Opus 4.8
  • Generated by: Claude Opus 4.8

Related Tickets & Documents

  • Related Issue # LCORE-4724
  • 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

uv run pytest tests/unit/query -v

Four tests drive synthetic PartStartEvent, PartDeltaEvent, PartEndEvent and AgentRunResultEvent through transform_stream and compare the encoded lines with the contract: the start body, token ids and texts, turn_complete with the final text and the refusal variants, the turn summary's response text and chunk counter after the stream, and the plain-text media type. ruff, black, pydocstyle, mypy, pyright and pylint (10.00) are clean on the new package. No stack run: the projector has no caller yet.

Summary by CodeRabbit

  • New Features
    • Query responses can now be delivered as they’re generated, with streamed text and a clear indication when a response is complete.
    • When a response is blocked by a content filter, the stream displays a refusal message instead of presenting it as a normal answer.

/v1/streaming_query has a public SSE contract; on the pydantic-ai agent
path the run produces native events that dispatch_stream_event maps one
by one. The migration replaces that dispatcher with a UIEventStream
adapter, one hook per event kind, that the endpoint switch-over
(LCORE-4728) will use. Add it as StreamingQueryEventStream in a new
query.projector package, mirroring the Responses projector layout.

This first part covers the text of a turn: before_stream opens with the
start event; text starts and deltas become token events with the chunk
counter the accumulator keeps; a text end folds the part into the turn's
response text; the run result closes with turn_complete, with the
refusal text when the model refused, exactly as the dispatcher does. The
media type is a field of the stream, so plain-text clients still get the
token text alone. The end event stays with the endpoint, which needs the
persisted turn and the quota balances the projector cannot see.

Tools, compaction, error and interruption follow in the next parts.
Nothing calls the projector yet.
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The query projector adds StreamingQueryEventStream to convert agent text and run-result events into streaming-query payloads. It tracks turn state, supports JSON and text output, and selects refusal text for content-filter results.

Changes

Streaming query event projection

Layer / File(s) Summary
Project text events and track turn state
src/query/__init__.py, src/query/projector/*, tests/unit/query/projector/test_event_stream.py
The projector package exports StreamingQueryEventStream. The stream emits start and token payloads, updates turn-summary state, and encodes output as JSON or text. Tests cover event output and preservation of streamed chunks.
Complete turns from run results
src/query/projector/event_stream.py, tests/unit/query/projector/test_event_stream.py
Run-result handling stores the result and provider response ID, selects final text, and emits a turn-complete payload. Content-filter results use provider refusal text or a default message. Tests cover both cases.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: asimurka, tisnik

Merge Risk: Minimal · up to 10866

This change adds an unused projector with no effect on current endpoints, so production behavior is unchanged. The CI pydocstyle check currently fails on two new test package files. Add a docstring to each before merging so the check passes.

Pre-merge checks: Passed 6

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: a projector that maps a streaming-query agent run onto the existing SSE contract. The raw summary confirms the new StreamingQueryEventStream class in src/query/project…
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.
Performance And Algorithmic Complexity Passed Checked the PR's full changed-file list (six added files) and the patch for src/query/projector/event_stream.py and src/query/projector/__init__.py. Tests and docstrings add no runtime cost. Each …
Security And Secret Handling Passed PR #3376 (lightspeed-core/lightspeed-stack, author max-svistunov) adds six files: a package docstring, src/query/projector/__init__.py, src/query/projector/event_stream.py (`StreamingQueryEventStr…
Full details: Title check

Explanation

The title names the main change: a projector that maps a streaming-query agent run onto the existing SSE contract. The raw summary confirms the new StreamingQueryEventStream class in src/query/projector/ does this. The title also carries a ticket ID (LCORE-4724), which is acceptable. The title is specific and matches the PR objectives.

Full details: Performance And Algorithmic Complexity

Explanation

Checked the PR's full changed-file list (six added files) and the patch for src/query/projector/event_stream.py and src/query/projector/__init__.py. Tests and docstrings add no runtime cost. Each of the five BLOCKING categories was checked against the new code: 1. O(n^2)+ algorithms: None. Each delta does one O(1) list.append in _token. handle_text_end and handle_run_result each run one "".join over the current part's chunks. Total work is linear in the response size. 2. N+1 patterns: None. No calls to external APIs, databases, or K8s resources happen in the new code. 3. Expensive work in loops: None. The per-event work is one payload construction and one serialization (serialize_json or serialize_text). Serialization is required to emit each SSE line. No regex compilation or extra JSON parsing occurs inside a loop. 4. Unbounded growth: text_parts is cleared in handle_text_end. turn_summary.partial_tokens grows with each chunk, but it lives on a per-turn accumulator that the stream creates for one run. Its size is bounded by that run's output. No module-level cache, watcher, or long-lived buffer is added. 5. Missing pagination or limits: Not applicable. The PR adds no List operation or API endpoint. The projector has no caller yet, so it adds no request-path work. No meaningful performance regression is introduced.

Full details: Security And Secret Handling

Explanation

PR #3376 (lightspeed-core/lightspeed-stack, author max-svistunov) adds six files: a package docstring, src/query/projector/__init__.py, src/query/projector/event_stream.py (StreamingQueryEventStream), and unit tests under tests/unit/query/. I checked each rule in the Security and Secret Handling check against the diff: 1. Secrets or tokens: no hardcoded credentials. The grep over the test diff found no matches for secret, password, api_key, or token= patterns. The token names in the source refer to streamed text chunks, not credentials. 2. Auth or authz: the change adds no API endpoint or route. The projector is not called yet, so no new unauthenticated surface exists. 3. Injection: no SQL, shell, file-path, or eval/exec operations appear in the diff. 4. Sensitive data in responses or logs: the projector emits only the response text and refusal text the model already returns, using the existing StreamEventPayload models. The module imports get_logger but never logs. No new data leaves through a new path. 5. K8s or RH secrets: no manifests or secret resources are changed. Rule 4 relies on the model output being intended for the client. This matches the existing dispatcher contract. The diff adds no new exposure beyond the existing stream. Limitation: the verdict covers the diff only. I did not inspect the existing dispatcher or endpoint code, which this PR does not change.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
Simplify code

  • Create a new PR
Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between fe3314f and 1086682.

Files selected for processing: 6

  • src/query/__init__.py
  • src/query/projector/__init__.py
  • src/query/projector/event_stream.py
  • tests/unit/query/__init__.py
  • tests/unit/query/projector/__init__.py
  • tests/unit/query/projector/test_event_stream.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Recent review details

Context from checks skipped due to timeout: 18

  • GitHub Check: E2E: ci / skills
  • GitHub Check: E2E: ci / shields
  • GitHub Check: E2E: ci / other
  • GitHub Check: E2E: ci / authorized
  • GitHub Check: E2E: ci / rbac
  • GitHub Check: E2E: ci / default
  • GitHub Check: E2E: ci / mcp
  • GitHub Check: Red Hat Konflux / lightspeed-core-0-8-enterprise-contract / lightspeed-stack-0-8
  • GitHub Check: Red Hat Konflux / rag-content-0-8-e2e-tests / lightspeed-stack-0-8
  • GitHub Check: Red Hat Konflux / lightspeed-stack-0-8-e2e-tests / lightspeed-stack-0-8
  • GitHub Check: Pylinter
  • GitHub Check: integration_tests (3.13)
  • GitHub Check: integration_tests (3.12)
  • GitHub Check: integration_tests (3.14)
  • GitHub Check: unit_tests (3.13)
  • GitHub Check: unit_tests (3.12)
  • GitHub Check: build-pr
  • GitHub Check: Konflux kflux-prd-rh02 / lightspeed-stack-0-8-on-pull-request
CI failures not shown inline: 1

GitHub Actions: Pydocstyle / pydocstyle: LCORE-4724: project a streaming-query agent run onto the SSE contract

Conclusion: failure

View job details

##[group]Run uv tool run pydocstyle -v src tests
 �[36;1muv tool run pydocstyle -v src tests�[0m
 shell: /usr/bin/bash -e {0}
 env:
   UV_PYTHON: 3.12
   VIRTUAL_ENV: /home/runner/work/lightspeed-stack/lightspeed-stack/.venv
   UV_CACHE_DIR: /home/runner/work/_temp/setup-uv-cache
 ##[endgroup]
 Installed 2 packages in 1ms
 Checking file src/configuration.py.
 Checking file src/constants.py.
 Checking file src/__init__.py.
 Checking file src/version.py.
 Checking file src/ogx_configuration.py.
 Checking file src/lightspeed_stack.py.
 Checking file src/log.py.
 Checking file src/metrics/__init__.py.
 Checking file src/metrics/recording.py.
 Checking file src/metrics/utils.py.
 Checking file src/query/__init__.py.
 Checking file src/query/projector/__init__.py.
 Checking file src/query/projector/event_stream.py.
 Checking file src/transcripts/transcripts.py.
 Checking file src/quota/__init__.py.
 Checking file src/quota/quota_limiter_factory.py.
 Checking file src/quota/connect_pg.py.
 Checking file src/quota/revokable_quota_limiter.py.
 Checking file src/quota/connect_sqlite.py.
 Checking file src/quota/user_quota_limiter.py.
 Checking file src/quota/quota_exceed_error.py.
 Checking file src/quota/quota_limiter.py.
 Checking file src/quota/token_usage_history.py.
 Checking file src/quota/sql.py.
 Checking file src/quota/cluster_quota_limiter.py.
 Checking file src/knowledge/__init__.py.
 Checking file src/knowledge/toolset.py.
 Checking file src/knowledge/search.py.
 Checking file src/knowledge/registry.py.
 Checking file src/knowledge/types.py.
 Checking file src/knowledge/utils.py.
 Checking file src/knowledge/errors.py.
 Checking file src/knowledge/reranker.py.
 Checking file src/knowledge/capability.py.
 Checking file src/knowledge/sources/pgvector.py.
 Checking file src/knowledge/sources/__init__.py.
 Checking file src/knowledge/sources/okp.py.
 Checking file src/knowledge/sources/utils.py.
 Checking file src/knowledge/sources/base.py.
 Checking file src/knowl...
Additional context used

Code guidelines: 2

AGENTS.md — auto-discovered
CLAUDE.md — auto-discovered
Path-based instructions: 5

Source excerpt: **Required**: Use pytest for all unit and integration tests Source excerpt: **Forbidden**: Do not use unittest - pytest is the standard for this project Source excerpt: **Coverage**: Unit tests require 60% coverage, integrat...

CodeRabbit inference engine (AGENTS.md)

Files:

  • tests/unit/query/projector/test_event_stream.py
Source excerpt: **Required**: Use pytest for all unit and integration tests Source excerpt: **Forbidden**: Do not use unittest - pytest is the standard for this project Source excerpt: **Mocking**: `pytest-mock` for AsyncMock objects

CodeRabbit inference engine (CLAUDE.md)

Files:

  • tests/unit/query/projector/test_event_stream.py
Source excerpt: **Coverage**: Unit tests require 60% coverage, integration 10% Source excerpt: **Async tests**: Use marker `pytest.mark.asyncio`

CodeRabbit inference engine (CLAUDE.md)

Files:

  • tests/unit/query/projector/test_event_stream.py
Source excerpt: **Mocking**: `pytest-mock` for AsyncMock objects Source excerpt: **Async tests**: Use marker `pytest.mark.asyncio`

CodeRabbit inference engine (AGENTS.md)

Files:

  • tests/unit/query/projector/test_event_stream.py
Source excerpt: Package `__init__.py` files contain brief package descriptions

CodeRabbit inference engine (CLAUDE.md)

Files:

  • src/query/__init__.py
  • src/query/projector/__init__.py
Learnings: 6

Common learnings

Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-11-05T07:39:34.259Z
Learning: Applies to tests/{unit,integration}/** : Source excerpt:
# Lightspeed Core Stack Development Guide

## Testing Framework

### Testing Framework Requirements

- **Forbidden**: Do not use unittest - pytest is the standard for this project
Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-17T11:23:03.910Z
Learning: Applies to tests/{unit,integration}/** : Source excerpt:
# Lightspeed Core Stack Development Guide

## Testing Framework

### Testing Framework Requirements

- **Forbidden**: Do not use unittest - pytest is the standard for this project
Learning: 2026-11-17T11:23:09.731Z

Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-11-17T11:23:09.731Z
Learning: Applies to **/__init__.py : Source excerpt:
# Lightspeed Core Stack Development Guide

## Code Architecture & Patterns

### Coding Standards

#### Module Standards

- Package `__init__.py` files contain brief package descriptions

Applied to files:

  • src/query/__init__.py
  • src/query/projector/__init__.py
Learning: 2026-11-17T11:23:03.910Z

Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-17T11:23:03.910Z
Learning: Source excerpt:
# Lightspeed Core Stack Development Guide

## Code Architecture & Patterns

### Coding Standards

#### Module Standards

- Package `__init__.py` files contain brief package descriptions

Applied to files:

  • src/query/__init__.py
  • src/query/projector/__init__.py
Learning: 2026-07-21T11:10:05.060Z

Learnt from: are-ces
Repo: lightspeed-core/lightspeed-stack PR: 2162
File: src/a2a_client/__init__.py:3-9
Timestamp: 2026-07-21T11:10:05.060Z
Learning: In this repository, it is acceptable for Python package `__init__.py` files to contain functional code (not only docstrings/metadata) and to perform package-level re-exports. Do not flag `__init__.py` solely for containing imports or other logic used to re-export symbols; this is allowed when it’s implemented via imports and `__all__` (or otherwise clearly intended to define the package’s public API).

Applied to files:

  • src/query/projector/__init__.py
Learning: 2026-11-17T11:23:09.731Z

Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-11-17T11:23:09.731Z
Learning: Applies to tests/unit/** : Source excerpt:
# Lightspeed Core Stack Development Guide

## Testing Framework

### Unit Tests (pytest)

- **Async tests**: Use marker `pytest.mark.asyncio`

Applied to files:

  • tests/unit/query/projector/test_event_stream.py
Learning: 2026-11-17T11:23:03.910Z

Learnt from: CR
Repo: lightspeed-core/lightspeed-stack PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-17T11:23:03.910Z
Learning: Applies to tests/{unit,integration}/** : Source excerpt:
# Lightspeed Core Stack Development Guide

## Testing Framework

### Testing Framework Requirements

- **Required**: Use pytest for all unit and integration tests

Applied to files:

  • tests/unit/query/projector/test_event_stream.py
Additional comments: 2

src/query/projector/event_stream.py: 2

130-132: Data Integrity & Integration

The stored summary gap is not introduced by this projector.

The comment's concern is that the new projector leaves turn_summary.llm_response without the refusal text. The base dispatcher behaves the same way. It emits the refusal only in turn_complete and never writes llm_response on the run-result path. The projector's refusal selection mirrors that path. This PR therefore does not create the gap it describes.

115-115: Data Integrity & Integration

The projector does not change the post-stream text summary. Its text-end fold is identical to the legacy fold at src/utils/agents/streaming.py:704-710. Concatenating text ends without a separator is the current behavior, and this PR does not alter it. The pydantic-ai \n\n join in ModelResponse.text applies to the whole-response text used by turn_complete, not to this per-part fold, so it does not require a change here.

This branch has not been deployed

No deployments
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