Skip to content

fix: withhold ambiguous tail so split stop sequences cannot leak (#126) - #132

Merged
solderzzc merged 2 commits into
mainfrom
claude/fix-126-stop-holdback
Aug 8, 2026
Merged

solderzzc merged 2 commits into
mainfrom
claude/fix-126-stop-holdback

Conversation

@solderzzc

Copy link
Copy Markdown
Member

Fixes #126.

Reproduced first

The stop check only fires on the chunk that completes a stop sequence, so one split across two chunks has its first part streamed before the match is visible. Against a live server, with stop: ["own fox"] — a string that cannot be a single token, so it must straddle chunks:

streamed to client
before 'The quick brown' ← leaks own
after 'The quick br'

The fix

pendingStopPrefixLength(_:stopSequences:) reports how many trailing characters could still be the opening of a stop sequence. The streaming loop withholds exactly that many, releasing them when the next chunk resolves the ambiguity — or at end of generation, when they turn out to be ordinary text. Same technique ThinkingStateTracker already uses for partial tags. Costs one chunk of latency on the tail, nothing when the tail is unambiguous.

It also replaces the stop path's remainder arithmetic. That computation has now been wrong in both directions — first dropping text the tracker was holding, then leaking the stop sequence — because it assumed a relationship between chunk boundaries and what had been emitted that the tracker breaks. It now uses a running count of characters actually released, which does not depend on chunk boundaries at all.

Verification

  • Verified red: reverting the holdback restores the leak, live.
  • Three stop shapes checked against predictable output: brown → 'The quick ', own fox → 'The quick br', lazy → 'The quick brown fox jumps over the '.
  • The straddling case is added to tests/test-contract.sh, so CI guards it rather than my laptop: 7 passed, 0 failed, 2 skipped.
  • 7 new unit tests for the helper, including a character-by-character stream simulation asserting no stop prefix is ever emitted.
  • Full suite: 259 tests, 0 failures.

Note on my first attempt at this area

My initial live test used a prompt whose output was digits, so none of the stop strings appeared and all three "passed" vacuously. The results above come from a prompt with predictable output that actually contains the stop.

Given this is the streaming hot path and two previous changes here each introduced a defect that review caught, I would rather this had a review pass than be merged on green CI alone.

🤖 Generated with Claude Code

solderzzc and others added 2 commits August 7, 2026 21:43
The stop check only fires on the chunk that completes a stop sequence, so one
split across two chunks had its first part streamed before the match was
visible. Reproduced against a live server: stop "own fox" — which cannot be a
single token — returned "The quick brown", handing the client the "own" it had
asked to be cut.

pendingStopPrefixLength reports how many trailing characters could still be the
opening of a stop sequence; the streaming loop withholds exactly that many and
releases them once the next chunk resolves the ambiguity, or at end of
generation when they turn out to be ordinary text. This mirrors how
ThinkingStateTracker already handles partial tags. Cost is one chunk of latency
on the tail, and nothing when the tail is unambiguous.

The stop path's remainder is now computed from a running count of characters
actually released, rather than from fullText/chunk arithmetic. That arithmetic
has been wrong in both directions before — dropping text the tracker was
holding, then leaking the stop sequence — because it assumed a relationship
between chunk boundaries and what had been emitted that the tracker breaks.

Verified: "own fox" now returns "The quick br"; reverting the holdback restores
the leak. Contract suite gains that exact case so CI guards it. 259 unit tests
pass, contract suite 7 passed / 0 failed / 2 skipped.

Fixes #126.

Co-Authored-By: Claude Opus 5 <[email protected]>
- JSON-mode buffering emitted to the client then `continue`d past the counter,
  so emittedTextCount stayed 0 for everything the buffer flush had already
  sent. A later stop would then compute its remainder from 0 and re-emit that
  content — corrupt JSON on the wire. This was a regression introduced by the
  holdback commit: the previous chunk-scoped arithmetic could not duplicate
  prior output. The flush now advances the counter to fullText.count.
  Honesty note: I could not build a live reproduction — my attempt needed a
  buffer flush *and* a later stop hit in one response and only ever triggered
  one of the two. The fix restores an invariant the code plainly violates
  (emit without counting), but it is reasoned, not observed.
- The withheld tail was released only in `case .info`. A stream that ends
  without one — generation error, cancellation mid-decode — dropped up to
  maxStopLength-1 characters of real output. Added a post-loop flush.
- The contract test asserted only that no stop prefix leaked, which would also
  pass if the fix over-withheld and dropped the tail. It now also requires the
  preceding text to arrive.
- The "unicode" unit test used only multi-byte single-scalar characters, so it
  could not catch a scalar-vs-cluster mixup. Replaced with a ZWJ emoji cluster.
- Removed a stream-of-consciousness comment left in a test.

Deferred, and stated rather than silently skipped: /v1/completions has the
same straddling bug (Server.swift ~2470) and is not fixed here; the held tail
is emitted after a tool-call chunk rather than before it; and the loop body
itself still has no direct test, which is why two of these findings existed.

259 unit tests pass; contract suite 7 passed / 0 failed / 2 skipped.

Co-Authored-By: Claude Opus 5 <[email protected]>
@solderzzc
solderzzc merged commit 88be4c9 into main Aug 8, 2026
12 of 13 checks passed
@solderzzc
solderzzc deleted the claude/fix-126-stop-holdback branch August 8, 2026 06:43
solderzzc added a commit that referenced this pull request Aug 8, 2026
#132 fixed the chat path; the legacy text-completions path had the same
defect and was explicitly left out of scope. Reproduced there: stop
"own fox" — which cannot be a single token, so it must straddle chunks —
returned "The quick brown", handing the client the "own" it asked to be cut.

Applies the same treatment: withhold the tail that could still open a stop
sequence via pendingStopPrefixLength, release it when the next chunk resolves
the ambiguity, on normal completion, or via a post-loop safety net if the
stream ends without an .info event. The stop remainder is computed from
characters actually released, replacing the fullText/chunk arithmetic that was
wrong in both directions on the chat path before it was replaced.

This path has no thinking tracker, so it is the simpler of the two: released
text goes straight to the wire and emittedTextCount is exactly what the client
received.

Verified red: reverting the holdback restores 'The quick brown'. The contract
suite gains the /v1/completions case, so CI guards both endpoints — 8 passed,
0 failed, 2 skipped.

Fixes #133.

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stop sequences split across token chunks leak their prefix to the client

1 participant