Skip to content

feat(stdlib): add standard streaming event types #902

Closed

Description

@planetf1

What

Add a standard event dataclass hierarchy to mellea/stdlib/streaming.py (the module created in #901).

@dataclass
class StreamEvent:
    timestamp: float  # auto-populated via __post_init__

@dataclass
class ChunkEvent(StreamEvent):
    text: str
    chunk_index: int
    attempt: int

@dataclass
class QuickCheckEvent(StreamEvent):
    chunk_index: int
    attempt: int
    passed: bool
    results: list[PartialValidationResult]

@dataclass
class StreamingDoneEvent(StreamEvent):
    attempt: int
    full_text: str

@dataclass
class FullValidationEvent(StreamEvent):
    attempt: int
    passed: bool
    results: list[ValidationResult]

@dataclass
class RetryEvent(StreamEvent):
    attempt: int
    reason: str

@dataclass
class CompletedEvent(StreamEvent):
    success: bool
    full_text: str
    attempts_used: int

Why

These are the shared vocabulary between the streaming orchestrator and its consumers — UIs, m serve, and plugins. Without a standard set of types in mellea, every consumer defines its own parallel types or takes a dependency on mellea-partial. The sampling strategy plugin hooks (SAMPLING_LOOP_START, SAMPLING_REPAIR, etc.) do not fire during streaming — these event types are the Phase 1 observability substitute. Note that on early exit via cancel_generation(), post_processing() does not run, so mot.generation.usage (token counts) will be None; the CompletedEvent should capture whether generation completed normally or was cancelled.

These are plain dataclasses with no logic and no transport dependency — the minimum mellea needs to own. Once this lands, Hendrik can update mellea-partial to import and emit these types directly.

Implementation

Add to mellea/stdlib/streaming.py. timestamp should be auto-populated in __post_init__ using time.time() so callers do not need to supply it. Export all event types from mellea.stdlib.

Acceptance criteria

  • All seven event types exist in mellea/stdlib/streaming.py
  • StreamEvent.timestamp is auto-populated in __post_init__ — callers do not set it
  • QuickCheckEvent.results typed as list[PartialValidationResult]
  • FullValidationEvent.results typed as list[ValidationResult]
  • All types exported from mellea.stdlib
  • Unit tests in test/stdlib/test_streaming.py covering construction of each event type
  • Google-style docstring on each event type describing when it is emitted

Additional scope: orchestrator emits events and bridges to OTEL

Deferred from #901 per the epic's explicit instruction that streaming observability lives in the event types, not in the sampling plugin hooks. This issue is the right home because event emission and OTEL recording happen at the same call sites.

Event emission from stream_with_chunking

The orchestrator must emit each event type at the appropriate point:

  • ChunkEvent — on each validated chunk yielded to the consumer (post-validation, including the flushed trailing fragment)
  • QuickCheckEvent — after each per-chunk stream_validate batch (one per chunk, covering all active requirements)
  • StreamingDoneEvent — when the raw token stream ends, before final validate()
  • FullValidationEvent — after the final validate() call on non-failed requirements
  • CompletedEvent — on orchestrator exit, including early-exit cases where completed=False
  • New: ErrorEvent — if stream_validate raises or any other unplanned exit. Replaces the temporary MelleaLogger.warning stopgap in the exception path of _orchestrate_streaming (introduced in feat(stdlib): add stream_with_chunking() with per-chunk validation (#901) #942 to satisfy "fail loud" while this issue lands).

RetryEvent stays deferred — v1 retry is caller-driven re-invocation of stream_with_chunking, so there is no orchestrator-side emission point yet. Revisit when an orchestrator-side retry mechanism is introduced.

OTEL bridge at the event-emission sites

  • Open an application trace span for stream_with_chunking (mellea.application scope). No orchestrator-level span exists today. Close with set_span_error on early-exit fail. This is separate from the backend span, which cancel_generation() already closes correctly (base.py:413-419).
  • Each event additionally becomes a span event on the application span, with event fields attached as attributes.
  • QuickCheckEvent records record_requirement_check; QuickCheckEvent with passed=False additionally records record_requirement_failure with the fail reason.
  • CompletedEvent records record_sampling_outcome("stream_with_chunking", success=...).
  • ErrorEvent records record_error(error_type, provider, model).

Open design questions to resolve during implementation

  • Delivery mechanism. Two candidates: (a) StreamChunkingResult.events() async iterator mirroring the existing astream(); (b) stream_with_chunking(..., on_event=callback). (a) is more consistent with the existing API but requires a second queue and consumer-single-consumer discipline. (b) is simpler to bridge synchronously into mellea-partial UI consumers. Pick one during implementation based on whichever is cleaner to bridge to mellea-partial.
  • RetryEvent scope. Confirmed deferred here because v1 retry is caller-driven. When/if an orchestrator-side retry lands (likely a future issue, not in the current epic), decide at that point whether RetryEvent fires from within the orchestrator or from the caller that drives the retry loop.

Additional acceptance criteria

  • Add ErrorEvent dataclass with exception_type: str and detail: str fields (in addition to inherited timestamp)
  • stream_with_chunking emits ChunkEvent, QuickCheckEvent, StreamingDoneEvent, FullValidationEvent, CompletedEvent, and ErrorEvent at the documented points
  • Exception cleanup in _orchestrate_streaming replaces the MelleaLogger.warning stopgap with an ErrorEvent emission (remove the # TODO(#902) comment at the same time)
  • Application trace span opened and closed by the orchestrator, set_span_error called on early-exit fail
  • record_requirement_check, record_requirement_failure, record_sampling_outcome, record_error called at the documented points
  • Unit tests for event emission order and content via a capturing subscriber
  • OTEL side-effect tests via existing metric/span test fixtures
  • Delivery mechanism (async iterator vs. callback) decided and documented in the orchestrator docstring

Blocked by #901
Part of #891

Activity

  1. added
    enhancement
    on Apr 22, 2026
  2. self-assigned this
    on Apr 22, 2026
  3. added this to the Release 0.5.0 milestone on Apr 22, 2026
  4. planetf1 commented on Apr 24, 2026

    @planetf1
    ContributorAuthor

    Implementation note: CompletedEvent should capture whether generation completed normally or was cancelled via cancel_generation(). On early exit, post_processing() does not run, so mot.generation.usage (token counts) will be None. The event should make this visible — e.g. a cancelled: bool field — so consumers don't have to infer it from missing token counts.

  5. planetf1 commented on Apr 29, 2026

    @planetf1
    ContributorAuthor

    Documentation — mandatory deliverable for this PR

    This is the final PR in the streaming validation epic (#891). All narrative documentation for the entire feature ships here or it doesn't ship at all. There is no follow-on issue.

    The existing acceptance criteria above cover code and tests. The following documentation work is equally required before this PR can be merged.

    Required documentation changes

    1. docs/docs/how-to/use-async-and-streaming.md

    Add a new section covering streaming validation end-to-end:

    • When to use stream_with_chunking vs raw astream()
    • How to subclass Requirement and override stream_validate (with a self-contained code example)
    • How to consume StreamChunkingResult: iterating astream(), calling acomplete(), inspecting streaming_failures and final_validations
    • How to interpret the event stream (delivery mechanism decided during feat(stdlib): add standard streaming event types #902 implementation)
    • Early-exit behaviour: what completed=False means, what is and isn't populated

    2. docs/docs/concepts/requirements-system.md

    Add a paragraph (or short subsection) explaining:

    • That Requirement has two validation modes: batch (validate) and streaming (stream_validate)
    • What PartialValidationResult is and what the three return values ("pass", "fail", "unknown") mean
    • When stream_validate is called and how it relates to the chunking strategy

    3. docs/examples/streaming/streaming_chunking.py

    This file already exists (added in #942). Review it against the final #902 API — particularly the event delivery mechanism once that's decided — and update if the calling pattern changes. The example must remain runnable and marked # pytest: ollama, e2e.

    Acceptance criteria (documentation)

    • use-async-and-streaming.md has a streaming validation section covering all four points listed above
    • requirements-system.md has a stream_validate / PartialValidationResult paragraph or subsection
    • streaming_chunking.py example is consistent with the final feat(stdlib): add standard streaming event types #902 API and passes uv run pytest docs/examples/streaming/streaming_chunking.py
    • All new doc pages pass npx markdownlint-cli2 "docs/docs/**/*.md"
    • No H1 headings in doc body (Mintlify renders the frontmatter title automatically)
    • All code examples in docs verified against the mellea source at merge time

    Why this matters

    The auto-generated API docs (mdx from docstrings) will cover the types and function signatures. They will not explain when to use stream_with_chunking, how to write a streaming requirement, or what to do when the stream fails early. That context lives only in the narrative docs and example. Without these, the feature is undiscoverable to anyone who doesn't read the source.

  6. planetf1 commented on Apr 29, 2026

    @planetf1
    ContributorAuthor

    Implementation notes for epic rollup (#891)

    Items surfaced during implementation / code review that should be captured in the parent epic when this wave closes.

    CancelledError + Python 3.12 C Task timing (regression test added)

    When asyncio.create_task() is called and task.cancel() is called before the task receives its first coro.send(None), Python 3.12's C Task implementation skips the coroutine body entirely — including finally blocks. The task raises CancelledError without executing any cleanup.

    Consequence for stream_with_chunking: if a caller cancels result._orchestration_task immediately after the call returns (before yielding to the event loop), result.completed stays True even though generation was cancelled. The fix — result.completed = False in the finally block — is correct for the normal case (task reaches Queue.get() before cancel), but the regression test must yield at least once (await asyncio.sleep(0)) before calling cancel() to ensure the task has actually started.

    Regression test: test_cancelled_task_sets_completed_false in test/stdlib/test_streaming.py. Inline comment explains the sleep(0) requirement.

    Phase 2 consideration: document in the public API that callers who cancel _orchestration_task should yield once first, or provide a higher-level cancel() method on StreamChunkingResult that handles this correctly.

    O(n) re-scan per delta in ChunkingStrategy

    ChunkingStrategy.split(accumulated_text) is called on every streaming delta and receives the full accumulated text. All built-in chunkers are O(n) in accumulated length per call. This is intentional — it keeps chunkers stateless and removes the need for reset() or deep-copy support — but it is a cost that grows over long streams.

    Documentation added to ChunkingStrategy class docstring and split() Args section in this wave.

    Phase 2 consideration: a stateful chunker interface (receiving only the new delta) would be O(1) per call. If a use case with very long streams (tens of KB) emerges, this is the natural extension point. Would require careful thought about copy() semantics on stateful chunkers.

    Deferred design decisions (v1 intentional omissions)

    • RetryEvent — dataclass ships but is not emitted. v1 retry is caller-driven re-invocation of stream_with_chunking. Orchestrator-side retry deferred to a future issue.
    • "pass" is informational — a per-chunk "pass" result does not short-circuit the final validate() call. All non-"fail" requirements (both "pass" and "unknown") run full validation at stream end. This is the specified v1 behaviour; fast-path on "pass" is a potential phase 2 optimisation.
    • Single-consumer constraint on both astream() and events()** — second call blocks indefinitely. Acceptable for v1 but worth a clearer error message in a follow-up.
  7. psschwei commented on May 4, 2026

    @psschwei
    Contributor

    Once this lands, Hendrik can update mellea-partial to import and emit these types directly.

    I believe that the work related to #891 will ultimately replace mellea-partial (?)

  8. planetf1 commented on May 5, 2026

    @planetf1
    ContributorAuthor

    I believe that the work related to #891 will ultimately replace mellea-partial (?)

    yes ultimately, but I was thinking more of the demos, both after the current phase, and when we move some semantic decisions back into the MOT

  9. planetf1 commented on May 7, 2026

    @planetf1
    ContributorAuthor

    As well as docs

    • Add a tutorial for using Partials
    • Ensure there is clear disambiguation in docs/tutorial between partials & other async support such as m serve
  10. added
    area/stdlib
    area/streaming
    on May 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/stdlibarea/streamingenhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions