Skip to content

serve, tokenizer: control-token spellings in client text tokenize as text - #573

Merged
midagedev merged 5 commits into
mainfrom
ctlsafe
Oct 21, 2026
Merged

midagedev merged 5 commits into
mainfrom
ctlsafe

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What

The chat path renders the prompt through the model's template, then tokenizes the whole string with special tokens parsed. A special token's spelling in client text therefore became that token. For example <|im_start|>, </think> or |DSML| in a user message, a tool result, a tool call or a tool description became a turn boundary, a think close or a DSML tag.

The fix:

  • Every client string gets a short mark beside each spelling before the render.
  • After the render the marks are cut out. The tokenizer refuses any special-token match that spans a mark, so those bytes go to the BPE as text.
  • An assistant message's content and reasoning are the model's own output. They stay as they are, so the special ids the model printed round-trip.
  • A template that cuts a marked string apart gives a named 400 (GuardError::Severed). It never falls back to parsing the whole string.

llama-server has the same behaviour: it tokenizes the rendered prompt with parse_special on (tools/server/server-context.cpp).

Evidence

  • FAIL-first: on the base, control_strings_in_client_text_are_ordinary_tokens is red. It covers nine template families (qwen3, qwen36, qwen38, glm5, v41, nemotron, nemotron-bolt, solar, v41-spaced) × six fields, with 71 failing lines. One example: qwen3/user: 16 special ids in the prompt, the template wrote 3.
  • After the fix it is green.
  • A conversation with no spelling renders to the same ids as before (compared over the fixture conversations).
  • 19 mutants of the guard are each killed by a test.
  • Results:
    • cargo test -p bloomery-tokenizer: 32 passed.
    • The serve test targets with --include-ignored: all green (lib 329, serve 99, …).
    • mac-check check rc 0, lint 11 (the ratchet), fmt and check-comments rc 0.

Not covered (stated in docs/serving.md)

Two cases are not covered:

  • A template that builds a spelling from its own pieces around a client string ('<' ~ key ~ '>').
  • Two client strings that complete a spelling only when joined.

On the output side, generated </think> and DSML are still recognised by text, not by id. That is a follow-up.

The changes were written by a Claude agent (Sonnet round) and reviewed by the lead.

🤖 Generated with Claude Code

https://claude.ai/code/session_015btATo6y3zHmKzfE8eHYmN

@github-actions github-actions Bot added documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve labels Oct 20, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: Guard markers can remove template control tokens and corrupt client text.

Must fix

1. Keep marks inside text after trimming

crates/tokenizer/src/guard.rs:72 Qwen36 trims user content before appending <|im_end|>. For "<think>\n", the mark follows <think>; trimming puts that cut at the template token's start. Inclusive spans_cut rejects both tokens, removing the turn boundary.
Replace the full-match branch:

if start > 0 && !text[..start].trim().is_empty() {
    at.push(start);
} else if end < n && !text[end..].trim().is_empty() {
    at.push(end);
} else {
    let first = text[start..end].chars().next().expect("a nonempty spelling");
    at.push(start + first.len_utf8());
}

Add the trimmed-content case to the control-token gate.

2. Reserve markers against decoded arguments

crates/serve/src/guard.rs:82 The scan sees the escaped argument string, then arguments() decodes it. With Qwen3, {"q":"\u007e\u007e\u007e\u005e<think>"} decodes to ~~~^<think>, containing the chosen marker. finish() deletes the literal ~~~^ from the tool argument.
Replace the string arm:

Value::String(s) => {
    self.add(s);
    if let Ok(parsed) = serde_json::from_str::<Value>(s) {
        self.add_value(&parsed);
    }
}

3. Reject slices that change client text

crates/serve/src/guard.rs:287 For x<think>y, a template's content[:2] produces x~. Neither reserved pair remains, so the server accepts a marker byte. A slice of five characters removes a complete mark and returns x instead of x<thi; the new slice test incorrectly expects this.
Validate this new error contract against the unmarked render. Pass &state.template, &vars after marked at the sole call, remove the ends field and initializer, and replace:

pub(crate) fn finish(
    &self,
    marked: String,
    template: &jinja::ChatTemplate,
    vars: &Map<String, Value>,
) -> Result<(String, Option<Guarded>), GuardError> {
    if !self.any() {
        return Ok((marked, None));
    }
    let text = marked.replace(&self.mark, "");
    let encoded = serde_json::to_string(vars).expect("JSON values serialize");
    let original: Map<String, Value> =
        serde_json::from_str(&encoded.replace(&self.mark, ""))
            .expect("guard symbols cannot change JSON syntax");
    let expected = template.render(&original).map_err(|_| GuardError::Severed {
        mark: self.mark.clone(),
    })?;
    if text != expected {
        return Err(GuardError::Severed { mark: self.mark.clone() });
    }
    Ok((text, Some(Guarded {
        text: marked,
        mark: self.mark.clone(),
    })))
}

In the slice test, require 400 for lengths 2, 4 and 5; retain the successful length-1 case.

4. Reuse the byte-alphabet owner

crates/serve/src/ctl_tests.rs:131 duplicates crates/tokenizer/src/unicode.rs:138. Both encode GPT-2's byte alphabet. R14 requires one owner.
Make the existing table function public and re-export it from tokenizer's root:

pub use unicode::byte_to_cpt_table;

Delete byte_chars and replace the texts initializer:

let mut texts: Vec<String> = tokenizer::byte_to_cpt_table()
    .into_iter()
    .map(|cp| char::from_u32(cp).expect("a GPT-2 alphabet code point").to_string())
    .collect();

5. Remove unused elements

crates/serve/src/ctl_tests.rs:232 constructs a new decoder type and implementation, but every test only renders or tokenizes. Only generation calls decoder().
Delete PieceDecoder and its Decoder implementation, then replace:

fn decoder(&self) -> Box<dyn Decoder> {
    unreachable!("the chat-control tests do not generate")
}

Remove the unused derives on Guarded at crates/serve/src/guard.rs:303. crates/serve/src/media.rs:687 has only in-crate callers: change its header to pub(crate) fn flatten_with( (R13).

Non-blocking

⚠ Debugging path: crates/serve/src/api.rs:2397 returns clean text, so re-tokenizing it loses the guarded IDs. State how to inspect the engine's actual prompt IDs, or explain why that diagnostic is deferred.

Checked

Duplicates: both byte-alphabet implementations produce the same 256 values; the fix reuses the existing owner.
Complexity: cuts has three searches; render_chat adds guard branches.
Silent failure: followed trimming, argument decoding and slicing through rendering and tokenization.
Tests: the slice gate checks length 4 but accepts corrupted length-5 output; lengths 2 and 5 need rejection checks.
Gates: none moved or removed; main gate has stated FAIL-first.
Escape catalog: C1–C4 do not match.

Notes

Rust tests were not run. Source-derived reproductions confirmed the three failures.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev

Copy link
Copy Markdown
Owner Author

Box gates on 0ab6da7 (fixture tier): gate-jinja, gate-tokenizer, gate-serve, gate-gpu-serve-start-ds41 green (wall 337 s). gate-gpu-gates-lib green on the real tier (28 s).
The graph selects all 203 gates, because Tokenizer::from_gguf reaches every bin. The other gates only construct the tokenizer, and they do not run the guard path. So this run is the owning gates only (2026-10-21).

midagedev and others added 3 commits October 21, 2026 09:18
…ide a mark matches no special token

guard splices a short mark beside every special-token spelling a text carries (and beside a beginning or an end a
neighbour could finish); encode_marked cuts the marks out and refuses every special match that spans one, so the
bytes around it go to the BPE as text. Text with no mark encodes as encode does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015btATo6y3zHmKzfE8eHYmN
The chat path renders the prompt through the template and tokenizes it with special tokens parsed, so a spelling
such as <|im_start|>, </think> or |DSML| in a user message, a tool result, a tool call or a tool description became
a turn boundary, a think close or a DSML tag. Every client string is now guarded before the render and the prompt
encoded marked after it; an assistant message's content and reasoning (the model's own output) stay as they are.
A template that cuts a marked string apart is a named 400 (GuardError::Severed). A conversation with no such
spelling renders to the same ids as before. Red before on nine families x six fields, green after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015btATo6y3zHmKzfE8eHYmN
…erve the mark, finish checks the unmarked render

- tokenizer guard: a spelling with only whitespace beside it is marked after its first character, so a trim leaves
  the mark inside the text.
- serve guard: a string that holds JSON reserves the pairs of its decoded text too; finish renders the vars without
  the mark and refuses by name when the marked render without its marks differs (ends is gone).
- the byte alphabet has one owner (tokenizer::byte_to_cpt_table); PieceDecoder, Guarded's derives and a pub go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

Verdict: MUST_FIX: Trimming can still remove a template control token, and normalized tool arguments can panic during reconstruction.

Must fix

1. Match the template's whitespace rules

crates/tokenizer/src/guard.rs:73 Qwen36 user content "\u001c" puts the mark after the spelling. Jinja trims U+001C–U+001F (crates/jinja/src/lib.rs:255); Rust's trim does not. The mark reaches the template's following <|im_end|>, so inclusive spans_cut removes that turn token. finish accepts because the rendered text still matches.
Fixing the shared predicate keeps the correction in one place for every template. Replace the full-match branch below and extend the trimming test to all four separators:

let has_text = |s: &str| {
    s.chars()
        .any(|c| !c.is_whitespace() && !('\u{1c}'..='\u{1f}').contains(&c))
};
if start > 0 && has_text(&text[..start]) {
    at.push(start);
} else if end < n && has_text(&text[end..]) {
    at.push(end);
} else {
    let first = text[start..end]
        .chars()
        .next()
        .expect("a nonempty spelling");
    at.push(start + first.len_utf8());
}

2. Remove the depth-limited reconstruction parse

crates/serve/src/guard.rs:305 On Qwen36, send user content "", followed by an assistant tool call whose string arguments contain an object with a value of 124 nested arrays. The argument parser at api.rs:2755 accepts 125 containers; normalization embeds them below six wrappers, giving 131 [derived]. The user content activates the guard, so finish reparses those normalized variables. This exceeds serde_json's default limit of 128. The expect panics and closes the HTTP connection (R10).
Removing this extra parser now avoids maintaining two different depth contracts. Replace the serialization/reparse statements with this direct walk, and add the nested-argument request as a regression case:

let mut original = vars.clone();
{
    let mut pending: Vec<&mut Value> = original.values_mut().collect();
    while let Some(value) = pending.pop() {
        match value {
            Value::String(s) => *s = s.replace(&self.mark, ""),
            Value::Array(a) => pending.extend(a.iter_mut()),
            Value::Object(o) => {
                *o = std::mem::take(o)
                    .into_iter()
                    .map(|(k, v)| (k.replace(&self.mark, ""), v))
                    .collect();
                pending.extend(o.values_mut());
            }
            Value::Null | Value::Bool(_) | Value::Number(_) => {}
        }
    }
}

Non-blocking

⚠ Debugging path: crates/serve/src/api.rs:2397 still returns clean text whose re-tokenization loses the guarded IDs. Document how to inspect the engine's actual prompt IDs, or explain why that diagnostic is deferred.

Checked

Duplicates: the two must-fix items describe separate failure paths. The byte alphabet reuses its existing owner.
Complexity: cuts adds trim predicates; render_chat adds guard branches.
Silent failure: checked optional JSON decoding, reconstruction parsing, and comparison-render errors. Reconstruction can panic.
Tests: the existing trim regression covers a newline, not U+001C–U+001F; no nested-argument depth regression is present.
Gates: no threshold moved in the relevant hunks; the PR states FAIL-first for the original control-string gate.
Escape catalog: C1–C4 do not match.
Performance: prompt construction only; marked requests add one render and serialization/reparse of the template variables per request. No decode-step work changed.

Notes

Rust tests were not run. In-memory source-derived checks reproduced the separator failure and calculated the normalized argument depth.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

…walks the variables

A template's trim takes U+001C–U+001F as whitespace, so a spelling followed only by one of them
now gets its mark inside the spelling. finish strips the mark by a walk over the variables instead
of a JSON round trip, so tool arguments as deep as the argument parser takes no longer reach
serde_json's depth limit. Both cases are tests, red before the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

  • Whitespace separators: fixed for complete spellings; a partial-spelling path remains open below.
  • Deep argument reconstruction: fixed by removing the second JSON parse.
  • Debugging path: the new comment explains the text/ID difference; the diagnostic question remains below.

Verdict: MUST_FIX: Trimming a partial spelling still turns a template turn token into ordinary text.

