use std::hint::black_box;
use criterion::{criterion_group, criterion_main, Criterion};
use openlatch_client::zone_eval::{self, Bundle, Event};
use serde_json::{json, Value};
const NOW_MS: i64 = 1_756_742_400_000;
const ATOM_COUNT: usize = 2_000;
const SURFACE_WIDTH: usize = 40;
fn t1_artifact(index: usize, node: Value) -> Value {
json!({
"artifact_id": format!("artifact-{index:04}"),
"atom_id": format!("atom-{index:04}"),
"kind": "t1_predicate_tree",
"on_inconclusive": "ask",
"tier": 1,
"body": {
"node": node,
"verdict": "block",
"reason": "bench fixture fired",
},
})
}
fn leaf(pred: &str, field: &str, value: Value) -> Value {
json!({"op": "leaf", "leaf": {"pred": pred, "field": field, "value": value}})
}
fn regex_leaf(field: &str, pattern: &str) -> Value {
json!({"op": "leaf", "leaf": {"pred": "regex_lite", "field": field, "pattern": pattern}})
}
fn bundle_doc(artifacts: Vec<Value>) -> Value {
json!({
"schema_version": 2,
"organization_id": "org-bench",
"revision": 1,
"built_at": "2026-09-01T00:00:00Z",
"enforcement_enabled": true,
"signature": null,
"artifacts": artifacts,
})
}
fn load(doc: Value) -> Bundle {
let bundle = zone_eval::bundle::load(doc).expect("the bench fixture bundle loads");
assert!(
bundle.skipped.is_empty(),
"fixture skipped {} artifact(s): {:?}",
bundle.skipped.len(),
bundle.skipped,
);
assert_eq!(
bundle.artifacts.len(),
ATOM_COUNT,
"fixture must carry the full {ATOM_COUNT}-atom scale",
);
bundle
}
fn surface_lowercase_ascii() -> Vec<String> {
(0..SURFACE_WIDTH)
.map(|i| format!("src/core/policy/module_{i:02}/handler.rs - a short line of prose"))
.collect()
}
fn surface_mixed_case_ascii() -> Vec<String> {
(0..SURFACE_WIDTH)
.map(|i| format!("Src/Core/Policy/Module_{i:02}/Handler.rs - A Short Line Of Prose"))
.collect()
}
#[derive(Clone, Copy)]
enum FoldArm {
Borrowed,
AsciiLower,
Caseless,
}
fn assert_surface_shape(name: &str, values: &[String], arm: FoldArm) {
for value in values {
let has_upper = value.bytes().any(|b| b.is_ascii_uppercase());
let ascii = value.is_ascii();
let ok = match arm {
FoldArm::Borrowed => ascii && !has_upper,
FoldArm::AsciiLower => ascii && has_upper,
FoldArm::Caseless => !ascii,
};
assert!(
ok,
"surface '{name}' takes the wrong fold_keyword arm on {value:?}"
);
}
}
fn folding_surfaces() -> Vec<(&'static str, Vec<String>)> {
let surfaces = vec![
("keyword_lowercase_ascii", surface_lowercase_ascii()),
("keyword_mixed_case_ascii", surface_mixed_case_ascii()),
("keyword_non_ascii", surface_non_ascii()),
];
let arms = [FoldArm::Borrowed, FoldArm::AsciiLower, FoldArm::Caseless];
for ((name, values), arm) in surfaces.iter().zip(arms) {
assert_surface_shape(name, values, arm);
}
surfaces
}
fn surface_non_ascii() -> Vec<String> {
(0..SURFACE_WIDTH)
.map(|i| format!("le café {i:02} est fermé — ΣΊΣΥΦΟΣ pousse la pierre, Straße finale"))
.collect()
}
fn surface_event(values: &[String]) -> Event {
Event {
event_type: "pre_tool_use".to_string(),
session_id: "session-bench".to_string(),
tool_name: "Write".to_string(),
tool_input: json!({"values": values}),
..Event::default()
}
}
fn keyword_bundle() -> Bundle {
let artifacts = (0..ATOM_COUNT)
.map(|i| {
t1_artifact(
i,
leaf(
"keyword",
"input.strings",
json!([format!("needle_{i:04}_absent")]),
),
)
})
.collect();
load(bundle_doc(artifacts))
}
fn regex_bundle() -> Bundle {
let artifacts = (0..ATOM_COUNT)
.map(|i| {
t1_artifact(
i,
regex_leaf("input.strings", &format!(r"\bneedle_{i:04}\b")),
)
})
.collect();
load(bundle_doc(artifacts))
}
fn mixed_node(i: usize) -> Value {
match i % 5 {
0 if i == 0 => leaf("keyword", "tool.name", json!(["bash"])),
0 => leaf("keyword", "input.strings", json!([format!("kw_{i:04}")])),
1 => leaf("prefix", "input.strings", json!([format!("pre_{i:04}/")])),
2 => regex_leaf("input.strings", &format!(r"\brx_{i:04}\b")),
3 => leaf("glob", "path.value", json!([format!("/opt/g_{i:04}/**")])),
_ => leaf("equals", "tool.name", json!(format!("Tool{i:04}"))),
}
}
fn mixed_bundle() -> Bundle {
let artifacts = (0..ATOM_COUNT)
.map(|i| t1_artifact(i, mixed_node(i)))
.collect();
load(bundle_doc(artifacts))
}
fn shell_event() -> Event {
Event {
event_type: "pre_tool_use".to_string(),
session_id: "session-bench".to_string(),
tool_name: "Bash".to_string(),
tool_input: json!({
"command": "rm -rf /data/warehouse/staging && aws s3 cp report.csv s3://acme-exports/",
}),
..Event::default()
}
}
fn assert_decides(bundle: &Bundle, event: &Event) {
let (decision, _) = zone_eval::evaluate(bundle, event, None, NOW_MS);
assert!(
decision.artifact_id.is_some(),
"fixture matched no artifact — it would benchmark an empty path",
);
}
fn bench_load(c: &mut Criterion) {
let keyword = bundle_doc(
(0..ATOM_COUNT)
.map(|i| {
t1_artifact(
i,
leaf(
"keyword",
"input.strings",
json!([format!("needle_{i:04}_absent")]),
),
)
})
.collect(),
);
let regex = bundle_doc(
(0..ATOM_COUNT)
.map(|i| {
t1_artifact(
i,
regex_leaf("input.strings", &format!(r"\bneedle_{i:04}\b")),
)
})
.collect(),
);
let mixed = bundle_doc(
(0..ATOM_COUNT)
.map(|i| t1_artifact(i, mixed_node(i)))
.collect(),
);
let mut group = c.benchmark_group("zone_eval_load");
group.sample_size(10);
group.bench_function("keyword_2000_atoms", |b| {
b.iter(|| zone_eval::bundle::load(black_box(keyword.clone())).expect("loads"))
});
group.bench_function("regex_2000_atoms", |b| {
b.iter(|| zone_eval::bundle::load(black_box(regex.clone())).expect("loads"))
});
group.bench_function("mixed_2000_atoms", |b| {
b.iter(|| zone_eval::bundle::load(black_box(mixed.clone())).expect("loads"))
});
group.finish();
}
fn bench_scan(c: &mut Criterion) {
let keyword = keyword_bundle();
let regex = regex_bundle();
let surfaces = folding_surfaces();
let mut group = c.benchmark_group("zone_eval_scan");
for (name, values) in &surfaces {
let event = surface_event(values);
let facts = zone_eval::facts::resolve(&keyword, NOW_MS);
let class = zone_eval::effect::classify(&event, &facts, keyword.catalogue.as_ref());
let ctx = zone_eval::EvalContext::new(&event, &class, &facts, NOW_MS);
group.bench_function(*name, |b| b.iter(|| keyword.scan.scan(black_box(&ctx))));
}
let values = surface_lowercase_ascii();
let event = surface_event(&values);
let facts = zone_eval::facts::resolve(®ex, NOW_MS);
let class = zone_eval::effect::classify(&event, &facts, regex.catalogue.as_ref());
let ctx = zone_eval::EvalContext::new(&event, &class, &facts, NOW_MS);
group.bench_function("regex_unicode_boundary", |b| {
b.iter(|| regex.scan.scan(black_box(&ctx)))
});
group.finish();
}
fn bench_evaluate(c: &mut Criterion) {
let mixed = mixed_bundle();
let shell = shell_event();
assert_decides(&mixed, &shell);
let mut group = c.benchmark_group("zone_eval_evaluate");
group.bench_function("mixed_2000_atoms", |b| {
b.iter(|| zone_eval::evaluate(black_box(&mixed), black_box(&shell), None, NOW_MS))
});
group.finish();
}
fn bench_evaluate_wide(c: &mut Criterion) {
let keyword = keyword_bundle();
let surfaces = folding_surfaces();
let mut group = c.benchmark_group("zone_eval_evaluate_wide");
group.sample_size(10);
for (name, values) in surfaces
.iter()
.filter(|(name, _)| *name != "keyword_mixed_case_ascii")
{
let event = surface_event(values);
group.bench_function(*name, |b| {
b.iter(|| zone_eval::evaluate(black_box(&keyword), black_box(&event), None, NOW_MS))
});
}
group.finish();
}
criterion_group!(
benches,
bench_load,
bench_scan,
bench_evaluate,
bench_evaluate_wide
);
criterion_main!(benches);