perf(codemode): compile tool schemas once and keep host calls off the copy path

Schema::validated compiles its document into a validator once, so checking a
value does no keyword lookups and builds a path only when it fails. A failed
host call is boxed, so a successful one stays small in the inbox; synchronous
tools share one context; a program compiles when it is made and borrows its
source; the run id is made on first use.

The benchmark tools now declare the reference's schemas, so tool fan-out
also validates each input and output, as the reference does.
This commit is contained in:
kommander 2026-11-17 16:11:25 +00:00 • committed by Sebastian Herrlinger
parent 8bc1023f3d
commit 7c0a0fc3af
8 changed files with 302 additions and 234 deletions

View file

@ -9,7 +9,7 @@
use std::path::PathBuf;
use std::time::Instant;
use psychoscript::{Json, Runtime};
use psychoscript::{Json, Runtime, Schema, Tool};
use serde_json::json;
/// Case files and reference names, in the reference order.
@ -30,13 +30,34 @@ const CASES: [(&str, &str); 9] = [
/// `{ branch: string, dirty: boolean }` out); these Rust tools do not validate yet. Once `Runtime` takes tool schemas,
/// register both with the equivalent validating schemas here, so each side pays for validation.
fn tools(runtime: Runtime) -> Runtime {
// The reference's Effect Schemas, as the JSON Schema documents they render to.
runtime
.tool("echo", |input| {
Ok(input.get("id").cloned().unwrap_or(Json::Null))
})
.tool("git.status", |_| {
Ok(json!({ "branch": "main", "dirty": true }))
})
.with_tool(
"echo",
Tool::new("Echo an id", |input, _| Ok(input["id"].clone()))
.input(Schema::validated(json!({
"type": "object",
"properties": { "id": { "type": "number" } },
"required": ["id"],
"additionalProperties": false
})))
.output(Schema::validated(json!({ "type": "number" }))),
)
.with_tool(
"git.status",
Tool::new("Working tree status", |_, _| {
Ok(json!({ "branch": "main", "dirty": true }))
})
.input(Schema::validated(
json!({ "type": "object", "properties": {}, "additionalProperties": false }),
))
.output(Schema::validated(json!({
"type": "object",
"properties": { "branch": { "type": "string" }, "dirty": { "type": "boolean" } },
"required": ["branch", "dirty"],
"additionalProperties": false
}))),
)
}
fn main() {

View file

@ -95,11 +95,18 @@ pub struct Failed {
impl Settlement {
fn failure(kind: DiagnosticKind, message: String) -> Self {
Settlement::Failure(Box::new(Failed {
Settlement::Failure(Failed::new(kind, message))
}
}
impl Failed {
#[cold]
fn new(kind: DiagnosticKind, message: String) -> Box<Self> {
Box::new(Failed {
kind,
message,
suggestions: Vec::new(),
}))
})
}
}
@ -115,10 +122,11 @@ pub struct FnEntry {
/// The host state of one run.
pub struct RunHost<'rt> {
pub setup: &'rt Setup,
pub run_id: Arc<str>,
/// Names the run's host calls; made on first use when the host gave none.
run_id: Option<Arc<str>>,
next_call: u64,
/// The context handed to synchronous tools, its call id set for each call.
ctx: ToolContext,
ctx: Option<ToolContext>,
pub tasks: Tasks<'rt, Settlement>,
functions: Vec<FnEntry>,
/// Suggestions attached to failure values, by error object.
@ -129,11 +137,11 @@ pub struct RunHost<'rt> {
}
impl<'rt> RunHost<'rt> {
pub fn new(setup: &'rt Setup, run_id: String) -> Self {
pub fn new(setup: &'rt Setup, run_id: Option<String>) -> Self {
Self {
setup,
ctx: ToolContext::new(Arc::from(run_id.as_str()), 0),
run_id: Arc::from(run_id),
ctx: None,
run_id: run_id.map(Arc::from),
next_call: 0,
tasks: Tasks::default(),
functions: Vec::new(),
@ -155,9 +163,25 @@ impl<'rt> RunHost<'rt> {
id
}
pub fn run_id(&mut self) -> Arc<str> {
self.run_id
.get_or_insert_with(|| Arc::from(crate::run::random_run_id()))
.clone()
}
fn context(&mut self) -> ToolContext {
let id = self.next_call();
ToolContext::new(self.run_id.clone(), id)
ToolContext::new(self.run_id(), id)
}
/// The shared context for a synchronous call, without a reference count change per call.
fn sync_context(&mut self, call: u64) -> &ToolContext {
if self.ctx.is_none() {
self.ctx = Some(ToolContext::new(self.run_id(), 0));
}
let ctx = self.ctx.as_mut().expect("context");
ctx.call = call;
ctx
}
}
@ -206,22 +230,10 @@ fn native(vm: &mut Vm, name: &str, length: u8, f: crate::vm::NativeFn, data: Val
/// `tools.<path>(...args)`: returns a promise at once; the call starts now and settles it later.
pub fn call_tool(vm: &mut Vm, path: &str, args: &[Value]) -> Res {
let p = vm.new_promise();
match start_tool(vm, path, args) {
Started::Now(s) => vm.inbox.push_back((p, s)),
Started::Later(future) => {
if let Poll::Ready(s) = vm.host.tasks.spawn(p, future) {
vm.inbox.push_back((p, s));
}
}
}
start_tool(vm, p, path, args);
Ok(Value::Obj(p))
}
enum Started<'rt> {
Now(Settlement),
Later(BoxFuture<'rt, Settlement>),
}
/// Everything about a call that happens before its tool runs: the reference's `decode` and `admit`.
struct Admitted<'rt> {
tool: &'rt Tool,
@ -229,42 +241,54 @@ struct Admitted<'rt> {
call: u64,
}
fn start_tool<'rt>(vm: &mut Vm<'rt>, path: &str, args: &[Value]) -> Started<'rt> {
/// Starts a call whose promise is `p`. A call that ends at once queues its outcome; the rest become tasks.
fn start_tool<'rt>(vm: &mut Vm<'rt>, p: Id, path: &str, args: &[Value]) {
let setup = vm.host.setup;
// Models often write `tools.search(...)` for the bare `search(...)`; honor it unless a tool owns that path.
if path == "search" && !setup.registry.exists("search") {
return match run_search(vm, args) {
Ok(json) => Started::Now(Settlement::Json(json)),
Err(s) => Started::Now(s),
let s = match run_search(vm, args) {
Ok(json) => Settlement::Json(json),
Err(f) => Settlement::Failure(f),
};
vm.inbox.push_back((p, s));
return;
}
let admitted = match admit(vm, path, args) {
Ok(a) => a,
Err(s) => return Started::Now(s),
Err(f) => {
vm.inbox.push_back((p, Settlement::Failure(f)));
return;
}
};
let hooks = &setup.hooks;
if hooks.tool_before.is_none()
&& hooks.tool_after.is_none()
&& let Execute::Sync(f) = &admitted.tool.execute
{
vm.host.ctx.call = admitted.call;
let raw = f(admitted.input, &vm.host.ctx);
return Started::Now(finish(path, admitted.tool, raw));
let raw = f(admitted.input, vm.host.sync_context(admitted.call));
let s = finish(path, admitted.tool, raw);
vm.inbox.push_back((p, s));
return;
}
let ctx = ToolContext::new(vm.host.run_id(), admitted.call);
let future = Box::pin(hooked_tool(hooks, path.to_owned(), admitted, ctx));
if let Poll::Ready(s) = vm.host.tasks.spawn(p, future) {
vm.inbox.push_back((p, s));
}
let ctx = ToolContext::new(vm.host.run_id.clone(), admitted.call);
Started::Later(Box::pin(hooked_tool(hooks, path.to_owned(), admitted, ctx)))
}
fn admit<'rt>(vm: &mut Vm<'rt>, path: &str, args: &[Value]) -> Result<Admitted<'rt>, Settlement> {
#[inline]
fn admit<'rt>(vm: &mut Vm<'rt>, path: &str, args: &[Value]) -> Result<Admitted<'rt>, Box<Failed>> {
let setup = vm.host.setup;
let Some(tool) = setup.registry.get(path) else {
return Err(unknown_tool(setup, path));
};
let tool: &'rt Tool = tool;
let entry_field = tool
.freeform
.then(|| schema::string_parameter(tool.input.document()).map(|(name, _)| name))
.flatten();
let entry_field = if tool.freeform {
schema::string_parameter(tool.input.document()).map(|(name, _)| name)
} else {
None
};
let input = decode(vm, path, &tool.input, entry_field.as_deref(), args, false)?;
admit_call(vm, path, &input)?;
let call = vm.host.next_call();
@ -272,6 +296,7 @@ fn admit<'rt>(vm: &mut Vm<'rt>, path: &str, args: &[Value]) -> Result<Admitted<'
}
/// Copies the call's argument out as JSON and decodes it with the tool's input schema.
#[inline]
fn decode(
vm: &mut Vm,
name: &str,
@ -279,9 +304,9 @@ fn decode(
string_field: Option<&str>,
args: &[Value],
search: bool,
) -> Result<Json, Settlement> {
) -> Result<Json, Box<Failed>> {
if args.len() > 1 {
return Err(Settlement::failure(
return Err(Failed::new(
DiagnosticKind::InvalidToolInput,
format!("Tool '{name}' expects at most one input object."),
));
@ -292,7 +317,7 @@ fn decode(
Ok(j) => j,
Err(e) => {
let msg = vm.error_text(&e);
return Err(Settlement::failure(
return Err(Failed::new(
DiagnosticKind::InvalidDataValue,
format!("Invalid input for tool '{name}': {msg}"),
));
@ -309,7 +334,7 @@ fn decode(
};
schema
.validate(input)
.map_err(|e| Settlement::Failure(Box::new(Failed {
.map_err(|e| Box::new(Failed {
kind: DiagnosticKind::InvalidToolInput,
message: format!("Invalid input for tool '{name}': {e}"),
suggestions: vec![if search {
@ -317,15 +342,16 @@ fn decode(
} else {
"The signature may have changed. Use search to get the current signature.".into()
}],
})))
}))
}
/// Counts a call against `max_tool_calls` and records it.
fn admit_call(vm: &mut Vm, path: &str, input: &Json) -> Result<(), Settlement> {
#[inline]
fn admit_call(vm: &mut Vm, path: &str, input: &Json) -> Result<(), Box<Failed>> {
if let Some(max) = vm.limits.max_tool_calls
&& vm.tool_calls.len() as u64 >= max
{
return Err(Settlement::failure(
return Err(Failed::new(
DiagnosticKind::ToolCallLimitExceeded,
format!("Execution exceeded its tool-call limit of {max}."),
));
@ -338,6 +364,7 @@ fn admit_call(vm: &mut Vm, path: &str, input: &Json) -> Result<(), Settlement> {
}
/// A tool's raw result as the program receives it.
#[inline]
fn finish(name: &str, tool: &Tool, raw: Result<Json, crate::ToolError>) -> Settlement {
match raw {
Err(e) => Settlement::failure(DiagnosticKind::ToolFailure, e.message),
@ -407,7 +434,8 @@ async fn hooked_tool(hooks: &Hooks, name: String, a: Admitted<'_>, ctx: ToolCont
s
}
fn unknown_tool(setup: &Setup, path: &str) -> Settlement {
#[cold]
fn unknown_tool(setup: &Setup, path: &str) -> Box<Failed> {
let registry = &setup.registry;
let entries = registry.entries();
let index = registry.word_index();
@ -437,11 +465,11 @@ fn unknown_tool(setup: &Setup, path: &str) -> Settlement {
),
None => format!("Unknown tool '{path}'."),
};
return Settlement::Failure(Box::new(Failed {
return Box::new(Failed {
kind: DiagnosticKind::UnknownTool,
message,
suggestions: vec!["Use search to find available tools.".into()],
}));
});
}
let under = format!("{path}.");
let scope: Vec<usize> = (0..entries.len())
@ -480,11 +508,11 @@ fn unknown_tool(setup: &Setup, path: &str) -> Settlement {
} else {
"Use search to find available tools.".into()
};
Settlement::Failure(Box::new(Failed {
Box::new(Failed {
kind: DiagnosticKind::UnknownTool,
message,
suggestions: vec![suggestion],
}))
})
}
/// `Intl.ListFormat("en", { type: "disjunction" })`.
@ -550,13 +578,12 @@ fn search_native(vm: &mut Vm, _this: Value, args: &[Value], _callee: Id) -> Res
}
Ok(v)
}
Err(Settlement::Failure(f)) => Err(failure_value(vm, f.kind, f.message, f.suggestions)),
Err(_) => Ok(Value::Undef),
Err(f) => Err(failure_value(vm, f.kind, f.message, f.suggestions)),
}
}
/// The built-in search, blocking: decode, admit, the hooks, then the ranking.
fn run_search(vm: &mut Vm, args: &[Value]) -> Result<Json, Settlement> {
fn run_search(vm: &mut Vm, args: &[Value]) -> Result<Json, Box<Failed>> {
let setup = vm.host.setup;
let args: Vec<Value> = match args.first() {
Some(Value::Str(s)) => {
@ -583,7 +610,7 @@ fn run_search(vm: &mut Vm, args: &[Value]) -> Result<Json, Settlement> {
if let Some(before) = &hooks.tool_before
&& let Err(e) = block_on(before(&call))
{
return Err(Settlement::failure(DiagnosticKind::ToolFailure, e.message));
return Err(Failed::new(DiagnosticKind::ToolFailure, e.message));
}
let registry = &setup.registry;
let result = search::search(registry.entries(), registry.word_index(), &input);

View file

@ -257,12 +257,12 @@ impl Runtime {
}
/// A program ready to run once; nothing runs until [`Program::run`] or [`Program::run_async`]. Host calls get the keys `<run_id>:<callId>`; a random run id by default.
pub fn program(
&self,
code: &str,
pub fn program<'a>(
&'a self,
code: &'a str,
bindings: &serde_json::Map<String, Json>,
run_id: Option<&str>,
) -> Program<'_> {
) -> Program<'a> {
Program::new(self, code, bindings, run_id)
}

View file

@ -9,45 +9,41 @@ use crate::run;
use crate::vm::Vm;
use crate::{Json, Outcome, Runtime};
enum State<'rt> {
Ready {
code: String,
bindings: serde_json::Map<String, Json>,
run_id: String,
},
Running(Box<Running<'rt>>),
enum State<'a> {
Running(Box<Running<'a>>),
/// It ended before running: the program did not compile.
Failed(Box<Outcome>),
Done,
}
pub(crate) struct Running<'rt> {
pub vm: Vm<'rt>,
pub code: String,
pub(crate) struct Running<'a> {
pub vm: Vm<'a>,
pub code: &'a str,
started: bool,
timer_armed: bool,
}
/// A program ready to run once. Dropping it interrupts the run and cancels every host call in flight.
pub struct Program<'rt> {
rt: &'rt Runtime,
state: State<'rt>,
pub struct Program<'a> {
state: State<'a>,
/// How much of the native stack below the point it is driven from the run may use.
pub(crate) stack_budget: usize,
}
impl<'rt> Program<'rt> {
impl<'a> Program<'a> {
/// Compiles the program and sets up its globals; nothing runs yet.
pub(crate) fn new(
rt: &'rt Runtime,
code: &str,
rt: &'a Runtime,
code: &'a str,
bindings: &serde_json::Map<String, Json>,
run_id: Option<&str>,
) -> Self {
let state = match run::start(rt, code, bindings, run_id.map(str::to_owned)) {
Ok(r) => State::Running(r),
Err(outcome) => State::Failed(outcome),
};
Self {
rt,
state: State::Ready {
code: code.to_owned(),
bindings: bindings.clone(),
run_id: run_id.map_or_else(run::random_run_id, str::to_owned),
},
state,
stack_budget: run::INLINE_STACK_BUDGET,
}
}
@ -65,19 +61,11 @@ impl<'rt> Program<'rt> {
fn advance(&mut self, cx: &mut Context<'_>) -> Poll<Outcome> {
let probe = 0u8;
if let State::Ready { .. } = self.state {
let State::Ready {
code,
bindings,
run_id,
} = std::mem::replace(&mut self.state, State::Done)
else {
if let State::Failed(_) = self.state {
let State::Failed(outcome) = std::mem::replace(&mut self.state, State::Done) else {
unreachable!()
};
match run::start(self.rt, code, &bindings, run_id) {
Ok(vm) => self.state = State::Running(vm),
Err(outcome) => return Poll::Ready(*outcome),
}
return Poll::Ready(*outcome);
}
let State::Running(r) = &mut self.state else {
return Poll::Pending;
@ -126,8 +114,8 @@ impl<'rt> Program<'rt> {
}
}
impl<'rt> Running<'rt> {
pub fn new(vm: Vm<'rt>, code: String) -> Self {
impl<'a> Running<'a> {
pub fn new(vm: Vm<'a>, code: &'a str) -> Self {
Self {
vm,
code,

View file

@ -24,8 +24,7 @@ const THREAD_STACK_BUDGET: usize = 64 << 20;
pub fn execute(rt: &Runtime, code: &str, bindings: &serde_json::Map<String, Json>) -> Outcome {
if code.len() <= INLINE_SOURCE_BYTES && bracket_depth(code) <= INLINE_BRACKET_DEPTH {
let program = rt.program(code, bindings, None);
let run = AssertUnwindSafe(|| program.run());
let run = AssertUnwindSafe(|| rt.program(code, bindings, None).run());
return std::panic::catch_unwind(run).unwrap_or_else(|_| internal_error());
}
std::thread::scope(|s| {
@ -105,17 +104,17 @@ pub fn random_run_id() -> String {
}
/// Compiles a program and sets up its run, or the outcome when it does not compile.
pub fn start<'rt>(
rt: &'rt Runtime,
code: String,
pub fn start<'a>(
rt: &'a Runtime,
code: &'a str,
bindings: &serde_json::Map<String, Json>,
run_id: String,
) -> Result<Box<Running<'rt>>, Box<Outcome>> {
run_id: Option<String>,
) -> Result<Box<Running<'a>>, Box<Outcome>> {
let mut atoms = Strings::new();
let program = match compiler::compile(&code, &mut atoms) {
let program = match compiler::compile(code, &mut atoms) {
Ok(p) => p,
Err(e) => {
let location = e.offset.map(|o| line_col(&code, o));
let location = e.offset.map(|o| line_col(code, o));
let message = format!("{}{}", e.message, suffix(location));
return Err(Box::new(failed(Diagnostic {
kind: e.kind,
@ -162,7 +161,6 @@ pub fn finish(r: Running<'_>) -> Outcome {
let Running { mut vm, code, .. } = r;
vm.host.tasks.clear();
let vm = &mut vm;
let code = code.as_str();
let result = match (vm.fatal.clone(), vm.outcome.take()) {
(Some((kind, message)), _) => Err(diagnostic(kind, message)),
(None, Some(Ok(v))) => match convert::to_json(vm, &v) {

View file

@ -47,12 +47,19 @@ impl Schema {
/// `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `minLength`, `maxLength`, `minItems`, `maxItems` and
/// `uniqueItems`: the constraints an Effect Schema's JSON Schema document is made of. `pattern` and `format` only
/// render: the crate has no regular-expression engine, and Effect's `format` is an annotation.
#[inline]
pub fn validate(&self, value: Json) -> Result<Json, String> {
let Some(v) = &self.validator else {
return Ok(value);
};
let mut path = Vec::new();
check(&v.root, value, v, &mut path, 0)
match &self.validator {
None => Ok(value),
Some(v) => v.validate(value),
}
}
}
impl Validator {
#[inline(never)]
fn validate(&self, value: Json) -> Result<Json, String> {
check(&self.root, value, self, 0)
.map_err(|(message, path)| format!("SchemaError({message}{})", render_path(&path)))
}
}
@ -754,8 +761,8 @@ struct Node {
enumeration: Option<Vec<Json>>,
any_of: Vec<Node>,
all_of: Vec<Node>,
/// Type names, or empty for any type.
types: Vec<String>,
/// Type bits, or 0 for any type.
types: u8,
expected: String,
minimum: Option<f64>,
maximum: Option<f64>,
@ -768,8 +775,10 @@ struct Node {
max_items: Option<f64>,
unique_items: bool,
items: Option<Box<Node>>,
properties: Vec<(String, Node)>,
required: Vec<String>,
/// Each property with whether it is required, in schema order.
properties: Vec<(String, Node, bool)>,
/// Required keys that are not among the properties.
required_only: Vec<String>,
additional: Additional,
}
@ -852,7 +861,7 @@ fn compile(s: &Json, index: &dyn Fn(&str) -> Option<usize>, depth: usize) -> Nod
if let Some(Json::Array(all)) = field(s, "allOf") {
n.all_of = all.iter().map(sub).collect();
}
n.types = types_of(s);
n.types = type_bits(&types_of(s));
n.expected = expected(s);
n.minimum = number(s, "minimum");
n.maximum = number(s, "maximum");
@ -865,15 +874,23 @@ fn compile(s: &Json, index: &dyn Fn(&str) -> Option<usize>, depth: usize) -> Nod
n.max_items = number(s, "maxItems");
n.unique_items = s.get("uniqueItems") == Some(&Json::Bool(true));
n.items = field(s, "items").map(|i| Box::new(sub(i)));
if let Some(Json::Object(props)) = s.get("properties") {
n.properties = props.iter().map(|(k, v)| (k.clone(), sub(v))).collect();
}
if let Some(Json::Array(r)) = s.get("required") {
n.required = r
let required: Vec<String> = match s.get("required") {
Some(Json::Array(r)) => r
.iter()
.filter_map(|v| v.as_str().map(str::to_owned))
.collect(),
_ => Vec::new(),
};
if let Some(Json::Object(props)) = s.get("properties") {
n.properties = props
.iter()
.map(|(k, v)| (k.clone(), sub(v), required.contains(k)))
.collect();
}
n.required_only = required
.into_iter()
.filter(|r| !n.properties.iter().any(|(k, _, _)| k == r))
.collect();
n.additional = match s.get("additionalProperties") {
Some(Json::Bool(false)) => Additional::Drop,
Some(extra @ Json::Object(_)) => Additional::Check(Box::new(sub(extra))),
@ -882,9 +899,10 @@ fn compile(s: &Json, index: &dyn Fn(&str) -> Option<usize>, depth: usize) -> Nod
n
}
/// A failure's message and where it happened, innermost segment first: each level adds its own on the way out,
/// so checking a valid value builds no path at all.
type Failure = (String, Vec<PathPart>);
#[derive(Clone)]
enum PathPart {
Key(String),
Index(usize),
@ -895,7 +913,7 @@ fn render_path(path: &[PathPart]) -> String {
return String::new();
}
let mut out = String::from("\n at ");
for p in path {
for p in path.iter().rev() {
match p {
PathPart::Key(k) => {
out.push('[');
@ -908,22 +926,48 @@ fn render_path(path: &[PathPart]) -> String {
out
}
fn json_type(v: &Json) -> &'static str {
match v {
Json::Null => "null",
Json::Bool(_) => "boolean",
Json::Number(_) => "number",
Json::String(_) => "string",
Json::Array(_) => "array",
Json::Object(_) => "object",
}
fn at<T>(r: Result<T, Failure>, part: impl FnOnce() -> PathPart) -> Result<T, Failure> {
r.map_err(|(message, mut path)| {
path.push(part());
(message, path)
})
}
fn matches_type(t: &str, v: &Json) -> bool {
match t {
"integer" | "number" => v.is_number(),
other => json_type(v) == other,
}
const T_NULL: u8 = 1;
const T_BOOLEAN: u8 = 2;
const T_NUMBER: u8 = 4;
const T_INTEGER: u8 = 8;
const T_STRING: u8 = 16;
const T_ARRAY: u8 = 32;
const T_OBJECT: u8 = 64;
fn type_bits(types: &[String]) -> u8 {
types
.iter()
.map(|t| match t.as_str() {
"null" => T_NULL,
"boolean" => T_BOOLEAN,
"number" => T_NUMBER,
"integer" => T_INTEGER,
"string" => T_STRING,
"array" => T_ARRAY,
"object" => T_OBJECT,
_ => 0,
})
.fold(0, |a, b| a | b)
}
/// Whether a value is of one of the types; an `integer` type accepts any number here and is checked after.
fn type_matches(bits: u8, v: &Json) -> bool {
let bit = match v {
Json::Null => T_NULL,
Json::Bool(_) => T_BOOLEAN,
Json::Number(_) => T_NUMBER | T_INTEGER,
Json::String(_) => T_STRING,
Json::Array(_) => T_ARRAY,
Json::Object(_) => T_OBJECT,
};
bits & bit != 0
}
/// What a schema accepts, for an `Expected ...` message.
@ -958,92 +1002,81 @@ fn expected(s: &Json) -> String {
.join(" | ")
}
fn fail<T>(message: impl Into<String>, path: &[PathPart]) -> Result<T, Failure> {
Err((message.into(), path.to_vec()))
#[cold]
fn fail<T>(message: impl Into<String>) -> Result<T, Failure> {
Err((message.into(), Vec::new()))
}
fn check(
n: &Node,
mut value: Json,
v: &Validator,
path: &mut Vec<PathPart>,
depth: usize,
) -> Result<Json, Failure> {
fn check(n: &Node, mut value: Json, v: &Validator, depth: usize) -> Result<Json, Failure> {
if depth > 64 {
return fail("Schema nesting is too deep", path);
return fail("Schema nesting is too deep");
}
if n.never {
return fail("Expected never", path);
return fail("Expected never");
}
if let Some(r) = n.reference {
value = check(&v.defs[r], value, v, path, depth + 1)?;
value = check(&v.defs[r], value, v, depth + 1)?;
}
if let Some(c) = &n.constant
&& !json_eq(c, &value)
{
return fail(format!("Expected {}", js_stringify(c)), path);
return fail(format!("Expected {}", js_stringify(c)));
}
if let Some(values) = &n.enumeration
&& !values.iter().any(|c| json_eq(c, &value))
{
return fail(format!("Expected {}", n.expected), path);
return fail(format!("Expected {}", n.expected));
}
if !n.any_of.is_empty() {
value = check_union(n, value, v, path, depth)?;
value = check_union(n, value, v, depth)?;
}
for part in &n.all_of {
value = check(part, value, v, path, depth + 1)?;
value = check(part, value, v, depth + 1)?;
}
if !n.types.is_empty() {
if !n.types.iter().any(|t| matches_type(t, &value)) {
return fail(format!("Expected {}", n.expected), path);
if n.types != 0 {
if !type_matches(n.types, &value) {
return fail(format!("Expected {}", n.expected));
}
if n.types.iter().all(|t| t == "integer")
&& value.as_f64().is_some_and(|x| x.fract() != 0.0)
{
return fail("Expected an integer", path);
if n.types == T_INTEGER && value.as_f64().is_some_and(|x| x.fract() != 0.0) {
return fail("Expected an integer");
}
}
match &mut value {
Json::Number(x) => check_number(n, x.as_f64().unwrap_or(f64::NAN), path)?,
Json::String(text) => check_length(utf16_len(text), n.min_length, n.max_length, path)?,
Json::Number(x) => check_number(n, x.as_f64().unwrap_or(f64::NAN))?,
Json::String(text) if n.min_length.is_some() || n.max_length.is_some() => {
check_length(utf16_len(text), n.min_length, n.max_length)?
}
Json::Array(items) => {
check_length(items.len(), n.min_items, n.max_items, path)?;
check_length(items.len(), n.min_items, n.max_items)?;
if n.unique_items {
for i in 0..items.len() {
if items[..i].iter().any(|prev| json_eq(prev, &items[i])) {
return fail("Expected an array of unique items", path);
return fail("Expected an array of unique items");
}
}
}
if let Some(item_node) = &n.items {
for (i, item) in items.iter_mut().enumerate() {
path.push(PathPart::Index(i));
*item = check(item_node, std::mem::take(item), v, path, depth + 1)?;
path.pop();
*item = at(check(item_node, std::mem::take(item), v, depth + 1), || {
PathPart::Index(i)
})?;
}
}
}
Json::Object(map) => check_object(n, map, v, path, depth)?,
Json::Object(map) => check_object(n, map, v, depth)?,
_ => {}
}
Ok(value)
}
fn check_union(
n: &Node,
value: Json,
v: &Validator,
path: &mut Vec<PathPart>,
depth: usize,
) -> Result<Json, Failure> {
fn check_union(n: &Node, value: Json, v: &Validator, depth: usize) -> Result<Json, Failure> {
let mut candidate = None;
let mut same_type = 0;
for alt in &n.any_of {
match check(alt, value.clone(), v, path, depth + 1) {
match check(alt, value.clone(), v, depth + 1) {
Ok(decoded) => return Ok(decoded),
Err(e) => {
if alt.types.iter().any(|t| matches_type(t, &value)) {
if type_matches(alt.types, &value) {
same_type += 1;
candidate = Some(e);
}
@ -1053,69 +1086,64 @@ fn check_union(
// Like Effect, a single member of the value's own type explains the failure; otherwise the union does.
match candidate {
Some(e) if same_type == 1 => Err(e),
_ => fail(format!("Expected {}", n.expected), path),
_ => fail(format!("Expected {}", n.expected)),
}
}
fn check_number(n: &Node, x: f64, path: &[PathPart]) -> Result<(), Failure> {
fn check_number(n: &Node, x: f64) -> Result<(), Failure> {
if let Some(m) = n.minimum
&& x < m
{
return fail(
format!("Expected a value greater than or equal to {}", js_num(m)),
path,
);
return fail(format!(
"Expected a value greater than or equal to {}",
js_num(m)
));
}
if let Some(m) = n.maximum
&& x > m
{
return fail(
format!("Expected a value less than or equal to {}", js_num(m)),
path,
);
return fail(format!(
"Expected a value less than or equal to {}",
js_num(m)
));
}
if let Some(m) = n.exclusive_minimum
&& x <= m
{
return fail(format!("Expected a value greater than {}", js_num(m)), path);
return fail(format!("Expected a value greater than {}", js_num(m)));
}
if let Some(m) = n.exclusive_maximum
&& x >= m
{
return fail(format!("Expected a value less than {}", js_num(m)), path);
return fail(format!("Expected a value less than {}", js_num(m)));
}
if let Some(m) = n.multiple_of
&& (x / m).fract() != 0.0
{
return fail(
format!("Expected a value that is a multiple of {}", js_num(m)),
path,
);
return fail(format!(
"Expected a value that is a multiple of {}",
js_num(m)
));
}
Ok(())
}
fn check_length(
len: usize,
min: Option<f64>,
max: Option<f64>,
path: &[PathPart],
) -> Result<(), Failure> {
fn check_length(len: usize, min: Option<f64>, max: Option<f64>) -> Result<(), Failure> {
if let Some(m) = min
&& (len as f64) < m
{
return fail(
format!("Expected a value with a length of at least {}", js_num(m)),
path,
);
return fail(format!(
"Expected a value with a length of at least {}",
js_num(m)
));
}
if let Some(m) = max
&& (len as f64) > m
{
return fail(
format!("Expected a value with a length of at most {}", js_num(m)),
path,
);
return fail(format!(
"Expected a value with a length of at most {}",
js_num(m)
));
}
Ok(())
}
@ -1124,38 +1152,48 @@ fn check_object(
n: &Node,
map: &mut serde_json::Map<String, Json>,
v: &Validator,
path: &mut Vec<PathPart>,
depth: usize,
) -> Result<(), Failure> {
for name in &n.required {
for name in &n.required_only {
if !map.contains_key(name) {
path.push(PathPart::Key(name.clone()));
return fail("Missing key", path);
return at(fail("Missing key"), || PathPart::Key(name.clone()));
}
}
for (name, prop) in &n.properties {
if let Some(item) = map.get_mut(name) {
path.push(PathPart::Key(name.clone()));
*item = check(prop, std::mem::take(item), v, path, depth + 1)?;
path.pop();
let mut present = 0;
// Tool inputs are small objects, where a scan beats hashing every key.
let small = map.len() <= 8;
for (name, prop, required) in &n.properties {
let item = if small {
map.iter_mut().find(|(k, _)| *k == name).map(|(_, v)| v)
} else {
map.get_mut(name)
};
match item {
Some(item) => {
present += 1;
*item = at(check(prop, std::mem::take(item), v, depth + 1), || {
PathPart::Key(name.clone())
})?;
}
None if *required => return at(fail("Missing key"), || PathPart::Key(name.clone())),
None => {}
}
}
let known = |k: &str| n.properties.iter().any(|(p, _)| p == k);
if map.len() == present {
return Ok(());
}
let known = |k: &str| n.properties.iter().any(|(p, _, _)| p == k);
match &n.additional {
Additional::Keep => {}
Additional::Drop => {
if map.len() > n.properties.len() || map.keys().any(|k| !known(k)) {
map.retain(|k, _| known(k));
}
}
Additional::Drop => map.retain(|k, _| known(k)),
Additional::Check(extra) => {
for (name, item) in map.iter_mut() {
if known(name) {
continue;
}
path.push(PathPart::Key(name.clone()));
*item = check(extra, std::mem::take(item), v, path, depth + 1)?;
path.pop();
*item = at(check(extra, std::mem::take(item), v, depth + 1), || {
PathPart::Key(name.clone())
})?;
}
}
}

View file

@ -73,11 +73,7 @@ fn run_here(code: &str, timeout_ms: u64) -> Run {
..Limits::default()
};
let rt = crate::Runtime::new();
let mut vm = Vm::new(
crate::host::RunHost::new(rt.setup(), String::new()),
limits,
atoms,
);
let mut vm = Vm::new(crate::host::RunHost::new(rt.setup(), None), limits, atoms);
vm.stack_base = &probe as *const u8 as usize;
vm.stack_budget = STACK_BUDGET;
vm.setup();

View file

@ -165,7 +165,7 @@ pub struct Vm<'rt> {
pub coroutines: Vec<Coroutine>,
pub logs: Vec<String>,
pub tool_calls: Vec<ToolCall>,
pub host: Box<crate::host::RunHost<'rt>>,
pub host: crate::host::RunHost<'rt>,
pub tool_refs: FxHashMap<Rc<str>, Id>,
pub limits: Limits,
pub start: Instant,
@ -230,7 +230,7 @@ impl<'rt> Vm<'rt> {
coroutines: Vec::new(),
logs: Vec::new(),
tool_calls: Vec::new(),
host: Box::new(host),
host,
tool_refs: FxHashMap::default(),
limits,
start: Instant::now(),