Must fix

1. Keep partial-spelling marks inside the trimmed text

crates/tokenizer/src/guard.rs:120 (kind A): Qwen36 user content "think>\n" gets a mark after think>. The template trims the newline and appends <|im_end|> directly beside the mark (qwen36-chat-template.jinja:82–88). Inclusive spans_cut rejects that turn token (tokenizer/src/lib.rs:99,308). finish accepts because the rendered text still matches (serve/src/guard.rs:300–325), and chat_prompt uses the guarded IDs (serve/src/api.rs:2985). The engine receives ordinary text instead of the end-of-turn ID. The same failure occurs with U+001C–U+001F and with > followed by those whitespace characters.

The existing trim regression can cover this sibling path without another harness. Replace the if len < n branch with:

if len < n && has_text(&text[len..]) {
    at.push(len);
} else {
    at.extend(after_first.filter(|&cut| cut < len));
}

Extend the trim regression to think> and > followed by each whitespace case, asserting that the template's special IDs survive.

Non-blocking

⚠ Debugging path: crates/serve/src/api.rs:2394 documents that /apply-template returns text whose /tokenize result differs from the guarded chat IDs. It gives no way to inspect those IDs, and the PR body gives no reason to defer that debugging layer. Document an inspection method or explain the deferral.

Checked

Duplicates: 2 new items checked, the whitespace predicate and deep-argument regression; no removable duplicate. Dryer reported 0 pairs.
Complexity: crapper reports cuts at 20; this diff changes its whitespace predicates. The reported render_chat growth was already reviewed. Reconstruction adds a value-kind walk.
Silent failure: 2 paths followed. Primitive reconstruction values stay intact; render equality misses item 1's token-ID loss.
Tests: an in-memory source-derived check reproduced all 10 partial-spelling cases and verified the proposed branch; all 5 complete-spelling cases preserved the turn marker already. The trim regression covers only complete spellings. Mutation tests were not run by the validator.
Gates: no threshold, pin or case was relaxed. The PR body supplies FAIL-first evidence for the original control-string test.
Escape catalog: C1–C4 do not match.
Performance: prompt construction only; reconstruction now clones and walks the variables instead of serializing and reparsing them.

Notes

Rust tests were not run.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

A text that begins with the end of a spelling, or ends in the beginning of one, now gets its mark
beside the piece only when the other side holds text a trim keeps; otherwise the mark goes inside
the piece. The trim test covers whole, leading and trailing pieces beside each of the five spaces;
it was red before the fix ("think>\n" lost the template's <|im_end|>).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@midagedev

Copy link
Copy Markdown
Owner Author

Debugging path: deferred to #591. A route for the guarded ids is a new API field, separate from this fix.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

  • Partial-spelling trim failure: fixed. Marks stay inside multi-character pieces; single-character pieces receive none.

Verdict: CLEAN: The trim failure is fixed; the remaining finding concerns regression coverage.

Non-blocking

⚠ Leading-edge regression coverage: crates/serve/src/ctl_tests.rs:623. Restoring either old leading-edge branch still passes these cases: Qwen36 separates its start token from content with user\n. Extend this regression with served(QWEN, "<|im_start|>{{ messages[0].content | trim }}<|im_end|>", None) and content "\n<thi"; assert both template IDs survive. That catches both leading-edge mutants while this contract is being changed.

Checked

Duplicates: 0 new functions, types or constants in these commits; dryer reported 0 pairs.
Complexity: cuts gains two whitespace conditions in an existing function (reported complexity 22).
Silent failure: 1 new default followed. map_or(0) cannot select zero: start < n and the UTF-8 boundary check guarantee a first character.
Tests: a source-derived model passes all 25 trim cases. Reverting the trailing whitespace predicate fails 10; removing its fallback filter fails 5. Both leading-edge mutants pass those cases and fail the proposed adjacent-marker case.
Gates: no threshold, pin or case was relaxed. The existing regression was extended.
Escape catalog: C1–C4 do not match.

Notes

Rust tests were not run. The model checks mark placement, trimming and special-token matching; it does not execute the Rust/Jinja test target.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev
midagedev enabled auto-merge (rebase) October 21, 2026 04:47
@midagedev
midagedev merged commit c69b5d3 into main Oct 21, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant