Repository navigation
Description
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: intWhy
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.timestampis auto-populated in__post_init__— callers do not set it -
QuickCheckEvent.resultstyped aslist[PartialValidationResult] -
FullValidationEvent.resultstyped aslist[ValidationResult] - All types exported from
mellea.stdlib - Unit tests in
test/stdlib/test_streaming.pycovering 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-chunkstream_validatebatch (one per chunk, covering all active requirements)StreamingDoneEvent— when the raw token stream ends, before finalvalidate()FullValidationEvent— after the finalvalidate()call on non-failed requirementsCompletedEvent— on orchestrator exit, including early-exit cases wherecompleted=False- New:
ErrorEvent— ifstream_validateraises or any other unplanned exit. Replaces the temporaryMelleaLogger.warningstopgap 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.applicationscope). No orchestrator-level span exists today. Close withset_span_erroron early-exit fail. This is separate from the backend span, whichcancel_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.
QuickCheckEventrecordsrecord_requirement_check;QuickCheckEventwithpassed=Falseadditionally recordsrecord_requirement_failurewith the fail reason.CompletedEventrecordsrecord_sampling_outcome("stream_with_chunking", success=...).ErrorEventrecordsrecord_error(error_type, provider, model).
Open design questions to resolve during implementation
- Delivery mechanism. Two candidates: (a)
StreamChunkingResult.events()async iterator mirroring the existingastream(); (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 intomellea-partialUI consumers. Pick one during implementation based on whichever is cleaner to bridge tomellea-partial. RetryEventscope. 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 whetherRetryEventfires from within the orchestrator or from the caller that drives the retry loop.
Additional acceptance criteria
- Add
ErrorEventdataclass withexception_type: stranddetail: strfields (in addition to inheritedtimestamp) -
stream_with_chunkingemitsChunkEvent,QuickCheckEvent,StreamingDoneEvent,FullValidationEvent,CompletedEvent, andErrorEventat the documented points - Exception cleanup in
_orchestrate_streamingreplaces theMelleaLogger.warningstopgap with anErrorEventemission (remove the# TODO(#902)comment at the same time) - Application trace span opened and closed by the orchestrator,
set_span_errorcalled on early-exit fail -
record_requirement_check,record_requirement_failure,record_sampling_outcome,record_errorcalled 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
Activity
planetf1 commentedon Apr 24, 2026
Implementation note:
CompletedEventshould capture whether generation completed normally or was cancelled viacancel_generation(). On early exit,post_processing()does not run, somot.generation.usage(token counts) will beNone. The event should make this visible — e.g. acancelled: boolfield — so consumers don't have to infer it from missing token counts.fix(stdlib): address review feedback on streaming validation
fix(stdlib): address review feedback on streaming validation
planetf1 commentedon Apr 29, 2026
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.mdAdd a new section covering streaming validation end-to-end:
stream_with_chunkingvs rawastream()Requirementand overridestream_validate(with a self-contained code example)StreamChunkingResult: iteratingastream(), callingacomplete(), inspectingstreaming_failuresandfinal_validationscompleted=Falsemeans, what is and isn't populated2.
docs/docs/concepts/requirements-system.mdAdd a paragraph (or short subsection) explaining:
Requirementhas two validation modes: batch (validate) and streaming (stream_validate)PartialValidationResultis and what the three return values ("pass","fail","unknown") meanstream_validateis called and how it relates to the chunking strategy3.
docs/examples/streaming/streaming_chunking.pyThis 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.mdhas a streaming validation section covering all four points listed aboverequirements-system.mdhas astream_validate/PartialValidationResultparagraph or subsectionstreaming_chunking.pyexample is consistent with the final feat(stdlib): add standard streaming event types #902 API and passesuv run pytest docs/examples/streaming/streaming_chunking.pynpx markdownlint-cli2 "docs/docs/**/*.md"titleautomatically)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.docs: add streaming/ to examples catalogue index (generative-computin…
docs(stdlib): fix event dataclass docstrings to use Args not Attribut…
fix(stdlib): address code review feedback on streaming events (genera…
docs: add case _ fallback to streaming_chunking example match block (g…
docs: add word, paragraph, and custom chunking examples (generative-c…
planetf1 commentedon Apr 29, 2026
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 andtask.cancel()is called before the task receives its firstcoro.send(None), Python 3.12's CTaskimplementation skips the coroutine body entirely — includingfinallyblocks. The task raisesCancelledErrorwithout executing any cleanup.Consequence for
stream_with_chunking: if a caller cancelsresult._orchestration_taskimmediately after the call returns (before yielding to the event loop),result.completedstaysTrueeven though generation was cancelled. The fix —result.completed = Falsein thefinallyblock — is correct for the normal case (task reachesQueue.get()before cancel), but the regression test must yield at least once (await asyncio.sleep(0)) before callingcancel()to ensure the task has actually started.Regression test:
test_cancelled_task_sets_completed_falseintest/stdlib/test_streaming.py. Inline comment explains thesleep(0)requirement.Phase 2 consideration: document in the public API that callers who cancel
_orchestration_taskshould yield once first, or provide a higher-levelcancel()method onStreamChunkingResultthat 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 forreset()or deep-copy support — but it is a cost that grows over long streams.Documentation added to
ChunkingStrategyclass docstring andsplit()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 ofstream_with_chunking. Orchestrator-side retry deferred to a future issue."pass"is informational — a per-chunk"pass"result does not short-circuit the finalvalidate()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.astream()andevents()** — second call blocks indefinitely. Acceptable for v1 but worth a clearer error message in a follow-up.fix(stdlib): address fourth-round review findings on streaming events (…
psschwei commentedon May 4, 2026
I believe that the work related to #891 will ultimately replace mellea-partial (?)
feat(core): add cancelled flag on ModelOutputThunk
planetf1 commentedon May 5, 2026
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
planetf1 commentedon May 7, 2026
As well as docs
docs(tutorials): add Tutorial 06 — Streaming Validation
feat(stdlib): add stream_with_chunking() with per-chunk validation (g…
feat(stdlib): add streaming event types, events() iterator, and OTEL …
feat(stdlib): add stream_with_chunking() with per-chunk validation (g…
feat(stdlib): add streaming event types, events() iterator, and OTEL …