radiance 1.0.3

- A tool whose schema bounds a string or an array past 2000 (maxLength, minLength, maxItems,
  minItems) no longer fails every request carrying it (issue #5). The bound is held exactly, up to
  about 200,000; past that the request is refused with a 400 naming the tool's property and the
  count. A bound past 2^31, such as Number.MAX_SAFE_INTEGER, is no bound.
- Compiling a grammar with a long bounded repetition is linear in the bound instead of quadratic:
  maxLength 32000 compiles in 0.7 s instead of 2.1 s.
This commit is contained in:
Deadcode committed 2026-10-04 16:30:28 +02:00
1 parent 8e3463c173
commit f48786483d
8 files changed
+376 -78

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
# a plugin contract and a server release do not move together.
project(radiance VERSION 1.0.2 LANGUAGES C CXX)
project(radiance VERSION 1.0.3 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+80 -61
View File
@@ -30,11 +30,6 @@ using gbnf::match_token;
using gbnf::kMaxCompileBytes;
using gbnf::kMaxNesting;
/* A repetition `S{m,n}` expands into rules, and the expansion multiplies. Past this many the
* grammar is a denial of service against the machine that compiled it, so refuse rather than
* allocate. Upstream calls it MAX_REPETITION_THRESHOLD and picks the same number. */
static constexpr uint64_t MAX_REPETITION_THRESHOLD = 2000;
namespace gbnf {
void throw_set_limit() {
@@ -254,6 +249,19 @@ static const char* parse_int(const char* src) {
return pos;
}
/* The repetition count written in [src, end), which parse_int has checked is digits. A count past
* 2^64 - 2 is refused here; any smaller one is the compile budget's to judge, by what it expands
* to (handle_repetitions). UINT64_MAX itself is reserved for "no maximum". */
static uint64_t parse_count(const char* src, const char* end) {
uint64_t v = 0;
for (const char* p = src; p < end; ++p)
if (__builtin_mul_overflow(v, 10u, &v) ||
__builtin_add_overflow(v, (uint64_t)(*p - '0'), &v) || v == UINT64_MAX)
throw std::runtime_error("repetition count " + std::string(src, (size_t)(end - src)) +
" is past what any grammar can expand to");
return v;
}
static std::pair<uint32_t, const char*> parse_char(const char* src) {
if (*src == '\\') {
switch (src[1]) {
@@ -311,12 +319,14 @@ static std::pair<uint32_t, const char*> parse_token(const VocabView* vocab, cons
/* What a symbol costs beyond its name: the map node that holds it and the rule slot it owns. */
static constexpr uint64_t kSymbolOverhead = 64 + sizeof(GbnfRule);
/* Saturating: `bytes` may be a count from the grammar text times a size, and a sum that wrapped
* would pass. budget_used_ never exceeds the budget, so the comparison cannot overflow. */
void GbnfParser::charge(uint64_t bytes) {
budget_used_ += bytes;
if (budget_used_ > kMaxCompileBytes)
if (bytes > kMaxCompileBytes - budget_used_)
throw std::runtime_error("the grammar expands past " +
std::to_string(kMaxCompileBytes >> 20) + " MiB when compiled; "
"reduce its repetition counts or the size of what they repeat");
budget_used_ += bytes;
}
uint32_t GbnfParser::get_symbol_id(const char* src, size_t len) {
@@ -358,14 +368,21 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
GbnfRule& rule, bool is_nested) {
size_t last_sym_start = rule.size();
const char* pos = src;
uint64_t n_prev_rules = 1;
/* S{m,n} is rewritten into rules rather than counted at match time, which is what keeps the
* state machine a pushdown automaton with no counters in it:
* S{m,n} -> S S ... (m times) S'(n-m), S'(x) ::= S S'(x-1) |
* S{m,} -> S S ... (m times) S', S' ::= S S' |
* S* -> S{0,} S+ -> S{1,} S? -> S{0,1}
* The cost is that the rule count multiplies, which is why the threshold above exists. */
*
* WHAT BOUNDS THE EXPANSION IS ITS SIZE, charged to the compile budget before any of it is
* made, and not a count of repetitions. Upstream refuses any count past 2000, and a JSON
* schema's `maxLength: 8000` -- an ordinary bound on a tool's free-text argument -- failed
* every request carrying the tool. The expansion is linear in the count: each optional link
* is a rule of a few elements and a generated name, and nothing after the parse is worse than
* linear in the rules (find_left_recursion, and the mask plan, which gives every link past
* the longest token one class). So `[^"]{0,8000}` costs about a megabyte and compiles to the
* plan `[^"]{0,1999}` does, and a count the budget cannot hold is refused naming its rule. */
auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
const bool no_max = max_times == UINT64_MAX;
if (last_sym_start == rule.size())
@@ -379,54 +396,59 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
const GbnfRule prev_rule(rule.begin() + (std::ptrdiff_t)last_sym_start, rule.end());
uint64_t total_rules = 1;
if (!no_max && max_times > 0) total_rules = max_times;
else if (min_times > 0) total_rules = min_times;
/* A refusal names the repetition: the count is what a client wrote. */
try {
/* The copies about to be made: the operand once per required count beyond the
* first, and once more in each optional rule with its reference, ALT and END. The
* counts are the grammar's own, up to 2^64 - 2, so the arithmetic saturates where it
* would wrap: a count past the budget is refused here, before the loops below start.
* Each generated rule's name and slot are charged again as it is made
* (generate_symbol_id). */
{
const uint64_t w = prev_rule.size();
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
uint64_t req = 0, opt = 0, copies = 0, bytes = 0;
const bool wraps =
__builtin_mul_overflow(min_times > 1 ? min_times - 1 : 0, w, &req) ||
__builtin_mul_overflow(n_rest, w + 3, &opt) ||
__builtin_add_overflow(req, opt, &copies) ||
__builtin_mul_overflow(copies, (uint64_t)sizeof(GbnfElement), &bytes);
charge(wraps ? UINT64_MAX : bytes);
}
if (n_prev_rules * total_rules >= MAX_REPETITION_THRESHOLD)
throw std::runtime_error("repeated rules multiplied past the sane limit; reduce the "
"number of repetitions or the rule's complexity");
if (min_times == 0) {
rule.resize(last_sym_start);
} else {
for (uint64_t i = 1; i < min_times; i++)
rule.insert(rule.end(), prev_rule.begin(), prev_rule.end());
}
/* The copies about to be made: the operand once per required count beyond the first, and
* once more in each optional rule with its reference, ALT and END. Both counts are below
* MAX_REPETITION_THRESHOLD here, so the product cannot overflow. */
{
const uint64_t w = prev_rule.size();
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
const uint64_t copies = (min_times > 1 ? (min_times - 1) * w : 0) + n_rest * (w + 3);
charge(copies * sizeof(GbnfElement));
uint32_t last_rec_rule_id = 0;
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
GbnfRule rec_rule(prev_rule);
for (uint64_t i = 0; i < n_opt; i++) {
rec_rule.resize(prev_rule.size());
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
if (i > 0 || no_max)
rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id });
rec_rule.push_back({ GRE_ALT, 0 });
rec_rule.push_back({ GRE_END, 0 });
add_rule(rec_rule_id, rec_rule);
last_rec_rule_id = rec_rule_id;
}
if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id });
} catch (const std::runtime_error& ex) {
throw std::runtime_error("the repetition {" + std::to_string(min_times) + "," +
(no_max ? std::string() : std::to_string(max_times)) + "}: " +
ex.what());
}
if (min_times == 0) {
rule.resize(last_sym_start);
} else {
for (uint64_t i = 1; i < min_times; i++)
rule.insert(rule.end(), prev_rule.begin(), prev_rule.end());
}
uint32_t last_rec_rule_id = 0;
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
GbnfRule rec_rule(prev_rule);
for (uint64_t i = 0; i < n_opt; i++) {
rec_rule.resize(prev_rule.size());
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
if (i > 0 || no_max)
rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id });
rec_rule.push_back({ GRE_ALT, 0 });
rec_rule.push_back({ GRE_END, 0 });
add_rule(rec_rule_id, rec_rule);
last_rec_rule_id = rec_rule_id;
}
if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id });
n_prev_rules *= total_rules;
};
while (*pos) {
if (*pos == '"') { /* literal string */
pos++;
last_sym_start = rule.size();
n_prev_rules = 1;
while (*pos != '"') {
if (!*pos) throw std::runtime_error("unexpected end of input");
auto cp = parse_char(pos);
@@ -439,7 +461,6 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
GreType start_type = GRE_CHAR;
if (*pos == '^') { pos++; start_type = GRE_CHAR_NOT; }
last_sym_start = rule.size();
n_prev_rules = 1;
while (*pos != ']') {
if (!*pos) throw std::runtime_error("unexpected end of input");
auto cp = parse_char(pos);
@@ -459,7 +480,6 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
if (*pos == '!') { type = GRE_TOKEN_NOT; pos++; }
auto tp = parse_token(vocab_, pos);
last_sym_start = rule.size();
n_prev_rules = 1;
rule.push_back({ type, tp.first });
pos = parse_space(tp.second, is_nested);
} else if (is_word_char(*pos)) { /* rule reference */
@@ -467,25 +487,21 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
const uint32_t ref = get_symbol_id(pos, (size_t)(name_end - pos));
pos = parse_space(name_end, is_nested);
last_sym_start = rule.size();
n_prev_rules = 1;
rule.push_back({ GRE_RULE_REF, ref });
} else if (*pos == '(') { /* grouping */
if (++depth_ > kMaxNesting)
throw std::runtime_error("parentheses nest more than " +
std::to_string(kMaxNesting) + " deep");
pos = parse_space(pos + 1, true);
const uint32_t n_before = (uint32_t)symbol_ids_.size();
const uint32_t sub_rule_id = generate_symbol_id(rule_name);
pos = parse_alternates(pos, rule_name, sub_rule_id, true);
--depth_;
n_prev_rules = std::max(1u, (uint32_t)symbol_ids_.size() - n_before);
last_sym_start = rule.size();
rule.push_back({ GRE_RULE_REF, sub_rule_id });
if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + pos);
pos = parse_space(pos + 1, is_nested);
} else if (*pos == '.') { /* any char */
last_sym_start = rule.size();
n_prev_rules = 1;
rule.push_back({ GRE_CHAR_ANY, 0 });
pos = parse_space(pos + 1, is_nested);
} else if (*pos == '*') {
@@ -502,7 +518,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
if (!is_digit_char(*pos))
throw std::runtime_error(std::string("expecting an int at ") + pos);
const char* int_end = parse_int(pos);
const uint64_t min_times = std::stoull(std::string(pos, (size_t)(int_end - pos)));
const uint64_t min_times = parse_count(pos, int_end);
pos = parse_space(int_end, is_nested);
uint64_t max_times = UINT64_MAX;
@@ -513,7 +529,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
pos = parse_space(pos + 1, is_nested);
if (is_digit_char(*pos)) {
const char* e = parse_int(pos);
max_times = std::stoull(std::string(pos, (size_t)(e - pos)));
max_times = parse_count(pos, e);
pos = parse_space(e, is_nested);
}
if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + pos);
@@ -521,10 +537,6 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
} else {
throw std::runtime_error(std::string("expecting ',' at ") + pos);
}
const bool has_max = max_times != UINT64_MAX;
if (min_times > MAX_REPETITION_THRESHOLD ||
(has_max && max_times > MAX_REPETITION_THRESHOLD))
throw std::runtime_error("number of repetitions exceeds the sane limit");
handle_repetitions(min_times, max_times);
} else {
break;
@@ -544,7 +556,14 @@ const char* GbnfParser::parse_rule(const char* src) {
throw std::runtime_error(std::string("expecting ::= at ") + pos);
pos = parse_space(pos + 3, true);
pos = parse_alternates(pos, name, rule_id, false);
/* An error inside a rule names the rule. A grammar written from a JSON schema or a tool list
* names its rules after the tool and the property, so this is what tells a client which part
* of its request the grammar could not hold. */
try {
pos = parse_alternates(pos, name, rule_id, false);
} catch (const std::runtime_error& ex) {
throw std::runtime_error("rule '" + name + "': " + ex.what());
}
if (*pos == '\r') pos += pos[1] == '\n' ? 2 : 1;
else if (*pos == '\n') pos++;
+41 -8
View File
@@ -928,7 +928,7 @@ struct Grammar {
std::vector<std::vector<uint32_t>> tops; /* class -> its terminal elements, reachable */
std::vector<std::vector<uint32_t>> below; /* rule -> entries that can sit below it */
std::vector<char> below_done;
std::vector<uint32_t> stamp; /* rule -> the below_of search that last saw it */
std::vector<uint32_t> stamp; /* rule -> the below search that last saw it */
uint32_t stamp_now = 0;
explicit Grammar(const GbnfRuleSet& r, uint32_t rt) : R(r), root(rt) {}
@@ -1376,16 +1376,49 @@ static const std::vector<uint32_t>& below_of(Grammar& G, uint32_t r, OpWork& wor
return out;
}
/* The entries that can sit directly below any of `pos`, as (class, element), sorted. */
/* The entries that can sit directly below any of `pos`, as (class, element), sorted.
*
* ONE WALK FROM ALL OF `pos`'s RULES, not one below_of per rule. The links of a repetition chain
* hand over to each other by tail reference, so the walk up from one link climbs every link above
* it; and every link past the longest token is one class, so one key's positions are all n links
* of `x{0,n}`. Walked a rule at a time that is n^2/2 steps -- `maxLength: 32000` took two seconds
* to compile, and 48000 was refused for the work. Walked from every rule at once, each rule is
* visited once. A rule whose own set is already known contributes it and is not climbed past. A
* key of one rule, the common case, keeps the memo. */
static void preds_of(Grammar& G, const MaskPlan& P, const std::vector<uint32_t>& pos,
std::vector<std::pair<uint32_t, uint32_t>>* out, OpWork& work) {
out->clear();
uint32_t last_rule = kNone;
for (uint32_t p : pos) {
const uint32_t r = G.erule[p];
if (r == last_rule) continue;
last_rule = r;
for (uint32_t u : below_of(G, r, work)) out->push_back({ P.cls[u], u });
const uint32_t first = pos.empty() ? kNone : G.erule[pos[0]];
bool one_rule = true;
for (uint32_t p : pos)
if (G.erule[p] != first) { one_rule = false; break; }
if (one_rule) {
if (first != kNone)
for (uint32_t u : below_of(G, first, work)) out->push_back({ P.cls[u], u });
} else {
const uint32_t mark = ++G.stamp_now;
std::vector<uint32_t> todo;
for (uint32_t p : pos) {
const uint32_t r = G.erule[p];
if (G.stamp[r] != mark) { G.stamp[r] = mark; todo.push_back(r); }
}
work.add(pos.size());
while (!todo.empty()) {
const uint32_t b = todo.back();
todo.pop_back();
if (G.below_done[b]) {
for (uint32_t u : G.below[b]) out->push_back({ P.cls[u], u });
work.add(G.below[b].size() + 1);
continue;
}
for (uint32_t q : G.refs_to[b]) {
const uint32_t u = q + 1;
if (!is_end_of_sequence(&G.R.elems[u])) out->push_back({ P.cls[u], u });
}
for (uint32_t t : G.rev_tail[b])
if (G.stamp[t] != mark) { G.stamp[t] = mark; todo.push_back(t); }
work.add(G.refs_to[b].size() + G.rev_tail[b].size() + 1);
}
}
std::sort(out->begin(), out->end());
out->erase(std::unique(out->begin(), out->end()), out->end());
+7
View File
@@ -933,6 +933,13 @@ accepts no value — `false`, or `{"not": {}}`, which is how TypeBox and Arktype
an argument no call writes. Any other `not` is refused with a 400 naming it: the grammar cannot
express a complement, and dropping the constraint silently would serve a call the tool forbids.
Length bounds are held exactly: `maxLength`, `minLength`, `maxItems` and `minItems` up to about
200,000, which costs the first request carrying the tool under a second to compile on a
quarter-million-token vocabulary and nothing per token after that. A bound past 2^31 (as
`Number.MAX_SAFE_INTEGER` is) is no bound, since no context holds that much. One in between is
refused with a 400 naming the property's rule and the count. The same holds for `response_format`
schemas and `{m,n}` in a GBNF grammar.
### 5.5 Constrained output
```sh
+154
View File
@@ -1063,6 +1063,160 @@ TEST(gbnf_a_repetition_longer_than_any_token_costs_what_the_token_does) {
CHECK_EQ(t.mismatches, 0);
}
/* A LENGTH BOUND PAST 2000 IS HELD, EXACTLY. Upstream refused any repetition count past 2000, so
* a tool whose string argument declared `maxLength: 8000` failed every request carrying it. The
* expansion is bounded by what it costs to compile, not by the count: the bound is the string's
* length to the character, the plan is the one a count under 2000 compiles to, and only a count
* the compile budget cannot hold is refused -- naming the rule it is in. */
TEST(gbnf_a_length_bound_past_two_thousand_is_held_exactly) {
auto bv = bpe_like(59, 1500);
auto whole = [&](const std::string& gbnf, const std::string& text) {
std::unique_ptr<GbnfGrammar> g;
std::string err;
if (GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &g, &err) < 0) return false;
return g->accept_str(text) >= 0 && g->complete();
};
auto from_schema = [](const std::string& schema) {
std::string gbnf, err;
CHECK_OK(grammar_from_json_schema(schema, "root", &gbnf, &err));
return gbnf;
};
auto quoted = [](size_t n) { return "\"" + std::string(n, 'a') + "\""; };
for (int n : { 2001, 8000, 65536 }) {
const std::string g =
from_schema("{\"type\":\"string\",\"maxLength\":" + std::to_string(n) + "}");
CHECK(whole(g, quoted(0)));
CHECK(whole(g, quoted((size_t)n)));
CHECK(!whole(g, quoted((size_t)n + 1)));
}
{
const std::string g = from_schema(R"({"type":"string","minLength":3000,"maxLength":8000})");
CHECK(!whole(g, quoted(2999)));
CHECK(whole(g, quoted(3000)));
CHECK(whole(g, quoted(8000)));
CHECK(!whole(g, quoted(8001)));
}
{
const std::string g =
from_schema(R"({"type":"array","items":{"type":"integer"},"maxItems":5000})");
auto ones = [](int k) {
std::string s = "[";
for (int i = 0; i < k; ++i) s += i ? ",1" : "1";
return s + "]";
};
CHECK(whole(g, ones(5000)));
CHECK(!whole(g, ones(5001)));
}
/* The plan does not grow with the bound: past the longest token, no token tells the counts
* apart. */
std::vector<GbnfProgramInfo> info;
for (int n : { 1999, 8000, 65536 }) {
std::shared_ptr<const GbnfProgram> p;
std::string err;
REQUIRE(gbnf_compile(from_schema("{\"type\":\"string\",\"maxLength\":" +
std::to_string(n) + "}"),
"root", &bv->v, &p, &err) >= 0);
info.push_back(gbnf_program_info(*p));
}
CHECK_EQ(info[0].keys, info[1].keys);
CHECK_EQ(info[1].keys, info[2].keys);
CHECK_EQ(info[0].dense_masks, info[2].dense_masks);
/* The tool from the report, four 8000-character fields, through every served template's
* tool-call grammar and compiled: the request it is in is served. */
const char* tools = R"([{"type":"function","function":{"name":"clarify",
"description":"Ask the user to choose.","parameters":{"type":"object","properties":{
"question":{"type":"string","maxLength":8000},
"choices":{"type":"array","maxItems":4,"items":{"type":"string","maxLength":8000}}},
"required":["question","choices"]}}}])";
const ojson messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } } });
int compiled = 0, carried = 0;
for (const TemplateCase& tc : kTemplates) {
ChatTemplate ct;
REQUIRE(ct.load(slurp(fixture(tc.file)), tc.bos, tc.eos) >= 0);
for (int par = 0; par < 2; ++par) {
for (const char* choice : { "auto", "required" }) {
ChatOptions opt;
opt.tool_choice = choice;
opt.parallel_tool_calls = par != 0;
ChatPrompt cp;
CHECK(ct.apply(messages, ojson::parse(tools), opt, &cp) >= 0);
if (cp.grammar.empty()) continue;
std::shared_ptr<const GbnfProgram> p;
std::string err;
const auto t0 = std::chrono::steady_clock::now();
CHECK(gbnf_compile(cp.grammar, "root", &bv->v, &p, &err) >= 0);
if (!err.empty()) std::fprintf(stderr, " %s: %s\n", tc.file, err.c_str());
const double ms = ms_since(t0);
CHECK(ms < 2000.0);
++compiled;
if (cp.grammar.find("8000}") != std::string::npos) {
++carried;
std::fprintf(stderr, " %s, %s, parallel %s: the bound is in the grammar\n",
tc.file, choice, par ? "on" : "off");
}
}
}
}
CHECK(compiled >= 6);
CHECK(carried >= 1);
/* A group under a repetition is a reference to the group's rule, not a copy of it, so its
* cost is the two counts added, not multiplied; upstream refused it as multiplied. */
{
std::shared_ptr<const GbnfProgram> p;
std::string err;
CHECK(gbnf_compile("root ::= ([a-z]{3000}){3000} \";\"\n", "root", &bv->v, &p, &err) >= 0);
}
/* A schema's bound past INT_MAX -- Number.MAX_SAFE_INTEGER is a common "no limit" -- is no
* bound, which no context the engine serves can tell from the bound; it used to wrap to -1 and
* fail to parse. A negative or non-numeric bound is refused by the converter, naming it. */
for (const char* big : { "9007199254740991", "1e300", "2147483648" }) {
const std::string g =
from_schema(std::string("{\"type\":\"string\",\"maxLength\":") + big + "}");
CHECK(whole(g, quoted(3000)));
const std::string a = from_schema(std::string("{\"type\":\"array\",\"maxItems\":") + big +
",\"items\":{\"type\":\"integer\"}}");
CHECK(whole(a, "[1,2,3]"));
}
for (const char* bad : { R"({"type":"string","maxLength":-5})",
R"({"type":"string","minLength":"3"})",
R"({"type":"array","items":{},"maxItems":-1})" }) {
std::string gbnf, err;
CHECK(grammar_from_json_schema(bad, "root", &gbnf, &err) < 0);
CHECK(err.find("must be a non-negative number") != std::string::npos);
}
/* A bound the compile budget cannot hold is refused naming the property's rule and the
* count, which is what a client needs to find it in its tool list. */
{
std::shared_ptr<const GbnfProgram> p;
std::string err;
CHECK(gbnf_compile(from_schema(R"({"type":"object","properties":{"content":)"
R"({"type":"string","maxLength":1000000}}})"),
"root", &bv->v, &p, &err) < 0);
CHECK(err.find("rule 'content'") != std::string::npos);
CHECK(err.find("{0,1000000}") != std::string::npos);
}
/* What the budget cannot hold is refused, by rule, and a count past 2^64 - 2 is refused as
* one; none of them wraps into a small expansion that compiles. A repetition of a repetition
* copies the expanded run, so `{3000}{3000}` is nine million elements. */
for (const char* g : { "root ::= \"a\" item\nitem ::= [a-z]{0,100000000}\n",
"root ::= \"a\" item\nitem ::= [a-z]{0,18446744073709551614}\n",
"root ::= \"a\" item\nitem ::= [a-z]{18446744073709551614}\n",
"root ::= \"a\" item\nitem ::= [a-z]{0,99999999999999999999999}\n",
"root ::= \"a\" item\nitem ::= [a-z]{3000}{3000}\n" }) {
std::shared_ptr<const GbnfProgram> p;
std::string err;
CHECK(gbnf_compile(g, "root", &bv->v, &p, &err) < 0);
CHECK(err.find("rule 'item'") != std::string::npos);
}
}
/* EVERY TOOL'S COPY OF THE SAME CLAUSE IS ONE CLAUSE TO THE PLAN. A tool-calling template writes
* the same undeclared-parameter clause, the same free-text value and the same closing tags once
* per tool, as rules of their own; the plan hash-conses rules by body, so its size -- and the
+15 -3
View File
@@ -98,6 +98,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/*
patches/0009-chat-a-cdata-section-is-punctuation-not-content.patch
patches/0011-chat-add_bos-must-come-from-the-inputs.patch
patches/0012-json-schema-a-schema-no-value-satisfies.patch
patches/0013-json-schema-a-count-past-int-is-no-bound.patch
On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three
of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs
@@ -429,6 +430,17 @@ PATCH SERIES
`string="true|false"` format), which give every argument an arm of its own and so never see
the object, give an optional one of that kind no arm; a model that writes it reaches the
undeclared-argument arm of 0010 where the format has one. core/text/chatfmt.cpp, the
declared-format grammar, does the same outside this tree. Where a value is required (a required property, the root, an array's items, a union
with no alternative left) it is still refused, by name. Every other `not` is refused as 0004
refuses it.
declared-format grammar, does the same outside this tree. Where a value is required (a
required property, the root, an array's items, a union with no alternative left) it is still
refused, by name. Every other `not` is refused as 0004 refuses it.
patches/0013-json-schema-a-count-past-int-is-no-bound.patch
minLength, maxLength, minItems and maxItems were read with get<int>(), which casts: a bound
past INT_MAX wrapped, and Number.MAX_SAFE_INTEGER -- a common way for a schema generator to
write "no limit" -- came out as -1 and the grammar failed to parse, failing the request with
it. A count at or past INT_MAX is now INT_MAX, which build_repetition already reads as no
maximum. That is exact for anything served here: no context holds a string or an array that
long. A count that is negative or not a number is refused by name. A float count is
truncated, where maxItems used to ignore one. The other half of the same report -- any count
past 2000 refused -- was the GBNF parser's, and is fixed in core/sample/gbnf.cpp.
+24 -5
View File
@@ -904,6 +904,26 @@ public:
// which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an
// optional property no call may set. A `not` of the empty schema makes its whole schema
// unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
// RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition
// takes, or `dflt` where the schema has none. get<int>() casts, so a bound past INT_MAX wrapped:
// Number.MAX_SAFE_INTEGER, a common way to write "no limit", came out as -1 and the grammar did
// not parse. A count at or past INT_MAX is INT_MAX, which build_repetition reads as no maximum;
// no context the engine serves holds a string or an array that long, so the bound changes
// nothing a generation can write. A count that is not a non-negative number is refused.
int _schema_count(const json & schema, const char * key, int dflt, const std::string & name) {
if (!schema.contains(key)) {
return dflt;
}
const json & v = schema[key];
const double d = v.is_number() ? v.get<double>() : -1.0;
if (!(d >= 0)) {
_errors.push_back(std::string(key) + " of \"" + (name.empty() ? std::string("root") : name) +
"\" must be a non-negative number");
return dflt;
}
return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : (int) d;
}
static bool is_unsatisfiable(const json & schema) {
if (schema.is_boolean()) return !schema.get<bool>();
if (!schema.is_object() || !schema.contains("not")) return false;
@@ -1059,9 +1079,8 @@ public:
return _add_rule(rule_name, rule);
}
std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
int min_items = _schema_count(schema, "minItems", 0, name);
int max_items = _schema_count(schema, "maxItems", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
}
@@ -1077,8 +1096,8 @@ public:
}
if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
int min_len = _schema_count(schema, "minLength", 0, name);
int max_len = _schema_count(schema, "maxLength", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
}
if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
@@ -0,0 +1,54 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 95640fb..0bf2b72 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -904,6 +904,26 @@ public:
// which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an
// optional property no call may set. A `not` of the empty schema makes its whole schema
// unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
+ // RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition
+ // takes, or `dflt` where the schema has none. get<int>() casts, so a bound past INT_MAX wrapped:
+ // Number.MAX_SAFE_INTEGER, a common way to write "no limit", came out as -1 and the grammar did
+ // not parse. A count at or past INT_MAX is INT_MAX, which build_repetition reads as no maximum;
+ // no context the engine serves holds a string or an array that long, so the bound changes
+ // nothing a generation can write. A count that is not a non-negative number is refused.
+ int _schema_count(const json & schema, const char * key, int dflt, const std::string & name) {
+ if (!schema.contains(key)) {
+ return dflt;
+ }
+ const json & v = schema[key];
+ const double d = v.is_number() ? v.get<double>() : -1.0;
+ if (!(d >= 0)) {
+ _errors.push_back(std::string(key) + " of \"" + (name.empty() ? std::string("root") : name) +
+ "\" must be a non-negative number");
+ return dflt;
+ }
+ return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : (int) d;
+ }
+
static bool is_unsatisfiable(const json & schema) {
if (schema.is_boolean()) return !schema.get<bool>();
if (!schema.is_object() || !schema.contains("not")) return false;
@@ -1059,9 +1079,8 @@ public:
return _add_rule(rule_name, rule);
}
std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
- int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
- json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
- int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
+ int min_items = _schema_count(schema, "minItems", 0, name);
+ int max_items = _schema_count(schema, "maxItems", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
}
@@ -1077,8 +1096,8 @@ public:
}
if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
- int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
- int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
+ int min_len = _schema_count(schema, "minLength", 0, name);
+ int max_len = _schema_count(schema, "maxLength", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
}
if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {