Skip to content

feat: streaming validation — per-chunk requirement checking with early exit #891

Closed
5 of 5 issues completed

Description

@planetf1

Problem

All validation in mellea requires a fully-computed ModelOutputThunk. Generation must complete before any constraint is evaluated.

This doesn't match how inference actually works. Backends stream output incrementally — token by token for text, frame by frame for audio, segment by segment for structured data. mellea throws that away and waits for the end.

In practice:

  • A generation that fails on its first sentence runs to completion anyway.
  • Audio that goes wrong in the first few seconds can't be caught until the full clip is done.
  • There's no way to feed partial results to a UI or downstream system as generation proceeds.

Requirements

  1. Incremental validation
  2. Early exit on definitive failure
  3. Deferred judgement when there isn't enough data yet
  4. Backward compatibility — existing requirements work unchanged, streaming is opt-in
  5. Stateful validation — a requirement can accumulate information across chunks within a single attempt
  6. Multiple requirements checkable concurrently per chunk
  7. Configurable chunking boundary (sentence, word, paragraph, audio segment…) set at the call site
  8. A shared event vocabulary for consumers — UIs, m serve, downstream packages

Proposed approach

The work breaks into two layers.

Layer 1 — requirements get streaming support

Requirement gets a new method: stream_validate(backend, ctx, chunk). It receives one chunk at a time and returns a PartialValidationResult — a tri-state value of "pass", "fail", or "unknown". The default returns "unknown" every chunk and falls back to the existing validate() on the complete output at stream end, so existing requirements need no changes.

This default behaviour is correct for requirements that need a full output to do their job — LLM-as-judge and ALoRA requirements return "unknown" throughout streaming and receive the complete output via validate() at stream end. This is the intended path for any requirement that cannot make a meaningful incremental judgement.

The method is named stream_validate rather than avalidate. The a prefix in mellea means "async version of the same operation" — this is a different operation with different semantics (incremental input, tri-state result, stateful between calls) and should be clearly distinct from both validate() and mfuncs.avalidate().

One design question to settle: during streaming, ctx does not yet contain the model output — the MOT isn't complete, so a requirement cannot read accumulated content through context. A requirement that needs to inspect what has been generated so far must hold that state internally.

State isolation across retries: The orchestrator clones each requirement (copy(req)) before every streaming attempt. Streaming state lives on the clone; the original is never mutated. This is consistent with the existing defensive copy in validate() (requirement.py:178). Requirement authors using mutable container fields (e.g. self._buffer = []) should reassign rather than mutate in place, or override __copy__ to properly isolate those fields — self._buffer.append(chunk) on a clone mutates the original's list via the shared reference.

Phase 1 does not include a reset() method. State isolation is handled entirely by the orchestrator cloning requirements before each attempt. If Phase 2 reveals a clear use case for explicit lifecycle hooks, one can be added then.

Layer 2 — orchestration

A new stream_with_chunking() function drives generation and coordinates validation. It consumes mot.astream() in a single background task — MOT enforces a single-consumer constraint on its stream, so requirements cannot each pull from it independently. This function buffers the token stream, applies the chunking strategy, and fans out complete chunks to requirements. It runs stream_validate() across all requirements in parallel on each chunk, exits early on "fail", and calls validate() at stream end for any requirement that did not return "fail". Both "unknown" and "pass" results trigger a final validate() — partial "pass" is informational only in Phase 1 and cannot safely short-circuit final validation without monotonicity guarantees.

This function is a standalone primitive — it does not plug into BaseSamplingStrategy. The existing sampling loop (BaseSamplingStrategy.sample()) always awaits the full output before validation and is not changed in this phase. stream_with_chunking() bypasses it entirely: callers invoke it directly and own the retry loop themselves. For the common case, a session-level convenience function (stream_instruct()) wraps it — providing the same instruct()-style interface users already know, but with streaming validation and retry handled internally.

On early exit due to "fail", the orchestrator calls cancel_generation() on the MOT — a new public method on ModelOutputThunk that cancels the background generate task, drains the queue, and ends any open telemetry span. Without this, the backend's asyncio.Queue(maxsize=20) fills and the producer blocks indefinitely once the consumer stops. This method is introduced as part of #901.

Chunking is a call-site concern rather than a per-requirement one — it is a property of the output type, not the requirement. For now, an external ChunkingStrategy (split(accumulated_text) -> list[str]) handles this, with built-in sentence, word, and paragraph implementations.

A small set of standard event dataclasses — ChunkEvent, QuickCheckEvent, RetryEvent, CompletedEvent, and others — gives consumers a shared vocabulary rather than having every downstream package define its own types. These are specified as part of this work. The sampling strategy plugin hooks (SAMPLING_LOOP_START, SAMPLING_REPAIR, etc.) do not fire during streaming; the event types are the equivalent observability mechanism for the streaming path.

The second phase — MOT-owned chunking

The right long-term owner of chunking is the MOT itself, since it already owns parsed_repr and has the semantic knowledge to produce meaningful chunks for its specific type. A follow-on issue will cover adding stream_parsed_repr to MOT.

When that lands, two things change. First, stream_with_chunking() can accept a MOT-native chunker in place of the external ChunkingStrategy — call-site interface stays the same, external chunkers can be deprecated. Second, and more significantly, requirements that currently need internal state to track accumulated output can instead read directly from context, removing the need for per-requirement state management in most cases. Everything else written in this phase — stream_validate, PartialValidationResult, the event types, the orchestration logic — is unaffected.


Testing and documentation

Each child issue is expected to deliver the following alongside its code:

Unit tests — for all new types and methods in isolation: PartialValidationResult construction and tri-state semantics, ChunkingStrategy split logic (including empty input, no complete chunk yet, trailing fragment), stream_validate() default behaviour, and any stateful override behaviour.

Integration tests with a mock streaming backend — stream_with_chunking() orchestration logic should be covered by tests using a StreamingMockBackend (a backend that emits tokens from a fixed string on a configurable schedule). This allows the full chunk-validate-early-exit cycle to be tested without a live Ollama instance. Tests that exercise the real streaming path against Ollama are welcome but should be marked @pytest.mark.integration.

No e2e or qualitative tests — streaming validation correctness is verifiable without LLM quality judgements. The mock backend is sufficient.

Examples — at least one example in docs/examples/ showing how to write a stream_validate() override and use it with stream_with_chunking().

Docstrings — all public types and functions should have docstrings following the project's Google-style convention. These feed the auto-generated API docs.


Dependencies

Child issues

Sub-issues

Sub-issues

5 of 5 Issues completed
Loading 5 sub-issues

