Skip to content

feat(cli): thinking-stream sanitizer initial state, unopened-tag count and thought cap #590

Description

@dan-petty

Context & Rationale

Two hand-rolled FSMs implement one think-block sanitizer: ThinkingStreamProcessor (src/devops_cli/ai/thinking_stream.py:51, used by chat at commands/ai.py:881-884) and StreamingTokenProcessor (src/devops_cli/ai/client/streaming.py:23, behind sanitize=True at client/unified.py:793-796, unused in src/). Both start only in EMITTING (thinking_stream.py:74, streaming.py:58), so a closing tag seen while emitting passes through as text (_process_outside_think seeks only the open tag, thinking_stream.py:135-157); strip_think_blocks/extract_think_blocks (thinking_stream.py:15-40), the review pipeline's path (review/runner.py:457, client/structured.py:50,104, response_repair.py:53), match only open…close pairs. Neither caps the thought buffer (streaming.py:64-69 bounds only the whole stream) nor reports EOF inside a thought: streaming.py:176-191 resets in_think and tests/test_ai_streaming.py:128-137 asserts that erasure. vibes docs/RETROSPECTIVE.md:173 records this design leaking a whole chain of thought when the template pre-opens it; examples/streaming-reasoning-sanitizer/sanitizer.py fixes it with starts_thinking, unopened_close_tags, unclosed_stream and a 65,536-character cap (line 18). Today's pool (k8s/llm/gateway/configmap.yaml:17-96) is safe only because adapters re-wrap out-of-band reasoning as complete blocks (streaming.py:252,279,299); the leak goes live with the first DeepSeek-R1/Qwen3-class model reached via the ollama/* pass-through (configmap.yaml:103). vLLM, which could have served one without --reasoning-parser, is no longer deployed: k8s/llm/vllm/ went in ea49d6e, and vllm-profiles.yaml and the vLLM gateway routes went in #734, leaving an Ollama-only pool. Neither #475 nor #479 plans such a model: a latent defect to close before any pool change.

Scope & Deliverables

  • Context & Rationale*: Two hand-rolled FSMs implement one think-block sanitizer: ThinkingStreamProcessor (src/devops_cli/ai/thinking_stream.py:51, used by chat at commands/ai.py:881-884) and StreamingTokenProcessor (src/devops_cli/ai/client/streaming.py:23, behind sanitize=True at client/unified.py:793-796, unused in src/). Both start only in EMITTING (thinking_stream.py:74, streaming.py:58), so a closing tag seen while emitting passes through as text (_process_outside_think seeks only the open tag, thinking_stream.py:135-157); strip_think_blocks/extract_think_blocks (thinking_stream.py:15-40), the review pipeline's path (review/runner.py:457, client/structured.py:50,104, response_repair.py:53), match only open…close pairs. Neither caps the thought buffer (streaming.py:64-69 bounds only the whole stream) nor reports EOF inside a thought: streaming.py:176-191 resets in_think and tests/test_ai_streaming.py:128-137 asserts that erasure. vibes docs/RETROSPECTIVE.md:173 records this design leaking a whole chain of thought when the template pre-opens it; examples/streaming-reasoning-sanitizer/sanitizer.py fixes it with starts_thinking, unopened_close_tags, unclosed_stream and a 65,536-character cap (line 18). Today's pool (k8s/llm/gateway/configmap.yaml:17-96) is safe only because adapters re-wrap out-of-band reasoning as complete blocks (streaming.py:252,279,299); the leak goes live with the first DeepSeek-R1/Qwen3-class model reached via the ollama/* pass-through (configmap.yaml:103). vLLM, which could have served one without --reasoning-parser, is no longer deployed: k8s/llm/vllm/ went in ea49d6e, and vllm-profiles.yaml and the vLLM gateway routes went in feat(k8s): modernize monitoring stack, llm profiles, traefik routing, and remove squid proxy #734, leaving an Ollama-only pool. Neither feat(review): per-model review quality baseline for the devops-review pool #475 nor feat(ai): gpt-oss reasoning effort for group analysis is measured and set on its gateway deployments #479 plans such a model: a latent defect to close before any pool change.
  • Deliverable*: Maintained control first: Ollama's thinking field is already consumed (streaming.py:252), making the sanitizer defence in depth. vLLM's --reasoning-parser no longer applies, because feat(k8s): modernize monitoring stack, llm profiles, traefik routing, and remove squid proxy #734 removed the vLLM deployments. Then three PRs: (1) one FSM core behind ThinkingStreamProcessor's callbacks and the StreamingTokenProcessor adapter (both public re-exports, ai/__init__.py:904-905, ai/client/__init__.py:51-52; no deletion); add unopened_close_tags, unclosed_stream and discarded_thought_chars to to_dict() and the gen_ai.stream span (unified.py:780); run strip_think_blocks/extract_think_blocks through the core. (2) initial_state (emitting|thinking) and thinking_tags via get_model_thinking_tags/supports_thinking, overridable per model in ModelProfileSpec through _apply_profile_spec (ai/profiles/__init__.py:62), not the gateway configmap; default emitting. (3) max_thought_chars, default 65,536, discarding and counting, plus split-tag property tests under the Structured Fuzzing item (which adds Hypothesis). Port from vibes only the two regression tests (test_sanitizer.py:142-158) and metrics shape; add one closing-tag-only test through strip_think_blocks.
  • Constraint*: pydantic-ai 2.35.0 does not cover the mechanism (_parts_manager.py:200,214 matches a tag only as a whole delta; _thinking_part.py:24-26 emits an unclosed thought as TextPart): adopting it would regress split-tag handling 42 tests in tests/test_thinking.py and tests/test_ai_streaming.py cover. A wrong initial_state is worse than none (thinking on a never-closing model suppresses the whole answer), hence counters ship first, default emitting, per-model override. The cap discards and counts, never raises; 65,536 is the vibes default, to revisit against feat(ai): gpt-oss reasoning effort for group analysis is measured and set on its gateway deployments #479's budgets. tests/test_ai_streaming.py:128-137 must assert unclosed_stream is True instead of in_think is False.
  • Measured*: python - feeding ['Deciding what to commit.', '</think>', 'git commit -m x'] into ThinkingStreamProcessor(show_thinking=False), StreamingTokenProcessor() and strip_think_blocks(''.join(chunks)): all return 'Deciding what to commit.</think>git commit -m x', thought empty. '<think>' + 'a'*1_000_000 then flush(): both hold a 1000000-char thought; ThinkingStreamProcessor.in_think True, StreamingTokenProcessor.in_think False. python -m pytest tests/test_thinking.py tests/test_ai_streaming.py -o addopts="" -p no:cacheprovider --collect-only -q: 42 tests. importlib.metadata.version('pydantic-ai'): 2.35.0.
  • Source*: vibes docs/RETROSPECTIVE.md (the 'state machine that cannot be told where it starts' bullet), examples/streaming-reasoning-sanitizer/sanitizer.py, examples/streaming-reasoning-sanitizer/test_sanitizer.py — initial state, unopened-tag count, unclosed flag and cap; patterns/streaming-reasoning-isolation-and-token-budgeting.md — cap only; observations/devops-cli/13-streaming-reasoning-token-parsers-and-think-block-sanitization.md — cap only, and stale about devops-cli enforcing it.

Update 2026-10-08: refinement

Re-measured: the closing tag still leaks into content and an unclosed thought is erased (ai/client/streaming.py:36, :189-204). The ollama/* route is gone, and the gateway serves deepseek-r1:70b, qwen3.8:27b and gpt-oss:20b, so 'Neither #475 nor #479 plans such a model' no longer holds. Owner decision on #1001: no hand-written SSE decoder remains, so the re-wrapping (:288, :315, :355) goes; pydantic-ai 2.54.0 still matches whole-delta tags only, so PR 1's core reads #1001's stream deltas, with tags from the model profile. The alias StreamingReasoningSanitizer (:250) is deleted.

Proposed design

Problem statement

The current thinking-stream sanitizer in devops-cli has several flaws: it starts in EMITTING state, which causes closing tags seen while emitting to pass through as text; it does not cap the thought buffer or report EOF inside a thought; and it lacks proper handling of unopened tags. These issues can lead to leakage of reasoning content when models pre-open thinking blocks or when streams end unexpectedly.

Acceptance criteria

  • Criterion 1: The sanitizer correctly identifies and counts unopened closing tags
    Verification: Add a test that verifies unopened_close_tags is incremented when a closing tag appears without an opening tag, using strip_think_blocks with a string containing only a closing tag.
  • Criterion 2: The sanitizer properly handles unclosed streams at EOF
    Verification: Run ThinkingStreamProcessor(show_thinking=False) and StreamingTokenProcessor() with input that ends without closing a thinking block, asserting that unclosed_stream is True in the output of to_dict().
  • Criterion 3: The sanitizer caps the thought buffer and discards excess characters
    Verification: Feed a large string with a thinking block exceeding 65,536 characters to strip_think_blocks, asserting that only up to 65,536 characters are retained and discarded_thought_chars is incremented accordingly.
  • Criterion 4: The initial state can be overridden per model
    Verification: Configure a model profile with initial_state: thinking and verify that ThinkingStreamProcessor starts in the THINKING state by checking in_think after processing a single chunk.

Key questions

  • What is the default initial state for the thinking stream processor?: The default initial state should be EMITTING to maintain backward compatibility and prevent suppressing answers from models that never close their thinking blocks. [sources: docs/agent/tasks/task-590-thinking-stream-sanitizer-initial-state-unopened-tag-count-a.md:18]
  • What is the default maximum thought character limit?: The default maximum thought character limit is 65,536 characters. [sources: docs/agent/tasks/task-590-thinking-stream-sanitizer-initial-state-unopened-tag-count-a.md:18]
  • Should the sanitizer report unclosed streams?: Yes, the sanitizer should report unclosed streams by setting unclosed_stream to True when a stream ends while inside a thinking block. [sources: docs/agent/tasks/task-590-thinking-stream-sanitizer-initial-state-unopened-tag-count-a.md:18]
  • Should the sanitizer discard excessive thought content or raise an exception?: The sanitizer should discard excessive thought content and count it, never raising an exception. [sources: docs/agent/tasks/task-590-thinking-stream-sanitizer-initial-state-unopened-tag-count-a.md:18]
  • Where should the initial_state and thinking_tags be configured?: They should be overridable per model in ModelProfileSpec through _apply_profile_spec, not in the gateway configmap. [sources: docs/agent/tasks/task-590-thinking-stream-sanitizer-initial-state-unopened-tag-count-a.md:17]

Fit

Needs splitting into 3 items:

  1. Implement FSM core behind ThinkingStreamProcessor callbacks and StreamingTokenProcessor adapter
  2. Add initial_state and thinking_tags configuration per model
  3. Add max_thought_chars cap with discard and count behavior

Suspected block

None.

Dependencies

None.

Activity

  1. added this to the v0.2.23 milestone on Sep 25, 2026
  2. added
    type/feature
    scope/cli
    priority/p2-medium
    on Sep 25, 2026
  3. modified the milestones: v0.2.23, v0.2.24 on Sep 28, 2026
  4. removed this from the v0.2.23 milestone on Oct 1, 2026
  5. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    Moved from the shipped v0.2.23 to the backlog. It is still valid (checked 2026-10-01), and P2 items don't displace P1 work in the planned releases.

  6. added
    scope/ai
    and removed
    scope/cli
    on Oct 2, 2026
  7. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

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

    • Incomplete Thinking-Stream Sanitizer Implementation (src/devops_cli/ai/thinking_stream.py:51, re-rated LOW): The roadmap text is accurate: it describes an open backlog item, not a broken doc. The code gap it describes is real and unimplemented. Neither src/devops_cli/ai/thinking_stream.py nor src/devops_cli/ai/client/streaming.py contains initial_state, unopened_close_tags, unclosed_stream or max_thought (grep returns nothing). The roadmap's Measured section shows a bare closing tag passing through as answer text. Open issue feat(cli): thinking-stream sanitizer initial state, unopened-tag count and thought cap #590 ('thinking-stream sanitizer initial state, unopened-tag count and thought cap') covers it, and the roadmap calls it a latent defect that can't trigger until a model that …
  8. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Linked: #591 and #479. Reasoning text is split by hand-written tag state machines and never counted; #591 keeps its per-stream counters in this item's sanitizer. Found by the 2026-10-08 backlog review.

  9. modified the milestones: v0.2.39, v0.2.38 on Oct 17, 2026
  10. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Proposal needs splitting into 3 items at 3dd7fa6 (see proposed design in issue body).

  11. modified the milestones: v0.2.38, on Oct 20, 2026
  12. added a commit that references this issue on Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/aitype/feature

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions