radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

@@ -1,109 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index db3a6cc..ed895b5 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -121,13 +121,25 @@ common_peg_arena autoparser::build_parser(const generation_params & inputs, cons
ctx.content = &content;
ctx.reasoning = &reasoning;
+ bool has_tools = inputs.tools.is_array() && !inputs.tools.empty();
+ bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
+
+ // RADIANCE: tell the reasoning parser where a tool call starts, so an unclosed reasoning
+ // block cannot swallow one. This is the same marker the tool parsers below use to split
+ // content from calls, computed here because only this scope can see both analyzers.
+ if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE && jinja_caps.supports_tool_calls) {
+ const std::string & marker = !tools.format.section_start.empty()
+ ? tools.format.section_start
+ : tools.format.per_call_start;
+ if (!marker.empty()) {
+ ctx.reasoning_terminators.push_back(marker);
+ }
+ }
+
// Build reasoning parser
ctx.reasoning_parser = reasoning.build_parser(ctx);
auto parser = p.eps();
-
- bool has_tools = inputs.tools.is_array() && !inputs.tools.empty();
- bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
bool pure_content = reasoning.mode == reasoning_mode::NONE;
if (has_response_format) {
@@ -156,12 +168,57 @@ common_peg_parser analyze_reasoning::build_parser(parser_build_context & ctx) co
if (mode == reasoning_mode::TAG_BASED || mode == reasoning_mode::TOOLS_ONLY) {
if (!end.empty()) {
+ const std::string trimmed_end = trim_whitespace(end);
+
+ // RADIANCE: `until(end)` runs to the END OF THE INPUT when the closing tag never
+ // arrives, so a reasoning block the model forgot to close swallowed the entire
+ // reply -- including a <tool_call> written from inside it, which meant the call was
+ // parsed as reasoning text and LOST. The turn then carried no tool call and no
+ // content, and an agent driving it simply stopped. Templates in the wild carry
+ // explicit self-heals for this shape, which is how we know models emit it.
+ //
+ // The repair is an ORDERED CHOICE whose first branch is GUARDED BY A LOOKAHEAD, so
+ // it can only win in the one situation it was written for. The unclosed branch runs
+ // `until` over both the closing tag and the tool-call opener and then REQUIRES, on a
+ // peek that consumes nothing, that what stopped it was the opener. So:
+ //
+ // reasoning </think> <tool_call> -> stops at </think>, peek fails, upstream rule
+ // reasoning <tool_call> -> stops at the opener, peek holds, call parsed
+ // reasoning, no tag, no call -> runs to EOF, peek fails, upstream rule
+ //
+ // The guard is what makes this additive: every reply that closes its reasoning block
+ // takes the second branch, which is upstream's rule byte for byte. It also keeps
+ // reasoning that merely MENTIONS an opener on the upstream path, because such a reply
+ // still has its closing tag and the peek therefore never fires.
+ //
+ // Ordering matters and is not free to swap: `until` returns "need more input" rather
+ // than failing when it reaches the end of the input, so a closed branch placed first
+ // would short-circuit before its required closing literal was ever checked, and the
+ // unclosed branch would be unreachable. That is the bug this comment cost.
+ if (!ctx.reasoning_terminators.empty()) {
+ std::vector<std::string> stops = ctx.reasoning_terminators;
+ stops.insert(stops.begin(), trimmed_end);
+
+ std::vector<common_peg_parser> openers;
+ openers.reserve(ctx.reasoning_terminators.size());
+ for (const auto & t : ctx.reasoning_terminators) {
+ openers.push_back(p.literal(t));
+ }
+ auto unclosed = p.reasoning(p.until_one_of(stops)) + p.peek(p.choice(openers));
+ auto closed = p.reasoning(p.until(trimmed_end)) + p.optspace(end);
+ if (!start.empty()) {
+ return p.optional(p.choice({ p.optspace(start) + unclosed,
+ p.optspace(start) + closed }));
+ }
+ return p.optional(p.choice({ unclosed, closed }));
+ }
+
if (!start.empty()) {
// Standard tag-based: optional(<think>reasoning</think>)
- return p.optional(p.optspace(start) + p.reasoning(p.until(trim_whitespace(end))) + p.optspace(end));
+ return p.optional(p.optspace(start) + p.reasoning(p.until(trimmed_end)) + p.optspace(end));
}
// Delimiter-style (empty start)
- return p.optional(p.reasoning(p.until(trim_whitespace(end))) + p.optspace(end));
+ return p.optional(p.reasoning(p.until(trimmed_end)) + p.optspace(end));
}
}
diff --git a/common/chat-auto-parser.h b/common/chat-auto-parser.h
index 7858f65..478edef 100644
--- a/common/chat-auto-parser.h
+++ b/common/chat-auto-parser.h
@@ -228,6 +228,11 @@ struct parser_build_context {
const analyze_reasoning * reasoning = nullptr;
const analyze_content * content = nullptr;
+ // RADIANCE: markers that end an UNCLOSED reasoning block, in addition to its closing tag --
+ // in practice the tool-call opener. Empty unless this turn can call tools. See the comment
+ // in analyze_reasoning::build_parser for what goes wrong without it.
+ std::vector<std::string> reasoning_terminators;
+
parser_build_context(common_chat_peg_builder & p, const generation_params & inputs);
};
@@ -1,91 +0,0 @@
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -343,13 +343,15 @@ private:
rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
}
return string_join(rules, " | ");
}
std::string _visit_pattern(const std::string & pattern, const std::string & name) {
- if (!(pattern.front() == '^' && pattern.back() == '$')) {
+ // 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() == '$')) {
_errors.push_back("Pattern must start with '^' and end with '$'");
return "";
}
std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
std::unordered_map<std::string, std::string> sub_rule_ids;
@@ -407,12 +409,18 @@ private:
results.push_back(to_rule(item));
}
return std::make_pair(string_join(results, " "), false);
};
while (i < length) {
+ // RADIANCE: every arm below must consume at least one byte. The literal arm does not when
+ // it meets a byte that is in NON_LITERAL_SET but that no arm above claims -- a
+ // stray ']' or '}' -- so it breaks out with `literal` empty, nothing is pushed,
+ // and the loop reconsiders the same byte forever. `pattern` is client data, so
+ // that is a one-string denial of service. Checked at the bottom of the body.
+ const size_t progress_at = i;
char c = sub_pattern[i];
if (c == '.') {
seq.emplace_back(get_dot(), false);
i++;
} else if (c == '(') {
i++;
@@ -462,12 +470,17 @@ private:
i++;
seq.emplace_back(square_brackets, false);
} else if (c == '|') {
seq.emplace_back("|", false);
i++;
} else if (c == '*' || c == '+' || c == '?') {
+ if (seq.empty()) {
+ // RADIANCE: a leading quantifier, "^*$". back() on an empty vector is UB.
+ _errors.push_back("Quantifier with nothing to repeat");
+ break;
+ }
seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
i++;
} else if (c == '{') {
std::string curly_brackets = std::string(1, c);
i++;
while (i < length && sub_pattern[i] != '}') {
@@ -496,12 +509,17 @@ private:
}
}
} catch (const std::invalid_argument & e) {
_errors.push_back("Invalid number in curly brackets");
return std::make_pair("", false);
}
+ if (seq.empty()) {
+ // RADIANCE: a leading "{n,m}" has nothing before it to repeat; back() would be UB.
+ _errors.push_back("Quantifier with nothing to repeat");
+ break;
+ }
auto &last = seq.back();
auto &sub = last.first;
auto sub_is_literal = last.second;
if (!sub_is_literal) {
std::string & sub_id = sub_rule_ids[sub];
@@ -545,12 +563,16 @@ private:
}
}
if (!literal.empty()) {
seq.emplace_back(literal, true);
}
}
+ if (i == progress_at) {
+ _errors.push_back("Unsupported pattern syntax");
+ break;
+ }
}
return join_seq();
};
return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space");
}
@@ -1,97 +0,0 @@
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -276,12 +276,24 @@ static std::regex GRAMMAR_LITERAL_ESCAPE_RE("[\r\n\"\\\\]");
static std::regex GRAMMAR_RANGE_LITERAL_ESCAPE_RE("[\r\n\"\\]\\-\\\\]");
static std::unordered_map<char, std::string> GRAMMAR_LITERAL_ESCAPES = {
{'\r', "\\r"}, {'\n', "\\n"}, {'"', "\\\""}, {'-', "\\-"}, {']', "\\]"}, {'\\', "\\\\"}
};
static std::unordered_set<char> NON_LITERAL_SET = {'|', '.', '(', ')', '[', ']', '{', '}', '*', '+', '?'};
+
+// RADIANCE: the escapes GBNF can actually spell. Anything else in a pattern is refused rather
+// than copied into a grammar that will not load. See the use site in _visit_pattern.
+static inline bool is_gbnf_escape(char c) {
+ switch (c) {
+ case 'x': case 'u': case 'U': case 't': case 'r': case 'n':
+ case '\\': case '"': case '[': case ']':
+ return true;
+ default:
+ return false;
+ }
+}
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) {
std::smatch match;
std::string result;
@@ -545,12 +557,24 @@ private:
char next = sub_pattern[i + 1];
if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
i++;
literal += sub_pattern[i];
i++;
} else {
+ // RADIANCE: GBNF knows \x \u \U \t \r \n \\ \" \[ \] and nothing
+ // else. Copying an escape it cannot spell (\d \w \s \b \/ \-, a
+ // backreference) produces a grammar that returns success here and
+ // then fails to LOAD, which the caller sees as an internal error
+ // on a schema we told it was fine.
+ if (!is_gbnf_escape(next)) {
+ _errors.push_back(
+ std::string("Unsupported regex escape '\\") + next +
+ "' in a pattern: GBNF cannot spell it, so the grammar "
+ "would not load");
+ return std::make_pair(std::string(), true);
+ }
literal += sub_pattern.substr(i, 2);
i += 2;
}
} else if (sub_pattern[i] == '"') {
literal += "\\\"";
i++;
@@ -791,12 +815,21 @@ public:
for (auto & x : n) {
visit_refs(x);
}
} else if (n.is_object()) {
if (n.contains("$ref")) {
std::string ref = n["$ref"];
+ // RADIANCE: a sampler that reaches the network to decide what tokens are legal
+ // is not a sampler we will ship. Upstream fetches through an injected callback
+ // which the public entry point then stubs out to return null -- so a remote
+ // $ref silently degrades into "accepts any object". Refuse, and fetch nothing.
+ if (ref.rfind("http://", 0) == 0 || ref.rfind("https://", 0) == 0) {
+ throw std::runtime_error(
+ "remote $ref is not supported: '" + ref + "'. Inline the referenced "
+ "schema; this converter does not fetch over the network.");
+ }
if (_refs.find(ref) == _refs.end()) {
json target;
if (ref.find("https://") == 0) {
std::string base_url = ref.substr(0, ref.find('#'));
auto it = _refs.find(base_url);
if (it != _refs.end()) {
@@ -860,12 +893,22 @@ public:
std::string visit(const json & schema, const std::string & name) {
json schema_type = schema.contains("type") ? schema["type"] : json();
std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
+ // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything
+ // -- a constraint the caller asked for, did not get, and is not told about. Complementing
+ // a regular language is representable but the blowup is real; refusing beats pretending.
+ if (schema.is_object() && schema.contains("not")) {
+ _errors.push_back("Unsupported schema keyword \"not\": this converter cannot "
+ "complement a grammar, and accepting the schema without it would "
+ "silently drop the constraint");
+ return "";
+ }
+
if (schema.contains("$ref")) {
return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
}
if (schema.contains("oneOf") || schema.contains("anyOf")) {
std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
@@ -1,46 +0,0 @@
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
index 12e747d..111acd0 100644
--- a/common/chat-peg-parser.cpp
+++ b/common/chat-peg-parser.cpp
@@ -36,6 +36,31 @@ static std::string_view trim(std::string_view sv) {
return trim_trailing_space(trim_leading_space(sv, 1));
}
+// RADIANCE: the delimiter around an XML argument value is a NEWLINE, not "whitespace". The
+// template writes <parameter=old_string>\n return a + b\n</parameter>, and exactly the first
+// and last newline are punctuation -- everything between them, INCLUDING the indentation, is the
+// value the model meant to send. Stripping "one leading whitespace character" eats the first
+// column of every indented hunk, so an agent's exact-match edit never applies and the model that
+// wrote a perfectly good call gets the blame. Strip the delimiter and nothing else.
+static std::string_view strip_one_leading_newline(std::string_view sv) {
+ if (!sv.empty() && sv.front() == '\n') {
+ sv.remove_prefix(1);
+ } else if (sv.size() >= 2 && sv[0] == '\r' && sv[1] == '\n') {
+ sv.remove_prefix(2);
+ }
+ return sv;
+}
+
+static std::string_view strip_one_trailing_newline(std::string_view sv) {
+ if (!sv.empty() && sv.back() == '\n') {
+ sv.remove_suffix(1);
+ if (!sv.empty() && sv.back() == '\r') {
+ sv.remove_suffix(1);
+ }
+ }
+ return sv;
+}
+
// Count the number of unclosed '{' braces in a JSON-like string,
// properly skipping braces inside quoted strings.
static int json_brace_depth(const std::string & s) {
@@ -338,7 +363,8 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
}
if ((is_arg_value || is_arg_string_value) && current_tool) {
- std::string value_content = std::string(trim_trailing_space(trim_leading_space(node.text, 1), 1));
+ std::string value_content =
+ std::string(strip_one_trailing_newline(strip_one_leading_newline(node.text)));
std::string value_to_add;
if (value_content.empty() && is_arg_string_value) {
@@ -1,62 +0,0 @@
diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp
index 0b79098..16b8bbf 100644
--- a/common/jinja/value.cpp
+++ b/common/jinja/value.cpp
@@ -261,6 +261,44 @@ static value tojson(const func_args & args) {
return mk_val<value_string>(json_str);
}
+/* jinja2's min()/max() over a sequence: the smallest (largest) ITEM, compared by `attribute`
+ * where one is given, and undefined for an empty sequence. `case_sensitive` is accepted and
+ * ignored, exactly as `sort` above it does. */
+template<value_compare_op op>
+static value minmax_fn(const func_args & args) {
+ args.ensure_count(1, 3);
+ if (!is_val<value_array>(args.get_pos(0))) {
+ throw raised_exception("min/max: first argument must be an array");
+ }
+ value val = args.get_pos(0);
+ value attribute = args.get_kwarg_or_pos("attribute", 2);
+ const bool attr_is_int = is_val<value_int>(attribute);
+ const int64_t attr_int = attr_is_int ? attribute->as_int() : 0;
+ const std::vector<value> arr = val->as_array(); // copy, as sort does
+ if (arr.empty()) {
+ return mk_val<value_undefined>();
+ }
+ auto key = [&](const value & v) -> value {
+ if (attribute->is_undefined()) {
+ return v;
+ }
+ if (attr_is_int && is_val<value_array>(v)) {
+ return v->at(attr_int);
+ }
+ if (!attr_is_int && is_val<value_object>(v)) {
+ return v->at(attribute);
+ }
+ throw raised_exception("min/max: unsupported object attribute comparison on " + v->type());
+ };
+ value best = arr[0];
+ for (size_t i = 1; i < arr.size(); ++i) {
+ if (value_compare(key(arr[i]), key(best), op)) {
+ best = arr[i];
+ }
+ }
+ return best;
+}
+
template<bool is_reject>
static value selectattr(const func_args & args) {
args.ensure_count(2, 4);
@@ -1082,6 +1120,12 @@ const func_builtins & value_array_t::get_builtins() const {
});
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(arr)) : mk_val<value_array>(std::move(arr));
}},
+ /* RADIANCE: upstream has sort but neither min nor max, and a template that uses one
+ * throws mid-render -- which the capability probe SWALLOWS, so the model is reported as
+ * having no tool support at all instead of the engine being reported as short a filter.
+ * MiniCPM5-2B's tool block is exactly that template. */
+ {"min", minmax_fn<value_compare_op::lt>},
+ {"max", minmax_fn<value_compare_op::gt>},
{"reverse", [](const func_args & args) -> value {
args.ensure_vals<value_array>();
value val = args.get_pos(0);
@@ -1,104 +0,0 @@
diff --git a/common/chat-diff-analyzer.cpp b/common/chat-diff-analyzer.cpp
index 0875c53..695765a 100644
--- a/common/chat-diff-analyzer.cpp
+++ b/common/chat-diff-analyzer.cpp
@@ -25,6 +25,10 @@ static const std::string FUN_FIRST = "FFF_FIRST_FUN_F";
static const std::string FUN_SECOND = "SSS_SECOND_FUN_S";
static const std::string ARG_FIRST = "AA_ARG_FST_AA";
static const std::string ARG_SECOND = "BB_ARG_SND_BB";
+/* RADIANCE: the value the one- and two-argument probes give ARG_FIRST. Named so the split in
+ * extract_argument_separator can find it rather than repeating the literal. */
+static const std::string ARG_FIRST_VALUE = "XXXX";
+static const std::string ARG_SECOND_VALUE = "YYYY";
static const std::string USER_MSG = "U_USER_MSG Hello END_U";
static const std::string USER_MSG_TWO = "V_USER_MSG Hello END_V";
static const std::string ASSISTANT_MSG = "A_ASST_MSG I can help END_A";
@@ -261,6 +265,7 @@ void autoparser::analyze_template(const common_chat_template & tmpl) {
LOG_DBG("arg_name_suffix: '%s'\n", tools.arguments.name_suffix.c_str());
LOG_DBG("arg_value_prefix: '%s'\n", tools.arguments.value_prefix.c_str());
LOG_DBG("arg_value_suffix: '%s'\n", tools.arguments.value_suffix.c_str());
+ LOG_DBG("arg_separator: '%s'\n", tools.arguments.separator.c_str()); /* RADIANCE */
LOG_DBG("name_field: '%s'\n", tools.format.name_field.c_str());
LOG_DBG("args_field: '%s'\n", tools.format.args_field.c_str());
LOG_DBG("id_field: '%s'\n", tools.format.id_field.c_str());
@@ -1355,6 +1360,80 @@ void analyze_tools::extract_argument_separator() {
std::string separator = until_common_prefix(diff.right, ARG_FIRST, ARG_SECOND);
arguments.separator = separator;
}
+
+ /* RADIANCE: THE PER-ARGUMENT SUFFIX AND THE CALL CLOSE CAME OUT AS ONE STRING.
+ *
+ * analyze_arguments() takes everything after the argument value as `value_suffix` and then
+ * trims `function.close`, `per_call_end` or `section_end` off it. A template that declares
+ * none of the three has nothing to cut against. MiniCPM5-2B is one: its calls are
+ * `<function name="F"><param name="A">V</param></function>`, so the suffix came out
+ * `</param></function><|im_end|>\n` with an EMPTY close, and two things then cannot parse --
+ * a call carrying a SECOND argument, because the suffix closes the whole call, and a call
+ * carrying one, because a generated turn ends at `<|im_end|>` and never carries the newline
+ * the template writes BETWEEN turns.
+ *
+ * The boundary is right here, in the render this function already has. Between the first
+ * argument's value and the second argument's name marker is exactly the per-argument suffix.
+ * Nothing is guessed: it is measured off a two-argument render, and every step declines
+ * rather than assuming if the markers do not line up. */
+ if (format.mode == tool_format::TAG_WITH_TAGGED && function.close.empty() &&
+ !arguments.name_prefix.empty() && !arguments.value_suffix.empty()) {
+ const std::string two = diff.prefix + diff.right + diff.suffix;
+ const size_t v1 = two.find(ARG_FIRST_VALUE);
+ const size_t a2 = v1 == std::string::npos ? std::string::npos : two.find(ARG_SECOND, v1);
+ const size_t npx = a2 == std::string::npos
+ ? std::string::npos : two.rfind(arguments.name_prefix, a2);
+ if (npx != std::string::npos && npx >= v1 + ARG_FIRST_VALUE.size()) {
+ const std::string per_arg = two.substr(v1 + ARG_FIRST_VALUE.size(),
+ npx - (v1 + ARG_FIRST_VALUE.size()));
+ const std::string tail = arguments.value_suffix;
+ if (!per_arg.empty() && tail.size() > per_arg.size() &&
+ tail.compare(0, per_arg.size(), per_arg) == 0) {
+ arguments.value_suffix = per_arg;
+ function.close = trim_trailing_whitespace(tail.substr(per_arg.size()));
+
+ /* AND THE CLOSE FROM A TWO-CALL RENDER, for the same reason and by the same
+ * method. The tail above is what a template writes after the LAST call of a
+ * turn, so it carries the turn terminator -- `</function><|im_end|>` -- and a
+ * close that demands the terminator can only ever match a reply with exactly ONE
+ * call in it. Between the end of the first call and the opener of the second
+ * there is no terminator, so that render measures the close alone.
+ *
+ * Anchored on the first call's second argument VALUE rather than on a count of
+ * openers: `<function name="` also appears in this template's own instructions to
+ * the model, in the system prompt, so counting occurrences finds the wrong one. */
+ json assistant_two_calls = json{
+ { "role", "assistant" },
+ { "content", "" },
+ { "tool_calls", json::array({ first_tool_call, second_tool_call }) }
+ };
+ auto calls = compare_variants(*tmpl, params, [&](template_params & p) {
+ p.messages = json::array({ user_msg, assistant_two_calls }); });
+ if (calls) {
+ const std::string c2 = calls->diff.prefix + calls->diff.right + calls->diff.suffix;
+ const size_t lastv = c2.find(ARG_SECOND_VALUE);
+ const size_t open2 = lastv == std::string::npos
+ ? std::string::npos
+ : c2.find(function.name_prefix,
+ lastv + ARG_SECOND_VALUE.size());
+ if (open2 != std::string::npos) {
+ const std::string between =
+ c2.substr(lastv + ARG_SECOND_VALUE.size(),
+ open2 - (lastv + ARG_SECOND_VALUE.size()));
+ if (between.size() > per_arg.size() &&
+ between.compare(0, per_arg.size(), per_arg) == 0) {
+ /* Trailing whitespace is between-turn layout, never part of a
+ * generated close; the parser skips space between calls itself. */
+ function.close = trim_trailing_whitespace(between.substr(per_arg.size()));
+ }
+ }
+ }
+ LOG_DBG("RADIANCE split: value_suffix '%s', func_close '%s'\n",
+ arguments.value_suffix.c_str(), function.close.c_str());
+
+ }
+ }
+ }
}
void analyze_tools::extract_args_markers() {
@@ -1,174 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index ed895b5..104fe47 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -412,7 +412,11 @@ common_peg_parser analyze_tools::build_tool_parser_tag_json(parser_build_context
std::string trigger_marker = !format.section_start.empty() ? format.section_start : format.per_call_start;
auto content_before_tools = trigger_marker.empty() ? p.eps() : p.until(trigger_marker);
- return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls + p.end();
+ /* RADIANCE: and anything AFTER the last call is content too. p.end() immediately after the
+ * calls means a model that signs off -- "Created the file." -- fails the whole parse for it,
+ * which is the same trap as the one above with the ends swapped. */
+ return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls +
+ p.optional(p.content(p.rest())) + p.end();
}
common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_context & ctx) const {
@@ -443,15 +447,38 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
for (const auto & [param_name, param_schema] : properties.items()) {
bool is_required = required.find(param_name) != required.end();
+ /* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT.
+ *
+ * An array or object parameter is matched by a schema-constrained JSON parser, and
+ * models do not reliably write JSON inside an XML tag. MiniCPM5 writes Python:
+ * `<param name="edits">[{'oldText': 'a', 'newText': 'b'}]</param>`. The JSON parser
+ * cannot begin on a single quote, so the argument does not match, the call does not
+ * match, and p.end() makes that the whole reply -- which comes back as prose with
+ * the tags in it. The model reads that as the tool rejecting its call and tries
+ * again, differently and just as fruitlessly; in one session it went round four
+ * times, and once rewrote the call with the arguments reordered to appease it.
+ *
+ * Strict JSON is still tried FIRST, so nothing that parses today parses differently.
+ * The fallback takes the value the way a string argument takes it -- as the text up
+ * to `</param>`, which is what actually delimits it in this format -- and the mapper
+ * already normalises a Python-style container to JSON from there
+ * (normalize_container_value in chat-peg-parser.cpp). What is given up is schema
+ * VALIDATION of the argument, and a mistyped argument reaching the tool as a mistyped
+ * argument is strictly better than a correct call reaching the user as prose. */
+ common_peg_parser value_parser = p.choice();
+ if (schema_info.resolves_to_string(param_schema)) {
+ value_parser = p.tool_arg_string_value(until_suffix);
+ } else {
+ value_parser |= p.tool_arg_json_value(p.schema(
+ p.json(), "tool-" + name + "-arg-" + param_name + "-schema",
+ param_schema, false)) + p.space();
+ value_parser |= p.tool_arg_json_value(until_suffix);
+ }
+
auto arg =
p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param_name)) +
arguments.name_suffix) +
- arguments.value_prefix +
- (schema_info.resolves_to_string(param_schema) ?
- p.tool_arg_string_value(until_suffix) :
- p.tool_arg_json_value(p.schema(
- p.json(), "tool-" + name + "-arg-" + param_name + "-schema", param_schema, false)) +
- p.space()) +
+ arguments.value_prefix + value_parser +
p.tool_arg_close(p.literal(arguments.value_suffix)));
auto named_arg = p.rule("tool-" + name + "-arg-" + param_name, arg);
@@ -462,22 +489,33 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
}
}
- // Build required arg sequence in definition order
- common_peg_parser args_seq = p.eps();
- for (size_t i = 0; i < required_parsers.size(); i++) {
- if (i > 0) {
- args_seq = args_seq + p.space();
- }
- args_seq = args_seq + required_parsers[i];
+ /* RADIANCE: A NAMED ARGUMENT CARRIES ITS OWN NAME, SO ITS POSITION MEANS NOTHING.
+ *
+ * Required arguments were required IN SCHEMA ORDER. This format writes them as
+ * `<param name="path">..</param><param name="content">..</param>` -- the name is right
+ * there in the tag -- and a model emits them in whatever order it composed them, which
+ * for a write is very often the content first, because that is the part it was thinking
+ * about. The sequence then does not match, and since the rule ends in p.end() the failure
+ * is TOTAL: the call comes back to the client as prose with the tags still in it, which
+ * looks exactly like a model that cannot call tools.
+ *
+ * Every argument is accepted in any order here, required and optional alike. What the
+ * grammar gives up -- checking that each required argument appears exactly once -- was
+ * never its job: a call missing one is a bad call, and arriving at the tool AS a bad call
+ * says so, where arriving as prose says nothing at all. */
+ common_peg_parser any_arg = p.choice();
+ for (const auto & req : required_parsers) {
+ any_arg |= req;
+ }
+ for (const auto & opt : optional_parsers) {
+ any_arg |= opt;
}
- // Build optional args with flexible ordering
- if (!optional_parsers.empty()) {
- common_peg_parser any_opt = p.choice();
- for (const auto & opt : optional_parsers) {
- any_opt |= opt;
- }
- args_seq = args_seq + p.repeat(p.space() + any_opt, 0, -1);
+ common_peg_parser args_seq = p.eps();
+ if (!required_parsers.empty()) {
+ args_seq = any_arg + p.repeat(p.space() + any_arg, 0, -1);
+ } else if (!optional_parsers.empty()) {
+ args_seq = args_seq + p.repeat(p.space() + any_arg, 0, -1);
}
if (!arguments.start.empty()) {
@@ -510,6 +548,12 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
auto require_tools = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED;
+ /* RADIANCE: what opens a call, and therefore what content is read up to. See the return
+ * statement; computed here because the between-calls rule below needs it too. */
+ std::string trigger_marker = !format.section_start.empty() ? format.section_start
+ : !format.per_call_start.empty() ? format.per_call_start
+ : function.name_prefix;
+
common_peg_parser tool_calls = p.eps();
if (!format.per_call_start.empty()) {
@@ -525,11 +569,28 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
(format.section_end.empty() ? p.end() : p.literal(format.section_end) + p.space()));
}
} else {
- std::string separator = ", "; // Default
+ /* RADIANCE: A TAGGED CALL IS SELF-DELIMITING, SO THE SEPARATOR IS WHITESPACE.
+ *
+ * This used a literal ", " -- the separator of a JSON ARRAY of calls -- for a format
+ * whose calls are tags. MiniCPM5-2B writes
+ * `<function name="ls">..</function>\n<function name="bash">..</function>`, and the
+ * second call was required to begin with a comma and a space. It never does, so the
+ * rule failed -- and because the whole thing ends in p.end(), the failure is not "one
+ * call and some text", it is NO MATCH AT ALL: every reply with two calls in it came back
+ * as raw prose with the reasoning and the tags still in it. One call parsed, two never.
+ *
+ * A tagged call opens with its own name prefix and closes with its own close, so nothing
+ * between them is needed to tell one from the next. p.space() accepts the newline these
+ * models put there and the nothing that a template writing them adjacently produces. */
+ /* RADIANCE: and a model narrates BETWEEN calls too -- "Let me look at the tree." then a
+ * call, "Now the tests." then another. Only whitespace was allowed between them. */
+ common_peg_parser next_call =
+ p.space() + (trigger_marker.empty() ? p.eps() : p.optional(p.content(p.until(trigger_marker)))) +
+ tool_choice;
if (inputs.parallel_tool_calls) {
tool_calls = p.trigger_rule("tool-call", format.section_start + p.space() + tool_choice +
- p.zero_or_more(separator + tool_choice) + p.space() +
+ p.zero_or_more(next_call) + p.space() +
format.section_end);
} else {
tool_calls = p.trigger_rule(
@@ -541,7 +602,18 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
tool_calls = p.optional(tool_calls);
}
- std::string trigger_marker = !format.section_start.empty() ? format.section_start : format.per_call_start;
+ /* RADIANCE: WITH NO SECTION OR PER-CALL MARKER, NOTHING WAS ALLOWED BEFORE THE CALL.
+ *
+ * `content_before_tools` is what lets a model say something and THEN call a tool. It is
+ * driven by the section or per-call opener, and a format with neither -- this one -- got
+ * p.eps(), which permits no content at all. So a reply that opens with a sentence ("The
+ * workspace is empty. I will create a Tic Tac Toe implementation.") and then makes a
+ * perfectly well-formed call does not match, and p.end() turns that into a whole-parse
+ * failure: the call comes back as prose.
+ *
+ * What opens a call in a tagged format is the function name prefix, `<function name="`, so
+ * that is the marker to read up to. It is only a fallback -- a format that really does have
+ * a section or per-call opener still uses it, because that one starts earlier in the text. */
auto content_before_tools = trigger_marker.empty() ? p.eps() : p.until(trigger_marker);
return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls + p.end();
}
@@ -1,72 +0,0 @@
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
index 111acd0..b674d6e 100644
--- a/common/chat-peg-parser.cpp
+++ b/common/chat-peg-parser.cpp
@@ -51,6 +51,54 @@ static std::string_view strip_one_leading_newline(std::string_view sv) {
return sv;
}
+// RADIANCE: A CDATA SECTION IS PUNCTUATION, NOT CONTENT. MiniCPM5's template tells the model
+// verbatim: "If it contains <, & or newline characters, wrap it in a CDATA block:
+// <param name="param-name"><![CDATA[...multi-line value...]]></param>" -- so every source file an
+// agent writes arrives wrapped, and handing `<![CDATA[def main():...]]>` to a write tool puts
+// those characters into the file.
+//
+// THE TWO ENDS ARE STRIPPED INDEPENDENTLY, AND THAT IS THE WHOLE POINT. A streamed value is
+// parsed again from the top on every chunk, and what the server sends the client is the part
+// that is new -- so a value already emitted cannot be taken back. Requiring both delimiters
+// before removing either means the opener escapes in the first chunk, every time, and the
+// closing `]]>` is then half-eaten by the suffix match: the agent's files came out starting
+// `<![CDATA[` and ending `]]`, the model saw its own output corrupted, and it spent the rest of
+// the session trying to edit the markers back out.
+//
+// While a value is still partial, a trailing `]` or `]]` is held back: it is either the start of
+// the closer or the end of a JSON array, and withholding is safe either way -- what is emitted
+// stays a prefix of the finished value, which is the contract the streaming diff needs.
+static void unwrap_cdata(std::string_view & sv, bool is_partial) {
+ static constexpr std::string_view cd_open = "<![CDATA[";
+ static constexpr std::string_view cd_close = "]]>";
+ if (sv.size() < cd_open.size()) {
+ /* Not enough of it to tell yet. While the value is still arriving, anything that could
+ * still BECOME the opener is held back whole -- `<![CDATA` went out as content once and
+ * could never be taken back. A complete value this short is just a short value. */
+ if (is_partial && !sv.empty() && cd_open.compare(0, sv.size(), sv) == 0) {
+ sv = std::string_view();
+ }
+ return;
+ }
+ if (sv.compare(0, cd_open.size(), cd_open) != 0) {
+ return;
+ }
+ sv.remove_prefix(cd_open.size());
+ if (sv.size() >= cd_close.size() &&
+ sv.compare(sv.size() - cd_close.size(), cd_close.size(), cd_close) == 0) {
+ sv.remove_suffix(cd_close.size());
+ return;
+ }
+ if (!is_partial) {
+ return;
+ }
+ size_t hold = 0;
+ while (hold + 1 < cd_close.size() && sv.size() > hold && sv[sv.size() - 1 - hold] == ']') {
+ ++hold;
+ }
+ sv.remove_suffix(hold);
+}
+
static std::string_view strip_one_trailing_newline(std::string_view sv) {
if (!sv.empty() && sv.back() == '\n') {
sv.remove_suffix(1);
@@ -363,8 +411,10 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
}
if ((is_arg_value || is_arg_string_value) && current_tool) {
- std::string value_content =
- std::string(strip_one_trailing_newline(strip_one_leading_newline(node.text)));
+ std::string_view value_view =
+ strip_one_trailing_newline(strip_one_leading_newline(node.text));
+ unwrap_cdata(value_view, node.is_partial);
+ std::string value_content = std::string(value_view);
std::string value_to_add;
if (value_content.empty() && is_arg_string_value) {
@@ -1,46 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index 104fe47..b682578 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -511,6 +511,41 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
any_arg |= opt;
}
+ /* RADIANCE: AN ARGUMENT THE SCHEMA DOES NOT DECLARE MUST NOT TAKE THE REPLY DOWN WITH IT.
+ *
+ * Every arm above matches its parameter name as a LITERAL, so a name outside the schema
+ * matches nothing, the call matches nothing, and p.end() makes that the whole reply --
+ * which comes back to the caller as prose with the XML in it. Observed on MiniCPM5-2B
+ * calling a `read` tool whose only parameter is `path`:
+ *
+ * <function name="read"><param name="action">read</param></function>
+ *
+ * one hallucinated argument name, and the turn was lost. The model then reads its own
+ * call echoed back as text, concludes the tool is broken, and rewrites it.
+ *
+ * Tried LAST, so every declared name still binds to its own schema-checked arm and
+ * nothing that parses today parses differently. The value is taken the way a string
+ * argument takes it -- the text up to the value suffix, which is what delimits it in
+ * this format. What is given up is knowing that the argument was undeclared; the TOOL
+ * gets to say so, which it can do properly, and which a reply that never arrives cannot.
+ * Same argument as the non-JSON container fallback above. */
+ /* WHAT ENDS THE NAME IS NOT ALWAYS `name_suffix`. This format decomposes
+ * `<param name="path">v</param>` as prefix `<param name="`, name_suffix EMPTY and
+ * value_prefix `">` -- so a generic name runs until value_prefix here, and the first
+ * cut of this arm guarded on `!name_suffix.empty()` and silently never built itself. */
+ const std::string & name_end =
+ arguments.name_suffix.empty() ? arguments.value_prefix : arguments.name_suffix;
+ if (!arguments.name_prefix.empty() && !name_end.empty() &&
+ !arguments.value_suffix.empty()) {
+ auto unknown_arg =
+ p.tool_arg(p.tool_arg_open(arguments.name_prefix +
+ p.tool_arg_name(p.until(name_end)) +
+ arguments.name_suffix) +
+ arguments.value_prefix + p.tool_arg_string_value(until_suffix) +
+ p.tool_arg_close(p.literal(arguments.value_suffix)));
+ any_arg |= p.rule("tool-" + name + "-arg-undeclared", unknown_arg);
+ }
+
common_peg_parser args_seq = p.eps();
if (!required_parsers.empty()) {
args_seq = any_arg + p.repeat(p.space() + any_arg, 0, -1);
@@ -1,33 +0,0 @@
diff --git a/common/chat.cpp b/common/chat.cpp
index ef15169..1398152 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -2354,8 +2354,26 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
params.grammar = inputs.grammar;
params.now = inputs.now;
params.add_generation_prompt = inputs.add_generation_prompt;
- params.add_bos = tmpls->add_bos;
- params.add_eos = tmpls->add_eos;
+ /* RADIANCE: `add_bos` HAS TO COME FROM THE INPUTS, OR THE INPUT FIELD IS DEAD.
+ *
+ * `common_chat_templates_inputs` carries add_bos/add_eos and every caller fills them, but
+ * this conversion overwrote both from the TEMPLATES object -- which is only ever set inside
+ * common_chat_templates_init, from a llama_vocab. A host that passes `model = nullptr` and
+ * supplies the vocabulary's facts as overrides (which is what radiance does: the container
+ * carries the template, the BOS/EOS spellings and the add flags, so there is no llama_model
+ * to read them off) therefore had both flags stuck at false no matter what it asked for.
+ *
+ * What the flag does is strip a BOS the TEMPLATE rendered, because the tokeniser is about to
+ * add one -- so with it stuck off, a container whose tokeniser adds BOS and whose template
+ * also writes `bos_token` gets TWO. The Llama-family templates write it; Qwen's do not,
+ * which is why this stayed invisible here.
+ *
+ * The two upstream callers that do set it -- common_chat_format_single and
+ * common_chat_format_example -- assign `inputs.add_bos = tmpls->add_bos` immediately before
+ * calling apply, which is exactly the redundancy you would expect if apply were meant to read
+ * the inputs. Falling back to the templates object keeps them working unchanged. */
+ params.add_bos = inputs.add_bos || tmpls->add_bos;
+ params.add_eos = inputs.add_eos || tmpls->add_eos;
params.continue_final_message = inputs.continue_final_message;
if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) {
@@ -1,142 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index b682578..71520db 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -447,6 +447,17 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
for (const auto & [param_name, param_schema] : properties.items()) {
bool is_required = required.find(param_name) != required.end();
+ /* RADIANCE: AN OPTIONAL ARGUMENT NO VALUE SATISFIES IS ONE NO CALL WRITES -- an
+ * Arktype "never", exported as `{"not": {}}` (oh-my-pi's `task` tool declares its batch
+ * form's `model` so). It gets no arm: a schema-checked arm for it is a grammar for a
+ * value that does not exist, and the converter refuses to build one. A model that
+ * writes it anyway reaches the undeclared-argument arm below, as any name outside the
+ * schema does, and the tool says what is wrong. Required, it goes through the schema
+ * and is refused there by name. */
+ if (!is_required && schema_info.unsatisfiable(param_schema)) {
+ continue;
+ }
+
/* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT.
*
* An array or object parameter is matched by a schema-constrained JSON parser, and
diff --git a/common/chat.cpp b/common/chat.cpp
index 1398152..5bc91eb 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -1955,6 +1955,11 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha
std::vector<common_peg_parser> optional_parsers;
for (const auto & [param_name, param_schema] : props.items()) {
bool is_required = required.find(param_name) != required.end();
+ // RADIANCE: an optional argument no value satisfies is one no call writes, so it
+ // gets no arm (see chat-auto-parser-generator.cpp); required, it is refused by name.
+ if (!is_required && schema_info.unsatisfiable(param_schema)) {
+ continue;
+ }
bool is_string = schema_info.resolves_to_string(param_schema);
auto arg = p.tool_arg(
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index ccf857a..95640fb 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -697,6 +697,19 @@ private:
const auto &prop_name = kv.first;
const auto &prop_schema = kv.second;
+ // RADIANCE: a property no value satisfies is a key the object never carries, which the
+ // grammar states exactly by having no rule for it. Its name stays in prop_names, so an
+ // additionalProperties rule cannot readmit the key with a value of its own. Required,
+ // it makes the whole object unsatisfiable, and that is refused.
+ if (is_unsatisfiable(prop_schema)) {
+ if (required.find(prop_name) != required.end()) {
+ _errors.push_back("Property \"" + prop_name + "\" is required, but its schema "
+ "accepts no value");
+ }
+ prop_names.push_back(prop_name);
+ continue;
+ }
+
std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
prop_kv_rule_names[prop_name] = _add_rule(
name + (name.empty() ? "" : "-") + prop_name + "-kv",
@@ -887,6 +900,17 @@ public:
visit_refs(schema);
}
+ // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` --
+ // 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.
+ static bool is_unsatisfiable(const json & schema) {
+ if (schema.is_boolean()) return !schema.get<bool>();
+ if (!schema.is_object() || !schema.contains("not")) return false;
+ const json & n = schema["not"];
+ return (n.is_object() && n.empty()) || (n.is_boolean() && n.get<bool>());
+ }
+
static std::string _generate_constant_rule(const json & value) {
return format_literal(value.dump());
}
@@ -896,9 +920,19 @@ public:
std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
- // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything
- // -- a constraint the caller asked for, did not get, and is not told about. Complementing
- // a regular language is representable but the blowup is real; refusing beats pretending.
+ // RADIANCE: an unsatisfiable schema in a place that must hold a value -- the root, an array's
+ // items, a $ref target -- has no grammar: GBNF has no empty language to give it. An object
+ // property and a union alternative of this kind are handled where they occur.
+ if (is_unsatisfiable(schema)) {
+ _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\" accepts no "
+ "value, where a value is required");
+ return "";
+ }
+
+ // RADIANCE: any other "not" has no case below, so it would fall through to a rule that
+ // accepts anything -- a constraint the caller asked for, did not get, and is not told
+ // about. Complementing a regular language is representable but the blowup is real;
+ // refusing beats pretending.
if (schema.is_object() && schema.contains("not")) {
_errors.push_back("Unsupported schema keyword \"not\": this converter cannot "
"complement a grammar, and accepting the schema without it would "
@@ -911,6 +945,14 @@ public:
}
if (schema.contains("oneOf") || schema.contains("anyOf")) {
std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
+ // RADIANCE: an alternative no value satisfies contributes nothing to the union.
+ alt_schemas.erase(std::remove_if(alt_schemas.begin(), alt_schemas.end(), is_unsatisfiable),
+ alt_schemas.end());
+ if (alt_schemas.empty()) {
+ _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\": no "
+ "alternative of its union accepts a value");
+ return "";
+ }
return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
}
if (schema_type.is_array()) {
@@ -1108,6 +1150,10 @@ void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) {
impl_->resolve_refs(schema, "");
}
+bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) const {
+ return common_schema_converter::is_unsatisfiable(schema);
+}
+
// Determines if a JSON schema can resolve to a string type through any path.
// Some models emit raw string values rather than JSON-encoded strings for string parameters.
// If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns
diff --git a/common/json-schema-to-grammar.h b/common/json-schema-to-grammar.h
index 240d642..86c78f3 100644
--- a/common/json-schema-to-grammar.h
+++ b/common/json-schema-to-grammar.h
@@ -26,6 +26,8 @@ class common_schema_info {
void resolve_refs(nlohmann::ordered_json & schema);
bool resolves_to_string(const nlohmann::ordered_json & schema);
+ // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`.
+ bool unsatisfiable(const nlohmann::ordered_json & schema) const;
};
struct common_grammar_builder {
@@ -1,54 +0,0 @@
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"))) {
@@ -1,106 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 0bf2b72..12e2756 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -900,10 +900,6 @@ public:
visit_refs(schema);
}
- // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` --
- // 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
@@ -924,11 +920,74 @@ public:
return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : (int) d;
}
+ // RADIANCE: the schema every value satisfies, whose `not` is therefore the schema none does.
+ // `{}` and `true` are it, and so is a type list, or a union of bare types, that between them
+ // name all six JSON types -- the way Arktype exports the complement of `never` for an optional
+ // property: {"not": {"anyOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"},
+ // {"type": "object"}, {"type": "array"}, {"type": "null"}]}}. Annotations may sit beside; any
+ // other keyword narrows the schema, and its `not` is a real complement, refused below. A union
+ // alternative that constrains more than its type is not counted, so a union is only ever read
+ // as universal when it is.
+ static bool is_universal(const json & s) {
+ if (s.is_boolean()) return s.get<bool>();
+ if (!s.is_object()) return false;
+ static const std::unordered_set<std::string> annotations = {
+ "description", "title", "default", "examples", "$comment", "deprecated", "readOnly",
+ "writeOnly",
+ };
+ // Whether every key of `o` is an annotation or `allowed`.
+ auto only = [&](const json & o, const char * allowed) {
+ for (auto it = o.begin(); it != o.end(); ++it) {
+ if (annotations.count(it.key()) == 0 && (allowed == nullptr || it.key() != allowed)) {
+ return false;
+ }
+ }
+ return true;
+ };
+ // The types a bare `type` names, into `out`; false for anything that is not one.
+ auto types_of = [](const json & t, std::unordered_set<std::string> & out) {
+ if (t.is_string()) {
+ out.insert(t.get<std::string>());
+ return true;
+ }
+ if (!t.is_array()) return false;
+ for (const auto & e : t) {
+ if (!e.is_string()) return false;
+ out.insert(e.get<std::string>());
+ }
+ return true;
+ };
+ auto covers = [](const std::unordered_set<std::string> & ts) {
+ for (const char * t : { "string", "number", "boolean", "object", "array", "null" }) {
+ if (ts.count(t) == 0) return false;
+ }
+ return true;
+ };
+ if (only(s, nullptr)) return true;
+ std::unordered_set<std::string> ts;
+ if (s.contains("type") && only(s, "type")) {
+ return types_of(s["type"], ts) && covers(ts);
+ }
+ if (s.contains("anyOf") && only(s, "anyOf") && s["anyOf"].is_array()) {
+ for (const auto & a : s["anyOf"]) {
+ if (is_universal(a)) return true;
+ if (a.is_object() && a.contains("type") && only(a, "type")) {
+ types_of(a["type"], ts);
+ }
+ }
+ return covers(ts);
+ }
+ return false;
+ }
+
+ // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and TypeBox's
+ // Type.Never and Arktype's "never" export it as a `not` of the universal schema above, the
+ // latter for an optional property no call may set. Such a `not` makes its whole schema
+ // unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
static bool is_unsatisfiable(const json & schema) {
if (schema.is_boolean()) return !schema.get<bool>();
if (!schema.is_object() || !schema.contains("not")) return false;
- const json & n = schema["not"];
- return (n.is_object() && n.empty()) || (n.is_boolean() && n.get<bool>());
+ return is_universal(schema["not"]);
}
static std::string _generate_constant_rule(const json & value) {
diff --git a/common/json-schema-to-grammar.h b/common/json-schema-to-grammar.h
index 86c78f3..8223dd4 100644
--- a/common/json-schema-to-grammar.h
+++ b/common/json-schema-to-grammar.h
@@ -26,7 +26,8 @@ class common_schema_info {
void resolve_refs(nlohmann::ordered_json & schema);
bool resolves_to_string(const nlohmann::ordered_json & schema);
- // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`.
+ // RADIANCE: whether no value satisfies the schema -- `false`, or a `not` of a schema every
+ // value satisfies (`{}`, or types naming all six JSON types).
bool unsatisfiable(const nlohmann::ordered_json & schema) const;
};
@@ -1,67 +0,0 @@
diff --git a/common/jinja/runtime.h b/common/jinja/runtime.h
index b6f4a6ab..af84c910 100644
--- a/common/jinja/runtime.h
+++ b/common/jinja/runtime.h
@@ -606,7 +606,15 @@ static void gather_string_parts_recursive(const value & val, value_string & part
} else if (is_val<value_array>(val)) {
auto items = cast_val<value_array>(val)->as_array();
for (const auto & item : items) {
- gather_string_parts_recursive(item, parts);
+ /* RADIANCE: `val` is a block's statement results, and every block statement returns
+ * a string, so a list or a dict among them is the value of an expression the template
+ * prints. jinja2 prints its repr; flattening it ran its strings together and printed
+ * nothing for a dict. */
+ if (is_val<value_array>(item) || is_val<value_object>(item)) {
+ parts->val_str.append(item->as_string().str());
+ } else {
+ gather_string_parts_recursive(item, parts);
+ }
}
}
}
diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp
index 16b8bbf1..b7af1ae1 100644
--- a/common/jinja/value.cpp
+++ b/common/jinja/value.cpp
@@ -1496,13 +1496,35 @@ std::string value_to_json(const value & val, int indent, const std::string_view
// TODO: avoid circular references
std::string value_to_string_repr(const value & val) {
if (is_val<value_string>(val)) {
- const std::string val_str = val->as_string().str();
-
- if (val_str.find('\'') != std::string::npos) {
- return value_to_json(val);
- } else {
- return "'" + val_str + "'";
+ /* RADIANCE: Python's str repr, which jinja2 prints for a string inside a list or a dict:
+ * single quotes unless the text holds one and no double quote, and backslash escapes for
+ * the backslash, the quote, \t \n \r and the other ASCII controls. Python also escapes
+ * non-printable non-ASCII code points; those pass through here. */
+ const std::string s = val->as_string().str();
+ const char q = s.find('\'') != std::string::npos && s.find('"') == std::string::npos ? '"' : '\'';
+ std::string out(1, q);
+ for (const char ch : s) {
+ const unsigned char c = (unsigned char) ch;
+ if (ch == q || ch == '\\') {
+ out += '\\';
+ out += ch;
+ } else if (ch == '\t') {
+ out += "\\t";
+ } else if (ch == '\n') {
+ out += "\\n";
+ } else if (ch == '\r') {
+ out += "\\r";
+ } else if (c < 0x20 || c == 0x7f) {
+ static const char hex[] = "0123456789abcdef";
+ out += "\\x";
+ out += hex[c >> 4];
+ out += hex[c & 15];
+ } else {
+ out += ch;
+ }
}
+ out += q;
+ return out;
} else {
return val->as_repr();
}
-58
View File
@@ -1,58 +0,0 @@
diff --git a/common/chat.cpp b/common/chat.cpp
index 5bc91ebd..90172e9e 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -20,6 +20,8 @@
#include <ctime>
#include <exception>
#include <functional>
+#include <memory>
+#include <mutex>
#include <optional>
#include <sstream>
@@ -285,8 +287,33 @@ struct common_chat_templates {
bool has_explicit_template; // Model had builtin template or template overridden was specified.
std::unique_ptr<common_chat_template> template_default; // always set (defaults to chatml)
std::unique_ptr<common_chat_template> template_tool_use;
+ /* RADIANCE: the differential analysis of template_default ([0]) and template_tool_use ([1]),
+ * made on first use (template_analysis). */
+ mutable std::mutex analysis_lock;
+ mutable std::shared_ptr<const autoparser::autoparser> analysis[2];
};
+/* RADIANCE: autoparser::analyze_template renders the template over synthetic messages and reads
+ * nothing but the template, so one analysis serves every request rendered through it. One that
+ * throws is not kept, and the next request analyses again and throws again. */
+static std::shared_ptr<const autoparser::autoparser> template_analysis(
+ const common_chat_templates * tmpls, const common_chat_template & tmpl) {
+ const size_t slot = &tmpl == tmpls->template_default.get() ? 0 : 1;
+ {
+ std::lock_guard<std::mutex> lock(tmpls->analysis_lock);
+ if (tmpls->analysis[slot]) {
+ return tmpls->analysis[slot];
+ }
+ }
+ auto made = std::make_shared<autoparser::autoparser>();
+ made->analyze_template(tmpl);
+ std::lock_guard<std::mutex> lock(tmpls->analysis_lock);
+ if (!tmpls->analysis[slot]) {
+ tmpls->analysis[slot] = std::move(made);
+ }
+ return tmpls->analysis[slot];
+}
+
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) {
if (tool_choice == "auto") {
return COMMON_CHAT_TOOL_CHOICE_AUTO;
@@ -2465,8 +2492,8 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
try {
LOG_DBG("%s: using differential autoparser\n", __func__);
- struct autoparser::autoparser autoparser;
- autoparser.analyze_template(tmpl);
+ const std::shared_ptr<const autoparser::autoparser> analysis = template_analysis(tmpls, tmpl);
+ const autoparser::autoparser & autoparser = *analysis;
auto auto_params = autoparser::peg_generator::generate_parser(tmpl, params, autoparser);
std::vector<common_chat_msg_delimiter> delimiters;
@@ -1,60 +0,0 @@
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() == '$')) {
@@ -1,97 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index df4846d..4664833 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -330,6 +330,77 @@ static std::string anchor_pattern(const std::string & p) {
return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$";
}
+// RADIANCE: \d \w \s and their negations, which GBNF cannot spell, written out as the classes
+// ECMA-262 gives them, before the scanner reads the pattern. A JSON string holds text, not raw
+// bytes: the negated forms leave out '"', '\' and the control characters, which a string can only
+// carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote;
+// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
+// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
+// so false is returned and the pattern refused.
+static bool expand_shorthands(const std::string & p, std::string & out) {
+ static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
+ static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
+ static const std::string raw = "\"\\\\\\x00-\\x1F";
+ auto negated = [&](const std::string & cls) { return "(?:[^" + cls + raw + "]|" + esc + ")"; };
+ out.clear();
+ for (size_t i = 0; i < p.size(); ++i) {
+ const char c = p[i];
+ if (c == '\\' && i + 1 < p.size()) {
+ const char n = p[++i];
+ switch (n) {
+ case 'd': out += "[0-9]"; break;
+ case 'w': out += "[A-Za-z0-9_]"; break;
+ case 's': out += "(?:[" + sp + "]|\\\\[tnfr])"; break;
+ case 'D': out += negated("0-9"); break;
+ case 'W': out += negated("A-Za-z0-9_"); break;
+ case 'S': out += negated(sp); break;
+ default: out += c; out += n; break;
+ }
+ continue;
+ }
+ if (c != '[') {
+ out += c;
+ continue;
+ }
+ // The class runs to the first unescaped ']', as the scanner reads it.
+ size_t j = i + 1;
+ std::string body;
+ while (j < p.size() && p[j] != ']') {
+ if (p[j] == '\\' && j + 1 < p.size()) {
+ body += p.substr(j, 2);
+ j += 2;
+ } else {
+ body += p[j++];
+ }
+ }
+ if (body == "\\s\\S" || body == "\\S\\s" || body == "\\d\\D" || body == "\\D\\d" ||
+ body == "\\w\\W" || body == "\\W\\w") {
+ out += "(?:[^" + raw + "]|" + esc + ")";
+ i = j;
+ continue;
+ }
+ std::string cls = "[";
+ for (size_t k = 0; k < body.size(); ++k) {
+ if (body[k] == '\\' && k + 1 < body.size()) {
+ const char n = body[++k];
+ if (n == 'd') cls += "0-9";
+ else if (n == 'w') cls += "A-Za-z0-9_";
+ else if (n == 's') cls += sp;
+ else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else { cls += '\\'; cls += n; }
+ } else {
+ cls += body[k];
+ }
+ }
+ out += cls;
+ if (j < p.size()) {
+ out += ']';
+ }
+ i = j;
+ }
+ return true;
+}
+
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) {
@@ -397,7 +468,13 @@ private:
}
std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
- const std::string pattern = anchor_pattern(client_pattern);
+ std::string expanded;
+ if (!expand_shorthands(client_pattern, expanded)) {
+ _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class "
+ "cannot be spelled in GBNF");
+ return "";
+ }
+ const std::string pattern = anchor_pattern(expanded);
// 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() == '$')) {
@@ -1,58 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 4664833..92561c4 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -4,6 +4,7 @@
#include <nlohmann/json.hpp>
#include <algorithm>
+#include <cctype>
#include <map>
#include <regex>
#include <sstream>
@@ -336,7 +337,12 @@ static std::string anchor_pattern(const std::string & p) {
// carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote;
// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
-// so false is returned and the pattern refused.
+// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript
+// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read.
+static bool is_identity_punct(char c) {
+ return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast<unsigned char>(c));
+}
+
static bool expand_shorthands(const std::string & p, std::string & out) {
static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
@@ -354,7 +360,16 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
case 'D': out += negated("0-9"); break;
case 'W': out += negated("A-Za-z0-9_"); break;
case 'S': out += negated(sp); break;
- default: out += c; out += n; break;
+ default:
+ // An identity escape of punctuation GBNF has no escape for ("\/", "\-") is the
+ // bare character; regex syntax characters and '"' keep their backslash.
+ if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) {
+ out += n;
+ } else {
+ out += c;
+ out += n;
+ }
+ break;
}
continue;
}
@@ -387,6 +402,13 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
else if (n == 'w') cls += "A-Za-z0-9_";
else if (n == 's') cls += sp;
else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') {
+ // "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could
+ // read as a range or a negation, so they are written as \xHH.
+ cls += "\\x";
+ cls += "0123456789ABCDEF"[(n >> 4) & 0xF];
+ cls += "0123456789ABCDEF"[n & 0xF];
+ }
else { cls += '\\'; cls += n; }
} else {
cls += body[k];
@@ -1,150 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 92561c4..53f067c 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -338,12 +338,33 @@ static std::string anchor_pattern(const std::string & p) {
// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript
-// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read.
+// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. \t \n \r \f
+// \b (in a class) \v \0 are control characters, which a JSON string carries only as escapes, so
+// they match the escape. Any other escape in a class (\p{..}, \c, a backreference) has no GBNF
+// spelling: `bad` names it and false is returned, rather than copying it into a grammar that
+// would then fail to load.
static bool is_identity_punct(char c) {
return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast<unsigned char>(c));
}
-static bool expand_shorthands(const std::string & p, std::string & out) {
+// The JSON escape for the control character a regex escape names, or "" if it names none.
+static std::string json_control_escape(char n) {
+ switch (n) {
+ case 't': case 'n': case 'r': case 'f': case 'b': return std::string("\\\\") + n;
+ case 'v': return "\\\\u000[bB]";
+ case '0': return "\\\\u0000";
+ default: return "";
+ }
+}
+
+static std::string hex_escape(char n) {
+ std::string s = "\\x";
+ s += "0123456789ABCDEF"[(n >> 4) & 0xF];
+ s += "0123456789ABCDEF"[n & 0xF];
+ return s;
+}
+
+static bool expand_shorthands(const std::string & p, std::string & out, char & bad) {
static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
static const std::string raw = "\"\\\\\\x00-\\x1F";
@@ -365,6 +386,12 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
// bare character; regex syntax characters and '"' keep their backslash.
if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) {
out += n;
+ } else if (n != 'b' && !json_control_escape(n).empty()) {
+ // A group, so a following quantifier takes the whole escape. Outside a class
+ // \b is a word boundary, which the scanner refuses.
+ out += "(?:" + json_control_escape(n) + ")";
+ } else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) {
+ out += n;
} else {
out += c;
out += n;
@@ -395,28 +422,74 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
continue;
}
std::string cls = "[";
+ // A positive class's control characters can only appear as JSON escapes, which are two
+ // or six characters long, so they become alternatives beside the class.
+ std::vector<std::string> escapes;
+ const bool negated_cls = !body.empty() && body[0] == '^';
+ std::string excluded; // the control characters a negated class leaves out, by escape letter
for (size_t k = 0; k < body.size(); ++k) {
if (body[k] == '\\' && k + 1 < body.size()) {
const char n = body[++k];
if (n == 'd') cls += "0-9";
else if (n == 'w') cls += "A-Za-z0-9_";
- else if (n == 's') cls += sp;
- else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else if (n == 's') {
+ cls += sp;
+ if (!negated_cls) escapes.push_back("\\\\[tnfr]");
+ else excluded += "tnfr";
+ }
+ else if (n == 'D' || n == 'W' || n == 'S') { bad = n; return false; }
+ else if (!json_control_escape(n).empty()) {
+ if (n == '0' && k + 1 < body.size() && std::isdigit(static_cast<unsigned char>(body[k + 1]))) {
+ bad = n; // "\01" is a legacy octal escape
+ return false;
+ }
+ if (negated_cls) excluded += n;
+ else escapes.push_back(json_control_escape(n));
+ }
else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') {
// "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could
// read as a range or a negation, so they are written as \xHH.
- cls += "\\x";
- cls += "0123456789ABCDEF"[(n >> 4) & 0xF];
- cls += "0123456789ABCDEF"[n & 0xF];
+ cls += hex_escape(n);
}
- else { cls += '\\'; cls += n; }
+ else if (n == 'x' || n == 'u') {
+ // Copied for GBNF to read, so the hex digits must be there.
+ const size_t len = n == 'x' ? 2 : 4;
+ for (size_t h = 1; h <= len; ++h) {
+ if (k + h >= body.size() || !std::isxdigit(static_cast<unsigned char>(body[k + h]))) {
+ bad = n;
+ return false;
+ }
+ }
+ cls += '\\';
+ cls += n;
+ }
+ else if (std::string("\"[]\\").find(n) != std::string::npos) { cls += '\\'; cls += n; }
+ else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) cls += n;
+ else { bad = n; return false; }
} else {
cls += body[k];
}
}
- out += cls;
if (j < p.size()) {
- out += ']';
+ cls += ']';
+ }
+ if (negated_cls && !excluded.empty() && j < p.size()) {
+ // A string holds those characters only as escapes, so the class becomes text that is
+ // neither a listed character nor one of those escapes. Their \u forms (\u0009 for \t)
+ // are still admitted.
+ std::string letters;
+ for (char e : std::string("bfnrt")) {
+ if (excluded.find(e) == std::string::npos) letters += e;
+ }
+ out += "(?:[^" + cls.substr(2, cls.size() - 3) + raw + "]|\\\\(?:[\"\\\\/" + letters +
+ "]|u[0-9A-Fa-f]{4}))";
+ } else if (!escapes.empty() && j < p.size()) {
+ out += "(?:";
+ if (cls != "[]") out += cls + "|";
+ for (size_t e = 0; e < escapes.size(); ++e) out += (e ? "|" : "") + escapes[e];
+ out += ")";
+ } else {
+ out += cls;
}
i = j;
}
@@ -491,9 +564,10 @@ private:
std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
std::string expanded;
- if (!expand_shorthands(client_pattern, expanded)) {
- _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class "
- "cannot be spelled in GBNF");
+ char bad = 0;
+ if (!expand_shorthands(client_pattern, expanded, bad)) {
+ _errors.push_back(std::string("Unsupported regex escape '\\") + bad +
+ "' inside a character class: GBNF cannot spell it");
return "";
}
const std::string pattern = anchor_pattern(expanded);
@@ -1,17 +0,0 @@
diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp
index f81d98d..5a089d3 100644
--- a/common/jinja/runtime.cpp
+++ b/common/jinja/runtime.cpp
@@ -779,6 +779,12 @@ value member_expression::execute_impl(context & ctx) {
} else {
property = this->property->execute(ctx);
}
+ } else if (is_stmt<integer_literal>(this->property)) {
+ // syntax: obj.index
+ property = mk_val<value_int>(cast_stmt<integer_literal>(this->property)->val);
+ if (property->as_int() < 0) {
+ throw std::runtime_error("Static member property cannot be negative");
+ }
} else {
// syntax: obj.prop
if (!is_stmt<identifier>(this->property)) {