19 KiB
OutputEvent: the canonical output of a model in the gateway (STRA-338 S23)
One page: how model output reaches the Responses and Messages answers for each family, every place that branched on the family, the
canonical OutputEvent that replaced the family-specific text between the decoder and the answer, and what is left.
Every statement was read from the code at cbc1a9587 (before) and at the tip of claude/hexagonal-s23 (after). Detail pages:
hexagonal.md (layers and ports), gateway-ports.md (the five gateway ports), tech-debt.md (what a step moved but did not fix).
How output flows today
The engine side hands the gateway wire::Event::{Token(id), Done, Error} (gRPC EngineClient, or the worker pool for gpt-oss). The
gateway turns ids into a response in four places that differ only in when they publish:
| Consumer | Source file | Chosen when | Publishes |
|---|---|---|---|
| plain-text stream | responses/stream/text.rs |
no tools, no reasoning, no structured output | text deltas as UTF-8 completes |
| tool-call stream | responses/stream/tool_run.rs |
tools declared, no reasoning | text and each whole call as it completes |
| buffered stream | responses/stream/buffered.rs |
reasoning on or structured output | reasoning deltas live; the rest after DONE |
| buffered answer | responses/create/answer.rs |
stream: false |
the whole response |
Chat Completions (chat/) and Messages (messages/) do not read model output at all: they call the Responses handler and rewrite its
JSON or SSE events, so they never knew the family.
| Question | Qwen3.5 | gpt-oss |
|---|---|---|
| Generation ends on | <|im_end|>, <|endoftext|> (terminal_ids) |
<|return|>, <|call|>, <|endoftext|> |
| Ids to bytes | tokenizer, one id at a time, no state | HarmonyDecoder: parses Harmony messages, writes Qwen-style markup |
| Reasoning | the prompt opens <think> (effort other than none); the model closes with </think> |
always: the analysis channel becomes the text before </think> |
| Tool calls | <tool_call><function=NAME><parameter=P>.. read by tool_output |
commentary channel JSON becomes the same markup (tool_markup), read by the same parser |
| Usage | Done (prompt, generated, reused); reasoning tokens counted from the ids up to </think> |
the same |
| Finish | Done.finish Stop, Length, Cancel |
the same |
| Errors | Event::Error or a closed source: response.failed, or a 502 / memory refusal when buffered |
the same |
Before S23 the markup text (</think>, <tool_call>) was the canonical form: every stream loop owned a piece of the reader
(drain_utf8, ReasoningStream, tool_output::Incremental, decode_generation_noted), and gpt-oss worked only because its decoder
wrote that markup.
Where the family was asked (before)
| Site | What it did | After S23 |
|---|---|---|
gateway-domain/responses/effort.rs reasoning_enabled(request, family) |
family == GptOss means always reasoning; used by text.rs (which stream), buffered.rs, answer.rs, reasoning.rs |
reasoning_enabled(request, codec) reads TextCodec::always_reasons() |
responses/create/admit.rs check_live_features |
gpt-oss: refuse samplers the worker GEN line lacks (a hard-coded field list in effort.rs) |
TextCodec::sampling_limit() returns the set of samplers and the message; sampler_limit::unsupported_sampler reads it |
responses/create/admit.rs apply_sampling_defaults |
gpt-oss: drop the samplers it lacks (a second hard-coded list) | sampler_limit::drop_unsupported_samplers reads the same set |
responses/stream/*.rs, create/answer.rs |
tokenizer.decoder() bytes, then </think> and <tool_call> scanning in each loop |
TextCodec::live_decoder / at_end_decoder; the loops read OutputEvent |
responses/intake/parts.rs render_prompt |
match family: ChatML template with control-token marks, or the Harmony renderer |
unchanged (input side, see below) |
responses/intake.rs expand_images |
needs the Qwen tokenizer (qwen()) for pictures |
unchanged (input side) |
responses/reasoning.rs reasoning_plan |
reasoning budget uses the Qwen tokenizer (qwen()) |
unchanged (Qwen-only feature) |
serve/engine.rs |
the runtime backend counts with the Qwen tokenizer (qwen()) |
unchanged (composition) |
serve/state.rs |
builds GptOssCodec when gptoss_gguf is set |
unchanged (composition root) |
config/*, preflight.rs |
gptoss_gguf option checks |
unchanged (configuration) |
The canonical type
leleka_gateway_domain::output (pure, no IO, no tokio):
OutputEvent::ReasoningDelta(String) a piece of reasoning to show; not an item
OutputEvent::Reasoned { text, complete, tokens } the reasoning of the response, whether the model closed it, its tokens
OutputEvent::Text(String) answer text
OutputEvent::Call { name, arguments: Value } one whole call of a declared tool
OutputError::Decode(msg) the ids could not be read, the reasoning never ended, or the generation already ended -> 502 detokenization_failed
OutputError::Parse(msg) a tool call in the text is not acceptable -> 502 tool_call_parse_failed
A family hands out one decoder per generation and per reading: TextCodec::live_decoder(LivePlan) -> LiveDecoder and
TextCodec::at_end_decoder(AtEndPlan) -> AtEndDecoder. Both sit on the same private TokenBytes enum (Qwen, Harmony), so a
token costs a match, not a virtual call, and what one reading offers cannot be asked of the other. live_decoder has the default
None: a model that always reasons (gpt-oss) is read at its end, and the two live streams fail the response if they are ever given
None:
LiveDecoder(LivePlan { tools, recovery, keep_raw }): text and whole calls as the bytes arrive (UTF-8 completion, thentool_output::Incremental). Every event ofpushandfinishis final;finishalso takes the bytes the family held back. Accessors:notes()andraw_text(). Used by the plain-text stream and the tool-call stream.AtEndDecoder(AtEndPlan { reasoning, preview, tools, recovery, keep_raw }): the answer is read once the generation is over.pushreturns onlyReasoningDeltapreviews (none whenpreviewis off, which the buffered answer sets: nobody watches it);finish(Finish)returns the events that make up the response (Reasoned, thenTextandCallastool_output::parse_withreads them, or oneTextwhen the request declared no tools; an answer always has at least one text event). Accessors:notes(),accepted_call_in_reasoning(),split_text(). Used by the buffered stream and the buffered answer. The two readings stay apart because the incremental and the batch tool-call readers are not the same function (a</function>left out is accepted only at the end).
A generation ends once: push or finish after finish is a decode error (in the buffered stream it is a response.failed, not a
panic). output_items(events, response_id) turns the events into OutputItems and the reasoning token count. The cut of a finished
generation into reasoning and answer is text-level code in output/cut.rs (cut_text, one CutGeneration, also exposed as
cut_reasoning_for_corpus for the tool corpus tests; the tokens are counted from its extent); the </think> search and hold-back are in think_marker.rs, used by the reasoning previewer, the cut and the
reasoning budget.
Adding a family touches, for the output side: a TokenBytes arm and the constructors LiveDecoder::<family> and
AtEndDecoder::<family>, all inside gateway-domain (the enum is private to it, so those constructors are the only way in); a
TextCodec implementation in the crate that holds the family's tokenizer (harmony_family.rs in strata-control for gpt-oss) with
at_end_decoder, live_decoder only if the family can be read live, always_reasons, sampling_limit, terminal_ids, encode and
family() (a Family variant); and the choice of the codec in serve/state.rs. The stream loops and the answer builder do not
change. The input side (render_prompt, pictures, the reasoning budget) still has its own Family and qwen() branches.
Migrated sites
| Step | Site | What it reads |
|---|---|---|
| golden | control-plane/tests/output_golden/, tests/fixtures/golden/output_{cases,events}.json |
the proof harness (below) |
| 1 | stream/text.rs |
live, no tools: Text |
| 2 | stream/tool_run.rs, stream/tools.rs |
live, tools: Text, Call |
| 3 | create/answer.rs, tool_recovery.rs (at_end_plan, finish_generation) |
at end: all events |
| 4 | stream/buffered.rs |
at end: ReasoningDelta live, the rest at DONE |
| 5 | reasoning_enabled, admit.rs |
TextCodec::always_reasons, sampling_limit |
| 6 | the replaced readers | decode_generation_noted, decoded_items, ReasoningStream, drain_utf8 copies removed |
| 7 | the first review | live and at-end decoder types, TokenDecoder and the legacy item builder removed, the tool corpus on the gateway's cut, the sampler set |
| 8 | the second review | names, one CutGeneration, sampler_limit.rs, no gpt-oss live reading, 29 more golden cases and the tests of the store, the worker's sampling and the disconnect at DONE |
Identity proof
control-plane/tests/output_golden (a test binary of its own, because the cases switch the process-wide tool-call recovery) drives
the real create handler with 159 scripted token sequences, each as a stream and as a buffered answer: 318 captures of status,
content type and body bytes, SSE framing included. The expected captures were recorded on 08afbf216 (cbc1a9587, the code before
S23, plus the first harness) in a temporary worktree, and are checked against the new code; none was recorded on it and none differs. regenerate_output_golden
refuses to run unless OUTPUT_GOLDEN_RECORD names the pre-S23 commit and the tree has no output module, and
output_events.recorded_on names the commit the captures were recorded on (a test pins it).
Volatile text is normalised so that nothing identity-relevant is lost: every distinct id becomes <kind>_ID<k> by order of first
appearance and keeps its numeric suffix (call_ID3_1), so the index inside call_<response>_<n> is pinned, and
two_calls_of_one_response_have_different_call_ids checks the call ids Codex pairs tool outputs by; timestamps become 0.
The scripts cover: plain text; a terminal token followed by more tokens (also with reasoning, tools and structured output on); tools
with text, one call, two calls, unknown tool, schema violation, an unfinished call at the length limit, a missing closer, a custom
tool; reasoning that closes, that never closes (length and natural stop), that ends on whole calls, that closes and is followed by a
call cut at the length limit; the request's max_output_tokens reached in every reading; a second </think> in the answer and inside a tool argument; structured output valid and invalid, also with reasoning on and for gpt-oss, also with tools; namespaced tools; DONE before the first
token and an error after DONE; a worker that reports fewer generated tokens than the reasoning took (the clamp of the reasoning
tokens); the
tool-call recovery on and off with two drifted forms in the live tool stream, the buffered stream and the buffered answer; non-ASCII
call arguments, also as multi-byte tokens; a vocabulary with multi-byte tokens (a euro sign, an emoji, a token holding the whole
</think> and a token that ends in the middle of it, with reasoning_tokens asserted: 2 and 3) and raw byte tokens; characters cut
at the length limit and at stop in the live text, the live tool stream, the reasoning preview, the structured stream and gpt-oss
channels; a lone continuation byte in reasoning and in the answer; an id outside the vocabulary in the middle of a script; a source
that closes without DONE; Finish::Cancel; worker failures (also a memory refusal); and for gpt-oss the analysis, commentary and
final channels in their combinations, calls with and without declared tools, invalid arguments and the rest of the earlier list.
Scripts are synthetic.
Timing, which captures cannot show: with a worker that waits for a gate before DONE, the first response.reasoning_text.delta
(both families), the first text delta and the first whole call reach the client before DONE is sent; a client that leaves closes the
source in five stream modes, and also when it leaves at DONE; a stored response equals the one the client was sent (streamed and
not); a gpt-oss request that sets a sampler the worker lacks gets a 400 that names the first one; the server defaults for those
samplers do not reach the gpt-oss worker (top_k 20 and penalty_last_n 64 among them), neutral values are accepted, and Qwen keeps all
five samplers. All fifteen tests of the binary pass on 08afbf216 and on the new code.
Results on the tip: cargo test --no-fail-fast --all-targets for strata-control, leleka-gateway-domain, leleka-gateway-text,
leleka-harmony, leleka-tokenizer and leleka-runtime-client on Linux (WSL), before (cbc1a9587) and after, compared with
scripts/dev/test-outcomes.py compare: 0 missing, 0 outcome changes, 38 new ids; 515 ok / 1 ignored before, 552 ok / 2 ignored
after. The ids of the first golden harness moved to the new binary; the tests that read the replaced code (reasoning_marker_and_unicode_split_at_every_byte,
the unclosed-reasoning test, the utf8 test, the Harmony decoder tests) keep their ids and now read through the new decoders.
cargo check --all-targets and cargo clippy --no-deps --all-targets -- -D warnings for strata-control and leleka-gateway-domain:
0 warnings. check-limits.py --base origin/claude/hexagonal-integ, check-architecture.py and check-ci-coverage.py: green;
architecture-baseline.json tightened (dyn-trait gateway-domain 5 to 2, strata-control 14 to 11).
Not covered end to end: STRATA_DEBUG_FAILED_OUTPUT (read once per process through a OnceLock, so a test binary cannot switch it
beside other tests); the keep_raw, raw_text() and split_text() paths have unit tests in leleka-gateway-domain.
Behaviour that changed or moved
No response byte changes (the golden). What changes besides:
- Decoding time. Per-token decoding as the ids arrive is new only for the structured-output stream on Qwen (it kept the ids and
decoded them at DONE); the reasoning stream already decoded every token as it arrived, and the buffered (non-stream) answer still
decodes all ids at the end, inside
spawn_blocking. A decode error therefore surfaces at the offending token in the structured stream and not at DONE; the failure code and message and every response byte are the same (the golden has an id outside the vocabulary inq-structured-oov-idand the other modes). - The
post_decodestage (buffered.rs,docs/cp-latency.md,scripts/cp/summarize.py) now times onlyfinish(the cut and the batch parse), because the bytes are decoded as they arrive. It is not comparable with numbers measured before S23. - Logs. A refused tool call in the buffered stream now also writes the
STRATA_DEBUG_FAILED_OUTPUTdebug copy to stderr when that variable is set (the non-stream answer already did). In the non-stream answer the debug copy is written before the generation-failure line instead of after it. - Flags are read at stream start. The buffered stream builds its plan (tool-call recovery, debug copy) when the stream starts and not at DONE; the tool-call stream already read the recovery when it started. A recovery switch flipped during a request therefore no longer reaches that request's buffered stream (only the tests flip it).
- The worker sees an out-of-vocabulary id as a client that left. In the structured-output stream on Qwen the new code fails at
the offending token and drops the source then;
backend_worker/generation_run.rssees the closed result (Wake::ClientGone) and cancels the engine's generation at that point, andconclude.rscounts the request asdisconnected(metrics.rs: outcomedisconnect,cancelledplus one) where the code before S23 let the generation run toDONEand counted a finished generation with its stop or length. So the worker metrics of such a request differ (earlier cancel,disconnectinstead of the finish reason) while the client sees the sameresponse.failed. The reasoning stream and the live streams already behaved so for a decode or parse error. - A generation ends once.
finishtwice, orpushafter it, is a decode error.
Behaviours kept on purpose (they are in the golden):
- gpt-oss: a call when the request declares no tools is not an error: its markup stays in the answer text.
- gpt-oss: invalid JSON, a non-object, or an argument name that cannot be passed on is a decode error (
detokenization_failed) at the end of the call, while an unknown tool or a schema violation is a parse error (tool_call_parse_failed) after the whole generation was read. A decode error wins over an earlier parse problem because decoding finishes first. - Reasoning that never closes: at the length limit it is an incomplete reasoning item; on a natural stop it is an error, unless the text ends on whole calls of declared tools, which then become the answer (the live reasoning deltas have already shown the call text).
- The index in
call_<response>_<n>counts answer items in the buffered readings and all items in the tool-call stream, as before. - Reasoning tokens are the tokens up to the one that completed
</think>(for gpt-oss, the one that closed the analysis). - gpt-oss: a literal
</think>inside the analysis text ends the reasoning there, because the Harmony decoder writes markup that the shared cut reads (a latent defect, pinned byg-two-markers-analysis).
Not done, and why
- The gpt-oss adapter still writes the Qwen-style markup inside the decoder.
HarmonyDecoder(moved unchanged fromcontrol-plane/src/harmony_family.rstogateway-domain/src/output/harmony.rs;pushandfinishare its own methods now) turns Harmony messages into</think>and<tool_call>text, and the shared cut and parse read that. Reading the channels directly would change two corners that the golden pins: the</think>inside the analysis text above, and the call-without-tools quirk. Both are behaviour changes, so they are left for a step with an owner decision. - Prompt rendering is still chosen by
Family(intake/parts.rs), and the picture expansion, the reasoning budget and the runtime backend still ask for the Qwen tokenizer (qwen()). They are the input side of the codec; they need a prompt-rendering port, not an output one. GptOssCodeclives instrata-controlbecause it loads the BPE from a GGUF file; the decoder it hands out is in the domain.