From 74d1318e46b382b5d2f85dd33efbf93f3f24a624 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:43:13 +0800 Subject: [PATCH 1/3] fix(grammar): enforce array length limits without items --- CHANGELOG.md | 2 + llama_cpp/llama_grammar.py | 17 +++- tests/test_llama_grammar.py | 172 ++++++++++++++++++++++++++++++++++++ 3 files changed, 188 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917bd..c0ce12bfcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- fix(grammar): enforce array length limits without items by @remote-controlled-man + - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds diff --git a/llama_cpp/llama_grammar.py b/llama_cpp/llama_grammar.py index ba34dda831..2769fe8ed6 100644 --- a/llama_cpp/llama_grammar.py +++ b/llama_cpp/llama_grammar.py @@ -769,9 +769,16 @@ def add_component(comp_schema, is_required): ) elif schema_type in (None, "array") and ( - "items" in schema or "prefixItems" in schema + "items" in schema + or "prefixItems" in schema + or ( + schema_type == "array" + and ("minItems" in schema or "maxItems" in schema) + ) ): - items = schema.get("items") or schema["prefixItems"] + items = None + if "items" in schema or "prefixItems" in schema: + items = schema.get("items") or schema["prefixItems"] if isinstance(items, list): return self._add_rule( rule_name, @@ -783,7 +790,11 @@ def add_component(comp_schema, is_required): + ' "]" space', ) else: - item_rule_name = self.visit(items, f"{name}{'-' if name else ''}item") + item_rule_name = ( + self._add_primitive("value", PRIMITIVE_RULES["value"]) + if items is None + else self.visit(items, f"{name}{'-' if name else ''}item") + ) min_items = schema.get("minItems", 0) max_items = schema.get("maxItems") return self._add_rule( diff --git a/tests/test_llama_grammar.py b/tests/test_llama_grammar.py index 34ef2874df..618e07d9cb 100644 --- a/tests/test_llama_grammar.py +++ b/tests/test_llama_grammar.py @@ -1,5 +1,11 @@ import llama_cpp import json +import ctypes +import math + +import pytest + +from llama_cpp.llama_grammar import json_schema_to_gbnf tree = """ leaf ::= "." @@ -76,3 +82,169 @@ def test_grammar_anyof(): grammar = llama_cpp.LlamaGrammar.from_json_schema(json.dumps(sch)) # assert grammar.grammar is not None + + +@pytest.fixture(scope="module") +def grammar_accepts(): + """Check exact UTF-8 bytes and end-of-input with the native grammar sampler.""" + params = llama_cpp.llama_model_default_params() + params.vocab_only = True + model = llama_cpp.llama_model_load_from_file( + b"./vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf", params + ) + assert model + try: + vocab = llama_cpp.llama_model_get_vocab(model) + byte_tokens = {} + for token in range(llama_cpp.llama_vocab_n_tokens(vocab)): + text = llama_cpp.llama_vocab_get_text(vocab, token) + if text.startswith(b"<0x") and text.endswith(b">"): + byte_tokens[int(text[3:-1], 16)] = token + + def accepts(schema, document): + sampler = llama_cpp.llama_sampler_init_grammar( + vocab, json_schema_to_gbnf(json.dumps(schema)).encode(), b"root" + ) + assert sampler + try: + tokens = [byte_tokens[b] for b in document.encode()] + tokens.append(llama_cpp.llama_vocab_eos(vocab)) + for token in tokens: + candidates = (llama_cpp.llama_token_data * 1)( + llama_cpp.llama_token_data(id=token, logit=0.0, p=0.0) + ) + data = llama_cpp.llama_token_data_array( + data=candidates, size=1, selected=-1, sorted=False + ) + llama_cpp.llama_sampler_apply(sampler, ctypes.byref(data)) + if not math.isfinite(candidates[0].logit): + return False + llama_cpp.llama_sampler_accept(sampler, token) + return True + finally: + llama_cpp.llama_sampler_free(sampler) + + yield accepts + finally: + llama_cpp.llama_model_free(model) + + +@pytest.mark.parametrize( + ("limits", "document", "allowed"), + [ + ({"maxItems": 0}, "[]", True), + ({"maxItems": 0}, "[null]", False), + ({"minItems": 1}, "[]", False), + ({"minItems": 1}, "[1,2,3]", True), + ({"maxItems": 2}, "[]", True), + ({"maxItems": 2}, "[1,2]", True), + ({"maxItems": 2}, "[1,2,3]", False), + ({"minItems": 2, "maxItems": 3}, "[1]", False), + ({"minItems": 2, "maxItems": 3}, "[1,2]", True), + ({"minItems": 2, "maxItems": 3}, "[1,2,3]", True), + ({"minItems": 2, "maxItems": 3}, "[1,2,3,4]", False), + ({"minItems": 1, "maxItems": 1}, "[]", False), + ({"minItems": 1, "maxItems": 1}, "[1,2]", False), + ({"minItems": 1, "maxItems": 1}, "1", False), + ({"minItems": 1, "maxItems": 1}, "[1,]", False), + ({"minItems": 1, "maxItems": 1}, "[", False), + ], +) +def test_array_without_items_length_boundaries( + grammar_accepts, limits, document, allowed +): + assert grammar_accepts({"type": "array", **limits}, document) is allowed + + +@pytest.mark.parametrize( + "value", + [ + "42", + "-1.5", + '"text"', + "true", + "false", + "null", + "{}", + "[]", + '"中文"', + '{"nested":[1,null]}', + ], +) +def test_array_without_items_keeps_all_json_item_types(grammar_accepts, value): + assert grammar_accepts( + {"type": "array", "minItems": 1, "maxItems": 1}, f"[{value}]" + ) + + +@pytest.mark.parametrize( + ("schema", "document", "allowed"), + [ + ({"type": "array"}, "[]", True), + ({"type": "array"}, "[1,true,null,[]]", True), + ( + { + "type": "array", + "items": {"type": "integer"}, + "minItems": 1, + "maxItems": 2, + }, + "[1,2]", + True, + ), + ( + { + "type": "array", + "items": {"type": "integer"}, + "minItems": 1, + "maxItems": 2, + }, + '["text"]', + False, + ), + ( + { + "type": "array", + "prefixItems": [{"type": "integer"}, {"type": "string"}], + "items": False, + }, + '[1,"text"]', + True, + ), + ( + { + "type": "array", + "prefixItems": [{"type": "integer"}, {"type": "string"}], + "items": False, + }, + '["text",1]', + False, + ), + ( + { + "type": "object", + "properties": { + "values": {"type": "array", "minItems": 1, "maxItems": 1} + }, + "required": ["values"], + "additionalProperties": False, + }, + '{"values":[true]}', + True, + ), + ( + { + "type": "object", + "properties": { + "values": {"type": "array", "minItems": 1, "maxItems": 1} + }, + "required": ["values"], + "additionalProperties": False, + }, + '{"values":[]}', + False, + ), + ], +) +def test_array_length_compatibility(grammar_accepts, schema, document, allowed): + assert grammar_accepts(schema, document) is allowed From 8ab9906ee2b72a8b458f31465aa8f4aa6530e1fa Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:48:32 +0800 Subject: [PATCH 2/3] fix(grammar): reject unsatisfiable repetition bounds --- CHANGELOG.md | 1 + llama_cpp/llama_grammar.py | 3 +++ tests/test_llama_grammar.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0ce12bfcc..0cf5cde79c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] - fix(grammar): enforce array length limits without items by @remote-controlled-man + Reject unsatisfiable repetition bounds instead of producing a grammar that violates the maximum. - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds diff --git a/llama_cpp/llama_grammar.py b/llama_cpp/llama_grammar.py index 2769fe8ed6..cb9b9ea187 100644 --- a/llama_cpp/llama_grammar.py +++ b/llama_cpp/llama_grammar.py @@ -254,6 +254,9 @@ def from_json_schema(cls, json_schema: str, verbose: bool = True) -> "LlamaGramm def _build_repetition( item_rule, min_items, max_items, separator_rule=None, item_rule_is_literal=False ): + if max_items is not None and max_items < min_items: + raise ValueError("maximum repetition count is less than the minimum") + if not separator_rule: if min_items == 0 and max_items == 1: return f"{item_rule}?" diff --git a/tests/test_llama_grammar.py b/tests/test_llama_grammar.py index 618e07d9cb..8f6cbc106a 100644 --- a/tests/test_llama_grammar.py +++ b/tests/test_llama_grammar.py @@ -248,3 +248,31 @@ def test_array_without_items_keeps_all_json_item_types(grammar_accepts, value): ) def test_array_length_compatibility(grammar_accepts, schema, document, allowed): assert grammar_accepts(schema, document) is allowed + + +@pytest.mark.parametrize( + "schema", + [ + {"type": "array", "minItems": 2, "maxItems": 1}, + {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 1}, + {"type": "string", "minLength": 2, "maxLength": 1}, + ], +) +def test_grammar_rejects_unsatisfiable_length_bounds(schema): + with pytest.raises(ValueError, match="maximum.*minimum"): + llama_cpp.LlamaGrammar.from_json_schema(json.dumps(schema)) + + +@pytest.mark.parametrize( + ("schema", "document", "allowed"), + [ + ({"type": "string", "minLength": 1, "maxLength": 2}, '"a"', True), + ({"type": "string", "minLength": 1, "maxLength": 2}, '""', False), + ({"type": "string", "minLength": 1, "maxLength": 2}, '"abc"', False), + ({"type": "string", "pattern": "^[a-z]{1,2}$"}, '"ab"', True), + ({"type": "string", "pattern": "^[a-z]{1,2}$"}, '"abc"', False), + ({"type": "string", "pattern": "^a{1,2}$"}, '"aa"', True), + ], +) +def test_valid_string_repetition_bounds(grammar_accepts, schema, document, allowed): + assert grammar_accepts(schema, document) is allowed From 764088dde66129010ddc155471a1ddd725e05cb3 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:54:01 +0800 Subject: [PATCH 3/3] docs: link array length changelog to PR --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cf5cde79c..80b84209d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- fix(grammar): enforce array length limits without items by @remote-controlled-man +- fix(grammar): enforce array length limits without items by @remote-controlled-man in #2463 Reject unsatisfiable repetition bounds instead of producing a grammar that violates the maximum. - fix: load cached pretrained models in offline mode by @emme1t in #2396