Skip to content

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

Closed

Description

@solderzzc

Found during review of #125. Pre-existing — not introduced by any recent change — but it defeats the stated contract of the stop parameter.

Problem

handleChatStreaming only tests for a stop sequence on the chunk that completes it. A stop sequence spanning two chunks has its first part streamed to the client before the match is seen.

With stop: ["\nUser:"] and the model emitting "\nUser" then ":":

  • chunk 1 — no match yet, so the whole chunk is emitted; the client now has "\nUser"
  • chunk 2 — match found, trimmedFull.count - priorCount is negative, prefix(0) emits nothing and generation stops cleanly

Net: the client received "\nUser", which is exactly what stop asked to suppress. All four stop-handling sites in Server.swift share the shape (:1988, :2162, :2396, :2473).

Two related instances

Thinking tracker. With --thinking and a stop like "<|im_end|>" split as …"<" + "|im_end|>", the tracker holds the trailing < as a possible tag prefix; the stop path then calls flush(), which emits that < — a fragment of the stop sequence. Worst case is ~17 characters (<|channel>thought\n).

JSON mode (Server.swift:1949-1985) continues past the stop check entirely while buffering, so a stop inside the buffered prefix is emitted verbatim and only noticed on the following chunk, by which point the trim arithmetic no longer applies.

Suggested fix

Hold back a tail of max(stopSequence.count) - 1 characters before emitting — the same technique ThinkingStateTracker already uses for partial tags — and release it once the next chunk proves it is not the start of a stop sequence. That fixes all three instances at one point, at the cost of one chunk of extra latency on the tail.

Also worth fixing nearby

checkStopSequences (Server.swift:2630-2638) returns the first stop sequence in list order, not the earliest in the text. With stop: ["\nUser:", "X"] and output "abXc\nUser:" the trim keeps everything after X. One-line fix: pick the match with the lowest lowerBound.

Impact

Anything relying on stop for framing — agent loops that stop on "\nUser:" or a turn marker — can receive the marker it asked to be cut, and then feed it back as history. Not data loss, but it breaks the parameter's contract in exactly the setups that use it most.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions