Archived
gbnf: share bounded-repetition chains across identical operands
Reuse one optional-link chain per repeated operand, preserving exact bounds and existing compile limits. Includes a synthetic multi-bound schema regression. AI-assisted contribution; original implementation by claude-nanbeige.
This commit is contained in:
1 parent
caa468389c
commit
9497bf9061
3 files changed
+83
-15
No files matched your search
+37
-15
@@ -391,7 +391,10 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
* by a repetition count (upstream's cap of 2000 rejects ordinary schemas such as
|
||||
* `maxLength: 8000`). It is linear in the count, and nothing after the parse is worse than
|
||||
* linear in the rules; the mask plan gives every link past the longest token one class. So
|
||||
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`. */
|
||||
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`.
|
||||
*
|
||||
* S'(x) depends only on S and x, so the links are shared: every bounded repetition of the same
|
||||
* operand points into one chain (rep_links_), and S{0,2000} after S{0,4000} builds nothing. */
|
||||
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())
|
||||
@@ -407,17 +410,30 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
|
||||
/* A refusal names the repetition the client wrote. */
|
||||
try {
|
||||
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
|
||||
|
||||
/* A bounded repetition's chain of links for this operand, shared with every earlier
|
||||
* bounded repetition of it; only the links it lacks are built. */
|
||||
std::vector<uint32_t>* links = nullptr;
|
||||
uint64_t n_new = n_opt;
|
||||
if (!no_max && n_opt > 0) {
|
||||
std::vector<std::pair<uint32_t, uint32_t>> key;
|
||||
key.reserve(prev_rule.size());
|
||||
for (const auto& e : prev_rule) key.emplace_back((uint32_t)e.type, e.value);
|
||||
links = &rep_links_[std::move(key)];
|
||||
n_new = n_opt > links->size() ? n_opt - links->size() : 0;
|
||||
}
|
||||
|
||||
/* Charge the copies up front: the operand once per required count beyond the first,
|
||||
* and once per optional rule plus its reference, ALT and END. Counts reach 2^64 - 2,
|
||||
* so overflow saturates and is refused before the loops run. Each generated rule's
|
||||
* name and slot are charged again in generate_symbol_id. */
|
||||
* and once per optional rule built plus its reference, ALT and END. Counts reach
|
||||
* 2^64 - 2, so overflow saturates and is refused before the loops run. Each generated
|
||||
* rule's name and slot are charged again in 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_mul_overflow(n_new, w + 3, &opt) ||
|
||||
__builtin_add_overflow(req, opt, &copies) ||
|
||||
__builtin_mul_overflow(copies, (uint64_t)sizeof(GbnfElement), &bytes);
|
||||
charge(wraps ? UINT64_MAX : bytes);
|
||||
@@ -430,21 +446,26 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
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());
|
||||
if (no_max) {
|
||||
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_RULE_REF, 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;
|
||||
rule.push_back({ GRE_RULE_REF, rec_rule_id });
|
||||
} else if (n_opt > 0) {
|
||||
while (links->size() < n_opt) {
|
||||
rec_rule.resize(prev_rule.size());
|
||||
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
|
||||
if (!links->empty()) rec_rule.push_back({ GRE_RULE_REF, links->back() });
|
||||
rec_rule.push_back({ GRE_ALT, 0 });
|
||||
rec_rule.push_back({ GRE_END, 0 });
|
||||
add_rule(rec_rule_id, rec_rule);
|
||||
links->push_back(rec_rule_id);
|
||||
}
|
||||
rule.push_back({ GRE_RULE_REF, (*links)[n_opt - 1] });
|
||||
}
|
||||
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)) + "}: " +
|
||||
@@ -580,6 +601,7 @@ const char* GbnfParser::parse_rule(const char* src) {
|
||||
int GbnfParser::parse(const char* src, std::string* err) {
|
||||
if (!src) return RAD_E_INVAL;
|
||||
budget_used_ = 0;
|
||||
rep_links_.clear();
|
||||
depth_ = 0;
|
||||
try {
|
||||
const char* pos = parse_space(src, true);
|
||||
|
||||
@@ -146,6 +146,13 @@ private:
|
||||
uint32_t depth_ = 0;
|
||||
void charge(uint64_t bytes);
|
||||
|
||||
/* The optional links of bounded repetitions, keyed by the repeated operand's elements:
|
||||
* links[k - 1] is S'(k) ::= S S'(k-1) |, so every S{m,n} over the same S shares one chain and
|
||||
* builds only the links past the longest it has (handle_repetitions). A JSON schema's
|
||||
* `maxLength` bounds all repeat `char`, so a schema with many of them costs its longest bound
|
||||
* once instead of the sum of them. */
|
||||
std::map<std::vector<std::pair<uint32_t, uint32_t>>, std::vector<uint32_t>> rep_links_;
|
||||
|
||||
uint32_t get_symbol_id(const char* src, size_t len);
|
||||
uint32_t generate_symbol_id(const std::string& base);
|
||||
void add_rule(uint32_t id, const GbnfRule& rule);
|
||||
|
||||
@@ -1433,6 +1433,45 @@ TEST(gbnf_a_length_bound_past_two_thousand_is_held_exactly) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Bounded repetitions of one operand share one chain of links, so a schema's many length bounds
|
||||
* cost its longest once rather than their sum. 200 properties at `maxLength: 4000` were 200 chains,
|
||||
* past the compile budget (a tool schema like that is refused in full); shared, they compile, and
|
||||
* every bound, short or long, string or array, is still held exactly. */
|
||||
TEST(gbnf_bounds_over_one_operand_share_their_links) {
|
||||
auto bv = bpe_like(59, 1500);
|
||||
std::string props = R"("a":{"type":"string","maxLength":4000},"b":{"type":"string","maxLength":7},)"
|
||||
R"("c":{"type":"array","items":{"type":"string","maxLength":5},"maxItems":3})";
|
||||
for (int i = 0; i < 200; ++i)
|
||||
props += ",\"f" + std::to_string(i) + "\":{\"type\":\"string\",\"maxLength\":4000}";
|
||||
std::string gbnf, err;
|
||||
CHECK_OK(grammar_from_json_schema("{\"type\":\"object\",\"properties\":{" + props +
|
||||
"},\"required\":[\"a\",\"b\",\"c\"]}",
|
||||
"root", &gbnf, &err));
|
||||
std::unique_ptr<GbnfGrammar> g;
|
||||
CHECK_OK(GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &g, &err));
|
||||
auto whole = [&](const std::string& text) {
|
||||
std::unique_ptr<GbnfGrammar> h;
|
||||
std::string e;
|
||||
if (GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &h, &e) < 0) return false;
|
||||
return h->accept_str(text) >= 0 && h->complete();
|
||||
};
|
||||
auto doc = [](size_t a, size_t b, std::vector<size_t> c, size_t f7) {
|
||||
std::string s = "{\"a\":\"" + std::string(a, 'x') + "\",\"b\":\"" + std::string(b, 'y') +
|
||||
"\",\"c\":[";
|
||||
for (size_t i = 0; i < c.size(); ++i) s += (i ? ",\"" : "\"") + std::string(c[i], 'z') + "\"";
|
||||
s += "]";
|
||||
if (f7) s += ",\"f7\":\"" + std::string(f7, 'w') + "\"";
|
||||
return s + "}";
|
||||
};
|
||||
CHECK(whole(doc(4000, 7, { 5, 0, 5 }, 4000)));
|
||||
CHECK(whole(doc(0, 0, {}, 0)));
|
||||
CHECK(!whole(doc(4001, 7, { 5 }, 0)));
|
||||
CHECK(!whole(doc(10, 8, { 5 }, 0)));
|
||||
CHECK(!whole(doc(10, 7, { 6 }, 0)));
|
||||
CHECK(!whole(doc(10, 7, { 1, 1, 1, 1 }, 0)));
|
||||
CHECK(!whole(doc(10, 7, { 1 }, 4001)));
|
||||
}
|
||||
|
||||
/* Identical clauses across tools are one clause to the plan. A tool-calling template writes the
|
||||
* same undeclared-parameter clause, free-text value and closing tags as separate rules per tool;
|
||||
* the plan hash-conses rules by body, so its size and the compile's vocabulary walks do not grow
|
||||
|
||||
Reference in new issue
Block a user