Skip to content

feat: Phase 2 — validated streaming #1013

Open
3 of 4 issues completed
Open

Description

@planetf1

Context

mellea/stdlib/streaming.py (landing in PR #942, closing #901) provides Phase 1 streaming validation — a call-site ChunkingStrategy with three built-in chunkers (SentenceChunker, WordChunker, ParagraphChunker) and an orchestrator (stream_with_chunking). This is a scoped pragmatic choice. Phase 2 refines that foundation and extends it, broken into the sub-issues below.

Consolidated design summary

Motivation

Phase 1 collapses two semantic concerns onto the call site: how to chunk the stream (a property of the output type) and how to validate chunks (a property of the requirement). These are independent and belong in different owners.

  • Type semantics. What counts as a complete chunk of this kind of output? JSON value, prose sentence, code statement, audio segment, image region. Invariant across requirements.
  • Constraint semantics. What makes a particular output acceptable? Max three sentences, matches schema X, no hallucinated entities. Invariant across outputs of the same type.

Under Phase 1, both are author-written at the call site. Phase 2 separates them: chunking becomes a per-requirement concern, and the streaming parsed representation becomes its own capability.

Motivating output types (all in scope)

Phase 1 chunkers cover prose only (sentence/word/paragraph, all operating on accumulated_text: str). Phase 2 must support at least these output types, each with genuinely different chunk semantics:

  • Prose — sentence, word, paragraph boundaries. Already covered by Phase 1 chunkers; Phase 2 should subsume them.
  • Structured text — JSON values, YAML documents, code statements/blocks. Chunk boundary is "one complete parseable unit."
  • Multi-modal streams — audio (silence-delimited segments, fixed windows, VAD-detected utterances), image (region or tile boundaries), potentially video. Chunk boundary is inherently non-string.

Multi-modal is first-class motivation for this work, not deferred scope. Epic #891 explicitly names the audio case ("Audio that goes wrong in the first few seconds can't be caught until the full clip is done"), and the ChunkingStrategy.split(accumulated_text: str) -> list[str] signature in Phase 1 forecloses on multi-modal by design — that foreclosure is what this issue exists to address.

Sub-issues

Phase 2 is broken into four sub-issues (an earlier version of this issue proposed moving chunking onto the MOT; the direction has since changed — chunking is handled per-Requirement, and stream_parsed_repr is a separate concern from chunking):

#1440 blocks the rest; #1441, #403, and #1442 depend only on it and can proceed in parallel.

Open design questions (for comments)

  1. Signature and generator shape. Is stream_parsed_repr an async generator on the MOT? Does it share a queue with the raw astream(), or run in parallel? For multi-modal, does the signature accept bytes / frames / tensors rather than str?
  2. Chunking boundary authority. Which component decides what a "complete chunk" is — the MOT's parser, a pluggable chunk-boundary predicate, or both? Answer likely differs between text and multi-modal.
  3. Backpressure. If parsed chunks are slower to produce than raw tokens/frames, where does the buffering live?
  4. Backwards compatibility. How to migrate from the Phase 1 call sites?
  5. Typed output. Does stream_parsed_repr yield values of type S (the MOT's parsed_repr type parameter), or a richer container that carries partial-parse state? Multi-modal MOTs may need the latter.
  6. Error handling. What happens if the MOT's parser fails on a partial stream — surface immediately, wait for more data, or fall back to raw chunking?
  7. Testability. Each MOT type's stream_parsed_repr needs verification against its non-streaming parsed_repr. Shape of the shared test harness? Multi-modal test fixtures are their own problem.
  8. Agent authoring. If we want new MOT types to be agent-writable (see PR feat(stdlib): add stream_with_chunking() with per-chunk validation (#901) #942 discussion), what contracts are needed on the MOT base class? Clear APIs and guidelines are the substrate; a skill can sit on top where the framework supports one.

Broader scope (to discuss)

The PR #942 thread raised a parallel observation. Both stream_validate authoring and (future) stream_parsed_repr authoring have deterministic checks against a non-streaming counterpart (validate() and parsed_repr respectively), which makes them plausible candidates for agent-friendly extension patterns — potentially skills in frameworks that support them. Worth discussing whether this issue should cover just stream_parsed_repr or also the broader agent-authoring story, or whether the latter warrants its own separate issue.

Dependencies

References

Sub-issues

Sub-issues

3 of 4 Issues completed
Loading 4 sub-issues

Activity

  1. added
    epic
    on May 5, 2026
  2. added this to the Release 0.6.0 milestone on May 6, 2026
  3. planetf1 commented on May 11, 2026

    @planetf1
    ContributorAuthor

    Concrete Phase 1 data point worth recording here, from the current PR #942 review cycle.

    When a streaming delta produces multiple chunks and chunk N fails validation, the orchestrator has to maintain two separate views of the text:

    • accumulated — the full raw text, needed by the external ChunkingStrategy to maintain its split state across calls (split(accumulated) is how the chunker tracks where it left off)
    • emitted_text — only the chunks that actually passed validation and reached the consumer

    These diverge on early exit, and we had to introduce a second tracking variable to bridge them. The fix is clean enough, but the reason it's needed at all is that chunking is outside the MOT — the chunker needs the full accumulation to do its job, while full_text should only reflect what was validated. If the MOT owned the chunker, both views would be internal and there'd be no split to paper over.

    Small evidence, but it's a concrete instance of the "two semantic concerns collapsed onto the call site" argument in the issue description above.

  4. jakelorocco commented on May 19, 2026

    @jakelorocco
    Contributor

    @planetf1, can this be closed now?

  5. added
    area/stdlib
    area/streaming
    enhancement
    area/sampling
    on May 20, 2026
  6. ajbozarth commented on Jun 3, 2026

    @ajbozarth
    Member

    Coordination note from #909 design research (Discussion #1197): #909's Area 3 proposes splitting MOT computation logistics into a _GenerationState sub-object. That shape is intentionally designed to accommodate this issue's stream_parsed_repr parsed-repr stream buffer as a future field, so #1013 benefits if Area 3 lands first.

    Not blocking either direction; flagging so they don't collide later.

  7. added
    p2
    on Jun 18, 2026
  8. removed their assignment
    on Jun 19, 2026
  9. self-assigned this
    on Jun 29, 2026
  10. ajbozarth commented on Jul 7, 2026

    @ajbozarth
    Member

    Coordination note for the Phase 2 design outline, from telemetry work in PR #1361 (#1290).

    A StreamChunkingResult finalization-contract gap surfaced that's orthogonal to stream_parsed_repr but lives in the same lifecycle this issue will design, so flagging it here.

    Today: acomplete() is the documented terminal step (astream()'s docstring says "Call acomplete() after iterating"), but nothing enforces it. A caller who fully drains astream() never has to call it: the orchestrator task itself sets full_text / completed / final_validations and calls _done.set() — acomplete() only awaits _done. So results are readable and _done is set purely as a side effect of draining, and skipping acomplete() "works" by incidental ordering. The one thing acomplete() uniquely does is fire STREAMING_END (telemetry finalize), which by design can't fire on the orchestrator task — so the misuse silently drops the span + metrics.

    A concrete symptom of the same gap: as_thunk's docstring says it raises "before acomplete() has returned," but its guard actually checks self._done.is_set() — which the orchestrator sets, not acomplete(). A full drainer can call as_thunk without acomplete(), contradicting the docstring.

    Design question for the outline: should skipping acomplete() fail loudly instead of working by accident? e.g. gate the public accessors on a _finalized flag set only by acomplete(), rather than on _done. That turns the documented contract into an enforced one and removes the "it kind of works without acomplete()" footgun that keeps recurring in review.

  11. ajbozarth commented on Jul 8, 2026

    @ajbozarth
    Member

    Sharing some offline discussion spun off of #1361 here:

    While discussing #1361 (comment) @psschwei and I eventually came to the conclusion that any improvements to that PR's implementation would need to stem from changes to stream_with_chunking itself and make more sense attached to this phase 2 epic. I'll summarize some of our thought below:

    • can the streaming workflow be improved, ie where it makes certain calls (like generate_from_context), what functions the user is expected to use (acomplete vs astream), how StreamChunkingResult behaves compared to ModelOutputThunk
    • why is stream_with_chunking separate from generate_from_context streaming, why is it not an extension of it?

    I'll be scheduling a call for @planetf1 @psschwei @jakelorocco and I to discuss direction in more detail. I intend to share my further research notes here prior to that call

  12. removed this from the Release 0.7.0 milestone on Jul 13, 2026
  13. changed the title [-]feat(core): Phase 2 — MOT-owned streaming chunking via stream_parsed_repr (placeholder)[/-] [+]feat: Phase 2 — validated streaming[/+] on Jul 24, 2026
  14. added
    p1
    and removed
    p2
    on Aug 10, 2026
  15. added
    triage/accepted
    on Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/samplingarea/stdlibarea/streamingenhancementepicp1triage/accepted

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions