Repository navigation
Description
What
Create mellea/stdlib/streaming.py with a stream_with_chunking() function and a StreamChunkingResult return type.
async def stream_with_chunking(
action,
backend,
ctx,
*,
quick_check_requirements: list[Requirement] | None = None,
chunking: str | ChunkingStrategy = "sentence",
quick_check_backend: Backend | None = None,
) -> StreamChunkingResult:Why
This is the core orchestration primitive for streaming validation. It bridges the MOT's raw token stream, the ChunkingStrategy, and per-chunk stream_validate() calls on requirements. All higher-level streaming APIs build on this function.
Implementation
Internals:
- Clone each requirement (
copy(req)) before the attempt starts — streaming state accumulates on the clone; the original is never mutated - Start a single background
asyncio.Taskconsumingmot.astream()— the MOT enforces a single-consumer constraint (documented atmellea/core/base.py:434-436), so the orchestrator is the only caller; fanning out to requirements happens via a result queue, not by sharing the MOT - Accumulate token deltas, apply
ChunkingStrategy.split()to produce complete chunks - For each complete chunk: run
stream_validate()across all requirements in parallel viaasyncio.gather - On any
"fail"result: callmot.cancel_generation()to cancel the background task, drain the queue, and end any open telemetry span; setcompleted = False. Without this,asyncio.Queue(maxsize=20)blocks the producer indefinitely once the consumer stops - After the stream ends (
mot._computed is True): callvalidate()on every requirement that did not return"fail"— both"unknown"and"pass"trigger final validation;"pass"mid-stream is informational only in Phase 1 - Route validation calls to
quick_check_backendif provided
StreamChunkingResult (also defined in this module):
astream() -> AsyncIterator[str]— yields validated text chunks as they completeacomplete()— awaits full completioncompleted: bool—Falseif the stream exited early due to a"fail"resultfull_text: str— complete generated text (available afteracomplete())as_thunk— wraps the output as aModelOutputThunkfor interop with existing mellea code
Test infrastructure: A StreamingMockBackend test helper needs to be created (does not currently exist in the codebase). It should accept a fixed response string and feed it into a MOT's queue token by token. It can be defined in test/stdlib/test_streaming.py or a shared fixture. This is the primary vehicle for testing the orchestration logic without a live backend.
Example: Add docs/examples/streaming/stream_with_chunking.py demonstrating how to write a stream_validate() override and use it with this function. Marker: # pytest: ollama, integration.
Acceptance criteria
-
mellea/stdlib/streaming.pycreated withstream_with_chunking()andStreamChunkingResult - Requirements cloned (
copy(req)) before each attempt; the original requirement instance is never mutated - Single
asyncio.Taskconsumesmot.astream()— no other code callsastream()on the same MOT - Per-chunk
stream_validate()called viaasyncio.gather(parallel, not sequential) - Early exit on
"fail"cancels the remaining stream;StreamChunkingResult.completedisFalse - All non-
"fail"requirements (both"pass"and"unknown") getvalidate()called at stream end -
quick_check_backendroutes validation calls to the alternate backend -
StreamChunkingResult.as_thunkwraps the output as aModelOutputThunk -
StreamingMockBackendtest helper created - Integration tests in
test/stdlib/test_streaming.pyusingStreamingMockBackendcovering:- Normal completion (all
"unknown",validate()called at stream end) - Early exit on
"fail" - Stateful requirement verified across a retry — clone ensures clean state; no bleed from prior attempt
-
quick_check_backendrouting
- Normal completion (all
-
cancel_generation()added toModelOutputThunkinmellea/core/base.py; cancels_generatetask, drains queue, ends open telemetry span; orchestrator calls it on early"fail"exit - Test: deadlock scenario — early exit with queue near capacity does not hang
- Uses
mot.generation.*telemetry paths throughout (requires refactor!: partition ModelOutputThunk execution metadata into Generat… #908 merged;mot.generation.usagewill beNoneon early exit sincepost_processing()does not run —StreamChunkingResultexposes this) - Documents in docstring that v1 retry is simple re-invocation (no repair/rewrite); plugin hooks (
SAMPLING_LOOP_START,SAMPLING_REPAIR, etc.) do not fire — feat(stdlib): add standard streaming event types #902 event types are the observability substitute - Real-backend tests marked
@pytest.mark.integrationand@pytest.mark.ollama - Example in
docs/examples/streaming/with# pytest: ollama, integrationmarker - Google-style docstrings on
stream_with_chunking()andStreamChunkingResult
Blocked by #900, #899
Depends on #908 merging (uses mot.generation.* API throughout)
Part of #891
Activity
planetf1 commentedon Apr 23, 2026
Note from #908 review: The
ModelOutputThunk.__copy__method now shares theGenerationMetadatadataclass by reference (see #908 comment). Ifstream_with_chunking()orStreamChunkingResult.as_thunkshallow-copies a streamed MOT, generation metadata mutations will leak between copies. Fix is one line:copied.generation = copy(self.generation)— to be addressed here if the code path requires it.planetf1 commentedon Apr 24, 2026
Implementation notes:
cancel_generation()telemetry: PR refactor!: partition ModelOutputThunk execution metadata into Generat… #908 moved telemetry fields tomot.generation.*(GenerationMetadatadataclass). The telemetry span is no longer atself._meta.get("_telemetry_span")— check the post-refactor!: partition ModelOutputThunk execution metadata into Generat… #908base.pyfor the current span storage location before implementing the span cleanup incancel_generation().GenerationMetadatacopy safety: The shallow-copy fix is already in refactor!: partition ModelOutputThunk execution metadata into Generat… #908 (base.py:614:copied.generation = copy(self.generation)). IfStreamChunkingResult.as_thunkcreates a new MOT or copies one post-streaming, this is already handled — no additional fix needed.v1 retry is simple re-invocation — no repair/rewrite. This is intentional: early exit means there's no complete output to feed into a repair prompt. Document this in the
stream_with_chunking()docstring so it's clear this is a deliberate scope decision, not an oversight.No
reset()on requirements. State isolation is entirely viacopy(req)before each attempt. The epic and feat(core): add stream_validate() to Requirement #900 have been updated to reflect this.feat(core): add cancel_generation() to ModelOutputThunk
feat(stdlib): add stream_with_chunking() with per-chunk validation (g…
docs: add streaming_chunking example (generative-computing#901)
feat(core): add cancel_generation() to ModelOutputThunk
feat(stdlib): add stream_with_chunking() with per-chunk validation (g…
docs: add streaming_chunking example (generative-computing#901)
feat(core): add cancel_generation() to ModelOutputThunk
feat(stdlib): add stream_with_chunking() with per-chunk validation (g…
docs: add streaming_chunking example (generative-computing#901)
planetf1 commentedon Apr 30, 2026
Acceptance criteria clarification (raised in PR #942 review)
Two items in the AC have been refined during implementation — noted here for the record:
Example marker: AC says
# pytest: ollama, integration; the example uses# pytest: ollama, e2e. Thee2etier is the correct choice under the current four-tier taxonomy (unit→integration→e2e→qualitative) — the example exercises a full path through the system against a real Ollama backend. The issue predates the locked taxonomy. (discussion)Real-backend tests: AC mentions
@pytest.mark.integration @pytest.mark.ollamatests intest/stdlib/test_streaming.py. All orchestration behaviour is covered deterministically by the unit suite viaStreamingMockBackend; the example (# pytest: ollama, e2e) covers the real-backend path. No separate integration test file is planned. (comment)feat(stdlib): add stream_with_chunking() with per-chunk validation (g…
feat(stdlib): add stream_with_chunking() with per-chunk validation (g…