Skip to content

common : gracefully fallback on unsupported regex patterns in JSON schema - #26939

Merged
aldehir merged 2 commits into
ggml-org:masterfrom
aldehir:schema-regex-fallback
Aug 20, 2026
Merged

aldehir merged 2 commits into
ggml-org:masterfrom
aldehir:schema-regex-fallback

Conversation

@aldehir

@aldehir aldehir commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Overview

Fallback unsupported regex patterns in JSON schemas to a JSON string.

Additional information

Some regex patterns cannot be properly supported by the grammar sampler, for example:

  • Lookahead/Lookbehind
  • Unanchored expressions
    • Computing a rule that accepts any prefix and not the following pattern is non-trivial. Attempts to replace anchors with .* are incorrect and result in unconstrained output.

Rather than attempting to support these expressions, it is easier to degrade gracefully to any JSON string and rely on the model to produce valid output. If the output is invalid, the client can address it through a self-correcting loop.

This also handles unsupported PCRE shorthands, although nothing precludes true grammar support. Current open PRs perform naive replacement, which is an incomplete solution.

I also took the liberty to address other lingering regex parsing issues.

Supersedes #26931
Supersedes #25308
Supersedes #22606
Supersedes #20470
Fixes #26930
Fixes #25284

Invalid patterns are still raised as errors.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes, Opus 5 to drive the implementation.

@aldehir
aldehir requested review from a team and ggerganov as code owners August 12, 2026 01:16
@github-actions github-actions Bot added the testing Everything test related label Aug 12, 2026
@aldehir

aldehir commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Automated code review

Reading the surrounding parser to confirm the escape-handling interaction: the grammar parser's parse_char (src/llama-grammar.cpp:162) accepts exactly \x \u \U \t \r \n \\ \" \[ \] — the same set gbnf_escape_length now allows — so the new validation set is consistent with what the downstream grammar parser can actually consume.

Here is the review.


Code review: PR #26939 — graceful fallback for unsupported regex patterns

Scope: single-purpose change to common/json-schema-to-grammar.cpp (regex->grammar conversion) plus tests. Quick-reject gate is clean: linked issues (#26930, #25284), self-contained, no backend/API/quant-type surface, AI usage disclosed. The MAX_PATTERN_DEPTH guard and the bounded hex-escape parsing in gbnf_escape_length are good defensive additions (the pos + 2 + n_hex > pattern.length() check runs before the hex loop, so no OOB read on truncated \x/\u/\U). Security pass: no concerns.

Will slow the review

(point 1) Repetition quantifiers are not validated for negative or min > max values. common/json-schema-to-grammar.cpp ~lines 537-555. std::stoi("-3") succeeds and returns -3 without throwing, so a pattern like ^a{-3}$ sets min_times = max_times = -3, skips the catch, and build_repetition emits a{-3,-3} — an unparseable grammar rule, produced with no warning or error. Likewise {5,2} yields a{5,2} (also invalid), and {0,-1} silently collapses to an empty rule via the max_items == 0 short-circuit. In strict regex these are either errors or literal text, never quantifiers.

Since the PR explicitly sets out to "address other lingering regex parsing issues," add a guard right after the stoi block, e.g. throw invalid_pattern when min_times < 0 || max_times < 0 || min_times > max_times. It is a one-line fix and closes a silent-failure path.

(point 2) */+/? "nothing to repeat" check is incomplete. common/json-schema-to-grammar.cpp ~line 520. The new seq.empty() guard catches the leading-quantifier case, but */+/? immediately after | (e.g. ^a|*b$) still falls through: seq.back() is the | element and the code emits |*, which is malformed. Low impact (input is dubious regex), but the new validation reads as if it fully covers "nothing to repeat," so either tighten it (reject when seq.back() is the | marker) or drop the impression of completeness.

Nits

(point 3) The full-_rules-map copy in _visit_pattern (auto rules_snapshot = _rules;) runs once per pattern. Fine for realistic schemas; just flagging it so the cost is a conscious choice. A cheaper alternative would be to record the rule count/insertion order and truncate on throw, but the current approach is clearer and probably not worth changing.

(point 4) gbnf_escape_length accepts exactly the escape set the grammar parser's parse_char understands (\x \u \U \t \r \n \\ \" \[ \]), so escapes like \-, \^, \d, \w now degrade the whole pattern to "any string" rather than emitting an unparseable grammar. That is the right call given the downstream limitation (the old code silently produced grammars that parse_char would reject). Worth a one-line note in the PR description so reviewers/users understand why previously-"working" patterns now warn and fall back; supporting those escapes would require extending parse_char in src/llama-grammar.cpp, which is correctly out of scope here.

Tests

The new test cases cover the right things: unanchored degradation, partial-conversion rule leakage (the ^[0-9]{3}\w$ -> root ::= string case validates the snapshot revert), invalid-pattern error propagation, and per-property degradation in an object. Consider adding a test for point 1 above (^a{5,2}$ or ^a{-3}$) once the guard is added — currently there is no coverage for malformed quantifiers.

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

@aldehir
aldehir merged commit dc64a16 into ggml-org:master Aug 20, 2026
24 of 27 checks passed
therealkenc pushed a commit to therealkenc/llama.cpp that referenced this pull request Aug 24, 2026
thecodacus pushed a commit to thecodacus/llama.cpp that referenced this pull request Sep 7, 2026
zbrad pushed a commit to zbrad/llama.cpp that referenced this pull request Sep 10, 2026
Nathanw1014 pushed a commit to Nathanw1014/llama.cpp that referenced this pull request Oct 24, 2026
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

3 participants