Skip to content

feat(ai): finish reasons and stream completeness for model replies #599

Closed

Description

@dan-petty

Context & Rationale

No provider client reads why a model stopped.

  • The non-streamed parsers ignore done_reason, finish_reason and stop_reason:
    • Ollama: src/devops_cli/ai/client/ollama.py:326-381;
    • OpenAI-compatible backends: src/devops_cli/ai/client/openai.py:121-151;
    • Claude: src/devops_cli/ai/client/claude.py:83-118.
  • LLMResponse has no field for the reason (src/devops_cli/ai/client/models.py:83-129), and to_model_response does not set pydantic-ai's ModelResponse.finish_reason (models.py:141-155).
  • The dispatch span hardcodes gen_ai.response.finish_reasons to ["stop"] (src/devops_cli/ai/client/unified.py:101).

All lines were checked at ef21785.

A cut reply looks complete.

  • Persona review replies are capped at 8,192 tokens (src/devops_cli/config/defaults.py:386, used at src/devops_cli/ai/review/runner.py:866 and src/devops_cli/ai/review/pipeline.py:928).
  • json-repair closes a reply that was cut inside its last finding, and the reply still parses. In a probe at ef21785, a 5-finding reply cut two characters into the last description parsed to 5 findings. The last one had the description "de". ReviewResult has no field that marks this.
  • The reply then passes the validator (runner.py:870). It is cached for 7 days (unified.py:581, defaults.py:121) and served from the cache on the next run.
  • Neither the spend ledger nor profile.json can say how often this happens. The ledger has no reason column (src/devops_cli/ai/spend/ledger.py:29-46). StageProfile counts only calls, tokens and backends (src/devops_cli/ai/review/profile.py:80-98).

Streams end without an error.

  • All three stream paths read response.iter_lines() (src/devops_cli/ai/client/streaming.py:330). httpx2's line decoder splits on every str.splitlines() boundary, U+2028 included (httpx2 2.13.0, _decoders.py:400). So a delta with a raw U+2028 inside its JSON string is cut in two, fails to parse and is dropped without an error.

  • The Ollama extractor never reports done (streaming.py:306-308).

  • The Claude extractor stops on [DONE], which Anthropic never sends, and reads only content_block_delta (streaming.py:258-280). So it ignores message_delta, message_stop and error events.

  • A probe over an httpx2 MockTransport at ef21785 sent four kinds of broken stream. Each returned its partial text and raised nothing:

    • an OpenAI stream with no finish_reason and no [DONE];
    • an Ollama stream cut mid-line;
    • an Ollama {"error": ...} line;
    • an Anthropic event: error.

    A delta with a raw U+2028 was dropped. A frame split mid-code-point was decoded correctly.

  • After such a stream, chat_messages_stream records spend as for a normal call (unified.py:811-813). devops ai chat stores the partial text as the reply (src/devops_cli/commands/ai.py:953).

  • A failed non-streamed call records no spend: _record_response_telemetry_and_spend runs only after the provider returns (unified.py:377-384).

  • The Ollama stream request sends no options at all (ollama.py:464-474). The non-streamed request sends num_predict from the reply cap (ollama.py:310-312). So max_tokens and limit_completion_tokens never reach an Ollama stream, and a direct Ollama stream is never cut at the cap. That is a separate defect (see Related).

Background. vibes observations/devops-cli/15-llm-structured-output-repair-and-schema-reconciliation.md:32 records models retrying into the same token ceiling. vibes' RESP decoder returns (None, 0) until a whole frame arrives (examples/valkey-l2-repomap-cache/repomap_cache.py:180-186). It is tested over a socket that splits frames (test_repomap_cache.py:185-210).

What this item does. Every reply carries the reason it ended, and a stream ends only on its provider's final frame. Four things that the original text bundled, or that turned up while checking it, are separate items (see Related):

  • acting on cut review replies;
  • one JSON repair seam;
  • a defect in the streamed chat path;
  • Ollama streams that send no options.

