Skip to content

/v1/completions leaks stop-sequence prefixes split across chunks #133

Closed

Description

@solderzzc

#126 was fixed for /v1/chat/completions in #132. The legacy /v1/completions streaming path has the same defect and was left out of scope, deliberately — recording it so it is not mistaken for fixed.

Where

Sources/SwiftLM/Server.swift (~2470, the text-completions streaming loop):

if let (trimmedText, _) = checkStopSequences(fullText, stopSequences: stopSequences) {
    let emittedSoFar = fullText.count - text.count
    ...
} else {
    cont.yield(sseTextChunk(modelId: modelId, text: text, finishReason: nil))  // leaks a partial stop
}

The stop check only fires on the chunk that completes the sequence, so one spanning two chunks has its first part streamed before the match is visible — identical to the chat-path bug. It also still uses the fullText.count - text.count arithmetic that #132 replaced, having been wrong in both directions on the chat path (dropping held text, then leaking the stop).

Fix

pendingStopPrefixLength(_:stopSequences:) already exists from #132 and is directly reusable. The chat path also now tracks characters actually released rather than deriving position from chunk boundaries; the same approach applies here. There is no thinking tracker on this path, so it is the simpler of the two.

Reproduction

The chat-path case reproduces with a stop that cannot be a single token, e.g. "own fox" against a prompt whose output contains "brown fox". Before the fix that returned The quick brown — the client receives own, which it asked to be cut. The same request shape against /v1/completions should show it.

Impact

Lower than the chat path — most clients use /v1/chat/completions — but the endpoint exists and its stop parameter carries the same contract.

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