From c2c7c56d63d3aa74fa7d847e17d191d3da47fa48 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 2 Oct 2026 15:19:36 +0000 Subject: [PATCH] feat(ai): finish reasons and stream completeness for model replies (#599) --- changelog.d/599.md | 23 + docs/SELF_IMPROVEMENT.md | 5 + docs/TELEMETRY.md | 2 +- ...-completeness-and-truncation-markers-fo.md | 88 ++- src/devops_cli/ai/client/__init__.py | 10 - src/devops_cli/ai/client/claude.py | 16 +- src/devops_cli/ai/client/models.py | 25 +- src/devops_cli/ai/client/network.py | 11 +- src/devops_cli/ai/client/ollama.py | 18 +- src/devops_cli/ai/client/openai.py | 14 +- src/devops_cli/ai/client/streaming.py | 419 ++++++++---- src/devops_cli/ai/client/unified.py | 94 ++- src/devops_cli/ai/direct.py | 2 + src/devops_cli/ai/review/profile.py | 37 +- src/devops_cli/ai/review/runner.py | 4 +- src/devops_cli/ai/spend/ledger.py | 57 +- src/devops_cli/ai/spend/models.py | 3 + src/devops_cli/config/constants.py | 43 +- src/devops_cli/config/defaults.py | 3 + src/devops_cli/docs/generator.py | 9 +- tests/llm_stream_fakes.py | 102 +++ tests/test_ai_client_finish_reasons.py | 170 +++++ ...test_ai_client_providers_and_embeddings.py | 327 ++++----- tests/test_ai_client_telemetry.py | 56 ++ tests/test_ai_cmd.py | 21 + tests/test_ai_served_by.py | 5 +- tests/test_ai_spend_dispatch.py | 197 +++++- tests/test_ai_spend_ledger.py | 85 ++- tests/test_ai_streaming.py | 629 ++++++++++++------ tests/test_review_profile.py | 60 ++ tests/test_thinking_providers.py | 23 +- 31 files changed, 1869 insertions(+), 689 deletions(-) create mode 100644 changelog.d/599.md create mode 100644 tests/llm_stream_fakes.py create mode 100644 tests/test_ai_client_finish_reasons.py diff --git a/changelog.d/599.md b/changelog.d/599.md new file mode 100644 index 0000000000..69dc19aaf6 --- /dev/null +++ b/changelog.d/599.md @@ -0,0 +1,23 @@ +### Added +- **Every Model Reply Carries the Reason It Ended (`devops_cli.ai.client`, `devops_cli.ai.direct`)**: + - `LLMResponse.finish_reason` holds pydantic-ai's `FinishReason` (`stop`, `length`, `content_filter`, `tool_call` or `error`), read from the OpenAI-compatible `finish_reason`, Anthropic's `stop_reason` and Ollama's `done_reason` through three tables in `config/constants.py`. `max_tokens` and `model_context_window_exceeded` become `length`. An absent or unmapped value is `None`, meaning unknown, so truncation is never guessed. `to_model_response` passes the reason on and `from_model_response` reads it (#599). + - `ai.llm.dispatch` and `ai.llm.stream` set `gen_ai.response.finish_reasons` to the provider's reason, and leave it out when the reason is unknown (#599). +- **The Spend Ledger and Review Profiles Count Why Replies Ended (`devops_cli.ai.spend`, `devops review`)**: + - The spend ledger gains a `finish_reason` column. A ledger created before it gains the column in place and keeps its rows. Chat dispatches, streams and the pydantic-ai direct calls record the reason, and observers registered with `observe_llm_calls` receive it with each call (#599). + - Each stage in a review's `profile.json` counts its replies by reason (`finish_reasons`, with `unknown` when the provider gave none) and the replies cut at their token cap by serving backend (`truncated`). When any reply hit the cap, the profile's summary line says how many (#599). + +### Changed +- **A Stream Ends Only on Its Provider's Final Frame (`devops ai chat`, `devops_cli.ai.client`)**: + - OpenAI-compatible and Anthropic streams are read with httpx2's `EventSource`, which splits lines on CR and LF alone, and Ollama streams are split on LF from the raw bytes. A delta holding a raw U+2028, which the old line reader split in two and dropped, now arrives intact. Each event, and each unterminated Ollama line, is limited to 1 MiB (`DEFAULT_AI_STREAM_MAX_EVENT_BYTES`), and the whole stream is still limited to 50 MiB. Chunks are still yielded as they arrive (#599). + - A stream is complete on a chunk with a finish reason or `[DONE]` (OpenAI-compatible), `message_stop` (Anthropic) or `done: true` (Ollama). A stream that ends before that, an error frame, and an event stream sent with another content type raise `AIClientError`, where each used to return its partial text as a whole reply. An error frame's message is masked and cut to 256 characters. A stream cut after it yielded output is not replayed on the next Ollama host (#599). + - A stream that fails after yielding output records its spend with finish reason `error`, then re-raises. One that fails before its first chunk records nothing, as a failed non-streamed call records nothing (#599). + +### Fixed +- **Cut Replies Are No Longer Cached (`devops_cli.ai.client`)**: + - A reply that ended at its token cap (`length`), was filtered (`content_filter`) or failed (`error`) is returned but not stored in the response cache, so the next identical call reaches the provider instead of the cut reply for 7 days. Replies cached before this change expire as before, or go at once with `devops ai cache clear` (#599). +- **The Dispatch Span No Longer Says Every Reply Stopped (`devops_cli.ai.client`)**: + - `gen_ai.response.finish_reasons` was hard-coded to `["stop"]` on every `ai.llm.dispatch` span (#599). + +### Removed +- **Line-Based Stream Helpers (`devops_cli.ai.client`)**: + - `_consume_streaming_lines`, `_read_response_lines`, `_extract_claude_stream_chunk`, `_extract_openai_stream_chunk`, `_extract_ollama_stream_chunk`, `_extract_ollama_stream_tuple` and `_extract_stream_chunk` are replaced by `_read_event_stream`, `_read_ndjson_stream` and one frame parser per provider in `devops_cli.ai.client.streaming`. The five that `devops_cli.ai.client` re-exported are removed from it, with no alias (#599). diff --git a/docs/SELF_IMPROVEMENT.md b/docs/SELF_IMPROVEMENT.md index a5f7074b89..f74f26626e 100644 --- a/docs/SELF_IMPROVEMENT.md +++ b/docs/SELF_IMPROVEMENT.md @@ -385,6 +385,11 @@ tokens made during each stage, the backends the gateway routed them to, and the verified and reported finding counts. The profile's session ID is an attribute of the session's `review.session` span, so a slow stage can be followed into its trace. +Each stage also counts its replies by the reason the provider gave for their end +(`finish_reasons`, with `unknown` when it gave none), and the replies cut at their token cap by +the backend that served them (`truncated`). When any reply hit the cap, the profile's summary line +says how many. + A single review is not a measurement: identical runs produce different numbers of candidate findings, and verification time follows them. `devops review benchmark -n 3` reviews the same files several times with the response cache bypassed and saves the medians under diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 41ef0969e0..b747015f55 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -44,7 +44,7 @@ points devops-cli at the cluster's collector. LLM spans follow the OpenTelemetry GenAI semantic conventions, which live in `open-telemetry/semantic-conventions-genai` and have no tagged release. `src/devops_cli/telemetry/semconv_genai.json` pins them to commit `b31e9e8ea26ac1c086d3313d474e31d7c3f391ae`, resolved with weaver 0.26.1, and lists their current attribute keys, metric names and span types. -- **Inference spans**: `ai.llm.dispatch` and `ai.llm.stream` are CLIENT spans of the `gen_ai.inference.client` type. Both carry `gen_ai.operation.name` (`chat`), `gen_ai.provider.name` (`anthropic` for the `claude` provider, other provider ids unchanged) and `gen_ai.request.model`, plus `server.address` and `server.port` when one backend host served the request. Only `ai.llm.dispatch` carries the reply's usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), `gen_ai.response.model` and `gen_ai.response.finish_reasons`. `ai.llm.stream` carries `gen_ai.request.stream` and `gen_ai.response.time_to_first_chunk` in seconds. +- **Inference spans**: `ai.llm.dispatch` and `ai.llm.stream` are CLIENT spans of the `gen_ai.inference.client` type. Both carry `gen_ai.operation.name` (`chat`), `gen_ai.provider.name` (`anthropic` for the `claude` provider, other provider ids unchanged) and `gen_ai.request.model`, plus `server.address` and `server.port` when one backend host served the request. Only `ai.llm.dispatch` carries the reply's usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and `gen_ai.response.model`. `ai.llm.stream` carries `gen_ai.request.stream` and `gen_ai.response.time_to_first_chunk` in seconds. Both carry `gen_ai.response.finish_reasons` with the reason the provider gave for the reply's end (`stop`, `length`, `content_filter` or `tool_call`), and leave it out when the provider gave none. - **Wrapper spans**: `ai.llm.chat`, `ai.client.chat_structured` and `pydantic_ai.direct.*` are INTERNAL and set no operation, usage or response keys, so each request is counted once. - **Private keys**: Anything the conventions do not define is written under `llm.*`, such as `llm.request.priority`, `llm.tokens_per_second` and `llm.usage.cost_usd`, never under `gen_ai.*`. - **Check**: `tests/test_telemetry_semconv.py` reads every Python file under `src/devops_cli/`, comments and docstrings included. It fails on a quoted string starting with `gen_ai.` that is not a current attribute key or metric name in the snapshot, and on any f-string that builds one. diff --git a/docs/agent/tasks/task-599-finish-reasons-stream-completeness-and-truncation-markers-fo.md b/docs/agent/tasks/task-599-finish-reasons-stream-completeness-and-truncation-markers-fo.md index 458f59b38c..08c712e460 100644 --- a/docs/agent/tasks/task-599-finish-reasons-stream-completeness-and-truncation-markers-fo.md +++ b/docs/agent/tasks/task-599-finish-reasons-stream-completeness-and-truncation-markers-fo.md @@ -1,23 +1,69 @@ -# Task 599: Finish Reasons, Stream Completeness and Truncation Markers for Model Replies +# Task: Finish Reasons and Stream Completeness for Model Replies (#599) **Issue**: [#599](https://github.com/dan-petty/devops-cli/issues/599) -**Status**: Backlog -**Milestone**: `v0.2.24` -**Priority**: `priority/p1-high` -**Scope**: `type/feature`, `scope/ai`, `priority/p1-high` - ---- - -## 1. Description & Objectives - -No provider reads a finish reason, and the span hardcodes `gen_ai.response.finish_reasons` to `["stop"]` (`ai/client/unified.py:91`). A persona-review reply cut at its cap (`ai/review/runner.py:713`) is silently repaired, keeps its partial last finding, passes the validator and is cached (`unified.py:579`); failed validation resends the identical prompt (`unified.py:605-609`). Streaming: every provider reads `iter_lines()` (`ai/client/streaming.py:330`), the Ollama extractor never reports done (`:306-308`) and the Claude extractor handles only `content_block_delta` (`:269`). An early EOF or error frame is stored by `devops ai chat` (`commands/ai.py:954`) and billed as complete (`unified.py:816`). Repair enters through three functions (`ai/response_repair.py:51`, `ai/client/structured.py:57`, `core/serialization.py:23`); only `chat_structured`, which nothing calls, counts repairs (`structured.py:197,255`). vibes observation 15 shows retrying into the same token ceiling fails; vibes' RESP decoder returns `(None, 0)` until a whole frame arrives, tested over a frame-splitting socket. - -#### Key Deliverables: -- Context & Rationale*: No provider reads a finish reason, and the span hardcodes `gen_ai.response.finish_reasons` to `["stop"]` (`ai/client/unified.py:91`). A persona-review reply cut at its cap (`ai/review/runner.py:713`) is silently repaired, keeps its partial last finding, passes the validator and is cached (`unified.py:579`); failed validation resends the identical prompt (`unified.py:605-609`). Streaming: every provider reads `iter_lines()` (`ai/client/streaming.py:330`), the Ollama extractor never reports done (`:306-308`) and the Claude extractor handles only `content_block_delta` (`:269`). An early EOF or error frame is stored by `devops ai chat` (`commands/ai.py:954`) and billed as complete (`unified.py:816`). Repair enters through three functions (`ai/response_repair.py:51`, `ai/client/structured.py:57`, `core/serialization.py:23`); only `chat_structured`, which nothing calls, counts repairs (`structured.py:197,255`). vibes observation 15 shows retrying into the same token ceiling fails; vibes' RESP decoder returns `(None, 0)` until a whole frame arrives, tested over a frame-splitting socket. -- Deliverable*: (1) Byte-level characterization tests feeding `_consume_streaming_lines` from an httpx2 `MockTransport`: mid-line and mid-codepoint splits, raw U+2028 deltas, EOF without a terminal frame or mid-line, Ollama and Anthropic error frames, replacing whole-line `iter_lines` stubs. (2) Type `LLMResponse.finish_reason` as pydantic-ai `FinishReason` through `to_model_response`, mapping OpenAI `finish_reason`, Ollama `done_reason` and Anthropic `stop_reason` (`max_tokens` becomes `length`). Emit it on the chat and `gen_ai.stream` spans, never cache `length`, record it per spend-ledger row beside the backend (#474), and report truncation rate per stage and backend in `profile.json` (#473). (3) Read SSE with httpx-sse `EventSource`, pinned directly (already locked via `mcp`); split Ollama NDJSON from `iter_bytes()` on `\n` only. A stream completes only on `finish_reason`, `message_stop` or `done: true`; otherwise raise `AIClientError` with the provider message, which the chat loop already drops (`commands/ai.py:1106-1110`). (4) One `repair_json` seam over `json_repair.loads` returning `repaired`, counted per caller except `security/tflint.py:189`; with Lossless Structured Error Reflection, wire in or delete `chat_structured`. (5) Only if (2) shows a non-zero rate: pipeline-set `ReviewResult.truncated`, trailing-record drop on `length`, and re-chunking instead of identical retry. Budget sizing stays with #479. -- Constraint*: Truncation comes only from the provider reason; record unknown when absent. json-repair's log cannot stand in: a complete payload missing an inner `]` logs like a cut one. Read the reason before `str(res_obj)` (`runner.py:719`) drops it. Never drop a record for empty fields. Requiring `[DONE]` breaks Anthropic. The incompleteness error must not be an httpx2 transport exception, or the Ollama host loop (`ai/client/ollama.py:440-452`) would replay it on the next host mid-output. Keep yielding incrementally, enforcing `MAX_STREAM_BYTES` per event. -- Measured*: `.venv/bin/python probe/truncation_probe.py`: a review cut inside its final finding parsed to 5 findings, the last with description "de", and no truncation field. `.venv/bin/python probe/value_lens_log_fp_probe.py`: a trailing-comma repair logs 0 entries. `.venv/bin/python probe/split_frames.py`: all 4 early-end cases (no `[DONE]`, EOF mid-NDJSON line, Ollama and Anthropic error frames) return partial text without an exception. `grep -rn "\.chat_structured(" src | wc -l`: 0. -- Source*: vibes `observations/devops-cli/15-llm-structured-output-repair-and-schema-reconciliation.md`, vibes `examples/valkey-l2-repomap-cache/repomap_cache.py`, vibes `examples/valkey-l2-repomap-cache/test_repomap_cache.py` -- Unit and integration test coverage with structural tuple equality assertions. -- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$. -- 100% passing across Gated CI validation suite (`uv run devops ci`). +**Status**: Done +**Milestone**: v0.2.25 +**Priority**: priority/p1-high +**Scope**: scope/ai + +## Description +No provider client read why a model stopped. The non-streamed parsers ignored `finish_reason`, `stop_reason` and `done_reason`, `LLMResponse` had no field for the reason, and the dispatch span hard-coded `gen_ai.response.finish_reasons` to `["stop"]`. A persona reply cut at its 8,192-token cap was repaired by json-repair, passed the validator and was cached for 7 days, and neither the spend ledger nor `profile.json` could say how often that happened. Every stream read `response.iter_lines()`, whose decoder splits on U+2028, so a delta holding a raw U+2028 was cut in two and dropped. The Ollama extractor never reported done, and the Claude extractor stopped on `[DONE]`, which Anthropic never sends. An OpenAI stream with no end marker, an Ollama stream cut mid-line, an Ollama error line and an Anthropic `event: error` each returned their partial text as a whole reply, and `chat_messages_stream` billed them as complete. + +Every reply now carries the reason it ended, and a stream ends only on its provider's final frame. + +- **Finish reason** (`ai/client/models.py`, `config/constants.py`): `LLMResponse.finish_reason` is pydantic-ai 2.35.0's `FinishReason`. `CONST_OPENAI_FINISH_REASONS`, `CONST_ANTHROPIC_STOP_REASONS` and `CONST_OLLAMA_DONE_REASONS` copy pydantic-ai's private OpenAI and Anthropic maps, including `pause_turn` to `None` and `compaction` to `stop`; Ollama's `stop` and `length` map directly and `load` and `unload` to `None`. `provider_finish_reason(table, value)` returns `None` for an absent, unmapped or non-string value. `_parse_compat_response`, `_claude_messages` and `_ollama_request` fill the field, `to_model_response` passes it to `ModelResponse.finish_reason`, and `from_model_response` reads it back. +- **Spans** (`ai/client/unified.py`): `_set_finish_reason_attribute` sets `gen_ai.response.finish_reasons` to `[reason]`, or nothing when the reason is unknown, on `ai.llm.dispatch` (from `_set_response_span_attributes`) and on `ai.llm.stream` (from `chat_messages_stream`). `ai.llm.chat` never carries it. The `["stop"]` literal is gone, and the event payload moved to `_response_event_payload`, so `_set_response_span_attributes` is no longer over the complexity cap. +- **Ledger** (`ai/spend/ledger.py`, `ai/spend/models.py`): the table gains `finish_reason TEXT`. Older ledgers gain it in place through `_ADDED_COLUMNS`, which now drives `served_by`, `stage` and `finish_reason` through one `_add_column`. `record_request`, `SpendRecord` and `track_request_spend` take `finish_reason`, and the call dict observers receive carries it. `_record_response_telemetry_and_spend` passes `res.finish_reason`, `_record_stream_spend` the stream's reason, and both pydantic-ai direct calls `resp.finish_reason`. +- **Profile** (`ai/review/profile.py`, `ai/review/runner.py`): `StageProfile.finish_reasons` counts a stage's replies by reason, `unknown` for `None`, and `StageProfile.truncated` counts `length` replies by `served_by`, keyed like `backends`. Cached calls stay counted apart and are in neither. `ReviewProfile.truncated_replies` sums the stages' `length` replies, and `_write_review_profile` adds `, N hit the reply cap` to its summary line when N is not zero. +- **Cache**: `_handle_successful_chat_dispatch` stores no reply whose reason is in `CONST_UNCACHED_FINISH_REASONS` (`length`, `content_filter`, `error`) and still returns it. Validation and retries are unchanged. +- **Stream framing** (`ai/client/streaming.py`): `_read_event_stream` reads OpenAI-compatible and Anthropic streams with `httpx2.EventSource(response, max_event_size=...)`, and `_read_ndjson_stream` reads Ollama's `iter_bytes()`, splits on `\n` only and decodes each whole line as UTF-8, refusing an unterminated line past its limit. Both limits default to `DEFAULT_AI_STREAM_MAX_EVENT_BYTES` (1 MiB, httpx2's `DEFAULT_MAX_EVENT_SIZE_BYTES`). Both feed `_read_frames`, which counts each frame towards `MAX_STREAM_BYTES` before parsing it and yields each chunk as it arrives. One `StreamFrame` parser per provider (`_openai_stream_frame`, `_claude_stream_frame`, `_ollama_stream_frame`) says what a frame carries: text, whether the stream is complete, whether reading stops, the reason, or the provider's error. +- **Completeness**: OpenAI-compatible streams are complete on a chunk with a non-null `finish_reason` or on `[DONE]`; reading goes on after the reason to `[DONE]` or EOF, so a usage chunk after it is read (#591). Anthropic streams are complete on `message_stop`, with the reason from `message_delta`; `[DONE]` is not an end. Ollama streams are complete on `done: true`, with the reason from `done_reason`. An Ollama `{"error": ...}` line, an Anthropic `error` event and an OpenAI-compatible `data:` object with an `error` raise `AIClientError` with the provider's message, masked with `mask_secrets` and then cut to 256 characters. A stream that ends before its final frame raises `AIClientError`, and so does an event stream whose content type is not `text/event-stream`, naming the type. `_read_failures` raises httpx2's `SSEError` and every other `RequestError` as `AIClientError`: a `TransportError` or a `DecodingError` escaping mid-output would be replayed on the next host by the Ollama loop, which catches both. +- **Stream reason and spend**: `_read_frames` sets `network.stream_finish_reason` once the stream is complete, and `chat_messages_stream` resets it beside `stream_served_by` as each stream starts. A stream that fails after yielding a chunk records its spend with reason `error` and re-raises. One that fails before its first chunk (connection error, HTTP status error, rejected credentials or an error frame first) records nothing. +- **Removed**: `_consume_streaming_lines`, `_read_response_lines`, `_extract_claude_stream_chunk`, `_extract_openai_stream_chunk`, `_extract_ollama_stream_chunk`, `_extract_ollama_stream_tuple` and the unused `_extract_stream_chunk`, with their re-exports from `devops_cli.ai.client`. No alias is left. +- **Tests**: every whole-line `iter_lines` stub in `tests/test_ai_streaming.py`, `tests/test_ai_client_providers_and_embeddings.py` and `tests/test_ai_spend_dispatch.py` is replaced by an httpx2 `MockTransport`, through `tests/llm_stream_fakes.py` (canned SSE and NDJSON frames, a body that records how far it was read, and `route_client`, which sends an `LLMClient`'s requests to a handler), as `tests/web_fakes.py` does for web pages. The tests that called the extractors with whole `data:` lines, there and in `tests/test_thinking_providers.py`, call the frame parsers with `httpx2.ServerSentEvent`s or NDJSON lines. `tests/test_ai_served_by.py`'s streamed gateway reply gains `content-type: text/event-stream`. +- **Docs**: `DocGenerator._llm_span_attribute_lines` says both inference spans carry the finish reason, and `docs/TELEMETRY.md` is regenerated. `docs/SELF_IMPROVEMENT.md` describes the profile's new counts. The changelog entry is `changelog.d/599.md`. +- Out of scope, as the issue decided: acting on cut persona replies (#876), one JSON repair seam (#875), streamed `devops ai chat` turns that send the user's message (#874), Ollama streams that send the configured options (the issue's fourth split-off), a finish-reason label on `devops_cli_ai_requests_total`, and purging cut replies already cached, which expire within 7 days or go with `devops ai cache clear`. + +## Acceptance Criteria +- [x] **Mapping.** `test_each_parser_reads_its_providers_stop_value[openai|anthropic|ollama]` (`tests/test_ai_client_finish_reasons.py`) sends each value the issue lists, and a reply without the field, through `_openai_compat_messages`, `_claude_messages` and `_ollama_request` over a `MockTransport`, and asserts the list of `(value, reason)` tuples equals the table: OpenAI `stop`, `length`, `tool_calls`, `function_call`, `content_filter` and absent; Anthropic `end_turn`, `stop_sequence`, `max_tokens`, `model_context_window_exceeded`, `tool_use`, `refusal`, `pause_turn` and absent; Ollama `stop`, `length`, `load`, `unload` and absent. `test_every_mapped_reason_is_a_pydantic_ai_finish_reason` finds no map value, and no `CONST_UNCACHED_FINISH_REASONS` member, outside `typing.get_args(FinishReason)` and `None`. +- [x] **Conversion.** `test_the_reason_survives_conversion_both_ways` asserts `("length", "content_filter", None)`: `LLMResponse(..., finish_reason="length").to_model_response()`, `from_model_response` of a `content_filter` `ModelResponse`, and a reply without a reason. +- [x] **Spans.** `test_the_dispatch_span_names_the_reason_the_reply_ended[length-expected0]` (`tests/test_ai_client_telemetry.py`) captures the OTLP payload and finds `["length"]` on `ai.llm.dispatch` and no `gen_ai.response.finish_reasons` on `ai.llm.chat`; `[None-None]` finds the key on neither. `test_a_complete_stream_names_the_reason_on_the_stream_span` streams an OpenAI-compatible reply ending `finish_reason: "length"`, `[DONE]` and finds `["length"]` on `ai.llm.stream`. `rg -n '\["stop"\]' src/devops_cli/ai/client` prints nothing (exit 1). +- [x] **Cache.** `test_only_replies_that_ended_normally_are_cached[length-False|content_filter-False|error-False]` call `chat` twice with a fake provider: the reply is returned with its reason, `client.cache.set` is never called and the provider is called twice. `[stop-True]` and `[None-True]` store one entry, call the provider once and serve the second call from the cache. +- [x] **Ledger.** `test_a_ledger_records_each_replys_finish_reason` (`tests/test_ai_spend_ledger.py`) finds the `finish_reason` column in a new ledger, and `track_request_spend(..., finish_reason="length")` returns a record with `length`, writes `length` to the row and hands `length` to an `observe_llm_calls` observer. `test_an_existing_ledger_gains_the_finish_reason_column` creates the table without the column with one row, opens it with `SpendLedger` and records a `stop` reply: the rows read `[("qwen", None), ("llama3:8b", "stop")]`. `test_spend_ledger_init_db_duplicate_column_tolerance` also checks `finish_reason` after a second `_init_db`. +- [x] **End to end.** `test_a_chat_reply_reaches_observers_and_the_ledger_with_its_finish_reason` (`tests/test_ai_spend_dispatch.py`) runs `LLMClient.chat` inside `observe_llm_calls` with a fake Ollama reply whose reason is `length`: the observer sees `["length"]` and the ledger holds `[("chat_dispatch", "length")]`. `test_a_direct_request_hands_its_finish_reason_to_observers` patches `model_request_sync` and `model_request` to return a `ModelResponse` with `finish_reason="length"` and usage, runs `direct_model_request_sync` and `direct_model_request`, and the observer sees `[("direct_sync", "length"), ("direct_async", "length")]`. +- [x] **Profile.** `test_profile_counts_replies_by_finish_reason_and_cut_replies_by_backend` (`tests/test_review_profile.py`) shows the profiler two `stop` replies and one `length` reply from backend `b1`, and one reply without a reason or backend in another stage. `ReviewProfile.load` reads back `("persona_review", {"stop": 2, "length": 1}, {"b1": 1})` and `("verification", {"unknown": 1}, {})`. `test_the_profile_summary_says_how_many_replies_hit_the_cap[one-cut]` captures `_write_review_profile`'s line as `... 2 LLM calls, 1 hit the reply cap; persona_review ...`, and `[none-cut]` as `... 1 LLM calls; persona_review ...`, the line as before. +- [x] **Streams.** Each runs over a `MockTransport` in `tests/test_ai_streaming.py`; no socket is opened. `test_a_stream_is_complete_only_at_its_final_frame` asserts the yielded text, the stream's reason and the error for 12 cases: `openai-length-then-done` (`["Hel", "lo"]`, `length`), `openai-reason-then-eof` (`stop`), `openai-done-alone` (reason `None`), `openai-eof-without-either` (the chunks, then "Provider stream ended before its final frame."), `anthropic-max-tokens-then-message-stop` (`length`, no `[DONE]`), `anthropic-eof-before-message-stop`, `anthropic-error-event` ("... reported an error: Overloaded"), `ollama-done-length` (`length`), `ollama-eof-mid-line`, `ollama-error-line` (the provider's message), `openai-error-object` and `ollama-line-not-utf8` ("Provider stream line is not UTF-8: ..."). `test_reading_goes_on_past_the_finish_reason_to_done` sends a `stop` chunk, a usage chunk with empty `choices` and `[DONE]`: reason `stop`, and the body was read through all 4 frames. `test_reading_stops_at_the_final_frame[openai-done|anthropic-message-stop|ollama-done]` sends one more text frame after `[DONE]`, `message_stop` or `done: true`: it is neither read nor yielded. +- [x] **Masking.** `test_an_error_frame_is_masked_and_cut[openai|ollama]` puts `"ghp_" + "A" * 36` and 400 more characters in an error frame: the raised message starts with the provider's text, holds no token and is exactly the prefix plus 256 characters. +- [x] **Reset.** `test_each_stream_starts_with_no_finish_reason` streams through `chat_messages_stream` four times: a `length` stream, a stream cut before its final frame (it raises), a `length` stream and a `[DONE]`-only stream. `stream_finish_reason` reads `["length", None, "length", None]`; the cut stream's `None` comes only from the reset when the stream starts. +- [x] **Splitting.** `test_a_frame_split_across_chunks_reads_as_whole[openai|ollama]` sends `"naïve € \u2028 end"`, with the raw U+2028 bytes in the body, whole and then one byte per chunk, which splits every line and every multi-byte code point. Both give `(["naïve € \u2028 end"], "stop", None)`. +- [x] **Size limits.** `test_an_oversized_event_or_line_is_refused` gives a 64-byte limit: a 200-character SSE event raises "Server-sent event exceeded the 64 byte limit.", an NDJSON line that never ends raises "Provider stream line exceeded the 64 bytes limit." before the body is read to its end, and so does a whole 200-character NDJSON line that arrives in one chunk. `test_a_stream_past_its_size_limit_is_refused[openai|ollama]` gives a 200-byte stream limit and raises "Provider response exceeded maximum stream size (200 bytes)." before the tenth frame. +- [x] **Incremental output.** `test_chunks_reach_the_caller_as_they_arrive[openai|ollama]` takes the first chunk when the recording body has produced 1 of its 3 frames. +- [x] **Content type.** `test_an_event_stream_of_another_content_type_is_refused` sends an SSE body as `application/json` and raises "Provider stream could not be read: Expected response with content type 'text/event-stream', got 'application/json'." +- [x] **Ollama failover.** `test_an_ollama_stream_failing_after_output_is_not_replayed_on_another_host` configures two hosts and a body that yields one line and raises `httpx2.ReadError`: `AIClientError` ("connection terminated unexpectedly"), chunks `["Hi"]`, and the transport received one request. +- [x] **No line reader.** `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` prints nothing (exit 1). +- [x] **Stream spend.** `test_a_complete_stream_records_its_finish_reason` writes `[("stream", "length")]` and the observer sees `length`. `test_a_stream_failing_after_output_records_its_spend_as_an_error` yields `["Hel"]`, raises `AIClientError` to the caller and writes `[("stream", "error")]`. `test_a_stream_failing_before_its_first_chunk_records_nothing[connect|http-500]` (a transport raising `httpx2.ConnectError`, and an HTTP 500) raises `AIClientError`, writes no row and notifies no observer. +- [x] **Chat.** `test_a_cut_stream_stores_no_reply_in_chat_memory` (`tests/test_ai_cmd.py`) runs `_stream_interactive_chat_turn` with a client whose stream yields one chunk and raises `AIClientError`: the error propagates and memory holds only the user entry. +- [x] **Gate, the parts run here.** `uv run ruff check src tests` and `uv run ruff format --check src tests` pass, and `uv run mypy --strict` passes on the touched source modules (18 files, with the rest of `ai/client`). `uv run devops docs check` prints "All documentation files are up to date." after `uv run devops docs generate --sync-readme`, which changed only `docs/TELEMETRY.md`. The complexity scan (`run_complexity_scan`, cap 10, depth 5) reports no new function over either cap in the touched files. `uv run pytest -p no:cacheprovider -q -n 6 tests`: 7028 passed, 8 xfailed after the review's added tests, with `tests/test_agent_task_files.py` passing on this file. +- Pending a person: the speed criterion as the issue words it. `uv run pytest --durations=0` runs with pyproject's `-n logical`, and there the new and rewritten tests sum to 2.13 s, over the 1 s budget: 16 workers contend for the cores, and 0.97 s of the 2.13 s is the conftest setup every test pays. The same tests sum to 0.61 s when the touched files run serially and 0.92 s in the full suite (`-n 6`), and each one is under 0.25 s in every run. The figures are in Measurements. +- Pending a person: `uv run devops ci` on the delivering commit, and the pull request's own checks. +- Pending a person, on the homelab gateway: `DEVOPS_CLI_AI__MAX_TOKENS=64 uv run python -c "..."` with the script in the issue's manual check, which prints `length` twice (the non-streamed `chat` and `chat_stream`). +- Pending a person, with a direct Ollama URL: the same script without the `chat_stream` line, which prints `length`. Ollama streams do not send the reply cap yet, so the stream line is left out there. +- Pending a person, on the gateway: `DEVOPS_CLI_AI__MAX_TOKENS=256 uv run devops ai review benchmark src/devops_cli/ai/client/streaming.py --runs 1 --persona architect`, then `jq '.stages[] | {name, finish_reasons, truncated}'` on the profile.json it names, which shows `length` counts. +- The ROADMAP entry is not edited: item PRs leave `docs/ROADMAP.md` to `devops roadmap render` at the cut (#933), which overrides the issue's request to rewrite it in this change. + +## Measurements +Durations are the setup, call and teardown that `pytest --durations=0 --durations-min=0` reports for the 52 new or rewritten test ids, summed, on 16 shared cores. The first two runs are of the 10 touched test files, the third the final full suite. + +| Run | Calls | Setup and teardown | Total | Largest entry | +| :--- | ---: | ---: | ---: | :--- | +| Serial (`-n0`), load average about 4 | 0.44 s | 0.17 s | 0.61 s | `test_a_ledger_records_each_replys_finish_reason` 0.06 s | +| Default parallel (`-n logical`), load average about 4 | 1.16 s | 0.97 s | 2.13 s | `test_a_ledger_records_each_replys_finish_reason` 0.22 s | +| Full suite (`-n 6`), load average 5 rising to 15 | 0.60 s | 0.32 s | 0.92 s | `test_a_ledger_records_each_replys_finish_reason` 0.09 s | + +In the parallel run 16 workers share the cores, so every test runs slower, and the setup column is mostly the conftest autouse fixtures that every test pays. A test that runs first in a worker can also pay that worker's one-time tracer imports (about 2 s), which belong to the session: before its fake reply carried token counts, `test_the_dispatch_span_names_the_reason_the_reply_ended` paid a tokenizer load too, and now takes under 0.01 s. The final full suite (`uv run pytest -p no:cacheprovider -q -n 6 tests`) took 126.5 s: 7024 passed, 8 xfailed. The review then added 4 test ids (`test_reading_stops_at_the_final_frame`, three cases, and `ollama-line-not-utf8`) and extended 3 tests (the reset, direct-request and size-limit tests), after these runs. A serial re-run of the touched files during the review, at load average about 38, put each of them at 0.29 s or less, most under 0.01 s; that run is too loaded to compare with the table. + +## Notes +- In `devops ai chat` with streaming and no tools, a cut stream now raises instead of storing its partial text. The chat loop's handler (`commands/ai.py:1106-1110`) then pops the last memory entry, which is the previous reply, because the streamed turn never adds the user's message. #874 fixes that turn. +- Anthropic's `message_delta` usage and the OpenAI-compatible usage chunk are read and ignored; #591 reads provider-reported usage from the same final frames. +- An event stream's size counts each event's data. Comment lines carry none, and the per-event limit still bounds one left unterminated. An NDJSON stream's size counts each line. +- An error frame is the server's answer, so it does not fail over to the next Ollama host; only connection failures before any output do, as before. The Ollama stream's errors now name `Ollama` instead of `LLM`. diff --git a/src/devops_cli/ai/client/__init__.py b/src/devops_cli/ai/client/__init__.py index cd8733da34..77530a35a4 100644 --- a/src/devops_cli/ai/client/__init__.py +++ b/src/devops_cli/ai/client/__init__.py @@ -27,11 +27,6 @@ from devops_cli.ai.client.streaming import ( StreamingReasoningSanitizer, StreamingTokenProcessor, - _consume_streaming_lines, - _extract_claude_stream_chunk, - _extract_ollama_stream_chunk, - _extract_ollama_stream_tuple, - _extract_openai_stream_chunk, ) from devops_cli.ai.client.structured import StructuredOutputMixin from devops_cli.ai.client.unified import ( @@ -51,11 +46,6 @@ "StreamingReasoningSanitizer", "StreamingTokenProcessor", "StructuredOutputMixin", - "_consume_streaming_lines", - "_extract_claude_stream_chunk", - "_extract_ollama_stream_chunk", - "_extract_ollama_stream_tuple", - "_extract_openai_stream_chunk", "_is_json_error_payload", "acquire_ollama_slot", "current_request_priority", diff --git a/src/devops_cli/ai/client/claude.py b/src/devops_cli/ai/client/claude.py index aad4e83844..26939f8605 100644 --- a/src/devops_cli/ai/client/claude.py +++ b/src/devops_cli/ai/client/claude.py @@ -10,13 +10,10 @@ import httpx2 from devops_cli.ai.client.base import BaseLLMProviderMixin -from devops_cli.ai.client.models import LLMResponse +from devops_cli.ai.client.models import LLMResponse, provider_finish_reason from devops_cli.ai.client.network import read_limited_json -from devops_cli.ai.client.streaming import ( - _consume_streaming_lines, - _extract_claude_stream_chunk, -) -from devops_cli.config.constants import CONST_URL_ANTHROPIC_API_BASE +from devops_cli.ai.client.streaming import _claude_stream_frame, _read_event_stream +from devops_cli.config.constants import CONST_ANTHROPIC_STOP_REASONS, CONST_URL_ANTHROPIC_API_BASE from devops_cli.models.ai import ChatMessage from devops_cli.telemetry import inject_trace_context @@ -115,6 +112,9 @@ def _claude_messages( completion_tokens=completion_tokens, total_tokens=total_tokens, model=raw_json.get("model"), + finish_reason=provider_finish_reason( + CONST_ANTHROPIC_STOP_REASONS, raw_json.get("stop_reason") + ), ) except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc @@ -172,9 +172,7 @@ def _claude_stream( if response.status_code >= 400: response.read() response.raise_for_status() - yield from _consume_streaming_lines( - response, _extract_claude_stream_chunk, "Claude" - ) + yield from _read_event_stream(response, _claude_stream_frame, "Claude") except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc except httpx2.HTTPError as exc: diff --git a/src/devops_cli/ai/client/models.py b/src/devops_cli/ai/client/models.py index 1c9c5b2767..dc514b7810 100644 --- a/src/devops_cli/ai/client/models.py +++ b/src/devops_cli/ai/client/models.py @@ -3,8 +3,9 @@ from __future__ import annotations import json +from collections.abc import Mapping from enum import StrEnum -from typing import Any +from typing import TYPE_CHECKING, Any from devops_cli.config.constants import ( CONST_GENAI_PROVIDER_NAMES, @@ -16,6 +17,9 @@ from devops_cli.config.options import AI_API_KEY from devops_cli.exceptions import LLMInferenceError +if TYPE_CHECKING: + from pydantic_ai.messages import FinishReason + MAX_STREAM_BYTES = 50 * 1024 * 1024 # 50MB maximum streamed response size @@ -96,6 +100,7 @@ class LLMResponse(str): prompt_eval_duration_ms: float | None served_by: str | None model: str | None + finish_reason: FinishReason | None def __new__( cls, @@ -112,6 +117,7 @@ def __new__( cached: bool = False, served_by: str | None = None, model: str | None = None, + finish_reason: FinishReason | None = None, ) -> LLMResponse: obj = str.__new__(cls, content) obj.processing_seconds = processing_seconds @@ -127,6 +133,8 @@ def __new__( # The backend a gateway routed the call to; None when no gateway named one. obj.served_by = served_by obj.model = model + # Why the provider says the reply ended; None when it did not say. + obj.finish_reason = finish_reason return obj @property @@ -153,7 +161,12 @@ def to_model_response(self, model_name: str | None = None) -> Any: input_tokens=self.prompt_tokens or 0, output_tokens=self.completion_tokens or 0, ) - return ModelResponse(parts=parts, model_name=model_name or self.backend_info, usage=usage) + return ModelResponse( + parts=parts, + model_name=model_name or self.backend_info, + usage=usage, + finish_reason=self.finish_reason, + ) @classmethod def from_model_response( @@ -184,6 +197,7 @@ def from_model_response( total_tokens=tot_tokens, cached=cached, model=response.model_name, + finish_reason=response.finish_reason, ) @@ -207,6 +221,13 @@ def _is_json_error_payload(raw_str: str) -> bool: return False +def provider_finish_reason( + table: Mapping[str, FinishReason | None], value: object +) -> FinishReason | None: + """A provider's own stop value as a FinishReason; None when it is absent or unmapped.""" + return table.get(value) if isinstance(value, str) else None + + def genai_provider_name(provider: str) -> str: """The conventions' `gen_ai.provider.name` for a provider id: its well-known value or the id.""" return CONST_GENAI_PROVIDER_NAMES.get(provider, provider) diff --git a/src/devops_cli/ai/client/network.py b/src/devops_cli/ai/client/network.py index 2bb92a5abf..1bfe924d61 100644 --- a/src/devops_cli/ai/client/network.py +++ b/src/devops_cli/ai/client/network.py @@ -12,7 +12,7 @@ from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from urllib.parse import urlparse import httpx2 @@ -26,6 +26,9 @@ DEFAULT_OLLAMA_SLOT_TIMEOUT_SECONDS, ) +if TYPE_CHECKING: + from pydantic_ai.messages import FinishReason + logger = logging.getLogger(__name__) ALLOW_PRIVATE_NETWORK_ENV = CONST_AI_ALLOW_PRIVATE_NETWORK_ENV @@ -48,6 +51,12 @@ # The backend a gateway named in a streamed response's headers. A stream is a generator consumed # in the caller's context, so its spend is recorded after the last chunk, not where headers arrive. stream_served_by: ContextVar[str | None] = ContextVar("stream_served_by", default=None) +# Why a streamed reply ended, set by the stream reader when the provider's final frame arrives. +# A generator's return value would be lost in the caller's `for` loop and the sanitizer wrapping +# it, so the reason travels like the serving backend. +stream_finish_reason: ContextVar[FinishReason | None] = ContextVar( + "stream_finish_reason", default=None +) # A reply-token cap for the calls made inside `limit_completion_tokens`. It travels with the # context, like the request priority, so one call site can bound a reply without every layer diff --git a/src/devops_cli/ai/client/ollama.py b/src/devops_cli/ai/client/ollama.py index 4b0964fb82..5f73a6ea2a 100644 --- a/src/devops_cli/ai/client/ollama.py +++ b/src/devops_cli/ai/client/ollama.py @@ -12,7 +12,12 @@ import httpx2 from devops_cli.ai.client.base import BaseLLMProviderMixin -from devops_cli.ai.client.models import AIClientError, LLMResponse, RequestPriority +from devops_cli.ai.client.models import ( + AIClientError, + LLMResponse, + RequestPriority, + provider_finish_reason, +) from devops_cli.ai.client.network import ( acquire_ollama_slot, active_ollama_requests, @@ -20,10 +25,8 @@ read_limited_json, request_priority_scope, ) -from devops_cli.ai.client.streaming import ( - _consume_streaming_lines, - _extract_ollama_stream_tuple, -) +from devops_cli.ai.client.streaming import _ollama_stream_frame, _read_ndjson_stream +from devops_cli.config.constants import CONST_OLLAMA_DONE_REASONS from devops_cli.config.defaults import ( DEFAULT_AI_EVICT_KEEP_ALIVE, DEFAULT_AI_PREWARM_KEEP_ALIVE, @@ -378,6 +381,9 @@ def _ollama_request( eval_duration_ms=eval_dur_ms, prompt_eval_duration_ms=prompt_eval_dur_ms, model=raw_res.get("model"), + finish_reason=provider_finish_reason( + CONST_OLLAMA_DONE_REASONS, raw_res.get("done_reason") + ), ) def _try_single_ollama_stream( @@ -481,7 +487,7 @@ def _ollama_stream_request( response.raise_for_status() if think and self._ollama_thinking_supported is None: self._ollama_thinking_supported = True - yield from _consume_streaming_lines(response, _extract_ollama_stream_tuple, "LLM") + yield from _read_ndjson_stream(response, _ollama_stream_frame, "Ollama") def _fetch_ollama_tags(self, base: str) -> list[str]: """Fetch available model tags from single Ollama host.""" diff --git a/src/devops_cli/ai/client/openai.py b/src/devops_cli/ai/client/openai.py index d956e6c2f6..053989ad35 100644 --- a/src/devops_cli/ai/client/openai.py +++ b/src/devops_cli/ai/client/openai.py @@ -13,14 +13,13 @@ from devops_cli.ai.client.models import ( LLMResponse, is_reasoning_model, + provider_finish_reason, ) from devops_cli.ai.client.network import read_limited_json, stream_served_by -from devops_cli.ai.client.streaming import ( - _consume_streaming_lines, - _extract_openai_stream_chunk, -) +from devops_cli.ai.client.streaming import _openai_stream_frame, _read_event_stream from devops_cli.config.constants import ( CONST_AI_GATEWAY_SERVED_BY_HEADER, + CONST_OPENAI_FINISH_REASONS, CONST_URL_GITHUB_COPILOT_API_BASE, CONST_URL_OPENAI_API_BASE, ) @@ -148,6 +147,9 @@ def _parse_compat_response( total_tokens=usage.get("total_tokens"), served_by=served_by, model=raw_json.get("model"), + finish_reason=provider_finish_reason( + CONST_OPENAI_FINISH_REASONS, first_choice.get("finish_reason") + ), ) def _openai_compat_messages( @@ -202,9 +204,7 @@ def _openai_compat_stream( response.read() response.raise_for_status() stream_served_by.set(response.headers.get(CONST_AI_GATEWAY_SERVED_BY_HEADER)) - yield from _consume_streaming_lines( - response, _extract_openai_stream_chunk, "Provider" - ) + yield from _read_event_stream(response, _openai_stream_frame, "Provider") except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc except httpx2.HTTPError as exc: diff --git a/src/devops_cli/ai/client/streaming.py b/src/devops_cli/ai/client/streaming.py index 962b2bf73f..cdeabd1212 100644 --- a/src/devops_cli/ai/client/streaming.py +++ b/src/devops_cli/ai/client/streaming.py @@ -1,14 +1,27 @@ -"""Streaming utilities for token chunks and SSE event streams.""" +"""Streaming utilities for token chunks, and readers for providers' event and NDJSON streams.""" from __future__ import annotations import json -from collections.abc import AsyncGenerator, AsyncIterable, Callable, Generator, Iterable -from typing import Any +from collections.abc import AsyncGenerator, AsyncIterable, Callable, Generator, Iterable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Final import httpx2 -from devops_cli.ai.client.models import MAX_STREAM_BYTES, AIClientError +from devops_cli.ai.client.models import MAX_STREAM_BYTES, AIClientError, provider_finish_reason +from devops_cli.ai.client.network import stream_finish_reason +from devops_cli.config.constants import ( + CONST_ANTHROPIC_STOP_REASONS, + CONST_OLLAMA_DONE_REASONS, + CONST_OPENAI_FINISH_REASONS, +) +from devops_cli.config.defaults import DEFAULT_AI_STREAM_MAX_EVENT_BYTES +from devops_cli.security.sanitizer import mask_secrets + +if TYPE_CHECKING: + from pydantic_ai.messages import FinishReason def _find_suffix_overlap(text: str, target: str) -> int: @@ -237,149 +250,291 @@ def to_dict(self) -> dict[str, Any]: StreamingReasoningSanitizer = StreamingTokenProcessor -def _extract_ollama_stream_chunk(line: str) -> str | None: - """Extract content or thinking chunk from an Ollama stream line.""" - if not line: - return None +@dataclass(frozen=True, slots=True) +class StreamFrame: + """What one provider frame means: text to yield, and whether and why the reply ended.""" + + chunk: str | None = None + # The provider's final word arrived: the stream is complete, even if reading goes on. + complete: bool = False + # Nothing after this frame is read. + last: bool = False + finish_reason: FinishReason | None = None + # The provider's own error message, which the reader raises. + error: str | None = None + + +def _json_object(text: str) -> dict[str, Any]: + """A frame's JSON object; an empty one for anything else, which carries nothing to read.""" try: - line_data = json.loads(line) + parsed = json.loads(text) except json.JSONDecodeError: + return {} + return parsed if isinstance(parsed, dict) else {} + + +def _error_text(error: object) -> str: + """The message of an error frame's `error` value: a string, or an object with a message.""" + if isinstance(error, dict): + return str(error.get("message") or error) + return str(error) + + +def _ollama_message_text(message: object) -> str | None: + """A chat message's thinking, wrapped in think tags, or else its content.""" + if not isinstance(message, dict): return None - msg = line_data.get("message", {}) - content = msg.get("content", "") - thinking = msg.get("thinking", "") - if thinking: + if thinking := message.get("thinking"): return f"{thinking}" - if content: - return str(content) + content = message.get("content") + return str(content) if content else None + + +def _ollama_stream_frame(line: str) -> StreamFrame: + """One line of an Ollama chat stream; `done: true` is its final frame, with `done_reason`.""" + payload = _json_object(line) + if payload.get("error") is not None: + return StreamFrame(error=_error_text(payload["error"])) + done = payload.get("done") is True + return StreamFrame( + chunk=_ollama_message_text(payload.get("message")), + complete=done, + last=done, + finish_reason=provider_finish_reason(CONST_OLLAMA_DONE_REASONS, payload.get("done_reason")), + ) + + +def _claude_delta_text(delta: object) -> str | None: + """A content block delta's text, or its thinking wrapped in think tags.""" + if not isinstance(delta, dict): + return None + delta_type = delta.get("type") + if delta_type == "text_delta" and delta.get("text"): + return str(delta["text"]) + if delta_type == "thinking_delta" and delta.get("thinking"): + return f"{delta['thinking']}" return None -def _extract_claude_stream_chunk(line: str) -> tuple[str | None, bool]: - """Extract content chunk from Claude SSE stream line. Returns (chunk, is_done).""" - if not line or not line.startswith("data:"): - return (None, False) - raw_data = line.removeprefix("data:").strip() - if raw_data == "[DONE]": - return (None, True) +def _claude_message_delta(payload: dict[str, Any]) -> StreamFrame: + """`message_delta` carries the reply's stop reason, ahead of the final `message_stop`.""" + delta = payload.get("delta") + stop_reason = delta.get("stop_reason") if isinstance(delta, dict) else None + return StreamFrame( + finish_reason=provider_finish_reason(CONST_ANTHROPIC_STOP_REASONS, stop_reason) + ) + + +# The Anthropic Messages stream events that carry text, the reason, the end or an error. Every +# other event (message_start, content_block_start, content_block_stop, ping) carries none. +_CLAUDE_EVENT_FRAMES: Final[dict[str, Callable[[dict[str, Any]], StreamFrame]]] = { + "content_block_delta": lambda payload: StreamFrame( + chunk=_claude_delta_text(payload.get("delta")) + ), + "message_delta": _claude_message_delta, + "message_stop": lambda _payload: StreamFrame(complete=True, last=True), + "error": lambda payload: StreamFrame(error=_error_text(payload.get("error"))), +} + + +def _claude_stream_frame(event: httpx2.ServerSentEvent) -> StreamFrame: + """One event of an Anthropic Messages stream; `message_stop` is its final frame. + + Anthropic never sends `[DONE]`, so it is not read as an end. + """ + payload = _json_object(event.data) + frame_for = _CLAUDE_EVENT_FRAMES.get(str(payload.get("type") or event.event)) + return frame_for(payload) if frame_for else StreamFrame() + + +def _openai_delta_text(delta: object) -> str | None: + """A chat completion delta's reasoning, wrapped in think tags, or else its content.""" + if not isinstance(delta, dict): + return None + if reasoning := delta.get("reasoning_content") or delta.get("reasoning"): + return f"{reasoning}" + content = delta.get("content") + return str(content) if content else None + + +def _first_choice(payload: dict[str, Any]) -> dict[str, Any]: + """A completion chunk's first choice; an empty one when it has none, as a usage chunk.""" + choices = payload.get("choices") + first = choices[0] if isinstance(choices, list) and choices else None + return first if isinstance(first, dict) else {} + + +def _openai_stream_frame(event: httpx2.ServerSentEvent) -> StreamFrame: + """One event of an OpenAI-compatible chat completion stream. + + A chunk with a finish reason completes the stream, and so does `[DONE]`, the server's own end + marker, with no reason before it. Reading goes on past the reason to `[DONE]` or EOF, so a + usage chunk sent after it is still read. + """ + if event.data.strip() == "[DONE]": + return StreamFrame(complete=True, last=True) + payload = _json_object(event.data) + if payload.get("error") is not None: + return StreamFrame(error=_error_text(payload["error"])) + choice = _first_choice(payload) + reason = choice.get("finish_reason") + return StreamFrame( + chunk=_openai_delta_text(choice.get("delta")), + complete=reason is not None, + finish_reason=provider_finish_reason(CONST_OPENAI_FINISH_REASONS, reason), + ) + + +def _size_limit_text(limit_bytes: int) -> str: + return ( + f"{limit_bytes // (1024 * 1024)}MB" + if limit_bytes >= 1024 * 1024 + else f"{limit_bytes} bytes" + ) + + +def _check_stream_size(total_bytes: int, provider_name: str, max_stream_bytes: int) -> None: + if total_bytes > max_stream_bytes: + raise AIClientError( + f"{provider_name} response exceeded maximum stream size " + f"({_size_limit_text(max_stream_bytes)})." + ) + + +def _error_frame(provider_name: str, message: str) -> AIClientError: + """The provider's error frame as an error, its message masked and cut to 256 characters.""" + return AIClientError(f"{provider_name} stream reported an error: {mask_secrets(message)[:256]}") + + +def _read_frames[FrameT]( + frames: Iterable[tuple[FrameT, int]], + parse_frame: Callable[[FrameT], StreamFrame], + provider_name: str, + max_stream_bytes: int, +) -> Generator[str]: + """Yield each frame's text as it arrives, until the provider's final frame. + + Every frame counts towards `max_stream_bytes` before it is parsed, including frames that + carry no text. Once the stream is complete its finish reason is set in + `stream_finish_reason`. An error frame, and a stream that ends before its final frame, + raise `AIClientError`. + """ + total_bytes = 0 + complete = False + reason: FinishReason | None = None + for raw_frame, frame_bytes in frames: + total_bytes += frame_bytes + _check_stream_size(total_bytes, provider_name, max_stream_bytes) + frame = parse_frame(raw_frame) + if frame.error is not None: + raise _error_frame(provider_name, frame.error) + if frame.chunk: + yield frame.chunk + complete = complete or frame.complete + reason = frame.finish_reason or reason + if frame.last: + break + if not complete: + raise AIClientError(f"{provider_name} stream ended before its final frame.") + stream_finish_reason.set(reason) + + +def _event_frames( + response: httpx2.Response, max_event_bytes: int +) -> Iterator[tuple[httpx2.ServerSentEvent, int]]: + """Each server-sent event with the size of its data. + + httpx2's EventSource splits lines on CR and LF alone, decodes a code point split across + chunks, and refuses an event over `max_event_bytes` and a body that is not + `text/event-stream`. + """ + for event in httpx2.EventSource(response, max_event_size=max_event_bytes): + yield event, len(event.data.encode("utf-8")) + + +def _check_line_size(line_bytes: int, provider_name: str, max_line_bytes: int) -> None: + if line_bytes > max_line_bytes: + raise AIClientError( + f"{provider_name} stream line exceeded the {_size_limit_text(max_line_bytes)} limit." + ) + + +def _ndjson_line(raw: bytearray, provider_name: str, max_line_bytes: int) -> tuple[str, int]: + _check_line_size(len(raw), provider_name, max_line_bytes) try: - event_json = json.loads(raw_data) - except json.JSONDecodeError: - return (None, False) - if event_json.get("type") == "content_block_delta": - delta = event_json.get("delta", {}) - delta_type = delta.get("type") - if delta_type == "text_delta": - text_val = delta.get("text", "") - if text_val: - return (str(text_val), False) - if delta_type == "thinking_delta": - think_val = delta.get("thinking", "") - if think_val: - return (f"{think_val}", False) - return (None, False) - - -def _extract_openai_stream_chunk(line: str) -> tuple[str | None, bool]: - """Extract content chunk from OpenAI SSE stream line. Returns (chunk, is_done).""" - if not line or not line.startswith("data:"): - return (None, False) - raw_data = line.removeprefix("data:").strip() - if raw_data == "[DONE]": - return (None, True) + return raw.decode("utf-8"), len(raw) + except UnicodeDecodeError as exc: + raise AIClientError(f"{provider_name} stream line is not UTF-8: {exc}") from exc + + +def _ndjson_lines( + response: httpx2.Response, provider_name: str, max_line_bytes: int +) -> Iterator[tuple[str, int]]: + """Each line of a newline-delimited JSON body with its size, split on LF alone. + + A line is decoded once it is whole, so a code point split across chunks decodes intact and + a U+2028 inside a JSON string stays in its line. A line still unterminated past + `max_line_bytes` is refused rather than buffered; one unterminated at EOF is read as it is. + """ + pending = bytearray() + for data in response.iter_bytes(): + head, *rest = data.split(b"\n") + pending += head + for piece in rest: + yield _ndjson_line(pending, provider_name, max_line_bytes) + pending = bytearray(piece) + _check_line_size(len(pending), provider_name, max_line_bytes) + if pending: + yield _ndjson_line(pending, provider_name, max_line_bytes) + + +@contextmanager +def _read_failures(provider_name: str) -> Iterator[None]: + """Raise a failed read as `AIClientError`, never as an httpx2 request error. + + The Ollama host loop fails over on request and transport errors, so one escaping here would + replay the request on the next host after output had been yielded. httpx2's SSEError, which + a refused content type or an oversized event raises, is a TransportError too, and a body + that fails to decompress raises a DecodingError. + """ try: - event_json = json.loads(raw_data) - except json.JSONDecodeError: - return (None, False) - choices = event_json.get("choices", []) - if choices: - delta = choices[0].get("delta", {}) - reasoning = delta.get("reasoning_content") or delta.get("reasoning") - if reasoning: - return (f"{reasoning}", False) - content = delta.get("content") - if content: - return (str(content), False) - return (None, False) - - -def _extract_ollama_stream_tuple(line: str) -> tuple[str | None, bool]: - """Extract content or thinking chunk from Ollama stream line as (chunk, is_done).""" - return (_extract_ollama_stream_chunk(line), False) - - -def _extract_stream_chunk(line: str, provider: str) -> tuple[str | None, bool]: - """Unified chunk extractor dispatching to provider-specific parser.""" - norm_p = provider.lower() - if norm_p in ("claude", "anthropic"): - return _extract_claude_stream_chunk(line) - if norm_p in ("openai", "copilot", "github_copilot"): - return _extract_openai_stream_chunk(line) - return _extract_ollama_stream_tuple(line) - - -def _read_response_lines( + yield + except httpx2.SSEError as exc: + raise AIClientError(f"{provider_name} stream could not be read: {str(exc)[:256]}") from exc + except httpx2.RequestError as exc: + raise AIClientError( + f"{provider_name} streaming connection terminated unexpectedly: {str(exc)[:256]}" + ) from exc + + +def _read_event_stream( response: httpx2.Response, - chunk_extractor: Callable[[str], tuple[str | None, bool]], + parse_event: Callable[[httpx2.ServerSentEvent], StreamFrame], provider_name: str, - max_bytes: int, - initial_bytes: int, -) -> Generator[tuple[str, int]]: - """Iterate response lines and yield (chunk_str, cumulative_bytes).""" - current_bytes = initial_bytes - for line in response.iter_lines(): - line_bytes = len(line.encode("utf-8")) if isinstance(line, str) else len(line) - current_bytes += line_bytes - if current_bytes > max_bytes: - limit_str = ( - f"{max_bytes // (1024 * 1024)}MB" - if max_bytes >= 1024 * 1024 - else f"{max_bytes} bytes" - ) - raise AIClientError( - f"{provider_name} response exceeded maximum stream size ({limit_str})." - ) - chunk_str, is_done = chunk_extractor(line) - if is_done: - break - if chunk_str is None: - continue - yield chunk_str, current_bytes + *, + max_event_bytes: int = DEFAULT_AI_STREAM_MAX_EVENT_BYTES, + max_stream_bytes: int = MAX_STREAM_BYTES, +) -> Generator[str]: + """Yield the text of a server-sent event stream as it arrives, until its final event.""" + with _read_failures(provider_name): + yield from _read_frames( + _event_frames(response, max_event_bytes), parse_event, provider_name, max_stream_bytes + ) -def _consume_streaming_lines( +def _read_ndjson_stream( response: httpx2.Response, - chunk_extractor: Callable[[str], tuple[str | None, bool]], + parse_line: Callable[[str], StreamFrame], provider_name: str, *, - max_stream_bytes: int | None = None, + max_line_bytes: int = DEFAULT_AI_STREAM_MAX_EVENT_BYTES, + max_stream_bytes: int = MAX_STREAM_BYTES, ) -> Generator[str]: - """Yield extracted tokens from an HTTP streaming response with bounded size and error safety.""" - import devops_cli.ai.client as client_pkg - import devops_cli.ai.client.models as client_models - - effective_max = ( - max_stream_bytes - if max_stream_bytes is not None - else getattr( - client_pkg, - "MAX_STREAM_BYTES", - getattr(client_models, "MAX_STREAM_BYTES", MAX_STREAM_BYTES), + """Yield the text of a newline-delimited JSON stream as it arrives, until its final line.""" + with _read_failures(provider_name): + yield from _read_frames( + _ndjson_lines(response, provider_name, max_line_bytes), + parse_line, + provider_name, + max_stream_bytes, ) - ) - total_bytes = 0 - try: - for chunk_str, total_bytes in _read_response_lines( - response, chunk_extractor, provider_name, effective_max, total_bytes - ): - yield chunk_str - except ( - httpx2.RemoteProtocolError, - httpx2.ReadTimeout, - httpx2.TransportError, - httpx2.ReadError, - ) as exc: - safe_err = str(exc)[:256] - raise AIClientError( - f"{provider_name} streaming connection terminated unexpectedly: {safe_err}" - ) from exc diff --git a/src/devops_cli/ai/client/unified.py b/src/devops_cli/ai/client/unified.py index 27514c3159..df7df94afd 100644 --- a/src/devops_cli/ai/client/unified.py +++ b/src/devops_cli/ai/client/unified.py @@ -8,7 +8,7 @@ import time from collections.abc import AsyncGenerator, Callable, Generator, Sequence from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from urllib.parse import urlparse, urlsplit import httpx2 @@ -34,7 +34,9 @@ from devops_cli.ai.thinking_stream import strip_think_blocks from devops_cli.config.constants import ( CONST_AI_BACKEND_HOST_UNKNOWN, + CONST_FINISH_REASON_ERROR, CONST_OTEL_SPAN_KIND_CLIENT, + CONST_UNCACHED_FINISH_REASONS, CONST_URL_ANTHROPIC_API_BASE, CONST_URL_GITHUB_COPILOT_API_BASE, CONST_URL_OPENAI_API_BASE, @@ -52,6 +54,9 @@ from devops_cli.models.ai import ChatMessage from devops_cli.telemetry import record_metric, trace_span +if TYPE_CHECKING: + from pydantic_ai.messages import FinishReason + logger = logging.getLogger(__name__) @@ -105,11 +110,31 @@ def _set_timing_span_attributes(span_handle: Any, res: LLMResponse) -> None: span_handle.set_attribute("llm.wall_seconds", res.wall_seconds) +def _set_finish_reason_attribute(span_handle: Any, reason: FinishReason | None) -> None: + """Name why the reply ended; an unknown reason sets nothing, as truncation is never guessed.""" + if reason is not None: + span_handle.set_attribute("gen_ai.response.finish_reasons", [reason]) + + +def _response_event_payload(res: LLMResponse, p: str) -> dict[str, Any]: + """The `llm_response_received` event's summary of a reply.""" + event_payload: dict[str, Any] = { + "total_tokens": res.total_tokens or 0, + "wall_seconds": res.wall_seconds or 0.0, + "backend": res.backend_info or p, + } + if getattr(res, "served_by", None): + event_payload["served_by"] = res.served_by + if getattr(res, "model", None): + event_payload["model"] = res.model + return event_payload + + def _set_response_span_attributes(span_handle: Any, res: LLMResponse, p: str) -> None: """Set the reply's GenAI attributes on the `ai.llm.dispatch` inference span. - This is the only writer of the usage, response model and finish reason keys, so a - request's tokens are counted once, on the span that made it. + This is the only writer of the usage and response model keys, so a request's tokens are + counted once, on the span that made it. """ netloc = _extract_server_from_backend_info(res.backend_info, "") for key, value in _server_span_attributes(netloc).items(): @@ -123,19 +148,10 @@ def _set_response_span_attributes(span_handle: Any, res: LLMResponse, p: str) -> if res.completion_tokens is not None: span_handle.set_attribute("gen_ai.usage.output_tokens", res.completion_tokens) _set_timing_span_attributes(span_handle, res) - span_handle.set_attribute("gen_ai.response.finish_reasons", ["stop"]) + _set_finish_reason_attribute(span_handle, res.finish_reason) span_handle.set_attribute("llm.response_preview", res.text[:200].replace("\n", " ").strip()) span_handle.set_attribute("llm.response.thinking", bool(res.thinking)) - event_payload: dict[str, Any] = { - "total_tokens": res.total_tokens or 0, - "wall_seconds": res.wall_seconds or 0.0, - "backend": res.backend_info or p, - } - if getattr(res, "served_by", None): - event_payload["served_by"] = res.served_by - if getattr(res, "model", None): - event_payload["model"] = res.model - span_handle.add_event("llm_response_received", event_payload) + span_handle.add_event("llm_response_received", _response_event_payload(res, p)) class LLMClient( @@ -477,6 +493,7 @@ def _record_response_telemetry_and_spend( request_type="chat_dispatch", duration_seconds=res.wall_seconds or duration, stage=resolve_spend_stage(None, getattr(self._config, "task_name", None)), + finish_reason=res.finish_reason, ) if rec is not None: span_handle.set_attribute("llm.usage.cost_usd", rec.cost_usd) @@ -600,9 +617,13 @@ def _handle_successful_chat_dispatch( context_tag: str | None, span_h: Any, ) -> LLMResponse: - """Record telemetry, optionally cache successful response, and return.""" + """Record telemetry, optionally cache successful response, and return. + + A reply cut at its cap, filtered or failed is returned but never cached, so the next + identical call reaches the provider again rather than the cut reply. + """ self._record_chat_telemetry(span_h, res) - if use_cache: + if use_cache and res.finish_reason not in CONST_UNCACHED_FINISH_REASONS: self._cache_chat_entry(cache_key, system, out_messages, res, context_tag) return res @@ -793,11 +814,15 @@ def chat_messages_stream( sanitize: bool = False, priority: RequestPriority | str | None = None, ) -> Generator[str]: - """Send a multi-turn conversation and yield streaming tokens as they arrive.""" + """Send a multi-turn conversation and yield streaming tokens as they arrive. + + A stream that fails after yielding output records its spend with finish reason `error` + and re-raises; one that fails before its first chunk records nothing, as a failed + non-streamed call records nothing. + """ p = self._config.provider t_start = time.perf_counter() first_token_time: float | None = None - token_chunks_count = 0 resolved_p = ( RequestPriority(priority) if isinstance(priority, str) @@ -818,6 +843,8 @@ def chat_messages_stream( "ai.llm.stream", attributes=stream_attrs, kind=CONST_OTEL_SPAN_KIND_CLIENT ) as span_h: network.stream_served_by.set(None) + network.stream_finish_reason.set(None) + accumulated_chunks: list[str] = [] try: gen = self._dispatch_stream( system, messages, enable_thinking=enable_thinking, priority=resolved_p @@ -826,23 +853,34 @@ def chat_messages_stream( from devops_cli.ai.client.streaming import StreamingTokenProcessor gen = StreamingTokenProcessor().sanitize_stream(gen) - accumulated_chunks: list[str] = [] for chunk in gen: first_token_time = self._record_first_token(span_h, t_start, first_token_time) - token_chunks_count += 1 accumulated_chunks.append(chunk) yield chunk - - total_dur = time.perf_counter() - t_start - span_h.set_attribute("llm.stream.chunk_count", token_chunks_count) - span_h.set_attribute("llm.wall_seconds", total_dur) - self._record_stream_spend( - span_h, p, messages, system, "".join(accumulated_chunks), total_dur - ) except Exception as exc: span_h.record_exception(exc) + if accumulated_chunks: + # The provider produced tokens before failing, so they were spent. + self._record_stream_spend( + span_h, + p, + messages, + system, + "".join(accumulated_chunks), + time.perf_counter() - t_start, + CONST_FINISH_REASON_ERROR, + ) raise + total_dur = time.perf_counter() - t_start + finish_reason = network.stream_finish_reason.get() + _set_finish_reason_attribute(span_h, finish_reason) + span_h.set_attribute("llm.stream.chunk_count", len(accumulated_chunks)) + span_h.set_attribute("llm.wall_seconds", total_dur) + self._record_stream_spend( + span_h, p, messages, system, "".join(accumulated_chunks), total_dur, finish_reason + ) + def _record_stream_spend( self, span_h: Any, @@ -851,6 +889,7 @@ def _record_stream_spend( system: str, accumulated_text: str, total_dur: float, + finish_reason: FinishReason | None, ) -> None: """Record streaming request spend to ledger and telemetry.""" from devops_cli.ai.context_budget import count_tokens @@ -873,6 +912,7 @@ def _record_stream_spend( request_type="stream", duration_seconds=total_dur, stage=resolve_spend_stage(None, getattr(self._config, "task_name", None)), + finish_reason=finish_reason, ) if rec is not None: span_h.set_attribute("llm.usage.cost_usd", rec.cost_usd) diff --git a/src/devops_cli/ai/direct.py b/src/devops_cli/ai/direct.py index 9f99c4e25b..ef647f835e 100644 --- a/src/devops_cli/ai/direct.py +++ b/src/devops_cli/ai/direct.py @@ -124,6 +124,7 @@ def direct_model_request_sync( request_type="direct_sync", duration_seconds=time.monotonic() - started, stage=current_stage.get(), + finish_reason=resp.finish_reason, ) return resp @@ -169,6 +170,7 @@ async def direct_model_request( request_type="direct_async", duration_seconds=time.monotonic() - started, stage=current_stage.get(), + finish_reason=resp.finish_reason, ) return resp diff --git a/src/devops_cli/ai/review/profile.py b/src/devops_cli/ai/review/profile.py index d53acc71b6..57d8abbb8b 100644 --- a/src/devops_cli/ai/review/profile.py +++ b/src/devops_cli/ai/review/profile.py @@ -32,7 +32,11 @@ from devops_cli.ai.personas import review_prompt_digest from devops_cli.ai.spend.ledger import observe_llm_calls -from devops_cli.config.constants import CONST_PERSONA_REPLY_UNPARSED +from devops_cli.config.constants import ( + CONST_FINISH_REASON_LENGTH, + CONST_FINISH_REASON_UNKNOWN, + CONST_PERSONA_REPLY_UNPARSED, +) PROFILE_FILENAME = "profile.json" BENCHMARKS_DIRNAME = "benchmarks" @@ -90,6 +94,10 @@ class StageProfile(BaseModel): cost_usd: float = 0.0 backends: dict[str, int] = Field(default_factory=dict) activity: dict[str, BackendActivity] = Field(default_factory=dict) + # Replies by why the provider says they ended, `unknown` when it did not say. + finish_reasons: dict[str, int] = Field(default_factory=dict) + # Replies cut at their token cap (`length`), by serving backend, keyed like `backends`. + truncated: dict[str, int] = Field(default_factory=dict) def busy_share(self, backend: str) -> float: """The share of the stage's wall time the backend had a call in flight.""" @@ -125,6 +133,11 @@ class ReviewProfile(BaseModel): unparsed_personas: list[str] = Field(default_factory=list) stages: list[StageProfile] = Field(default_factory=list) + @property + def truncated_replies(self) -> int: + """Replies cut at their token cap, whichever backend served them.""" + return sum(s.finish_reasons.get(CONST_FINISH_REASON_LENGTH, 0) for s in self.stages) + @property def seconds_per_candidate(self) -> float | None: """Wall time per candidate finding, which scales with verification work.""" @@ -202,14 +215,24 @@ def observe(self, call: dict[str, Any]) -> None: stage.prompt_tokens += int(call.get("prompt_tokens") or 0) stage.completion_tokens += int(call.get("completion_tokens") or 0) stage.cost_usd = round(stage.cost_usd + float(call.get("cost_usd") or 0.0), 6) + reason = call.get("finish_reason") or CONST_FINISH_REASON_UNKNOWN + stage.finish_reasons[reason] = stage.finish_reasons.get(reason, 0) + 1 served_by = call.get("served_by") if served_by: - stage.backends[served_by] = stage.backends.get(served_by, 0) + 1 - # Observers run as a call finishes, so it started its duration ago. - end = time.monotonic() - duration = max(0.0, float(call.get("duration_seconds") or 0.0)) - by_backend = self._intervals.setdefault(name, {}) - by_backend.setdefault(served_by, []).append((end - duration, end)) + self._observe_served_call(stage, served_by, call) + + def _observe_served_call( + self, stage: StageProfile, served_by: str, call: dict[str, Any] + ) -> None: + """Credit a call to the backend that served it; the caller holds the lock.""" + stage.backends[served_by] = stage.backends.get(served_by, 0) + 1 + if call.get("finish_reason") == CONST_FINISH_REASON_LENGTH: + stage.truncated[served_by] = stage.truncated.get(served_by, 0) + 1 + # Observers run as a call finishes, so it started its duration ago. + end = time.monotonic() + duration = max(0.0, float(call.get("duration_seconds") or 0.0)) + by_backend = self._intervals.setdefault(stage.name, {}) + by_backend.setdefault(served_by, []).append((end - duration, end)) def add_stage_time(self, name: str, seconds: float) -> None: with self._lock: diff --git a/src/devops_cli/ai/review/runner.py b/src/devops_cli/ai/review/runner.py index 9835411b33..151db16159 100644 --- a/src/devops_cli/ai/review/runner.py +++ b/src/devops_cli/ai/review/runner.py @@ -2063,9 +2063,11 @@ def _write_review_profile( for s in profile.stages if s.wall_seconds >= 1 or s.llm_calls ) + capped = profile.truncated_replies + capped_note = f", {capped} hit the reply cap" if capped else "" print_info( f"[dim]Profile: {format_duration(profile.total_wall_seconds)}, " - f"{profile.llm_calls} LLM calls; {stages} -> {path}[/dim]", + f"{profile.llm_calls} LLM calls{capped_note}; {stages} -> {path}[/dim]", prefix=False, ) return profile diff --git a/src/devops_cli/ai/spend/ledger.py b/src/devops_cli/ai/spend/ledger.py index 9000d4fc22..a566f45662 100644 --- a/src/devops_cli/ai/spend/ledger.py +++ b/src/devops_cli/ai/spend/ledger.py @@ -8,7 +8,7 @@ from contextvars import ContextVar from datetime import UTC, datetime, timedelta from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from devops_cli.ai.spend.models import ( BackendSpendSummary, @@ -26,6 +26,9 @@ ) from devops_cli.config.settings import load_settings +if TYPE_CHECKING: + from pydantic_ai.messages import FinishReason + _QUERY_CREATE_TABLE = """ CREATE TABLE IF NOT EXISTS ai_spend_records ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -42,7 +45,8 @@ cached INTEGER NOT NULL DEFAULT 0, request_type TEXT NOT NULL DEFAULT 'chat', duration_seconds REAL NOT NULL DEFAULT 0.0, - stage TEXT + stage TEXT, + finish_reason TEXT ); """ _QUERY_IDX_TIMESTAMP = ( @@ -55,17 +59,20 @@ "CREATE INDEX IF NOT EXISTS idx_spend_served_by ON ai_spend_records(served_by);" ) _QUERY_IDX_STAGE = "CREATE INDEX IF NOT EXISTS idx_spend_stage ON ai_spend_records(stage);" -# Ledgers created before served_by existed gain the column in place, keeping their rows. +# Ledgers created before a column existed gain it in place, keeping their rows. _QUERY_TABLE_COLUMNS = "PRAGMA table_info(ai_spend_records);" -_QUERY_ADD_SERVED_BY = "ALTER TABLE ai_spend_records ADD COLUMN served_by TEXT;" -_QUERY_ADD_STAGE = "ALTER TABLE ai_spend_records ADD COLUMN stage TEXT;" +_ADDED_COLUMNS: tuple[tuple[str, str], ...] = ( + ("served_by", "ALTER TABLE ai_spend_records ADD COLUMN served_by TEXT;"), + ("stage", "ALTER TABLE ai_spend_records ADD COLUMN stage TEXT;"), + ("finish_reason", "ALTER TABLE ai_spend_records ADD COLUMN finish_reason TEXT;"), +) _QUERY_INSERT_RECORD = """ INSERT INTO ai_spend_records ( timestamp, provider, server, backend_info, served_by, model, prompt_tokens, completion_tokens, total_tokens, - cost_usd, cached, request_type, duration_seconds, stage -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + cost_usd, cached, request_type, duration_seconds, stage, finish_reason +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); """ _QUERY_STAGE_BREAKDOWN = """ @@ -197,6 +204,15 @@ def _annotate_stages(stages: list[StageSpendSummary], ref_pricing: ModelPricing) ) +def _add_column(conn: sqlite3.Connection, add_column: str) -> None: + """Add a column, tolerating another process having added it first.""" + try: + conn.execute(add_column) + except sqlite3.OperationalError as exc: + if "duplicate column name" not in str(exc).lower(): + raise + + class SpendLedger: """Persistent thread-safe SQLite ledger recording AI token spend across backends.""" @@ -227,18 +243,9 @@ def _init_db(self) -> None: with contextlib.closing(self._get_connection()) as conn, conn: conn.execute(_QUERY_CREATE_TABLE) columns = {row["name"] for row in conn.execute(_QUERY_TABLE_COLUMNS).fetchall()} - if "served_by" not in columns: - try: - conn.execute(_QUERY_ADD_SERVED_BY) - except sqlite3.OperationalError as exc: - if "duplicate column name" not in str(exc).lower(): - raise - if "stage" not in columns: - try: - conn.execute(_QUERY_ADD_STAGE) - except sqlite3.OperationalError as exc: - if "duplicate column name" not in str(exc).lower(): - raise + for column, add_column in _ADDED_COLUMNS: + if column not in columns: + _add_column(conn, add_column) conn.execute(_QUERY_IDX_SERVED_BY) conn.execute(_QUERY_IDX_STAGE) conn.execute(_QUERY_IDX_TIMESTAMP) @@ -262,6 +269,7 @@ def record_request( duration_seconds: float = 0.0, timestamp: str | None = None, stage: str | None = None, + finish_reason: FinishReason | None = None, ) -> SpendRecord | None: """Record an inference request in the persistent SQLite ledger.""" ts = timestamp or datetime.now(UTC).isoformat() @@ -287,6 +295,7 @@ def record_request( request_type, round(duration_seconds, 4), stage, + finish_reason, ), ) rec_id = cursor.lastrowid @@ -306,6 +315,7 @@ def record_request( request_type=request_type, duration_seconds=duration_seconds, stage=stage, + finish_reason=finish_reason, ) except Exception: # Defensive logging: database failure must never crash user workflows @@ -611,8 +621,13 @@ def track_request_spend( duration_seconds: float = 0.0, stage: str | None = None, ledger: SpendLedger | None = None, + finish_reason: FinishReason | None = None, ) -> SpendRecord | None: - """Calculate pricing, persist to lifetime ledger, and emit OpenTelemetry metrics.""" + """Calculate pricing, persist to lifetime ledger, and emit OpenTelemetry metrics. + + ``finish_reason`` is why the provider says the reply ended, None when it did not say; the + ledger stores it and observers receive it. + """ from devops_cli.ai.spend.pricing import get_pricing_registry from devops_cli.ai.spend.stage import resolve_spend_stage from devops_cli.telemetry.instruments import ( @@ -653,6 +668,7 @@ def track_request_spend( duration_seconds=duration_seconds, timestamp=now_utc.isoformat(), stage=effective_stage, + finish_reason=finish_reason, ) except Exception: rec = None @@ -668,6 +684,7 @@ def track_request_spend( "cached": cached, "request_type": request_type, "duration_seconds": duration_seconds, + "finish_reason": finish_reason, } ) source = { diff --git a/src/devops_cli/ai/spend/models.py b/src/devops_cli/ai/spend/models.py index 4194b4c862..d846be47ec 100644 --- a/src/devops_cli/ai/spend/models.py +++ b/src/devops_cli/ai/spend/models.py @@ -3,6 +3,7 @@ from __future__ import annotations from pydantic import BaseModel, ConfigDict, Field +from pydantic_ai.messages import FinishReason class ModelPricing(BaseModel): @@ -43,6 +44,8 @@ class SpendRecord(BaseModel): request_type: str = "chat" duration_seconds: float = 0.0 stage: str | None = None + # Why the provider says the reply ended; None when it did not say. + finish_reason: FinishReason | None = None class ServerSpendSummary(BaseModel): diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 2984996421..55fc8328f4 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -4,7 +4,10 @@ import re from pathlib import Path -from typing import Final +from typing import TYPE_CHECKING, Final + +if TYPE_CHECKING: + from pydantic_ai.messages import FinishReason # ── Application & Configuration ─────────────────────────────────────────────── CONST_APP_NAME = "devops-cli" @@ -1869,6 +1872,44 @@ CONST_AI_GATEWAY_PROVIDER: Final[str] = "gateway" # Response header in which the LiteLLM gateway names the backend (api_base) that served a call. CONST_AI_GATEWAY_SERVED_BY_HEADER: Final[str] = "x-litellm-model-api-base" +# Why a provider says a reply ended, as pydantic-ai's FinishReason. The OpenAI-compatible and +# Anthropic tables copy pydantic-ai 2.35.0's private maps (models/openai.py, models/anthropic.py), +# which are not imported because they are private. A value absent from a table, or mapped to +# None, is unknown: truncation is never guessed. +CONST_OPENAI_FINISH_REASONS: Final[dict[str, FinishReason]] = { + "stop": "stop", + "length": "length", + "tool_calls": "tool_call", + "content_filter": "content_filter", + "function_call": "tool_call", +} +CONST_ANTHROPIC_STOP_REASONS: Final[dict[str, FinishReason | None]] = { + "compaction": "stop", + "end_turn": "stop", + "max_tokens": "length", + "model_context_window_exceeded": "length", + "stop_sequence": "stop", + "tool_use": "tool_call", + "pause_turn": None, + "refusal": "content_filter", +} +CONST_OLLAMA_DONE_REASONS: Final[dict[str, FinishReason | None]] = { + "stop": "stop", + "length": "length", + "load": None, + "unload": None, +} +# A reply cut at its token cap, and the reason a stream that failed after yielding output is +# recorded with. +CONST_FINISH_REASON_LENGTH: Final[FinishReason] = "length" +CONST_FINISH_REASON_ERROR: Final[FinishReason] = "error" +# Replies the response cache never stores: one cut short, filtered or failed is not the answer +# the prompt asked for, and serving it again for 7 days would repeat the cut. +CONST_UNCACHED_FINISH_REASONS: Final[frozenset[FinishReason]] = frozenset( + {"length", "content_filter", "error"} +) +# How a review profile counts a reply whose provider gave no finish reason. +CONST_FINISH_REASON_UNKNOWN: Final[str] = "unknown" CONST_AI_GATEWAY_PROVIDERS: Final[tuple[str, ...]] = ("litellm", "portkey") CONST_AI_GATEWAY_PROVIDER_LITELLM: Final[str] = "litellm" CONST_AI_GATEWAY_PROVIDER_PORTKEY: Final[str] = "portkey" diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 9335d14910..09b5e12ee6 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -76,6 +76,9 @@ DEFAULT_OLLAMA_SLOT_TIMEOUT_SECONDS: float = 900.0 DEFAULT_OLLAMA_SLOT_POLL_INTERVAL_SECONDS: float = 2.0 DEFAULT_AI_MAX_RESPONSE_BYTES: int = 50 * 1024 * 1024 # 50 MiB limit +# The most one streamed event, or one unterminated stream line, may hold before the stream is +# refused: httpx2's DEFAULT_MAX_EVENT_SIZE_BYTES. MAX_STREAM_BYTES still bounds the whole stream. +DEFAULT_AI_STREAM_MAX_EVENT_BYTES: int = 1024 * 1024 DEFAULT_AI_PREWARM_KEEP_ALIVE: str = "1h" DEFAULT_AI_EVICT_KEEP_ALIVE: int = 0 DEFAULT_AI_MAX_RETRIES: int = 4 diff --git a/src/devops_cli/docs/generator.py b/src/devops_cli/docs/generator.py index 38a42b7262..b38066cd78 100644 --- a/src/devops_cli/docs/generator.py +++ b/src/devops_cli/docs/generator.py @@ -938,9 +938,12 @@ def _llm_span_attribute_lines() -> list[str]: "`gen_ai.provider.name` (`anthropic` for the `claude` provider, other provider ids " "unchanged) and `gen_ai.request.model`, plus `server.address` and `server.port` when " "one backend host served the request. Only `ai.llm.dispatch` carries the reply's " - "usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), " - "`gen_ai.response.model` and `gen_ai.response.finish_reasons`. `ai.llm.stream` " - "carries `gen_ai.request.stream` and `gen_ai.response.time_to_first_chunk` in seconds.", + "usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and " + "`gen_ai.response.model`. `ai.llm.stream` carries `gen_ai.request.stream` and " + "`gen_ai.response.time_to_first_chunk` in seconds. Both carry " + "`gen_ai.response.finish_reasons` with the reason the provider gave for the reply's " + "end (`stop`, `length`, `content_filter` or `tool_call`), and leave it out when the " + "provider gave none.", "- **Wrapper spans**: `ai.llm.chat`, `ai.client.chat_structured` and " "`pydantic_ai.direct.*` are INTERNAL and set no operation, usage or response keys, so " "each request is counted once.", diff --git a/tests/llm_stream_fakes.py b/tests/llm_stream_fakes.py new file mode 100644 index 0000000000..fb2617b159 --- /dev/null +++ b/tests/llm_stream_fakes.py @@ -0,0 +1,102 @@ +"""Canned model streams for tests of the LLM client's stream readers, with no network. + +Streams are answered by httpx2's own `MockTransport`, so a reply is read through the same +response, content decoders and event parser it would be against a real server, and no socket is +opened. Hosts are `example.com`, as AGENTS.md requires of fixtures. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from typing import Any + +import httpx2 +import pytest + +SSE = "text/event-stream" +NDJSON = "application/x-ndjson" + + +def sse_data(payload: object) -> bytes: + """One server-sent event whose data is `payload`, as JSON unless it is a string.""" + text = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False) + return f"data: {text}\n\n".encode() + + +OPENAI_DONE = sse_data("[DONE]") + + +def openai_chunk(content: str | None = None, finish_reason: str | None = None) -> bytes: + """An OpenAI-compatible chat completion chunk with one choice.""" + delta = {"content": content} if content is not None else {} + return sse_data({"choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}]}) + + +def anthropic_event(event_type: str, **fields: Any) -> bytes: + """One Anthropic Messages stream event, named in both its `event:` line and its data.""" + data = json.dumps({"type": event_type, **fields}, ensure_ascii=False) + return f"event: {event_type}\ndata: {data}\n\n".encode() + + +def anthropic_text(text: str) -> bytes: + """An Anthropic text delta.""" + return anthropic_event( + "content_block_delta", index=0, delta={"type": "text_delta", "text": text} + ) + + +def ollama_line(content: str = "", **fields: Any) -> bytes: + """One line of an Ollama chat stream; `done` is false unless a field says otherwise.""" + payload = {"message": {"role": "assistant", "content": content}, "done": False, **fields} + return (json.dumps(payload, ensure_ascii=False) + "\n").encode() + + +class RecordedBody: + """A response body that records how many of its frames have been read.""" + + def __init__(self, frames: Sequence[bytes]) -> None: + self.frames = frames + self.read = 0 + + def __iter__(self) -> Iterator[bytes]: + for frame in self.frames: + self.read += 1 + yield frame + + +def reply(frames: Iterable[bytes], content_type: str = SSE, status: int = 200) -> httpx2.Response: + """A response whose body is produced frame by frame, as a server streams it.""" + return httpx2.Response(status, headers={"content-type": content_type}, content=iter(frames)) + + +@contextmanager +def streamed(frames: Iterable[bytes], content_type: str = SSE) -> Iterator[httpx2.Response]: + """An open streamed response to a POST, served by a MockTransport.""" + transport = httpx2.MockTransport(lambda request: reply(frames, content_type)) + with ( + httpx2.Client(transport=transport) as http_client, + http_client.stream("POST", "http://example.com/v1/chat/completions") as response, + ): + yield response + + +def route_client( + client: Any, + monkeypatch: pytest.MonkeyPatch, + handler: Callable[[httpx2.Request], httpx2.Response], +) -> list[httpx2.Request]: + """Send every request an LLMClient makes to `handler`; return the requests, in order.""" + sent: list[httpx2.Request] = [] + + def record(request: httpx2.Request) -> httpx2.Response: + sent.append(request) + return handler(request) + + transport = httpx2.MockTransport(record) + monkeypatch.setattr(client, "_shared_client", lambda: httpx2.Client(transport=transport)) + monkeypatch.setattr( + client, "_create_http_client", lambda timeout=None: httpx2.Client(transport=transport) + ) + return sent diff --git a/tests/test_ai_client_finish_reasons.py b/tests/test_ai_client_finish_reasons.py new file mode 100644 index 0000000000..4463161037 --- /dev/null +++ b/tests/test_ai_client_finish_reasons.py @@ -0,0 +1,170 @@ +"""Every model reply carries the reason it ended, read from its provider and never guessed.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, get_args + +import httpx2 +import pytest +from pydantic_ai.messages import FinishReason, ModelResponse, TextPart + +from devops_cli.ai.client import LLMClient, LLMResponse, RequestPriority +from devops_cli.config.constants import ( + CONST_ANTHROPIC_STOP_REASONS, + CONST_OLLAMA_DONE_REASONS, + CONST_OPENAI_FINISH_REASONS, + CONST_UNCACHED_FINISH_REASONS, +) +from devops_cli.config.settings import AIConfig +from devops_cli.models.ai import ChatMessage +from tests.llm_stream_fakes import route_client + +_PROMPT = [ChatMessage(role="user", content="hi")] + +# Each provider's stop values, as the issue lists them, and the reason each must become. +_STOP_VALUES: dict[str, list[tuple[str | None, FinishReason | None]]] = { + "openai": [ + ("stop", "stop"), + ("length", "length"), + ("tool_calls", "tool_call"), + ("function_call", "tool_call"), + ("content_filter", "content_filter"), + (None, None), + ], + "anthropic": [ + ("end_turn", "stop"), + ("stop_sequence", "stop"), + ("max_tokens", "length"), + ("model_context_window_exceeded", "length"), + ("tool_use", "tool_call"), + ("refusal", "content_filter"), + ("pause_turn", None), + (None, None), + ], + "ollama": [ + ("stop", "stop"), + ("length", "length"), + ("load", None), + ("unload", None), + (None, None), + ], +} + + +def _with(key: str, value: str | None) -> dict[str, str]: + """The provider's stop field, or no field at all when the value is absent.""" + return {key: value} if value is not None else {} + + +# A non-streamed reply body from each provider, carrying one stop value. +_REPLY_BODIES: dict[str, Callable[[str | None], dict[str, Any]]] = { + "openai": lambda value: { + "choices": [{"message": {"content": "ok"}, **_with("finish_reason", value)}] + }, + "anthropic": lambda value: { + "content": [{"type": "text", "text": "ok"}], + **_with("stop_reason", value), + }, + "ollama": lambda value: { + "message": {"content": "ok"}, + "done": True, + **_with("done_reason", value), + }, +} + +# Each provider's non-streamed request, which parses the reply. +_REQUESTS: dict[str, Callable[[LLMClient], LLMResponse]] = { + "openai": lambda client: client._openai_compat_messages("sys", _PROMPT), + "anthropic": lambda client: client._claude_messages("sys", _PROMPT), + "ollama": lambda client: client._ollama_request( + "http://example.com:11434", "sys", _PROMPT, think=False + ), +} + +_CONFIGS: dict[str, AIConfig] = { + "openai": AIConfig(provider="openai", model="gpt-test", api_base_url="http://example.com/v1"), + "anthropic": AIConfig( + provider="claude", model="claude-test", api_base_url="http://example.com" + ), + "ollama": AIConfig(provider="ollama", model="llama3", ollama_urls=["http://example.com:11434"]), +} + + +@pytest.mark.parametrize("provider", ["openai", "anthropic", "ollama"]) +def test_each_parser_reads_its_providers_stop_value( + provider: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify each non-streamed parser maps every stop value its provider sends, absent included.""" + table = _STOP_VALUES[provider] + bodies = iter([_REPLY_BODIES[provider](value) for value, _ in table]) + client = LLMClient( + _CONFIGS[provider].model_copy(update={"allow_private_network": True}), api_key="sk-test" + ) + route_client(client, monkeypatch, lambda request: httpx2.Response(200, json=next(bodies))) + + assert [(value, _REQUESTS[provider](client).finish_reason) for value, _ in table] == table + + +def test_every_mapped_reason_is_a_pydantic_ai_finish_reason() -> None: + """Verify each map yields only pydantic-ai's FinishReason values, or None for unknown.""" + known = {*get_args(FinishReason), None} + tables = (CONST_OPENAI_FINISH_REASONS, CONST_ANTHROPIC_STOP_REASONS, CONST_OLLAMA_DONE_REASONS) + + assert ( + [[value for value in table.values() if value not in known] for table in tables], + sorted(CONST_UNCACHED_FINISH_REASONS - known), + ) == ([[], [], []], []) + + +def test_the_reason_survives_conversion_both_ways() -> None: + """Verify `to_model_response` passes the reason on and `from_model_response` reads it.""" + filtered = ModelResponse(parts=[TextPart(content="ok")], finish_reason="content_filter") + + assert ( + LLMResponse("ok", finish_reason="length").to_model_response().finish_reason, + LLMResponse.from_model_response(filtered).finish_reason, + LLMResponse("ok").to_model_response().finish_reason, + ) == ("length", "content_filter", None) + + +@pytest.mark.parametrize( + ("reason", "cached"), + [("length", False), ("content_filter", False), ("error", False), ("stop", True), (None, True)], +) +def test_only_replies_that_ended_normally_are_cached( + reason: FinishReason | None, cached: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify a cut, filtered or failed reply is returned but not cached, so it is asked again.""" + provider_calls: list[str] = [] + + def provider( + _self: object, + _system: str, + _messages: list[ChatMessage], + *, + enable_thinking: bool = True, + priority: RequestPriority | str | None = None, + ) -> LLMResponse: + provider_calls.append(_system) + return LLMResponse("reply", prompt_tokens=3, completion_tokens=2, finish_reason=reason) + + monkeypatch.setattr(LLMClient, "_ollama_messages", provider) + monkeypatch.setattr("devops_cli.ai.spend.track_request_spend", lambda **kwargs: None) + client = LLMClient(AIConfig(provider="ollama", model="llama3")) + stored: list[str] = [] + store = client.cache.set + monkeypatch.setattr( + client.cache, "set", lambda **entry: (stored.append(entry["key"]), store(**entry))[1] + ) + + first = client.chat("sys", "user") + second = client.chat("sys", "user") + + assert (str(first), first.finish_reason, len(stored), len(provider_calls), second.cached) == ( + "reply", + reason, + 1 if cached else 0, + 1 if cached else 2, + cached, + ) diff --git a/tests/test_ai_client_providers_and_embeddings.py b/tests/test_ai_client_providers_and_embeddings.py index c7e9a4e5c1..af54b8431e 100644 --- a/tests/test_ai_client_providers_and_embeddings.py +++ b/tests/test_ai_client_providers_and_embeddings.py @@ -9,6 +9,7 @@ import httpx2 import pytest +from devops_cli.ai import context_budget from devops_cli.ai.benchmark.document_chunker import ( InMemoryDocumentTokenizer, load_test_document_corpus, @@ -21,11 +22,6 @@ AIClientError, LLMClient, LLMResponse, - _consume_streaming_lines, - _extract_claude_stream_chunk, - _extract_ollama_stream_chunk, - _extract_ollama_stream_tuple, - _extract_openai_stream_chunk, _is_json_error_payload, model_request, model_request_sync, @@ -33,8 +29,26 @@ validate_base_url, ) from devops_cli.ai.client.base import BaseLLMProviderMixin +from devops_cli.ai.client.streaming import ( + StreamFrame, + _claude_stream_frame, + _ollama_stream_frame, + _openai_stream_frame, + _read_event_stream, +) from devops_cli.config.settings import AIConfig from devops_cli.models.ai import ChatMessage +from tests.llm_stream_fakes import ( + NDJSON, + OPENAI_DONE, + anthropic_event, + anthropic_text, + ollama_line, + openai_chunk, + reply, + route_client, + streamed, +) @pytest.fixture(autouse=True) @@ -44,6 +58,16 @@ def _bypass_dns_validation(monkeypatch: pytest.MonkeyPatch) -> None: ) +def _quiet_stream_spend(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep a stream's spend estimate off the tokenizer and the ledger, neither under test.""" + monkeypatch.setattr(context_budget, "count_tokens", lambda text, *args, **kwargs: len(text)) + monkeypatch.setattr("devops_cli.ai.spend.track_request_spend", lambda **kwargs: None) + + +def _sse_event(data: str) -> httpx2.ServerSentEvent: + return httpx2.ServerSentEvent(data=data) + + def _make_resp(status_code: int = 200, json_data: dict | None = None) -> httpx2.Response: req = httpx2.Request("POST", "http://localhost") return httpx2.Response(status_code, request=req, json=json_data) @@ -180,42 +204,37 @@ def test_embedding_runner_similarity_and_ndcg() -> None: def test_chunk_extractors_and_stream_helpers() -> None: - """Test chunk extractor functions for Ollama, Claude, and OpenAI.""" - from devops_cli.ai.client import ( - _extract_claude_stream_chunk, - _extract_ollama_stream_chunk, - _extract_openai_stream_chunk, - _is_json_error_payload, - ) - - # 1. Ollama chunk extraction - assert _extract_ollama_stream_chunk('{"message": {"content": "hello"}}') == "hello" + """Test stream frame parsers for Ollama, Claude, and OpenAI, and the error payload check.""" + # 1. Ollama frames assert ( - _extract_ollama_stream_chunk('{"message": {"thinking": "pondering"}}') - == "pondering" - ) - assert _extract_ollama_stream_chunk("") is None - assert _extract_ollama_stream_chunk("invalid json") is None - - # 2. Claude chunk extraction - c_chunk, c_done = _extract_claude_stream_chunk( - 'data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "claude text"}}' - ) - assert c_chunk == "claude text" - assert c_done is False - - _, c_done_true = _extract_claude_stream_chunk("data: [DONE]") - assert c_done_true is True - - # 3. OpenAI chunk extraction - o_chunk, o_done = _extract_openai_stream_chunk( - 'data: {"choices": [{"delta": {"content": "openai text"}}]}' - ) - assert o_chunk == "openai text" - assert o_done is False + _ollama_stream_frame('{"message": {"content": "hello"}}'), + _ollama_stream_frame('{"message": {"thinking": "pondering"}}'), + _ollama_stream_frame(""), + _ollama_stream_frame("invalid json"), + ) == ( + StreamFrame(chunk="hello"), + StreamFrame(chunk="pondering"), + StreamFrame(), + StreamFrame(), + ) + + # 2. Claude frames: Anthropic ends a stream with message_stop and never sends [DONE] + assert ( + _claude_stream_frame( + _sse_event( + '{"type": "content_block_delta", ' + '"delta": {"type": "text_delta", "text": "claude text"}}' + ) + ), + _claude_stream_frame(_sse_event('{"type": "message_stop"}')), + _claude_stream_frame(_sse_event("[DONE]")), + ) == (StreamFrame(chunk="claude text"), StreamFrame(complete=True, last=True), StreamFrame()) - _, o_done_true = _extract_openai_stream_chunk("data: [DONE]") - assert o_done_true is True + # 3. OpenAI frames + assert ( + _openai_stream_frame(_sse_event('{"choices": [{"delta": {"content": "openai text"}}]}')), + _openai_stream_frame(_sse_event("[DONE]")), + ) == (StreamFrame(chunk="openai text"), StreamFrame(complete=True, last=True)) # 4. JSON error payload detector assert _is_json_error_payload('{"error": "model not found"}') is True @@ -299,19 +318,13 @@ def test_llm_client_streaming_and_error_branches(monkeypatch: pytest.MonkeyPatch client._read_limited_json(mock_bad_json) # 4. Stream max bytes exceeded - class DummyStreamResp: - def iter_lines(self): - for _ in range(100): - yield "data: huge line of stream tokens" - - with pytest.raises(AIClientError, match="exceeded maximum stream size"): - gen = _consume_streaming_lines( - DummyStreamResp(), # type: ignore[arg-type] - lambda line: (line, False), - "TestProvider", - max_stream_bytes=50, + with ( + streamed([openai_chunk("huge line of stream tokens")] * 100) as response, + pytest.raises(AIClientError, match="exceeded maximum stream size"), + ): + list( + _read_event_stream(response, _openai_stream_frame, "TestProvider", max_stream_bytes=50) ) - list(gen) # 5. Ollama semaphore and active tracking with client._track_ollama_url("http://localhost:11434", max_parallel=2): @@ -325,37 +338,14 @@ def iter_lines(self): allow_private_network=True, ) claude_client = LLMClient(claude_cfg) - - class MockStreamContext: - def __init__(self, lines): - self._lines = lines - self.status_code = 200 - - def __enter__(self): - return self - - def __exit__(self, *args): - pass - - def iter_lines(self): - yield from self._lines - - def raise_for_status(self): - pass - - monkeypatch.setattr( - httpx2.Client, - "stream", - lambda self, method, url, **kwargs: MockStreamContext( - [ - 'data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "hello "}}', - 'data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "world"}}', - "data: [DONE]", - ] - ), - ) - streamed = list(claude_client.chat_stream("system", "user")) - assert "".join(streamed) == "hello world" + _quiet_stream_spend(monkeypatch) + claude_frames = [ + anthropic_text("hello "), + anthropic_text("world"), + anthropic_event("message_stop"), + ] + route_client(claude_client, monkeypatch, lambda request: reply(claude_frames)) + assert "".join(claude_client.chat_stream("system", "user")) == "hello world" # 7. OpenAI models listing openai_cfg = AIConfig( @@ -619,39 +609,37 @@ def test_read_limited_json_errors() -> None: def test_streaming_extractors_edge_cases() -> None: - assert _extract_ollama_stream_chunk("") is None - assert _extract_ollama_stream_chunk("invalid json") is None assert ( - _extract_ollama_stream_chunk('{"message": {"thinking": "reasoning"}}') - == "reasoning" - ) - assert _extract_ollama_stream_chunk('{"message": {"content": "token"}}') == "token" - - tok, done = _extract_ollama_stream_tuple('{"message": {"thinking": "th"}}') - assert (tok, done) == ("th", False) - assert _extract_ollama_stream_tuple("invalid") == (None, False) - - chunk, is_done = _extract_claude_stream_chunk("") - assert (chunk, is_done) == (None, False) - chunk, is_done = _extract_claude_stream_chunk("data: [DONE]") - assert (chunk, is_done) == (None, True) - chunk, is_done = _extract_claude_stream_chunk("data: invalid json") - assert (chunk, is_done) == (None, False) - chunk, is_done = _extract_claude_stream_chunk( - 'data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "token"}}' - ) - assert (chunk, is_done) == ("token", False) - - chunk, is_done = _extract_openai_stream_chunk("") - assert (chunk, is_done) == (None, False) - chunk, is_done = _extract_openai_stream_chunk("data: [DONE]") - assert (chunk, is_done) == (None, True) - chunk, is_done = _extract_openai_stream_chunk("data: invalid json") - assert (chunk, is_done) == (None, False) - chunk, is_done = _extract_openai_stream_chunk( - 'data: {"choices": [{"delta": {"content": "token"}}] }' + _ollama_stream_frame(""), + _ollama_stream_frame("invalid json"), + _ollama_stream_frame('{"message": {"thinking": "reasoning"}}'), + _ollama_stream_frame('{"message": {"content": "token"}}'), + _claude_stream_frame(_sse_event("")), + _claude_stream_frame(_sse_event("[DONE]")), + _claude_stream_frame(_sse_event("invalid json")), + _claude_stream_frame( + _sse_event( + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "token"}}' + ) + ), + _openai_stream_frame(_sse_event("")), + _openai_stream_frame(_sse_event("[DONE]")), + _openai_stream_frame(_sse_event("invalid json")), + _openai_stream_frame(_sse_event('{"choices": [{"delta": {"content": "token"}}] }')), + ) == ( + StreamFrame(), + StreamFrame(), + StreamFrame(chunk="reasoning"), + StreamFrame(chunk="token"), + StreamFrame(), + StreamFrame(), + StreamFrame(), + StreamFrame(chunk="token"), + StreamFrame(), + StreamFrame(complete=True, last=True), + StreamFrame(), + StreamFrame(chunk="token"), ) - assert (chunk, is_done) == ("token", False) def test_ollama_streaming_and_failover(monkeypatch: pytest.MonkeyPatch) -> None: @@ -662,62 +650,33 @@ def test_ollama_streaming_and_failover(monkeypatch: pytest.MonkeyPatch) -> None: allow_private_network=True, ) client_ollama = LLMClient(ollama_cfg) + _quiet_stream_spend(monkeypatch) + ollama_frames = [ollama_line("Ollama "), ollama_line("stream", done=True)] # 1. Successful stream - class MockOllamaStreamResponse: - status_code = 200 - - def __enter__(self) -> MockOllamaStreamResponse: - return self - - def __exit__(self, *args: Any) -> None: - pass - - def raise_for_status(self) -> None: - pass - - def iter_lines(self) -> list[str]: - return [ - '{"message": {"content": "Ollama "}, "done": false}', - '{"message": {"content": "stream"}, "done": true}', - ] - - monkeypatch.setattr(httpx2.Client, "stream", lambda *args, **kwargs: MockOllamaStreamResponse()) + route_client(client_ollama, monkeypatch, lambda request: reply(ollama_frames, NDJSON)) tokens = list(client_ollama.chat_stream("system", "prompt")) assert "".join(tokens) == "Ollama stream" # 2. Failover on connection error - call_count = 0 - - def mock_failover_stream(*args: Any, **kwargs: Any) -> MockOllamaStreamResponse: - nonlocal call_count - call_count += 1 - if call_count == 1: - raise httpx2.ConnectError("Server 1 down") - return MockOllamaStreamResponse() + def failover_stream(request: httpx2.Request) -> httpx2.Response: + if len(failover_sent) == 1: + raise httpx2.ConnectError("Server 1 down", request=request) + return reply(ollama_frames, NDJSON) - monkeypatch.setattr(httpx2.Client, "stream", mock_failover_stream) + failover_sent = route_client(client_ollama, monkeypatch, failover_stream) tokens_failover = list(client_ollama.chat_stream("system", "prompt")) - assert "".join(tokens_failover) == "Ollama stream" + assert ("".join(tokens_failover), len(failover_sent)) == ("Ollama stream", 2) # 3. Failover on HTTP 404 model not found (streaming) - call_404 = 0 - - def mock_404_stream(*args: Any, **kwargs: Any) -> MockOllamaStreamResponse: - nonlocal call_404 - call_404 += 1 - if call_404 == 1: - resp_404 = httpx2.Response( - 404, - text='{"error":"model \'llama3\' not found"}', - request=httpx2.Request("POST", "http://localhost:11434/api/chat"), - ) - raise httpx2.HTTPStatusError("Not Found", request=resp_404.request, response=resp_404) - return MockOllamaStreamResponse() + def not_found_stream(request: httpx2.Request) -> httpx2.Response: + if len(not_found_sent) == 1: + return httpx2.Response(404, text='{"error":"model \'llama3\' not found"}') + return reply(ollama_frames, NDJSON) - monkeypatch.setattr(httpx2.Client, "stream", mock_404_stream) + not_found_sent = route_client(client_ollama, monkeypatch, not_found_stream) tokens_404 = list(client_ollama.chat_stream("system", "prompt")) - assert "".join(tokens_404) == "Ollama stream" + assert ("".join(tokens_404), len(not_found_sent)) == ("Ollama stream", 2) # 4. Failover on HTTP 404 model not found (non-streaming) call_post_404 = 0 @@ -749,30 +708,9 @@ def test_copilot_and_openai_streaming_and_errors(monkeypatch: pytest.MonkeyPatch reasoning_effort="high", ) client_copilot = LLMClient(copilot_cfg) - - class MockCopilotStreamResponse: - status_code = 200 - headers: dict[str, str] = {} - - def __enter__(self) -> MockCopilotStreamResponse: - return self - - def __exit__(self, *args: Any) -> None: - pass - - def raise_for_status(self) -> None: - pass - - def iter_lines(self) -> list[str]: - return [ - 'data: {"choices": [{"delta": {"content": "Copilot "}}]}', - 'data: {"choices": [{"delta": {"content": "stream"}}]}', - "data: [DONE]", - ] - - monkeypatch.setattr( - httpx2.Client, "stream", lambda *args, **kwargs: MockCopilotStreamResponse() - ) + _quiet_stream_spend(monkeypatch) + copilot_frames = [openai_chunk("Copilot "), openai_chunk("stream"), OPENAI_DONE] + route_client(client_copilot, monkeypatch, lambda request: reply(copilot_frames)) tokens = list(client_copilot.chat_stream("system", "prompt")) assert "".join(tokens) == "Copilot stream" @@ -810,28 +748,15 @@ def test_claude_streaming_and_errors(monkeypatch: pytest.MonkeyPatch) -> None: allow_private_network=True, ) client_claude = LLMClient(claude_cfg) + _quiet_stream_spend(monkeypatch) # 1. Streaming - class MockClaudeStreamResponse: - status_code = 200 - - def __enter__(self) -> MockClaudeStreamResponse: - return self - - def __exit__(self, *args: Any) -> None: - pass - - def raise_for_status(self) -> None: - pass - - def iter_lines(self) -> list[str]: - return [ - 'data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Claude "}}', - 'data: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "stream"}}', - "data: [DONE]", - ] - - monkeypatch.setattr(httpx2.Client, "stream", lambda *args, **kwargs: MockClaudeStreamResponse()) + claude_frames = [ + anthropic_text("Claude "), + anthropic_text("stream"), + anthropic_event("message_stop"), + ] + route_client(client_claude, monkeypatch, lambda request: reply(claude_frames)) tokens = list(client_claude.chat_stream("system", "prompt")) assert "".join(tokens) == "Claude stream" diff --git a/tests/test_ai_client_telemetry.py b/tests/test_ai_client_telemetry.py index e192bf0371..31536e60f8 100644 --- a/tests/test_ai_client_telemetry.py +++ b/tests/test_ai_client_telemetry.py @@ -14,6 +14,7 @@ from devops_cli.models.ai import ChatMessage from devops_cli.telemetry.semconv import load_genai_snapshot from devops_cli.telemetry.tracer import get_tracer, reset_tracer +from tests.llm_stream_fakes import OPENAI_DONE, openai_chunk, reply, route_client INFERENCE_REQUIRED = load_genai_snapshot()["spans"]["gen_ai.inference.client"]["required"] @@ -235,3 +236,58 @@ def test_provider_names_follow_the_conventions_well_known_values() -> None: "copilot", "github_copilot", ] + + +@pytest.mark.parametrize(("reason", "expected"), [("length", ["length"]), (None, None)]) +def test_the_dispatch_span_names_the_reason_the_reply_ended( + monkeypatch: pytest.MonkeyPatch, + sent_spans: list[dict[str, Any]], + reason: str | None, + expected: list[str] | None, +) -> None: + """A reply's reason is on ai.llm.dispatch only; an unknown one sets no attribute.""" + + def cut_reply(*args: Any, **kwargs: Any) -> LLMResponse: + return LLMResponse( + "OK", + backend_info="ollama (example.com:11434)", + prompt_tokens=12, + completion_tokens=3, + finish_reason=reason, + ) + + monkeypatch.setattr(LLMClient, "_ollama_messages", cut_reply) + monkeypatch.setattr("devops_cli.ai.spend.track_request_spend", lambda **kwargs: None) + cfg = AIConfig(provider="ollama", model="test-model", ollama_urls=["http://example.com:11434"]) + + LLMClient(cfg).chat("system instructions", "hello", use_cache=False) + + (dispatch,) = _spans(sent_spans, "ai.llm.dispatch") + (chat,) = _spans(sent_spans, "ai.llm.chat") + key = "gen_ai.response.finish_reasons" + assert (_attributes(dispatch).get(key), key in _attributes(chat)) == (expected, False) + + +def test_a_complete_stream_names_the_reason_on_the_stream_span( + monkeypatch: pytest.MonkeyPatch, sent_spans: list[dict[str, Any]] +) -> None: + """The reason in a stream's final frames is on ai.llm.stream.""" + monkeypatch.setattr(context_budget, "count_tokens", lambda text, *args, **kwargs: len(text)) + monkeypatch.setattr("devops_cli.ai.spend.track_request_spend", lambda **kwargs: None) + config = AIConfig( + provider="openai", + model="gpt-test", + api_base_url="http://example.com/v1", + allow_private_network=True, + ) + client = LLMClient(config, api_key="sk-test") + frames = [openai_chunk("Hel"), openai_chunk("lo", "length"), OPENAI_DONE] + route_client(client, monkeypatch, lambda request: reply(frames)) + + chunks = list(client.chat_messages_stream("sys", [ChatMessage(role="user", content="hi")])) + + (stream,) = _spans(sent_spans, "ai.llm.stream") + assert (chunks, _attributes(stream).get("gen_ai.response.finish_reasons")) == ( + ["Hel", "lo"], + ["length"], + ) diff --git a/tests/test_ai_cmd.py b/tests/test_ai_cmd.py index 0e6ba0d105..712d96ce7f 100644 --- a/tests/test_ai_cmd.py +++ b/tests/test_ai_cmd.py @@ -574,3 +574,24 @@ def test_ai_token_count_route_pipeline_bundle(tmp_path: Path) -> None: res_bundle = runner.invoke(ai_app, ["bundle-models"]) assert res_bundle.exit_code == 0 assert "Bundled 2 model(s)" in res_bundle.output + + +def test_a_cut_stream_stores_no_reply_in_chat_memory() -> None: + """Verify a stream that raises after its first chunk leaves no assistant entry in memory.""" + from devops_cli.ai.agents.memory import AgentMemory + from devops_cli.ai.client import AIClientError + from devops_cli.commands.ai import _stream_interactive_chat_turn + + def cut_stream(*args: Any, **kwargs: Any) -> Any: + yield "Partial " + raise AIClientError("Provider stream ended before its final frame.") + + client = MagicMock(chat_messages_stream=cut_stream) + agent = MagicMock(memory=AgentMemory()) + agent.memory.add_interaction("user", "Explain the deploy.") + agent._build_system_prompt_with_tools.return_value = "You are an architect." + + with pytest.raises(AIClientError, match="before its final frame"): + _stream_interactive_chat_turn(client, agent, False, "Explain the deploy.") + + assert [entry.role for entry in agent.memory.entries] == ["user"] diff --git a/tests/test_ai_served_by.py b/tests/test_ai_served_by.py index b01103bb64..c06e7271f6 100644 --- a/tests/test_ai_served_by.py +++ b/tests/test_ai_served_by.py @@ -163,9 +163,8 @@ def test_streamed_response_records_its_serving_backend( sse = b'data: {"choices": [{"delta": {"content": "OK"}}]}\n\ndata: [DONE]\n\n' def fake_send(self: Any, request: httpx2.Request, **kwargs: Any) -> httpx2.Response: - return httpx2.Response( - 200, headers={SERVED_BY_HEADER: OLLAMA}, content=sse, request=request - ) + headers = {SERVED_BY_HEADER: OLLAMA, "content-type": "text/event-stream"} + return httpx2.Response(200, headers=headers, content=sse, request=request) monkeypatch.setattr(httpx2.Client, "send", fake_send) diff --git a/tests/test_ai_spend_dispatch.py b/tests/test_ai_spend_dispatch.py index 251d37be92..4ce013e862 100644 --- a/tests/test_ai_spend_dispatch.py +++ b/tests/test_ai_spend_dispatch.py @@ -3,6 +3,8 @@ from __future__ import annotations import asyncio +import sqlite3 +from pathlib import Path from typing import Any import httpx2 @@ -11,11 +13,21 @@ from pydantic_ai.usage import RequestUsage import devops_cli.ai.spend as spend_mod -from devops_cli.ai.client import LLMClient +from devops_cli.ai import context_budget +from devops_cli.ai.client import AIClientError, LLMClient, LLMResponse, RequestPriority from devops_cli.ai.direct import direct_model_request, direct_model_request_sync +from devops_cli.ai.spend import ledger as ledger_module +from devops_cli.ai.spend.ledger import SpendLedger, observe_llm_calls from devops_cli.ai.spend.models import SpendRecord from devops_cli.config.settings import AIConfig from devops_cli.models.ai import ChatMessage +from tests.llm_stream_fakes import ( + NDJSON, + OPENAI_DONE, + openai_chunk, + reply, + route_client, +) @pytest.fixture(autouse=True) @@ -99,30 +111,12 @@ def mock_track_spend(**kwargs: Any) -> SpendRecord: monkeypatch.setattr(spend_mod, "track_request_spend", mock_track_spend) - # Mock streaming response from Ollama + # Streaming response from Ollama stream_lines = [ b'{"message": {"content": "Hello "}, "done": false}\n', b'{"message": {"content": "world!"}, "done": true, "prompt_eval_count": 8, "eval_count": 4}\n', ] - class MockStreamResponse: - status_code = 200 - - def raise_for_status(self) -> None: - pass - - def iter_lines(self) -> Any: - for line in stream_lines: - yield line.decode("utf-8") - - def __enter__(self) -> MockStreamResponse: - return self - - def __exit__(self, *args: object) -> None: - pass - - monkeypatch.setattr(httpx2.Client, "stream", lambda self, *args, **kwargs: MockStreamResponse()) - cfg = AIConfig( provider="ollama", model="llama3:8b", @@ -130,6 +124,7 @@ def __exit__(self, *args: object) -> None: allow_private_network=True, ) client = LLMClient(cfg) + route_client(client, monkeypatch, lambda request: reply(stream_lines, NDJSON)) generator = client.chat_messages_stream( system="sys", messages=[ChatMessage(role="user", content="stream query")], @@ -216,3 +211,165 @@ async def async_req(*args: Any, **kwargs: Any) -> Any: 40, 60, ) + + +# ── Why a reply ended, from the provider to the ledger and its observers ────────────────────── + + +@pytest.fixture +def spend_ledger(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SpendLedger: + """A fresh ledger that every recorded call in the test writes to.""" + ledger = SpendLedger(db_path=tmp_path / "spend.db") + monkeypatch.setattr(ledger_module, "_GLOBAL_LEDGER", ledger) + return ledger + + +def _ledger_rows(ledger: SpendLedger) -> list[tuple[str, str | None]]: + with sqlite3.connect(ledger.db_path) as conn: + return conn.execute( + "SELECT request_type, finish_reason FROM ai_spend_records ORDER BY id" + ).fetchall() + + +def _cut_reply( + _self: object, + _system: str, + _messages: list[ChatMessage], + *, + enable_thinking: bool = True, + priority: RequestPriority | str | None = None, +) -> LLMResponse: + return LLMResponse( + "partial", prompt_tokens=12, completion_tokens=8, total_tokens=20, finish_reason="length" + ) + + +def test_a_chat_reply_reaches_observers_and_the_ledger_with_its_finish_reason( + monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger +) -> None: + """Verify `LLMClient.chat` hands the reply's reason to the observer and the ledger row.""" + monkeypatch.setattr(LLMClient, "_ollama_messages", _cut_reply) + client = LLMClient(AIConfig(provider="ollama", model="llama3:8b"), cache_enabled=False) + seen: list[dict[str, Any]] = [] + + with observe_llm_calls(seen.append): + client.chat("system", "user", use_cache=False) + + assert ([call["finish_reason"] for call in seen], _ledger_rows(spend_ledger)) == ( + ["length"], + [("chat_dispatch", "length")], + ) + + +def test_a_direct_request_hands_its_finish_reason_to_observers( + monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger +) -> None: + """Verify both direct requests record the `ModelResponse` finish reason.""" + cut = ModelResponse( + parts=[TextPart(content="partial")], + usage=RequestUsage(input_tokens=40, output_tokens=60), + finish_reason="length", + ) + + async def async_request(*args: Any, **kwargs: Any) -> ModelResponse: + return cut + + monkeypatch.setattr( + "devops_cli.ai.pydantic_ai_bridge.resolve_pydantic_ai_model", + lambda m, **kwargs: "test-model", + ) + monkeypatch.setattr("devops_cli.ai.direct.model_request_sync", lambda *args, **kwargs: cut) + monkeypatch.setattr("devops_cli.ai.direct.model_request", async_request) + seen: list[dict[str, Any]] = [] + + with observe_llm_calls(seen.append): + direct_model_request_sync("Sync test prompt", model="test-model") + asyncio.run(direct_model_request("Async test prompt", model="test-model")) + + assert [(call["request_type"], call["finish_reason"]) for call in seen] == [ + ("direct_sync", "length"), + ("direct_async", "length"), + ] + + +def _stream_client(monkeypatch: pytest.MonkeyPatch) -> LLMClient: + # The stream's spend estimate counts tokens; loading the tokenizer is not under test. + monkeypatch.setattr(context_budget, "count_tokens", lambda text, *args, **kwargs: len(text)) + config = AIConfig( + provider="openai", + model="gpt-test", + api_base_url="http://example.com/v1", + allow_private_network=True, + ) + return LLMClient(config, api_key="sk-test", cache_enabled=False) + + +def _stream_reply(client: LLMClient) -> tuple[list[str], list[dict[str, Any]], str | None]: + """Stream one reply: the chunks it yielded, the calls observers saw and any error.""" + chunks: list[str] = [] + seen: list[dict[str, Any]] = [] + with observe_llm_calls(seen.append): + try: + for chunk in client.chat_messages_stream( + "sys", [ChatMessage(role="user", content="hi")] + ): + chunks.append(chunk) + except AIClientError as exc: + return chunks, seen, type(exc).__name__ + return chunks, seen, None + + +def test_a_complete_stream_records_its_finish_reason( + monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger +) -> None: + """Verify a stream that reaches its final frame writes one row with its reason.""" + client = _stream_client(monkeypatch) + frames = [openai_chunk("Hel"), openai_chunk("lo", "length"), OPENAI_DONE] + route_client(client, monkeypatch, lambda request: reply(frames)) + + chunks, seen, error = _stream_reply(client) + + assert (chunks, [c["finish_reason"] for c in seen], error, _ledger_rows(spend_ledger)) == ( + ["Hel", "lo"], + ["length"], + None, + [("stream", "length")], + ) + + +def test_a_stream_failing_after_output_records_its_spend_as_an_error( + monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger +) -> None: + """Verify tokens yielded before a failure are recorded with reason `error`, then it raises.""" + client = _stream_client(monkeypatch) + route_client(client, monkeypatch, lambda request: reply([openai_chunk("Hel")])) + + chunks, seen, error = _stream_reply(client) + + assert (chunks, [c["finish_reason"] for c in seen], error, _ledger_rows(spend_ledger)) == ( + ["Hel"], + ["error"], + "AIClientError", + [("stream", "error")], + ) + + +def _refuse_connection(request: httpx2.Request) -> httpx2.Response: + raise httpx2.ConnectError("connection refused", request=request) + + +def _server_error(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response(500, json={"error": {"message": "internal error"}}) + + +@pytest.mark.parametrize( + "handler", [_refuse_connection, _server_error], ids=["connect", "http-500"] +) +def test_a_stream_failing_before_its_first_chunk_records_nothing( + monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger, handler: Any +) -> None: + """Verify a stream no provider served writes no row and notifies no observer.""" + client = _stream_client(monkeypatch) + route_client(client, monkeypatch, handler) + + assert (_stream_reply(client), _ledger_rows(spend_ledger)) == (([], [], "AIClientError"), []) diff --git a/tests/test_ai_spend_ledger.py b/tests/test_ai_spend_ledger.py index 1134f22c9e..38b7d25c5c 100644 --- a/tests/test_ai_spend_ledger.py +++ b/tests/test_ai_spend_ledger.py @@ -8,7 +8,7 @@ import pytest -from devops_cli.ai.spend.ledger import SpendLedger, track_request_spend +from devops_cli.ai.spend.ledger import SpendLedger, observe_llm_calls, track_request_spend def test_spend_ledger_schema_and_wal_initialization(tmp_path: Path) -> None: @@ -483,6 +483,87 @@ def test_spend_ledger_iso_date_filtering(tmp_path: Path) -> None: assert (report_7d.total_requests, report_all.total_requests) == (1, 2) +# The ledger schema before the finish_reason column existed. +_SCHEMA_BEFORE_FINISH_REASON = """ +CREATE TABLE ai_spend_records ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp TEXT NOT NULL, + provider TEXT NOT NULL, + server TEXT NOT NULL, + backend_info TEXT, + served_by TEXT, + model TEXT NOT NULL, + prompt_tokens INTEGER NOT NULL DEFAULT 0, + completion_tokens INTEGER NOT NULL DEFAULT 0, + total_tokens INTEGER NOT NULL DEFAULT 0, + cost_usd REAL NOT NULL DEFAULT 0.0, + cached INTEGER NOT NULL DEFAULT 0, + request_type TEXT NOT NULL DEFAULT 'chat', + duration_seconds REAL NOT NULL DEFAULT 0.0, + stage TEXT +); +""" + + +def _columns(db_path: Path) -> set[str]: + with sqlite3.connect(db_path) as conn: + return {row[1] for row in conn.execute("PRAGMA table_info(ai_spend_records);")} + + +def _finish_reasons(db_path: Path) -> list[tuple[str, str | None]]: + with sqlite3.connect(db_path) as conn: + return conn.execute( + "SELECT model, finish_reason FROM ai_spend_records ORDER BY id" + ).fetchall() + + +def test_a_ledger_records_each_replys_finish_reason(tmp_path: Path) -> None: + """Verify a new ledger has the column, and a recorded reason reaches the row and observers.""" + ledger = SpendLedger(db_path=tmp_path / "spend.db") + seen: list[dict[str, object]] = [] + + with observe_llm_calls(seen.append): + record = track_request_spend( + provider="ollama", + model="llama3:8b", + server="localhost:11434", + prompt_tokens=10, + completion_tokens=5, + finish_reason="length", + ledger=ledger, + ) + + assert ( + "finish_reason" in _columns(ledger.db_path), + record.finish_reason if record else None, + [call["finish_reason"] for call in seen], + _finish_reasons(ledger.db_path), + ) == (True, "length", ["length"], [("llama3:8b", "length")]) + + +def test_an_existing_ledger_gains_the_finish_reason_column(tmp_path: Path) -> None: + """Verify a ledger written before finish_reason existed keeps its rows and records it.""" + db_path = tmp_path / "spend.db" + with sqlite3.connect(db_path) as conn: + conn.execute(_SCHEMA_BEFORE_FINISH_REASON) + conn.execute( + "INSERT INTO ai_spend_records (timestamp, provider, server, model) " + "VALUES ('2026-09-01T00:00:00+00:00', 'ollama', 'local', 'qwen')" + ) + + SpendLedger(db_path=db_path).record_request( + provider="ollama", + server="local", + model="llama3:8b", + prompt_tokens=10, + completion_tokens=5, + cost_usd=0.0, + finish_reason="stop", + ) + + assert _finish_reasons(db_path) == [("qwen", None), ("llama3:8b", "stop")] + + def test_spend_ledger_init_db_duplicate_column_tolerance(tmp_path: Path) -> None: """Verify concurrent schema migrations tolerate duplicate column errors.""" db_path = tmp_path / "race_spend.db" @@ -494,7 +575,7 @@ def test_spend_ledger_init_db_duplicate_column_tolerance(tmp_path: Path) -> None with sqlite3.connect(db_path) as conn: cols = {row[1] for row in conn.execute("PRAGMA table_info(ai_spend_records);").fetchall()} - assert ("served_by" in cols, "stage" in cols) == (True, True) + assert ("served_by" in cols, "stage" in cols, "finish_reason" in cols) == (True, True, True) def test_spend_ledger_export_prometheus_with_report(tmp_path: Path) -> None: diff --git a/tests/test_ai_streaming.py b/tests/test_ai_streaming.py index f70635cd08..f047abb2f0 100644 --- a/tests/test_ai_streaming.py +++ b/tests/test_ai_streaming.py @@ -2,28 +2,47 @@ from __future__ import annotations +import contextlib import json +from collections.abc import Iterable, Iterator from typing import Any -from unittest.mock import MagicMock import httpx2 import pytest +from devops_cli.ai import context_budget +from devops_cli.ai.client import LLMClient from devops_cli.ai.client.models import AIClientError +from devops_cli.ai.client.network import stream_finish_reason from devops_cli.ai.client.streaming import ( + StreamFrame, StreamingReasoningSanitizer, StreamingTokenProcessor, - _consume_streaming_lines, - _extract_claude_stream_chunk, - _extract_ollama_stream_chunk, - _extract_ollama_stream_tuple, - _extract_openai_stream_chunk, - _extract_stream_chunk, + _claude_stream_frame, _find_suffix_overlap, - _read_response_lines, + _ollama_stream_frame, + _openai_stream_frame, + _read_event_stream, + _read_ndjson_stream, ) from devops_cli.ai.review.runner import _review_to_markdown from devops_cli.ai.thinking_stream import ThinkingStreamProcessor +from devops_cli.config.settings import AIConfig +from devops_cli.models.ai import ChatMessage +from tests.llm_stream_fakes import ( + NDJSON, + OPENAI_DONE, + SSE, + RecordedBody, + anthropic_event, + anthropic_text, + ollama_line, + openai_chunk, + reply, + route_client, + sse_data, + streamed, +) class TestSuffixOverlap: @@ -224,151 +243,96 @@ def test_feed_exceeds_max_stream_bytes(self) -> None: proc.feed("B" * 20) -class TestProviderChunkExtractors: - """Test suite for Ollama, Claude, and OpenAI stream line parsers.""" - - def test_extract_ollama_content_and_thinking(self) -> None: - """Verify Ollama extraction handles message.content and message.thinking.""" - line_content = json.dumps({"message": {"content": "Hello Ollama"}}) - line_thinking = json.dumps({"message": {"thinking": "Deep Ollama thoughts"}}) - line_empty = "" - - c_text = _extract_ollama_stream_chunk(line_content) - c_think = _extract_ollama_stream_chunk(line_thinking) - c_empty = _extract_ollama_stream_chunk(line_empty) - c_tuple = _extract_ollama_stream_tuple(line_content) - - assert (c_text, c_think, c_empty, c_tuple) == ( - "Hello Ollama", - "Deep Ollama thoughts", - None, - ("Hello Ollama", False), - ) - - def test_extract_claude_sse_chunks(self) -> None: - """Verify Claude SSE parser handles text_delta, thinking_delta, and DONE.""" - line_text = "data: " + json.dumps( - {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Claude text"}} - ) - line_think = "data: " + json.dumps( - { - "type": "content_block_delta", - "delta": {"type": "thinking_delta", "thinking": "Claude thoughts"}, - } - ) - line_done = "data: [DONE]" - - res_text = _extract_claude_stream_chunk(line_text) - res_think = _extract_claude_stream_chunk(line_think) - res_done = _extract_claude_stream_chunk(line_done) - - assert (res_text, res_think, res_done) == ( - ("Claude text", False), - ("Claude thoughts", False), - (None, True), - ) - - def test_extract_openai_sse_chunks(self) -> None: - """Verify OpenAI SSE parser handles content, reasoning_content, and DONE.""" - line_content = "data: " + json.dumps({"choices": [{"delta": {"content": "OpenAI answer"}}]}) - line_reasoning = "data: " + json.dumps( - {"choices": [{"delta": {"reasoning_content": "OpenAI reasoning"}}]} - ) - line_done = "data: [DONE]" - - res_content = _extract_openai_stream_chunk(line_content) - res_reasoning = _extract_openai_stream_chunk(line_reasoning) - res_done = _extract_openai_stream_chunk(line_done) - - assert (res_content, res_reasoning, res_done) == ( - ("OpenAI answer", False), - ("OpenAI reasoning", False), - (None, True), - ) - - def test_extract_stream_chunk_unified_dispatcher(self) -> None: - """Verify _extract_stream_chunk routes properly to provider parser.""" - line_claude = "data: " + json.dumps( - {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hi"}} - ) - line_openai = "data: " + json.dumps({"choices": [{"delta": {"content": "Hey"}}]}) - line_ollama = json.dumps({"message": {"content": "Yo"}}) - - assert ( - _extract_stream_chunk(line_claude, "claude"), - _extract_stream_chunk(line_openai, "openai"), - _extract_stream_chunk(line_ollama, "ollama"), - ) == (("Hi", False), ("Hey", False), ("Yo", False)) - - -class TestConsumeStreamingLines: - """Test suite for bounded line consumption and reconnection handling.""" - - def test_consume_streaming_lines_success(self) -> None: - """Verify _consume_streaming_lines yields parsed lines within size limit.""" - mock_resp = MagicMock() - mock_resp.iter_lines.return_value = ["line1", "line2"] - - def extractor(line: str) -> tuple[str, bool]: - return (f"{line}_parsed", False) - - tokens = list(_consume_streaming_lines(mock_resp, extractor, "TestProvider")) - - assert tokens == ["line1_parsed", "line2_parsed"] - - def test_consume_streaming_lines_size_exceeded(self) -> None: - """Verify _consume_streaming_lines raises when max_stream_bytes exceeded.""" - mock_resp = MagicMock() - mock_resp.iter_lines.return_value = ["very_long_line" * 10] - - def extractor(line: str) -> tuple[str, bool]: - return (line, False) - - with pytest.raises(AIClientError, match="maximum stream size"): - list( - _consume_streaming_lines(mock_resp, extractor, "TestProvider", max_stream_bytes=20) - ) - - def test_read_response_lines_break_on_done(self) -> None: - """Verify _read_response_lines terminates on is_done.""" - mock_resp = MagicMock() - mock_resp.iter_lines.return_value = ["chunk", "done_signal", "should_not_reach"] - - def extractor(line: str) -> tuple[str | None, bool]: - if line == "done_signal": - return (None, True) - return (line, False) - - results = list(_read_response_lines(mock_resp, extractor, "Provider", 1000, 0)) - assert len(results) == 1 and results[0][0] == "chunk" - - def test_raw_lines_counted_before_extraction_exceeds_bytes(self) -> None: - """Verify raw lines are counted before extraction, enforcing limits even on ignored chunks.""" - mock_resp = MagicMock() - mock_resp.iter_lines.return_value = ["ignored_header_line" * 10] - - def extractor(line: str) -> tuple[str | None, bool]: - return (None, False) - - with pytest.raises(AIClientError, match="maximum stream size \\(20 bytes\\)"): - list( - _consume_streaming_lines(mock_resp, extractor, "TestProvider", max_stream_bytes=20) - ) - - def test_consume_streaming_lines_transport_error_truncation(self) -> None: - """Verify transport errors are caught and raised with bounded exception length.""" - long_message = "x" * 1000 - mock_resp = MagicMock() - mock_resp.iter_lines.side_effect = httpx2.RemoteProtocolError(long_message) - - with pytest.raises(AIClientError) as exc_info: - list(_consume_streaming_lines(mock_resp, lambda line: (line, False), "TestProvider")) - - err_str = str(exc_info.value) - assert ( - "TestProvider streaming connection terminated unexpectedly" in err_str - and len(err_str) < 400 - ) +def _event(data: object, event: str = "message") -> httpx2.ServerSentEvent: + """A parsed server-sent event, as httpx2's EventSource yields it.""" + return httpx2.ServerSentEvent( + event=event, data=data if isinstance(data, str) else json.dumps(data) + ) + + +class TestProviderStreamFrames: + """Each provider's frames: the text they carry, and whether and why the reply ended.""" + + def test_ollama_frames(self) -> None: + """Verify an Ollama line yields its content or thinking; `done: true` ends the stream.""" + lines = [ + {"message": {"content": "Hello Ollama"}}, + {"message": {"thinking": "Deep Ollama thoughts"}}, + {"message": {"content": "!"}, "done": True, "done_reason": "length"}, + {"message": {}}, + {"error": "model 'llama3' not found"}, + ] + + assert [_ollama_stream_frame(json.dumps(line)) for line in lines] + [ + _ollama_stream_frame(""), + _ollama_stream_frame("{not valid json"), + ] == [ + StreamFrame(chunk="Hello Ollama"), + StreamFrame(chunk="Deep Ollama thoughts"), + StreamFrame(chunk="!", complete=True, last=True, finish_reason="length"), + StreamFrame(), + StreamFrame(error="model 'llama3' not found"), + StreamFrame(), + StreamFrame(), + ] + + def test_claude_frames(self) -> None: + """Verify Claude events yield text and thinking, `message_stop` ends, `[DONE]` does not.""" + events = [ + {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Claude text"}}, + {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "Hm"}}, + {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": ""}}, + {"type": "content_block_delta", "delta": {"type": "other"}}, + {"type": "message_delta", "delta": {"stop_reason": "end_turn"}}, + {"type": "message_stop"}, + {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}, + {"type": "ping"}, + ] + + assert [_claude_stream_frame(_event(e)) for e in events] + [ + _claude_stream_frame(_event("[DONE]")), + _claude_stream_frame(_event("{invalid json", event="message_stop")), + ] == [ + StreamFrame(chunk="Claude text"), + StreamFrame(chunk="Hm"), + StreamFrame(), + StreamFrame(), + StreamFrame(finish_reason="stop"), + StreamFrame(complete=True, last=True), + StreamFrame(error="Overloaded"), + StreamFrame(), + StreamFrame(), + StreamFrame(complete=True, last=True), + ] + + def test_openai_frames(self) -> None: + """Verify OpenAI chunks yield content and reasoning; a finish reason or `[DONE]` ends.""" + chunks = [ + {"choices": [{"delta": {"content": "OpenAI answer"}}]}, + {"choices": [{"delta": {"reasoning_content": "OpenAI reasoning"}}]}, + {"choices": [{"delta": {"reasoning": "More reasoning"}}]}, + {"choices": [{"delta": {}}]}, + {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}, + {"choices": [{"delta": {}, "finish_reason": "unheard_of"}]}, + {"choices": [], "usage": {"completion_tokens": 3}}, + {"error": {"message": "upstream timed out"}}, + ] + + assert [_openai_stream_frame(_event(c)) for c in chunks] + [ + _openai_stream_frame(_event("[DONE]")), + _openai_stream_frame(_event("{invalid json")), + ] == [ + StreamFrame(chunk="OpenAI answer"), + StreamFrame(chunk="OpenAI reasoning"), + StreamFrame(chunk="More reasoning"), + StreamFrame(), + StreamFrame(complete=True, finish_reason="tool_call"), + StreamFrame(complete=True), + StreamFrame(), + StreamFrame(error="upstream timed out"), + StreamFrame(complete=True, last=True), + StreamFrame(), + ] class TestZeroLeakageDownstream: @@ -396,30 +360,6 @@ def test_thinking_stream_processor_reasoning_scratchpad_property(self) -> None: "Internal reasoning step", ) - def test_extract_stream_chunk_edge_cases(self) -> None: - """Verify stream chunk extraction handles malformed lines, invalid JSON, and unknown providers.""" - assert ( - _extract_ollama_stream_chunk("{not valid json"), - _extract_ollama_stream_chunk(json.dumps({"message": {}})), - _extract_claude_stream_chunk("not-data-prefix"), - _extract_claude_stream_chunk("data: {invalid json"), - _extract_openai_stream_chunk("not-data-prefix"), - _extract_openai_stream_chunk("data: {invalid json"), - _extract_stream_chunk("data: [DONE]", "claude"), - _extract_stream_chunk("data: [DONE]", "openai"), - _extract_stream_chunk("data: [DONE]", "unknown_provider"), - ) == ( - None, - None, - (None, False), - (None, False), - (None, False), - (None, False), - (None, True), - (None, True), - (None, False), - ) - def test_streaming_token_processor_empty_feed_and_flush(self) -> None: """Verify feeding empty string or flushing clean processor behaves deterministically.""" proc = StreamingTokenProcessor() @@ -487,32 +427,313 @@ def test_streaming_token_processor_callbacks_and_unclosed_flush(self) -> None: proc.clean_content, ) == ("unclosed thought", "", "unclosed thought", "") - def test_extract_stream_chunk_fallback_and_none_lines(self) -> None: - """Verify chunk extraction handles empty deltas and non-content choices.""" - claude_empty_delta = json.dumps({"type": "content_block_delta", "delta": {"type": "other"}}) - claude_empty_think = json.dumps( - {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": ""}} - ) - openai_empty_delta = json.dumps({"choices": [{"delta": {}}]}) - - mock_resp = MagicMock() - mock_resp.iter_lines.return_value = ["empty", "data: [DONE]"] - read_lines = list( - _read_response_lines( - mock_resp, lambda line: (None, line == "data: [DONE]"), "test", 1000, 0 - ) - ) - assert ( - _extract_claude_stream_chunk(f"data: {claude_empty_delta}"), - _extract_claude_stream_chunk(f"data: {claude_empty_think}"), - _extract_openai_stream_chunk(f"data: {openai_empty_delta}"), - _extract_ollama_stream_tuple("not json"), - read_lines, - ) == ( - (None, False), - (None, False), - (None, False), - (None, False), +# ── Stream readers, fed by an httpx2 MockTransport (no socket is opened) ────────────────────── + +_PROTOCOLS: dict[str, tuple[Any, Any, str]] = { + "openai": (_read_event_stream, _openai_stream_frame, SSE), + "anthropic": (_read_event_stream, _claude_stream_frame, SSE), + "ollama": (_read_ndjson_stream, _ollama_stream_frame, NDJSON), +} +_GITHUB_TOKEN = "ghp_" + "A" * 36 + + +@pytest.fixture(autouse=True) +def _no_stream_finish_reason() -> Iterator[None]: + """Start each test with no stream's finish reason, and leave none behind.""" + token = stream_finish_reason.set(None) + yield + stream_finish_reason.reset(token) + + +def _read( + protocol: str, frames: Iterable[bytes], content_type: str | None = None, **limits: int +) -> tuple[list[str], str | None, str | None]: + """Read a stream: the text it yielded, its finish reason, and the error that ended it.""" + reader, parse_frame, default_type = _PROTOCOLS[protocol] + chunks: list[str] = [] + with streamed(frames, content_type or default_type) as response: + try: + for chunk in reader(response, parse_frame, "Provider", **limits): + chunks.append(chunk) + except AIClientError as exc: + return chunks, stream_finish_reason.get(), str(exc) + return chunks, stream_finish_reason.get(), None + + +_ENDED_EARLY = "Provider stream ended before its final frame." +_NOT_UTF8 = "'utf-8' codec can't decode byte 0xff in position 0: invalid start byte" + + +@pytest.mark.parametrize( + ("protocol", "frames", "expected"), + [ + ( + "openai", + [openai_chunk("Hel"), openai_chunk("lo", "length"), OPENAI_DONE], + (["Hel", "lo"], "length", None), + ), + ( + "openai", + [openai_chunk("Hi"), openai_chunk(finish_reason="stop")], + (["Hi"], "stop", None), + ), + ("openai", [openai_chunk("Hi"), OPENAI_DONE], (["Hi"], None, None)), + ("openai", [openai_chunk("Hel"), openai_chunk("lo")], (["Hel", "lo"], None, _ENDED_EARLY)), + ( + "anthropic", + [ + anthropic_event("message_start", message={"id": "msg_1", "content": []}), + anthropic_text("Hi"), + anthropic_event("message_delta", delta={"stop_reason": "max_tokens"}), + anthropic_event("message_stop"), + ], + (["Hi"], "length", None), + ), + ("anthropic", [anthropic_text("Hi"), OPENAI_DONE], (["Hi"], None, _ENDED_EARLY)), + ( + "anthropic", + [ + anthropic_text("Hi"), + anthropic_event( + "error", error={"type": "overloaded_error", "message": "Overloaded"} + ), + ], + (["Hi"], None, "Provider stream reported an error: Overloaded"), + ), + ( + "ollama", + [ollama_line("Hi"), ollama_line(done=True, done_reason="length")], + (["Hi"], "length", None), + ), + ("ollama", [ollama_line("Hi"), ollama_line("lo")[:-9]], (["Hi"], None, _ENDED_EARLY)), + ( + "ollama", + [ollama_line("Hi"), b'{"error": "model requires more system memory"}\n'], + (["Hi"], None, "Provider stream reported an error: model requires more system memory"), + ), + ( + "openai", + [openai_chunk("Hi"), sse_data({"error": {"message": "upstream timed out"}})], + (["Hi"], None, "Provider stream reported an error: upstream timed out"), + ), + ( + "ollama", + [ollama_line("Hi"), b"\xff\n"], + (["Hi"], None, f"Provider stream line is not UTF-8: {_NOT_UTF8}"), + ), + ], + ids=[ + "openai-length-then-done", + "openai-reason-then-eof", + "openai-done-alone", + "openai-eof-without-either", + "anthropic-max-tokens-then-message-stop", + "anthropic-eof-before-message-stop", + "anthropic-error-event", + "ollama-done-length", + "ollama-eof-mid-line", + "ollama-error-line", + "openai-error-object", + "ollama-line-not-utf8", + ], +) +def test_a_stream_is_complete_only_at_its_final_frame( + protocol: str, frames: list[bytes], expected: tuple[list[str], str | None, str | None] +) -> None: + """Verify each stream yields its text, ends on its provider's final frame, and raises else.""" + assert _read(protocol, frames) == expected + + +def test_reading_goes_on_past_the_finish_reason_to_done() -> None: + """Verify a usage chunk after the finish reason is still read, through to `[DONE]`.""" + usage = sse_data({"choices": [], "usage": {"prompt_tokens": 5, "completion_tokens": 2}}) + body = RecordedBody( + [openai_chunk("Hi"), openai_chunk(finish_reason="stop"), usage, OPENAI_DONE] + ) + + assert (_read("openai", body), body.read) == ((["Hi"], "stop", None), 4) + + +@pytest.mark.parametrize( + ("protocol", "frames", "reason"), + [ + ("openai", [openai_chunk("Hi", "stop"), OPENAI_DONE, openai_chunk("late")], "stop"), + ( + "anthropic", + [anthropic_text("Hi"), anthropic_event("message_stop"), anthropic_text("late")], + None, + ), + ("ollama", [ollama_line("Hi", done=True, done_reason="stop"), ollama_line("late")], "stop"), + ], + ids=["openai-done", "anthropic-message-stop", "ollama-done"], +) +def test_reading_stops_at_the_final_frame( + protocol: str, frames: list[bytes], reason: str | None +) -> None: + """Verify nothing after `[DONE]`, `message_stop` or `done: true` is read or yielded.""" + body = RecordedBody(frames) + + assert (_read(protocol, body), body.read) == ((["Hi"], reason, None), len(frames) - 1) + + +@pytest.mark.parametrize("protocol", ["openai", "ollama"]) +def test_an_error_frame_is_masked_and_cut(protocol: str) -> None: + """Verify a token in a provider's error message never reaches the raised error.""" + message = f"bad credentials {_GITHUB_TOKEN} " + "x" * 400 + error_frames = { + "openai": sse_data({"error": {"message": message}}), + "ollama": (json.dumps({"error": message}) + "\n").encode(), + } + + _, _, error = _read(protocol, [error_frames[protocol]]) + + prefix = "Provider stream reported an error: bad credentials " + assert (str(error).startswith(prefix), _GITHUB_TOKEN in str(error), len(str(error))) == ( + True, + False, + len("Provider stream reported an error: ") + 256, + ) + + +@pytest.mark.parametrize("protocol", ["openai", "ollama"]) +def test_a_frame_split_across_chunks_reads_as_whole(protocol: str) -> None: + """Verify frames split mid-line and mid-code-point, and a raw U+2028, read intact.""" + text = "naïve € \u2028 end" + frames = { + "openai": [openai_chunk(text, "stop"), OPENAI_DONE], + "ollama": [ollama_line(text, done=True, done_reason="stop")], + }[protocol] + whole = b"".join(frames) + one_byte_chunks = [whole[i : i + 1] for i in range(len(whole))] + + assert ( + "\u2028".encode() in whole, + _read(protocol, [whole]), + _read(protocol, one_byte_chunks), + ) == (True, ([text], "stop", None), ([text], "stop", None)) + + +def test_an_oversized_event_or_line_is_refused() -> None: + """Verify one event, or one line whether whole or unterminated, past the limit raises.""" + endless_line = RecordedBody([b'{"message": {"content": "'] + [b"x" * 32] * 50) + line_limit = "Provider stream line exceeded the 64 bytes limit." + + assert ( + _read("openai", [openai_chunk("x" * 200), OPENAI_DONE], max_event_bytes=64), + _read("ollama", endless_line, max_line_bytes=64)[2], + endless_line.read < len(endless_line.frames), + _read("ollama", [ollama_line("x" * 200, done=True)], max_line_bytes=64), + ) == ( + ( [], - ) + None, + "Provider stream could not be read: Server-sent event exceeded the 64 byte limit.", + ), + line_limit, + True, + ([], None, line_limit), + ) + + +@pytest.mark.parametrize( + ("protocol", "frame"), [("openai", openai_chunk("x" * 10)), ("ollama", ollama_line("x" * 10))] +) +def test_a_stream_past_its_size_limit_is_refused(protocol: str, frame: bytes) -> None: + """Verify the whole-stream limit counts every frame and raises once it is passed.""" + chunks, _, error = _read(protocol, [frame] * 10, max_stream_bytes=200) + + assert (len(chunks) < 10, error) == ( + True, + "Provider response exceeded maximum stream size (200 bytes).", + ) + + +@pytest.mark.parametrize( + ("protocol", "frames"), + [ + ("openai", [openai_chunk("Hel"), openai_chunk("lo", "stop"), OPENAI_DONE]), + ("ollama", [ollama_line("Hel"), ollama_line("lo"), ollama_line(done=True)]), + ], +) +def test_chunks_reach_the_caller_as_they_arrive(protocol: str, frames: list[bytes]) -> None: + """Verify the first chunk is yielded before the transport has produced the last frame.""" + reader, parse_frame, content_type = _PROTOCOLS[protocol] + body = RecordedBody(frames) + with streamed(body, content_type) as response: + chunks = reader(response, parse_frame, "Provider") + first, read_at_first = next(chunks), body.read + rest = list(chunks) + + assert (first, read_at_first, rest, body.read) == ("Hel", 1, ["lo"], 3) + + +def test_an_event_stream_of_another_content_type_is_refused() -> None: + """Verify an SSE reply sent as `application/json` raises, naming the type.""" + _, _, error = _read("openai", [openai_chunk("Hi"), OPENAI_DONE], "application/json") + + assert error == ( + "Provider stream could not be read: Expected response with content type " + "'text/event-stream', got 'application/json'." + ) + + +def _openai_client(monkeypatch: pytest.MonkeyPatch) -> LLMClient: + # The stream's spend estimate counts tokens; loading the tokenizer is not under test. + monkeypatch.setattr(context_budget, "count_tokens", lambda text, *args, **kwargs: len(text)) + monkeypatch.setattr("devops_cli.ai.spend.track_request_spend", lambda **kwargs: None) + config = AIConfig( + provider="openai", + model="gpt-test", + api_base_url="http://example.com/v1", + allow_private_network=True, + ) + return LLMClient(config, api_key="sk-test", cache_enabled=False) + + +def test_each_stream_starts_with_no_finish_reason(monkeypatch: pytest.MonkeyPatch) -> None: + """Verify a stream ending on `[DONE]` alone, or cut, does not inherit the last one's reason.""" + client = _openai_client(monkeypatch) + cut_length = [openai_chunk("Hi", "length"), OPENAI_DONE] + replies = iter( + [cut_length, [openai_chunk("Hi")], cut_length, [openai_chunk("Hi"), OPENAI_DONE]] + ) + route_client(client, monkeypatch, lambda request: reply(next(replies))) + reasons: list[str | None] = [] + + for _ in range(4): + # The second stream ends before its final frame, so it raises and sets no reason. + with contextlib.suppress(AIClientError): + list(client.chat_messages_stream("sys", [ChatMessage(role="user", content="hi")])) + reasons.append(stream_finish_reason.get()) + + assert reasons == ["length", None, "length", None] + + +def test_an_ollama_stream_failing_after_output_is_not_replayed_on_another_host( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify a stream cut after it yielded output raises instead of failing over mid-reply.""" + monkeypatch.setattr(context_budget, "count_tokens", lambda text, *args, **kwargs: len(text)) + monkeypatch.setattr("devops_cli.ai.spend.track_request_spend", lambda **kwargs: None) + client = LLMClient( + AIConfig( + provider="ollama", + model="llama3", + ollama_urls=["http://example.com:11434", "http://example.com:11435"], + allow_private_network=True, + ), + cache_enabled=False, + ) + + def cut_body() -> Iterator[bytes]: + yield ollama_line("Hi") + raise httpx2.ReadError("connection reset by peer") + + sent = route_client(client, monkeypatch, lambda request: reply(cut_body(), NDJSON)) + chunks: list[str] = [] + with pytest.raises(AIClientError, match="connection terminated unexpectedly") as raised: + for chunk in client.chat_messages_stream("sys", [ChatMessage(role="user", content="hi")]): + chunks.append(chunk) + + assert (chunks, len(sent), type(raised.value)) == (["Hi"], 1, AIClientError) diff --git a/tests/test_review_profile.py b/tests/test_review_profile.py index 6057e77aa8..44eafec07d 100644 --- a/tests/test_review_profile.py +++ b/tests/test_review_profile.py @@ -14,6 +14,7 @@ from devops_cli.ai import personas from devops_cli.ai.personas import review_prompt_digest +from devops_cli.ai.review import profile as profile_module from devops_cli.ai.review import runner from devops_cli.ai.review.profile import ( BenchmarkSummary, @@ -117,6 +118,65 @@ def test_cached_replies_are_counted_apart_from_backend_calls(tmp_path: Path) -> assert (profile.llm_calls, profile.cached_calls, profile.completion_tokens) == (1, 1, 10) +def _observed(profiler: ReviewProfiler, served_by: str | None, reason: str | None) -> None: + """Show the profiler one served reply, as the spend ledger does when a call finishes.""" + profiler.observe({"served_by": served_by, "finish_reason": reason, "completion_tokens": 10}) + + +@pytest.fixture +def fixed_prompt_digest(monkeypatch: pytest.MonkeyPatch) -> None: + """Skip hashing every review prompt on disk; the digest is not under test here.""" + monkeypatch.setattr(profile_module, "review_prompt_digest", lambda: "digest") + + +@pytest.mark.usefixtures("fixed_prompt_digest") +def test_profile_counts_replies_by_finish_reason_and_cut_replies_by_backend( + tmp_path: Path, +) -> None: + """Verify each stage counts replies per reason, and `length` replies per serving backend.""" + with profiling() as profiler: + with review_stage("persona_review"): + for reason in ("stop", "stop", "length"): + _observed(profiler, "b1", reason) + with review_stage("verification"): + _observed(profiler, None, None) + profiler.build(session_id="s", target="t").write(tmp_path) + + loaded = ReviewProfile.load(tmp_path) + stages = loaded.stages if loaded else [] + assert [(s.name, s.finish_reasons, s.truncated) for s in stages] == [ + ("persona_review", {"stop": 2, "length": 1}, {"b1": 1}), + ("verification", {"unknown": 1}, {}), + ] + + +@pytest.mark.usefixtures("fixed_prompt_digest") +@pytest.mark.parametrize( + ("reasons", "summary"), + [ + (["stop", "length"], "2 LLM calls, 1 hit the reply cap; persona_review 1s (2 calls)"), + (["stop"], "1 LLM calls; persona_review 1s (1 calls)"), + ], + ids=["one-cut", "none-cut"], +) +def test_the_profile_summary_says_how_many_replies_hit_the_cap( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reasons: list[str], summary: str +) -> None: + """Verify the summary line counts replies cut at their cap, and is unchanged with none.""" + lines: list[str] = [] + monkeypatch.setattr(runner, "print_info", lambda message, **kwargs: lines.append(message)) + monkeypatch.setattr(runner, "format_duration", lambda seconds: "1s") + orchestrator = MagicMock(session_id="s1", session_dir=tmp_path) + + with profiling() as profiler: + with review_stage("persona_review"): + for reason in reasons: + _observed(profiler, VLLM, reason) + _write_review_profile(profiler, orchestrator, "playbooks", 2) + + assert lines == [f"[dim]Profile: 1s, {summary} -> {tmp_path / 'profile.json'}[/dim]"] + + def test_stage_is_a_no_op_without_a_profiler() -> None: """Verify stage markers cost nothing when no review is being profiled.""" with review_stage("persona_review"): diff --git a/tests/test_thinking_providers.py b/tests/test_thinking_providers.py index 8166a5d2b6..b7445d58c6 100644 --- a/tests/test_thinking_providers.py +++ b/tests/test_thinking_providers.py @@ -274,20 +274,21 @@ def test_ollama_separates_inline_think_blocks_into_thinking_field( class TestStreamingThinkingExtractors: - """Validate SSE streaming chunk extraction for thinking deltas.""" + """Validate SSE stream frames for thinking deltas.""" def test_extract_claude_thinking_delta(self) -> None: - from devops_cli.ai.client.streaming import _extract_claude_stream_chunk + from devops_cli.ai.client.streaming import StreamFrame, _claude_stream_frame - line = 'data: {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "step 1 reasoning"}}' - chunk, is_done = _extract_claude_stream_chunk(line) - assert chunk == "step 1 reasoning" - assert is_done is False + data = ( + '{"type": "content_block_delta", ' + '"delta": {"type": "thinking_delta", "thinking": "step 1 reasoning"}}' + ) + frame = _claude_stream_frame(httpx2.ServerSentEvent(event="content_block_delta", data=data)) + assert frame == StreamFrame(chunk="step 1 reasoning") def test_extract_openai_reasoning_content_delta(self) -> None: - from devops_cli.ai.client.streaming import _extract_openai_stream_chunk + from devops_cli.ai.client.streaming import StreamFrame, _openai_stream_frame - line = 'data: {"choices": [{"delta": {"reasoning_content": "step 1 reasoning"}}]}' - chunk, is_done = _extract_openai_stream_chunk(line) - assert chunk == "step 1 reasoning" - assert is_done is False + data = '{"choices": [{"delta": {"reasoning_content": "step 1 reasoning"}}]}' + frame = _openai_stream_frame(httpx2.ServerSentEvent(data=data)) + assert frame == StreamFrame(chunk="step 1 reasoning")