Commit dee778bd0 for llama.cpp

commit dee778bd0bac5f93c62d428678c785be93018b62
Author: SIDDHARTH U <cid066a86@gmail.com>
Date:   Tue Dec 1 14:44:52 2026 +0530

    grammar : fix builder crash on invalid minItems/maxItems (#29462) (#29497)

    * bug: fix grammar builder crash on invalid minItems/maxItems (#29462)

    When parsing JSON schemas with `minItems` greater than `maxItems`
    (e.g., `{"minItems": 10, "maxItems": 2}`), or direct GBNF like `{10,2}`,
    `llama-grammar.cpp` previously underflowed the `(max_times - min_times)`
    subtraction because it was evaluating it in unsigned arithmetic
    without a `min_times <= max_times` check. This underflow led to
    allocating quintillions of grammar rules, resulting in an immediate
    OOM / `std::bad_alloc`.

    Additionally, the `json-schema-to-grammar.cpp` builder lacked a check
    to cap `max_items = min_items` when the JSON schema contained logically
    contradictory inputs, leading to out-of-order bounds being forwarded to
    the grammar parser.

    This PR adds:
    1. A guard in `json-schema-to-grammar.cpp` that sets
       `max_items = min_items` if `min_items > max_items`.
    2. A strict runtime validation in `llama-grammar.cpp` that explicitly
       rejects out-of-order repetition bounds with a `std::runtime_error`,
       preventing catastrophic memory allocation.

    Closes #29462

    * grammar : simplify min/max repetition check (review feedback)

    ---------

    Co-authored-by: Siddharth U <cid@example.com>

diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 4690a57fa..da4fbfe7b 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -16,6 +16,9 @@
 using json = common_json;

 static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
+    if (min_items > max_items) {
+        max_items = min_items;
+    }
     auto has_max = max_items != std::numeric_limits<int>::max();

     if (max_items == 0) {
diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp
index 21a018c8c..db00050ca 100644
--- a/src/llama-grammar.cpp
+++ b/src/llama-grammar.cpp
@@ -529,6 +529,9 @@ const char * llama_grammar_parser::parse_sequence(
     // use UINT64_MAX as the empty value because we aligned to the proper uint64_t type so -1 can't be used
     // (though it's technically the same as -1 now)
     auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
+        if (min_times > max_times) {
+            throw std::runtime_error("min_times cannot be greater than max_times");
+        }
         bool no_max = max_times == UINT64_MAX;
         if (last_sym_start == rule.size()) {
             throw std::runtime_error(std::string("expecting preceding item to */+/?/{ at ") + pos);