json-schema: a pattern without ^ or $ searches, as JSON Schema reads it

_visit_pattern() read only ^...$ and refused every other `pattern` with "Pattern must start
with '^' and end with '$'". JSON Schema patterns are unanchored (ECMA-262 search, validation
6.3.3). Since 1.8 constrains tool-call arguments with a grammar, a bare pattern on array items
failed the whole request: an opencode agent's tool list did, on every request.

A missing anchor is now written out as any string text on that side, (?:[^"\\]|\\.)*, not ".*"
('.' matches '"' here, so on array items ["1","x"] read as one string holding a digit). A
one-sided anchor beside a top-level '|' is still refused. vendor/patches/0017, vendor/UPSTREAM;
tests in gbnf_test (json_schema_grammars_admit_exactly_their_instances) and sample_test (an
empty pattern now matches every string).
This commit is contained in:
davetha authored and StillDeadcode committed 2026-10-19 10:38:06 +02:00
1 parent 35b357825e
commit 52f47505c2
5 files changed
+140 -4

No files matched your search

+16
View File
@@ -1694,6 +1694,17 @@ TEST(json_schema_grammars_admit_exactly_their_instances) {
{ R"({"type":"string","pattern":"^[a-z]{2,5}-[0-9]+$"})", { R"({"type":"string","pattern":"^[a-z]{2,5}-[0-9]+$"})",
{ R"("ab-1")", R"("abcde-123")" }, { R"("ab-1")", R"("abcde-123")" },
{ R"("a-1")", R"("ab-")", R"("abcdef-1")", R"("AB-1")", R"("ab1")" } }, { R"("a-1")", R"("ab-")", R"("abcdef-1")", R"("AB-1")", R"("ab1")" } },
/* A pattern without ^ or $ searches, as JSON Schema says: the missing side is any text.
* Tool schemas send them bare; on array items a tool call's JSON arguments reach this
* converter, so one bare pattern there failed the whole request. */
{ R"({"type":"string","pattern":"[0-9]+"})",
{ R"("7")", R"("ab12c")" }, { R"("abc")", R"("")" } },
{ R"({"type":"string","pattern":"^ab"})", { R"("ab")", R"("abz")" }, { R"("zab")" } },
{ R"({"type":"string","pattern":"ab$"})", { R"("ab")", R"("zab")" }, { R"("abz")" } },
{ R"({"type":"string","pattern":"a\\$"})", { R"("a$")", R"("za$z")" }, { R"("a")" } },
{ R"({"type":"string","pattern":"x|yz"})", { R"("x")", R"("ayzb")" }, { R"("y")" } },
{ R"({"type":"array","items":{"type":"string","pattern":"[0-9]+"}})",
{ R"(["1","x2"])", R"(["x\"1"])", "[]" }, { R"(["x"])", R"(["1","x"])" } },
{ R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})", { R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})",
{ "[1]", "[1,2,3]", "[-4,0]" }, { "[]", "[1,2,3,4]", R"(["a"])" } }, { "[1]", "[1,2,3]", "[-4,0]" }, { "[]", "[1,2,3,4]", R"(["a"])" } },
{ R"({"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},)" { R"({"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},)"
@@ -1713,6 +1724,11 @@ TEST(json_schema_grammars_admit_exactly_their_instances) {
if (schema_admits(bv->v, R"({"type":"number","minimum":0.5})", "-1")) if (schema_admits(bv->v, R"({"type":"number","minimum":0.5})", "-1"))
fprintf(stderr, " SKIP number bounds: the converter does not enforce minimum/maximum " fprintf(stderr, " SKIP number bounds: the converter does not enforce minimum/maximum "
"on \"number\"\n"); "on \"number\"\n");
for (const char* schema : { R"({"type":"string","pattern":"^a|b"})",
R"({"type":"string","pattern":"a|b$"})" }) {
std::string gbnf, err;
CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0);
}
for (const Case& c : cases) { for (const Case& c : cases) {
for (const char* y : c.yes) { for (const char* y : c.yes) {
const bool ok = schema_admits(bv->v, c.schema, y); const bool ok = schema_admits(bv->v, c.schema, y);
+4 -3
View File
@@ -1123,10 +1123,11 @@ TEST(json_schema_refuses_what_it_cannot_actually_enforce) {
"{\"type\":\"string\",\"pattern\":\"^a]$\"}", "root", &gbnf, &err) < 0); "{\"type\":\"string\",\"pattern\":\"^a]$\"}", "root", &gbnf, &err) < 0);
CHECK(!err.empty()); CHECK(!err.empty());
/* An empty pattern would run front()/back() on an empty string. */ /* An empty pattern would run front()/back() on an empty string. Unanchored, as JSON Schema
* reads it, it now matches every string and never reaches them (vendor patch 0017). */
err.clear(); err.clear();
CHECK(grammar_from_json_schema( CHECK_OK(grammar_from_json_schema(
"{\"type\":\"string\",\"pattern\":\"\"}", "root", &gbnf, &err) < 0); "{\"type\":\"string\",\"pattern\":\"\"}", "root", &gbnf, &err));
/* A leading quantifier would run back() on an empty vector. */ /* A leading quantifier would run back() on an empty vector. */
err.clear(); err.clear();
+19
View File
@@ -101,6 +101,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/*
patches/0013-json-schema-a-count-past-int-is-no-bound.patch patches/0013-json-schema-a-count-past-int-is-no-bound.patch
patches/0014-json-schema-a-not-of-every-type-is-never.patch patches/0014-json-schema-a-not-of-every-type-is-never.patch
patches/0016-chat-analyse-a-template-once.patch patches/0016-chat-analyse-a-template-once.patch
patches/0017-json-schema-a-pattern-without-anchors-searches.patch
On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three 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 of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs
@@ -487,3 +488,21 @@ PATCH SERIES
from it per request is unchanged: the prompt, grammar, triggers, preserved tokens, stops and from it per request is unchanged: the prompt, grammar, triggers, preserved tokens, stops and
PEG parser of 32 requests through each shipped template hash the same with and without the PEG parser of 32 requests through each shipped template hash the same with and without the
cache, and a render took 1.4-1.6 ms with it against 10-13 ms without (one loaded machine). cache, and a render took 1.4-1.6 ms with it against 10-13 ms without (one loaded machine).
patches/0017-json-schema-a-pattern-without-anchors-searches.patch
_visit_pattern() read only ^...$ and refused every other `pattern` with "Pattern must
start with '^' and end with '$'". JSON Schema patterns are unanchored (ECMA-262 search,
validation 6.3.3), and tool schemas send them bare: an opencode agent's tool list drew
twelve of these refusals, so every request it made failed. A bare pattern on array items
is refused, since a tool call's JSON arguments reach this converter. (A top-level string
argument is written raw under the XML call formats and never reaches it, which is why a
bare pattern there passed.) A missing anchor is now written out as any string text on that
side, (?:[^"\\]|\\.)*, before the old check, which then refuses only what that cannot
spell: a one-sided anchor beside a top-level '|', where the anchor binds to one branch. The
filler is not ".*": '.' matches '"' here, and on array items ["1","x"] then read as one
string "1\",\"x" holding a digit. An empty pattern now matches every string rather than
being refused (tests/sample_test.cpp updated). A final '$' after an odd run of
backslashes is a literal and does not count as an anchor. tests/gbnf_test.cpp
(json_schema_grammars_admit_exactly_their_instances) holds the converter to the search
reading, on plain strings and on array items, and pins the refusal.
+41 -1
View File
@@ -291,6 +291,45 @@ static inline bool is_gbnf_escape(char c) {
return false; return false;
} }
} }
// RADIANCE: a JSON Schema `pattern` is unanchored (ECMA-262 search semantics, JSON Schema
// validation 6.3.3): "[0-9]+" admits any string holding a digit. _visit_pattern() reads only
// ^...$, so a missing anchor is written out as "any string text" on that side. That filler is
// not ".*": '.' here matches '"', and the string would run on past its closing quote. A
// one-sided anchor beside a top-level '|' binds to one branch only, so that pattern is
// returned as it came and refused.
static std::string anchor_pattern(const std::string & p) {
static const std::string any = "(?:[^\"\\\\]|\\\\.)*";
const bool starts = !p.empty() && p.front() == '^';
size_t slashes = 0; // backslashes before a final '$': an odd count makes it a literal
if (!p.empty() && p.back() == '$') {
for (size_t k = p.size() - 1; k > 0 && p[k - 1] == '\\'; --k) slashes++;
}
const bool ends = p.size() > (starts ? 1u : 0u) && p.back() == '$' && slashes % 2 == 0;
if (starts && ends) {
return p;
}
const size_t from = starts ? 1 : 0;
const std::string core = p.substr(from, p.size() - from - (ends ? 1 : 0));
if (core.empty()) {
return "^" + any + "$";
}
if (starts != ends) {
int depth = 0;
bool in_class = false;
for (size_t k = 0; k < core.size(); ++k) {
const char c = core[k];
if (c == '\\') { ++k; continue; }
if (in_class) { if (c == ']') in_class = false; continue; }
if (c == '[') in_class = true;
else if (c == '(') depth++;
else if (c == ')') depth--;
else if (c == '|' && depth == 0) return p;
}
}
return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$";
}
static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'}; static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) { static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
@@ -357,7 +396,8 @@ private:
return string_join(rules, " | "); return string_join(rules, " | ");
} }
std::string _visit_pattern(const std::string & pattern, const std::string & name) { std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
const std::string pattern = anchor_pattern(client_pattern);
// RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight
// off the wire. The size test has to come first. // off the wire. The size test has to come first.
if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) { if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) {
@@ -0,0 +1,60 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 12e2756..df4846d 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -291,6 +291,45 @@ static inline bool is_gbnf_escape(char c) {
return false;
}
}
+
+// RADIANCE: a JSON Schema `pattern` is unanchored (ECMA-262 search semantics, JSON Schema
+// validation 6.3.3): "[0-9]+" admits any string holding a digit. _visit_pattern() reads only
+// ^...$, so a missing anchor is written out as "any string text" on that side. That filler is
+// not ".*": '.' here matches '"', and the string would run on past its closing quote. A
+// one-sided anchor beside a top-level '|' binds to one branch only, so that pattern is
+// returned as it came and refused.
+static std::string anchor_pattern(const std::string & p) {
+ static const std::string any = "(?:[^\"\\\\]|\\\\.)*";
+ const bool starts = !p.empty() && p.front() == '^';
+ size_t slashes = 0; // backslashes before a final '$': an odd count makes it a literal
+ if (!p.empty() && p.back() == '$') {
+ for (size_t k = p.size() - 1; k > 0 && p[k - 1] == '\\'; --k) slashes++;
+ }
+ const bool ends = p.size() > (starts ? 1u : 0u) && p.back() == '$' && slashes % 2 == 0;
+ if (starts && ends) {
+ return p;
+ }
+ const size_t from = starts ? 1 : 0;
+ const std::string core = p.substr(from, p.size() - from - (ends ? 1 : 0));
+ if (core.empty()) {
+ return "^" + any + "$";
+ }
+ if (starts != ends) {
+ int depth = 0;
+ bool in_class = false;
+ for (size_t k = 0; k < core.size(); ++k) {
+ const char c = core[k];
+ if (c == '\\') { ++k; continue; }
+ if (in_class) { if (c == ']') in_class = false; continue; }
+ if (c == '[') in_class = true;
+ else if (c == '(') depth++;
+ else if (c == ')') depth--;
+ else if (c == '|' && depth == 0) return p;
+ }
+ }
+ return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$";
+}
+
static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
@@ -357,7 +396,8 @@ private:
return string_join(rules, " | ");
}
- std::string _visit_pattern(const std::string & pattern, const std::string & name) {
+ std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
+ const std::string pattern = anchor_pattern(client_pattern);
// RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight
// off the wire. The size test has to come first.
if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) {