Activity

  1. self-assigned this
    on Apr 21, 2026
  2. added
    enhancement
    epic
    on Apr 21, 2026
  3. planetf1 commented on Apr 21, 2026

    @planetf1
    ContributorAuthor

    @jakelorocco @psschwei First version of overall proposal. I'll likely update in situ to keep this as a clear reference.
    If you broadly agree I'll create sub-issues for each aspect so we can track at a more fine-grained level on our project board. Hopefully I captured our discussion ok

    @jakelorocco the proposal above does consider how to handle state.

    Open as to whether we create a placeholder item for MOT-owned chunking or not (but need not spend time on the detail)

  4. jakelorocco commented on Apr 21, 2026

    @jakelorocco
    Contributor

    I think this sounds good. I have two concerns:

    1. How do we signal when a stream is done to a requirement? or we don't and we just always call validate as a separate call?

    2. In reference to:

    Second, and more significantly, requirements that currently need internal state to track accumulated output can instead read directly from context, removing the need for reset() in most cases.

    We may need to introduce a new function for MOTs that gets current chunks but doesn't await new chunks or something like that for stream_parsed_repr to work. Current implementation of always getting new chunks is part of the reason chunks only allow for one consumer. But maybe the fan out approach already covers that.

  5. planetf1 commented on Apr 22, 2026

    @planetf1
    ContributorAuthor
    1. How do we signal when a stream is done to a requirement? or we don't and we just always call validate as a separate call?

    Yes, the latter -- stream_validate() doesn't know the stream ended, but rather the caller which would call validate() at the end, presuming it has only had 'unknown' results and not broken out earlier. So we get the addition of early chunk-based validation -- but the ultimate validation is still the regular validate(). I think that makes sense?

    When we do phase 2 and the MOT manages the chunking then it may be able to detect the end itself - without any external loop. but any validators that are written for stream or entire content remain the same. So there's a question there, but to come back to later

  6. planetf1 commented on Apr 22, 2026

    @planetf1
    ContributorAuthor
    1. In reference to:

    Second, and more significantly, requirements that currently need internal state to track accumulated output can instead read directly from context, removing the need for reset() in most cases.

    We may need to introduce a new function for MOTs that gets current chunks but doesn't await new chunks or something like that for stream_parsed_repr to work. Current implementation of always getting new chunks is part of the reason chunks only allow for one consumer. But maybe the fan out approach already covers that.

    Yes -- There's more work for phase 2, when MOT manages more, but the intent here is to exclude that for now. Thinking we should raise an explicit issue for phase 2 to start tracking these points.

    In phase 1 the MOT isn't involved. A requirement just gets passed a chunk and has to manage its own accumulated content (and why we have to add an ability to reset between retries)

    I still think the phasing makes sense - as it looks mostly ok, I should open up some sub-issues and a tracker for phase2

  7. psschwei commented on Apr 22, 2026

    @psschwei
    Contributor

    Nice work on this! Architecture seems right. I discussed it with a few AIs, and they all flagged the same three gaps (state ownership, partial-pass semantics, stream cancellation). Here's the full breakdown:


    Synthesis: Three-Model Review of Streaming Validation Plan

    Reviewers: Claude, Codex, Gemini
    Subject: Streaming Validation Plan

    Consensus: Sound Architecture, Under-Specified Lifecycle

    All three reviewers agree the plan's core architecture — fan-out from a single consumer, keeping streaming separate from BaseSamplingStrategy, and phased rollout — is correct. The disagreements are on details, not direction.

    High-Priority Issues (All Three Agree)

    1. reset() is the wrong state boundary

    All reviewers flag this. The existing codebase clones Requirement objects before mutation (copy(self) in requirement.py). Adding mutable per-stream state to shared instances contradicts this pattern and creates race conditions in concurrent use.

    • Claude suggests a Stateful mixin/protocol or deep copy per attempt
    • Codex recommends cloning per streaming run or storing state in the orchestration layer
    • Gemini proposes either cloning or passing an external state object through stream_validate

    Recommendation: Clone requirements per streaming run, or have the orchestrator own accumulation state and pass it in. Don't make reset() the primary mechanism.

    2. Partial "pass" is unsafe without monotonicity guarantees

    All three note that a partial output can look valid mid-stream and become invalid later. The tri-state API is fine for early "fail" (abort immediately) but dangerous for early "pass" (skip final validation).

    • Claude raises this as a design question
    • Codex and Gemini are more prescriptive: v1 should only support "fail" and "unknown", with validate() always running at stream end for non-failed requirements

    Recommendation: Phase 1 should use "fail" / "unknown" only. Reserve "pass" for requirements that can prove monotonicity (a concept that can be formalized later).

    3. No stream cancellation mechanism

    Codex and Gemini identify a concrete deadlock risk: ModelOutputThunk uses a bounded asyncio.Queue(maxsize=20). If the consumer stops early (requirement failed), the producer blocks on put() forever. Claude doesn't call this out explicitly.

    Recommendation: Phase 1 must include an abort path — cancel the backend generation task and/or drain the queue when streaming validation exits early.

    Medium-Priority Issues (Two of Three Agree)

    4. Retry vs. Repair gap (Claude + Gemini)

    The non-streaming sampling loop has repair logic (rewrite context based on failure analysis). The plan's stream_instruct() is unspecified — if it's just "retry N times," streaming validation is strictly less capable than the non-streaming path. This should be documented even if the answer is "simple retry for now."

    5. Observability / Hook compatibility (Claude + Gemini)

    The streaming path bypasses SAMPLING_LOOP_START and related hooks. These aren't just observability — they're writable (plugins can modify loop_budget). The plan's event dataclasses need to either map to existing hooks or explicitly acknowledge the capability reduction.

    Lower-Priority Observations (One Reviewer Each)

    • Phase 1 is text-only (Codex): The chunking API is split(text) -> list[str], which doesn't cover audio or structured output. Worth scoping explicitly to avoid overselling.
    • Per-requirement chunking granularity (Claude): A profanity checker wants word-level chunks; a coherence checker wants sentences. Sentence-level chunking for both is a tradeoff worth acknowledging.
    • GENERATION_POST_CALL timing (Claude): When does this hook fire in the streaming path? Affects telemetry plugins like TokenMetricsPlugin.

    Bottom Line

    The plan should be updated to address three things before implementation:

    1. State ownership — clone or externalize, don't reset()
    2. "pass" semantics — "fail" / "unknown" only in v1; final validate() always runs
    3. Stream abort — explicit cancellation/drain when consumption stops early

    Everything else is refinement that can be resolved during implementation.

  8. added this to the Release 0.5.0 milestone on Apr 22, 2026
  9. planetf1 commented on Apr 22, 2026

    @planetf1
    ContributorAuthor

    Thanks @psschwei - agree there's an issue you spotted. I ran out of time today - will revise the proposal tomorrow.

  10. 4 remaining items

  11. 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/streamingenhancementepic

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions