Skip to content

fix(grammar): enforce array length limits without items - #2463

Open
remote-controlled-man wants to merge 5 commits into
abetlen:mainfrom
remote-controlled-man:codex/prflow-510163f23201
Open

remote-controlled-man wants to merge 5 commits into
abetlen:mainfrom
remote-controlled-man:codex/prflow-510163f23201

Conversation

@remote-controlled-man

@remote-controlled-man remote-controlled-man commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Array schemas that specify minItems or maxItems without items or prefixItems fall back to the unrestricted array primitive. For example, {"type":"array","minItems":1,"maxItems":1} incorrectly permits both [] and [1,2].

Use the existing JSON value rule for unconstrained elements. Bounded arrays without items or prefixItems build their length constraints from named repetition rules. This keeps the grammar shallow and enforces large bounds above the bundled parser's 2,000-repeat quantifier threshold. JSON number forms such as 2.0 retain the same bound as 2. Typed arrays and prefix tuples retain their existing conversion paths. Contradictory repetition bounds raise ValueError, including on the typed-array and string-length paths.

Validation (macOS arm64, Python 3.12.14, bundled llama.cpp f5e6915c2):

  • At 764088d, the native sampler failed to load the new array grammar for maxItems of 257 and 1,000 because it exceeded the parser depth limit.
  • On the updated branch, the native sampler loads those bounds and enforces the upper and lower boundaries. A limit of 2,002 accepts 2,002 items and rejects 2,003.
  • make test: 83 passed, including 60 grammar tests. make lint and git diff --check passed.
  • The initial revision also verified CPU generation for exact lengths 0 through 3 using stories15M-q4_0.gguf. The follow-up was tested locally on macOS only.

The JSON Schema array length contract covers these bounds. Explicit empty items is tracked in #2378. Array bounds inside a list-valued type are a separate converter case.

Prepared with AI assistance, including independent review.

Copilot AI balanced review requested due to automatic review settings November 30, 2026 04:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@1AbdullahButt 1AbdullahButt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The fix is correct for small bounds, and it matches what upstream's common/json-schema-to-grammar.cpp does for an unconstrained array with bounds. But it turns maxItems above 256 from "accepted but unenforced" into "grammar fails to load". Here's what I ran: I built 764088d from source in Docker (Python 3.12, CPU). tests/test_llama_grammar.py passes (46 tests), and with the merge-base llama_grammar.py swapped in I get the 11 failures you describe.

  1. Large maxItems now breaks grammar loading. _build_repetition (llama_grammar.py:254) expands maxItems into nested ( ... )? groups, and the llama.cpp grammar parser caps nesting at 256. I bisected {"type": "array", "maxItems": N} through llama_sampler_init_grammar: N up to 256 loads, but N=257 returns NULL with grammar recursion depth limit exceeded (max 256). On main the same schema got the plain array primitive and loaded fine. Typed arrays already had this problem (items: integer, maxItems: 300 fails too, and that code path is unchanged by this PR), but untyped arrays now hit it as well, and something like maxItems: 1000 is a common pydantic max_length.

    Upstream avoids this by emitting GBNF's bounded repetition instead of nesting (build_repetition in vendor/llama.cpp/common/json-schema-to-grammar.cpp:38). I checked that the grammar form works: "[" space ( value ("," space value){0,4999} )? "]" space loads fine in the same sampler. A port of the separator branch could look like this (the Python is untested):

    if separator_rule:
        if max_items == 0:
            return ""
        lo = max(min_items - 1, 0)
        hi = "" if max_items is None else str(max_items - 1)
        rule = f"{item_rule} ({separator_rule} {item_rule}){{{lo},{hi}}}"
        return f"({rule})?" if min_items == 0 else rule

    If you'd rather keep this PR small, a test that {"type": "array", "maxItems": 1000} still yields a loadable grammar would at least pin the current behaviour.

  2. A gap for a follow-up: {"type": ["array", "null"], "maxItems": 1} is still unbounded, because the list-type branch (llama_grammar.py:714) drops the bounds.

  3. The new ValueError (llama_grammar.py:257) looks good to me. The CHANGELOG could say that it also applies to typed arrays and string lengths, since those callers used to get a grammar and will now get an exception.

@remote-controlled-man

Copy link
Copy Markdown
Contributor Author

Thanks, @1AbdullahButt. The updated branch at 1781d15 fixes the large-bound regression. The native sampler tests cover maxItems of 257 and 1,000, and verify that a limit of 2,002 accepts 2,002 items and rejects 2,003. All 83 local tests passed, and GitHub Tests and Lint are green. Could you take another look?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants