Skip to content

common/peg : handle invalid utf-8 sequences in the AST - #29161

Merged
aldehir merged 3 commits into
ggml-org:masterfrom
aldehir:utf8-strict
Sep 20, 2026
Merged

aldehir merged 3 commits into
ggml-org:masterfrom
aldehir:utf8-strict

Conversation

@aldehir

@aldehir aldehir commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Models may occasionally emit invalid UTF-8 which fails during parsing. This records invalid utf-8 sequences during parse and provides a sanitized_text() at every node in the AST.

Tool names/args are not passed through this, as they should be grammar constrained to only produce UTF-8. If this becomes a problem, we can easily change them to use sanitize_text() instead.

ref: #28724
fixes #24327
fixes #27543

Additional Information

Invalid UTF-8 runs are replaced with a single U+FFFD, aka the "maximal subpart" per https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G66453.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes, implementation defined by me and implemented by Fable 5.1.

@aldehir

aldehir commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Automated code review

Review of PR #29161 (common/peg : handle invalid utf-8 sequences in the AST).

The approach is sound and well-scoped: record invalid UTF-8 runs during the until scan, carry them up the AST, and expose sanitized_text(). The maximal-subpart replacement matches the Unicode recommendation, the changed bytes_consumed semantics are safe for all other callers (trie, jinja tojson, fs_validate_filename all check status before touching bytes_consumed), and backtracking deduplication is handled correctly (failed/peeked results drop their runs). Test coverage is good. A few things to address:

Blocking / should fix

(point 1) The non-strict default silently regresses the tool-call paths built on until, contradicting the PR's own rationale ("tool names/args should be grammar constrained"). These now consume invalid bytes and hand raw node.text to the mappers:

  • common/parsers/deepseek.cpp:168: p.tool_arg_string_value(p.until(PARAM_END)) feeds raw text into escape_json_string_inner(), which is ordered_json(s).dump() (common/chat-peg-parser.cpp:71) and throws nlohmann::json::type_error.316 on invalid UTF-8 - a different, uncaught exception type where the code previously failed the parse with the expected "does not match format" error.
  • common/parsers/gemma4.cpp:223: gemma4-string-content (p.until("<|\"|>")) same issue via gemma4_to_json().
  • common/chat-auto-parser-generator.cpp:305/307/426/428: p.tool_id(p.until(...)) puts raw invalid bytes into tool_calls[].id (raw node.text at common/chat-peg-parser.cpp:351-357), which blows up later at response serialization.
  • common/chat-auto-parser-generator.cpp:363: until-suffix for argument values, same as deepseek.

Since the flag exists for exactly this, pass strict = true at these tool-related call sites (restores the old fail-fast) or route them through sanitized_text(). Note grammar constraints don't save you here: the PR's premise is that models emit invalid UTF-8, and chat parsing also runs without a grammar applied.

Will slow the review

(point 2) sanitized_text() (common/peg-parser.cpp:169) computes invalid.pos - seg_start and indexes text.data() + (seg_start - start) with no bounds check. This is only safe because the entries are guaranteed ascending and within [start, end) by the merge logic in seq/repeat/until - an invariant nothing enforces. If it is ever violated (new combinator, refactor), the subtraction underflows and appends ~SIZE_MAX bytes from an out-of-bounds pointer. Given this runs on model output, add a cheap guard or GGML_ASSERT in sanitized_text() (e.g. invalid.pos >= seg_start && invalid.pos + invalid.len <= end) or enforce it where entries are merged.

(point 3) Truncated sequences at the end of a complete message are still silently dropped, not replaced: common_chat_peg_parse always parses with LENIENT, so a trailing \xE4\xB8 in a final (non-partial) message returns NEED_MORE_INPUT, the mapper maps the partial node, and the bytes vanish (no U+FFFD). strict doesn't help there either, since the INCOMPLETE && is_lenient() branch returns before the strict check. Same as the old behavior, so not a regression, but it's a gap versus the stated goal; worth a comment or a follow-up.

Nits

(point 4) The seq/repeat merge sites copy each child's vector (invalid_utf8.insert(..., result.invalid_utf8.begin(), ...)); result is a by-value local, so std::make_move_iterator avoids the copies. Also every enclosing tag/rule node stores a full copy of the vector (O(depth) copies per run) - fine for realistic sizes, just be aware.

(point 5) The strict flag round-trips through save/load (serialize_parser_variant now emits it), but no real parser uses strict = true and the new tests don't exercise save/load of a strict until, so that serialization branch is untested.

Everything else checks out: constructor arity changes are backward compatible, the {} nodes argument in the new 4-arg calls is unambiguous, choice/peek/not correctly discard runs from non-committed alternatives (verified against the new backtracking test), and the strict-mode FAIL restores the pre-PR behavior for the updated strict test.

This review was generated automatically by pi coding agent using zai-org/GLM-5.3. It may contain mistakes. Maintainers make the final call.

@aldehir
aldehir marked this pull request as ready for review September 19, 2026 22:23
@aldehir
aldehir requested review from a team and ggerganov as code owners September 19, 2026 22:23
@aetherbird

Copy link
Copy Markdown
Contributor

Tested against the issue outlined in #28724 by replaying the observed Ling 3.0 failure shape (valid U+2705 followed by a lone 0x85 continuation byte) through the native PEG parser. master fails the parse, whereas this branch succeeds and delivers both reasoning and content with U+FFFD at the corrupted byte. Unit tests pass here as well. LGTM from the Ling 3.0 serving side.

@ServeurpersoCom ServeurpersoCom 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.

LGTM, one place instead of scattered UTF-8 passes, and the raw text stays intact. Small nit: strict has no caller outside the tests, could we drop it (along with its serialization) until something needs it?

@aldehir

aldehir commented Sep 20, 2026

Copy link
Copy Markdown
Contributor Author

LGTM, one place instead of scattered UTF-8 passes, and the raw text stays intact. Small nit: strict has no caller outside the tests, could we drop it (along with its serialization) until something needs it?

Sure. I only included it thinking it was required by the preset parser, but that doesn't seem to be the case.

@ServeurpersoCom ServeurpersoCom 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.

Thanks for the refactor!

@aldehir
aldehir merged commit 3d82ef6 into ggml-org:master Sep 20, 2026
23 of 26 checks passed
slomin pushed a commit to potato-os/llama.cpp that referenced this pull request Sep 24, 2026
* common/peg : handle invalid utf-8 sequences in the AST

* cont : return maximal subpart per Unicode recommendations

* cont : remove strict argument

(cherry picked from commit 3d82ef6)
(cherry picked from commit ef06fedd8901ac691867d6d514a4bc2505a17ac1)
LadislavSopko pushed a commit to 0ics-srls/llama.cpp that referenced this pull request Oct 5, 2026
* common/peg : handle invalid utf-8 sequences in the AST

* cont : return maximal subpart per Unicode recommendations

* cont : remove strict argument
edwardyoon pushed a commit to edwardyoon/focus-llama that referenced this pull request Oct 7, 2026
* common/peg : handle invalid utf-8 sequences in the AST

* cont : return maximal subpart per Unicode recommendations

* cont : remove strict argument

(cherry picked from commit 3d82ef6)
Nathanw1014 pushed a commit to Nathanw1014/llama.cpp that referenced this pull request Oct 24, 2026
* common/peg : handle invalid utf-8 sequences in the AST

* cont : return maximal subpart per Unicode recommendations

* cont : remove strict argument

(cherry picked from commit 3d82ef6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

testing Everything test related

Projects

None yet

4 participants