Scope & Deliverables

  • Deliverable:
    • A finish reason on every reply.
      • LLMResponse gains finish_reason: FinishReason | None, typed with pydantic-ai's FinishReason (pydantic_ai.messages, 2.35.0: stop, length, content_filter, tool_call, error).
      • to_model_response passes the reason on and from_model_response reads it, so the pydantic-ai path (src/devops_cli/ai/direct.py:258) carries it too.
      • Three maps in src/devops_cli/config/constants.py translate provider values: the OpenAI-compatible finish_reason, Anthropic's stop_reason and Ollama's done_reason. max_tokens and model_context_window_exceeded become length. An absent or unmapped value becomes None, which means unknown.
      • The three non-streamed parsers fill the field.
    • Telemetry.
      • These spans set gen_ai.response.finish_reasons to the real reason, and leave it out when the reason is unknown:

        The gen_ai.chat wrapper span (_record_chat_telemetry, unified.py:485) does not get it, because feat(cli): genai span attributes checked against the pinned semantic conventions #588 keeps gen_ai.response.* keys on the inference spans only.

        The hardcoded ["stop"] is removed.

      • The spend ledger gains a finish_reason column, added in place as served_by and stage were (ledger.py:58-61, 230-241). track_request_spend stores the reason and passes it in the call dict that observers receive (ledger.py:640).

      • Every caller passes the reason to track_request_spend:

        • _record_response_telemetry_and_spend (unified.py:417-455) passes res.finish_reason;
        • the two pydantic-ai direct calls (src/devops_cli/ai/direct.py:118, :163) pass resp.finish_reason;
        • _record_stream_spend (unified.py:818) passes the stream's reason.
      • StageProfile gains two counts, and profile.json carries both:

        • finish_reasons: replies per reason, with unknown for None;
        • truncated: length replies per backend, keyed like backends.
      • The one-line profile summary (_write_review_profile, runner.py:1971) adds how many replies hit the cap, when that number is not zero.

    • Cut replies are not cached. _handle_successful_chat_dispatch (unified.py:568) skips the cache for length, content_filter and error. The reply is still returned to the caller.
    • Stream framing.
      • OpenAI-compatible and Claude streams are read with httpx2.EventSource, which ships in the pinned httpx2 2.13.0 (httpx2/_sse.py). It splits lines only on CR and LF, decodes code points split across chunks and limits the size of each event.
      • Ollama NDJSON is read with iter_bytes(), split on \n only, and each line is decoded as UTF-8.
      • A new default, DEFAULT_AI_STREAM_MAX_EVENT_BYTES (1 MiB, the same as httpx2's DEFAULT_MAX_EVENT_SIZE_BYTES), limits each event and each unterminated line. MAX_STREAM_BYTES (models.py:18) still limits the whole stream.
      • Chunks are still yielded as they arrive.
    • Stream completeness.
      • A stream is complete when its final frame arrives:
      • An error frame raises AIClientError with the provider's message, masked with mask_secrets (src/devops_cli/security/sanitizer.py:269, as ollama.py:406 already does) and cut to 256 characters. Error frames are:
        • an Ollama {"error": ...} line;
        • an Anthropic event: error;
        • an OpenAI-compatible data: object with an error key.
      • AIClientError is also raised when the stream ends before its final frame, and when an SSE response's content type is not text/event-stream.
      • The stream's reason reaches chat_messages_stream through a stream_finish_reason context variable, next to stream_served_by (src/devops_cli/ai/client/network.py:48-50). It is reset when each stream starts (unified.py:792).
      • When a stream fails after it has yielded at least one chunk, chat_messages_stream records its spend with finish reason error, and then re-raises.
      • A stream that fails before its first chunk records nothing, as a failed non-streamed call records nothing (unified.py:377-384). This covers connection errors, HTTP status errors, rejected credentials and an error frame that arrives first.
    • Tests.
      • Characterization tests feed each stream reader from an httpx2 MockTransport.
      • They replace every whole-line iter_lines stub: 12 references in tests/test_ai_streaming.py, tests/test_ai_client_providers_and_embeddings.py and tests/test_ai_spend_dispatch.py.
      • If the extractors change signature, the tests that call them with whole data: lines change with them: 68 references in tests/test_ai_streaming.py, tests/test_ai_client_providers_and_embeddings.py and tests/test_thinking_providers.py.
    • Docs.
      • docs/agent/tasks/task-599-finish-reasons-stream-completeness-and-truncation-markers-fo.md still says milestone v0.2.24, status Backlog and the old five-part scope. The delivering commit rewrites it to the delivered scope, with Milestone v0.2.25 and Status Done.
      • The ROADMAP entry (docs/ROADMAP.md:530-535) sits under the completed v0.2.23 section. The same commit rewrites it to match what ships.
  • Acceptance criteria:
    • Mapping. A table-driven unit test calls each non-streamed parser with these provider values and checks the expected result:

      • OpenAI-compatible: stop, length, tool_calls, function_call, content_filter, and an absent value;
      • Anthropic: end_turn, stop_sequence, max_tokens, model_context_window_exceeded, tool_use, refusal, pause_turn, and an absent value;
      • Ollama: stop, length, load, unload, and an absent value.

      A second test checks that every map value is either None or in typing.get_args(FinishReason). Both are verified with pytest and structural tuple assertions.

    • Conversion. Unit tests check both directions:

      • LLMResponse(..., finish_reason="length").to_model_response().finish_reason == "length";
      • from_model_response keeps the reason of a ModelResponse.
    • Spans. With a recording span:

      rg -n '\["stop"\]' src/devops_cli/ai/client finds nothing.

    • Cache. With a fake provider:

      • for each of length, content_filter and error, the reply is returned, _cache.set is not called, and a second identical call reaches the provider again;
      • stop and unknown replies are cached as before.
    • Ledger.

      • A new ledger has the finish_reason column.
      • A ledger created without it gains the column and keeps its rows.
      • track_request_spend(..., finish_reason="length") stores the reason, and an observer registered with observe_llm_calls receives it.
    • End to end.

      • LLMClient.chat runs inside observe_llm_calls, with a fake provider whose reply has finish_reason="length". The observer receives one call with finish_reason == "length", and the ledger row stores length.
      • direct_model_request_sync runs with model_request_sync patched to return a ModelResponse with finish_reason="length" and usage. The observer receives finish_reason == "length".
    • Profile. A profiler observes three calls: two stop and one length, all served by backend b1.

      • The stage reports finish_reasons == {"stop": 2, "length": 1} and truncated == {"b1": 1}.
      • ReviewProfile.load reads both fields back from profile.json.
      • With one length reply, the summary line from _write_review_profile says that one reply hit the cap. With none, the line is unchanged.
    • Streams. Each case is a MockTransport test that opens no socket.

      • OpenAI-compatible:
        • a chunk with finish_reason: "length" followed by [DONE] yields the full text, and the stream's reason is length;
        • a finish_reason chunk with no [DONE] completes;
        • [DONE] with no finish_reason before it completes, and the stream's reason is None;
        • a finish_reason: "stop" chunk, then a chunk with empty choices, then [DONE], completes with reason stop, and the transport's body generator is read to its end;
        • EOF with neither yields the earlier chunks and then raises AIClientError.
      • Anthropic:
        • message_delta with stop_reason: max_tokens, then message_stop and no [DONE], completes with reason length;
        • EOF before message_stop raises AIClientError;
        • event: error raises AIClientError, and its message contains the provider's message.
      • Ollama:
        • done: true, done_reason: "length" completes with reason length;
        • EOF in the middle of a line raises AIClientError;
        • a {"error": "..."} line raises AIClientError that contains that message.
      • Masking: an error frame whose message contains a GitHub-token-shaped string raises AIClientError whose message does not contain that string.
      • Reset: after a stream that ends with reason length, a second stream that ends with [DONE] alone leaves stream_finish_reason at None.
      • Splitting: for the SSE reader and for the NDJSON reader, a frame split mid-line and mid-code-point across chunks yields the same text as the unsplit frame. A delta that contains a raw U+2028 is yielded intact.
      • Size limits. The tests pass small limits, so they stay fast.
        • a single event, or an unterminated NDJSON line, over the per-event limit raises AIClientError;
        • a stream over the whole-stream limit raises AIClientError.
      • Incremental output: the first chunk reaches the caller before the transport has produced the last one. The test uses a generator body that records how far it has been read.
      • An SSE response with content type application/json raises AIClientError.
      • Ollama failover: two hosts are configured, and the stream fails after output has been yielded. It raises AIClientError, and the transport receives exactly one request.
      • rg -n iter_lines src/devops_cli/ai tests/test_ai_streaming.py tests/test_ai_client_providers_and_embeddings.py tests/test_ai_spend_dispatch.py finds nothing.
    • Stream spend.

      • A complete stream writes one ledger row with request_type stream and its reason.
      • A stream that fails after one chunk writes one row with reason error, and the error still reaches the caller.
      • A stream that fails before its first chunk writes no row and notifies no observer. It is checked twice: with a transport that raises httpx2.ConnectError, and with an HTTP 500 response.
    • Chat. _stream_interactive_chat_turn runs with a fake client whose stream raises AIClientError after one chunk. The error propagates and no assistant entry is added to memory.

    • Gate.

      • uv run devops ci passes.
      • uv run pytest <the new and changed test files> --durations=0 shows the new tests together take under 1 s.
      • tests/test_agent_task_files.py passes with the rewritten task file.
    • Manual check (a person runs it).

      • On the homelab gateway, run:
        DEVOPS_CLI_AI__MAX_TOKENS=64 uv run python -c "
        from devops_cli.ai.client import LLMClient
        from devops_cli.ai.client.network import stream_finish_reason
        from devops_cli.config.settings import get_ai_api_key, load_settings
        s = load_settings(); c = LLMClient(s.ai.for_task('chat'), api_key=get_ai_api_key(s))
        print(c.chat('Be brief.', 'Count from 1 to 500.', use_cache=False, enable_thinking=False).finish_reason)
        ''.join(c.chat_stream('Be brief.', 'Count from 1 to 500.', enable_thinking=False)); print(stream_finish_reason.get())
        "
        
        It prints length twice.
      • With a direct Ollama URL, run the same command without the chat_stream line. It prints length. The stream line is left out there, because Ollama streams do not send the reply cap yet (see Related).
      • Then, on the gateway, run DEVOPS_CLI_AI__MAX_TOKENS=256 uv run devops ai review benchmark src/devops_cli/ai/client/streaming.py --runs 1 --persona architect. In the profile.json whose path it prints, jq '.stages[] | {name, finish_reasons, truncated}' shows length counts.
  • Key questions:
    • httpx-sse, or httpx2's own EventSource? httpx2.EventSource (proposed).

      • The pinned httpx2 2.13.0 ships it (httpx2/_sse.py). It is derived from httpx-sse, typed for httpx2.Response, and limits the size of each event.
      • httpx-sse is locked only through mcp (uv.lock:1718-1725), and it is typed for httpx.Response, so using it would need a cast.
      • No new dependency is added.
    • How does a stream's reason reach the caller? Through a stream_finish_reason context variable (proposed). This follows the stream_served_by precedent (network.py:48-50).

      • chat_messages_stream iterates the provider generator with a for loop, and the optional sanitizer wraps it, so a generator's return value would be lost.
    • Does [DONE] alone complete an OpenAI-compatible stream? Yes, with reason unknown (proposed).

      • [DONE] is the server's own end marker, not an early EOF.
      • Requiring a finish_reason as well would turn a server that omits it into errors.
      • The profile counts such replies as unknown, so a gateway that drops reasons still shows up.
      • Anthropic never sends [DONE], so it is never required.
    • Does the OpenAI-compatible reader stop at the finish_reason chunk? No (proposed). It reads on to [DONE] or EOF. With stream_options.include_usage, the usage chunk comes after the finish_reason chunk, and feat(cli): reasoning-token share in the spend ledger and provider-reported stream usage #591 reads it.

    • What does an unknown reason look like? None on LLMResponse, no span attribute, NULL in the ledger and unknown in the profile (proposed). Truncation is never guessed.

    • Which replies are cached? Every reply except length, content_filter and error (proposed). Unknown replies stay cacheable, as today.

    • Does a length reply change retries? No (proposed). The validator and the retry loop (unified.py:599-612) are unchanged here. Re-chunking instead of an identical retry is the review split-off, which acts on the rate this item measures.

    • Is a failed stream's spend recorded? Only when the stream has yielded at least one chunk, with reason error (proposed).

      • Then the provider produced tokens.
      • A failure before the first chunk records nothing, which matches a failed non-streamed call (unified.py:377-384). Recording it would add ledger rows, observer calls and devops_cli_ai_requests_total counts for calls that no provider served.
    • Where do the mapping tables live? In config/constants.py (proposed), because AGENTS.md:24 requires matching tables there.

      • They copy the entries of pydantic-ai 2.35.0's private maps (pydantic_ai/models/openai.py:300-308, pydantic_ai/models/anthropic.py:99-108), including pause_turn → None and compaction → stop. They are not imported, because those names are private.
      • Ollama's stop and length map directly. load and unload become None.
    • Does an error frame fail over to the next Ollama host? No (proposed). The frame is the server's answer, not a transport fault. Only connection failures before any output fail over, as today (ollama.py:441-451).

    • What if an SSE response has another content type? It raises AIClientError naming the type (proposed). There is no fallback to line parsing.

    • How is the profile keyed by backend? By served_by, like backends (proposed). Direct Ollama calls have no served_by, so they count only in the stage's finish_reasons.

    • Does devops_cli_ai_requests_total get a finish-reason label? No (proposed). The span, ledger and profile are enough, and a new label would change the dashboards feat(cli): devops-cli dashboards chart the metrics the cli sends and the grafana sidecar provisions them #692 just fixed.

    • Are cut replies already in the cache purged? No (proposed). They expire within 7 days (defaults.py:121), and devops ai cache clear drops them at once.

    • Do Ollama streams get the reply cap here? No (proposed).

      • The stream payload sends no options (ollama.py:464-474), so it also lacks num_ctx, temperature and top_p.
      • Sending them changes what an Ollama stream generates, not how its end is read, so it is a separate split-off.
      • Until it lands, a direct Ollama stream ends at the model's own limit, and its reason is still read from done_reason.
    • Does devops ai chat need changes here? No (proposed). The reply is added to memory only after the stream ends (commands/ai.py:953), so a raised error stores nothing.

      The streamed chat turn has a separate defect, filed as a split-off: it never sends the user's message, and the loop's error handling (commands/ai.py:1106-1110) then removes the wrong entry.

    • Where does the ROADMAP entry go? If feat(github): github-sourced roadmap, migration and generated roadmap view (devops roadmap migrate, render) #739's generated roadmap view has landed, it follows that. Otherwise the entry moves to the v0.2.25 section (docs/ROADMAP.md:808) and is rewritten to match what ships (proposed).

  • Constraint:
    • Truncation comes only from the provider's reason. json-repair's log cannot stand in:

      • a trailing-comma repair logs 0 entries;
      • a complete payload that is missing an inner ] logs 3 entries, as a cut payload does.
    • Requiring [DONE] would break Anthropic.

    • The incompleteness error is always AIClientError, never an httpx2 transport exception. Otherwise the Ollama host loop (ollama.py:425-458) would replay the request on the next host after output had been yielded.

      httpx2.SSEError subclasses TransportError, so it is wrapped as well, as the reader already wraps transport errors (streaming.py:376-385).

    • Output keeps streaming: chunks are yielded as they arrive, each event is size-limited and so is the whole stream.

    • No new dependency. If _consume_streaming_lines or the extractors are renamed, their re-exports in src/devops_cli/ai/client/init.py (:30-34, :54-58) are renamed or removed with them, with no alias left behind.

    • Tests open no socket and touch no network or cluster. The new tests add at most 1 s to the gate. They use structural tuple assertions, and complexity stays at 10 or below.

Strategic Alignment

Activity

  1. added this to the v0.2.23 milestone on Sep 25, 2026
  2. added
    type/feature
    scope/ai
    priority/p1-high
    on Sep 25, 2026
  3. modified the milestones: v0.2.23, v0.2.24 on Sep 28, 2026
  4. modified the milestones: v0.2.23, v0.2.25 on Oct 1, 2026
  5. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    Retargeted from the shipped v0.2.23 to v0.2.25. It is still valid (checked 2026-10-01), and a P1 left open in a shipped release keeps precedence over P1 work committed later.

  6. changed the title [-]feat(ai): finish reasons, stream completeness and truncation markers for model replies[/-] [+]feat(ai): finish reasons and stream completeness for model replies[/+] on Oct 1, 2026
  7. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    More evidence for this issue from the devsecops review session 20261001-224227 (2026-10-02). Each finding below was triaged against release/v0.2.25 (c279c18), judged real and covered by this issue, and then upheld by a second agent that tried to refute it.

    • Potential Resource Exhaustion via Unbounded HTTP Stream Processing (src/devops_cli/ai/client/streaming.py:330, re-rated LOW): The mechanism the finding describes is wrong. _read_response_lines adds every line into current_bytes (streaming.py:331-333), so many small lines do reach the max_bytes cap, and a line-count limit adds nothing. A real gap exists in the same loop. The cap is checked only after httpx2's LineDecoder (httpx2/_decoders.py:418-421) has assembled a whole line, and it buffers an unterminated line without limit. Line terminators and blank lines also count as 0 bytes. So a hostile or MITM'd endpoint (for example plain-HTTP Ollama on the LAN) can grow memory past MAX_STREAM_BYTES before any …
  8. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Closed by #966, merged into release/v0.2.25.

    GitHub only acts on closing keywords when a pull request merges into the default branch, so this was closed by devops gh issues close-merged.

  9. added a commit that references this issue on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/aitype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions