#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
#[allow(dead_code)]
mod baseline {
include!(env!("INSTINCT_BENCH_BASELINE"));
}
#[allow(dead_code)]
mod candidate {
include!(env!("INSTINCT_BENCH_CANDIDATE"));
}
use std::hint::black_box;
use std::time::Instant;
#[derive(Debug, Clone, PartialEq)]
enum Json {
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
fn get(&self, key: &str) -> Option<&Json> {
let Self::Obj(fields) = self else { return None };
fields
.iter()
.find(|(name, _)| name == key)
.map(|(_, value)| value)
}
fn as_str(&self) -> Option<&str> {
match self {
Self::Str(s) => Some(s),
_ => None,
}
}
fn as_f64(&self) -> Option<f64> {
match self {
Self::Num(n) => Some(*n),
_ => None,
}
}
}
fn object<const N: usize>(entries: [(&str, Json); N]) -> Json {
Json::Obj(
entries
.into_iter()
.map(|(key, value)| (key.into(), value))
.collect(),
)
}
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn index(&mut self, limit: usize) -> usize {
(self.next() % limit as u64) as usize
}
}
fn facts(width: usize, known: u16, truth: u16) -> Json {
Json::Obj(
(0..width)
.filter(|bit| known & (1 << bit) != 0)
.map(|bit| {
(
format!("feature{bit:02}"),
Json::Bool(truth & (1 << bit) != 0),
)
})
.collect(),
)
}
fn casebook(rng: &mut Random, size: usize, width: usize, handoff: bool) -> Json {
let checks = (0..width)
.map(|bit| {
object([
("key", Json::Str(format!("feature{bit:02}"))),
(
"question",
Json::Str(format!("What did check {bit} observe?")),
),
(
"cost",
Json::Num(if handoff {
1.0
} else {
(1 + rng.index(5)) as f64
}),
),
])
})
.collect();
let mut history: Vec<(u16, usize)> = Vec::new();
let mut examples = Vec::new();
for i in 0..size {
let (truth, action) = if handoff {
(
i as u16,
if i & 1 != 0 {
0
} else if i & 2 != 0 {
1
} else if i & 4 != 0 {
2
} else {
3
},
)
} else if i % 5 == 1 {
let (truth, prior_action) = history[rng.index(i)];
(truth, prior_action + usize::from(i % 3 == 0))
} else {
(rng.next() as u16, rng.index(12))
};
history.push((truth, action));
examples.push(object([
("ref", Json::Str(format!("row{i:03}"))),
("facts", facts(width, u16::MAX, truth)),
("action", Json::Str(format!("repair{action}"))),
]));
}
object([
("checks", Json::Arr(checks)),
("examples", Json::Arr(examples)),
])
}
fn compare_advice() -> usize {
let mut rng = Random(0x34210abc645a2f75);
let mut compared = 0;
for book in 0..192 {
let width = 1 + rng.index(16);
let size = 1 + rng.index(128);
let input = casebook(&mut rng, size, width, false);
let old = baseline::Casebook::parse(&input).unwrap();
let new = candidate::Casebook::parse(&input).unwrap();
for query in 0..64 {
let known = match query % 4 {
0 => 0,
1 => rng.next() as u16,
2 => u16::MAX,
_ => 1 << rng.index(width),
};
let observed = facts(width, known, rng.next() as u16);
assert_eq!(
old.advise(&observed).unwrap(),
new.advise(&observed).unwrap(),
"book {book}, {size} rows, {width} checks, {observed:?}"
);
compared += 1;
}
}
compared
}
fn measure(iterations: usize, mut advise: impl FnMut() -> Json) -> f64 {
let start = Instant::now();
for _ in 0..iterations {
black_box(advise());
}
start.elapsed().as_nanos() as f64 / iterations as f64
}
fn median(mut values: [f64; 12]) -> f64 {
values.sort_by(f64::total_cmp);
(values[5] + values[6]) / 2.0
}
fn benchmark(width: usize, size: usize, handoff: bool, known: u16, iterations: usize) {
let input = casebook(&mut Random(0x5ca1a2c091821443), size, width, handoff);
let old = baseline::Casebook::parse(&input).unwrap();
let new = candidate::Casebook::parse(&input).unwrap();
let observed = facts(width, known, 0);
let run_old = || measure(iterations, || old.advise(black_box(&observed)).unwrap());
let run_new = || measure(iterations, || new.advise(black_box(&observed)).unwrap());
let mut times = [(0.0, 0.0); 12];
black_box((run_old(), run_new()));
for (round, slot) in times.iter_mut().enumerate() {
*slot = if round % 2 == 0 {
let new_time = run_new();
(run_old(), new_time)
} else {
(run_old(), run_new())
};
}
let old_ns = median(times.map(|(o, _)| o));
let new_ns = median(times.map(|(_, n)| n));
let ratio = median(times.map(|(o, n)| o / n));
println!("{size} rows / {width} checks, mask {known:#x}: baseline {old_ns:.0} ns, candidate {new_ns:.0} ns, paired speedup {ratio:.3}x");
}
fn main() {
println!(
"Full advice matched on {} seeded decisions.",
compare_advice()
);
benchmark(3, 8, true, 0, 18_000);
benchmark(3, 8, true, 1, 18_000);
benchmark(16, 128, false, 0, 700);
benchmark(16, 128, false, 1, 1_200);
}