#[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
}
use std::{
env,
fs::{self, File},
io::{self, BufRead, BufReader, BufWriter, Write},
path::Path,
process::{Command, Stdio},
time::{Instant, SystemTime, UNIX_EPOCH},
};
fn resident(engine: &Path, store: &Path, count: usize, format: &str) -> io::Result<()> {
let mut cmd = Command::new(engine);
for (key, _) in env::vars_os().filter(|(k, _)| k.to_string_lossy().starts_with("INSTINCT_")) {
cmd.env_remove(key);
}
let mut child = cmd
.arg("mcp")
.env("INSTINCT_STORE", store)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let mut input = child.stdin.take().unwrap();
let mut output = BufReader::new(child.stdout.take().unwrap());
let mut samples = Vec::new();
for trial in 0..33 {
let id = 1 + (trial * 271) % (count - 1);
let message = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"instinct_recall","arguments":{"project":"studio","q":"groupKEY itemKEY","k":1}}}"#.replace("KEY",&id.to_string());
let now = Instant::now();
writeln!(input, "{message}")?;
input.flush()?;
let mut reply = String::new();
output.read_line(&mut reply)?;
let elapsed = now.elapsed().as_secs_f64() * 1000.0;
if !reply.contains(&format!("[fixture-{id}]")) || !reply.contains(r#""isError":false"#) {
return Err(io::Error::other("resident MCP returned the wrong fixture"));
}
if trial >= 2 {
samples.push(elapsed);
}
}
drop(input);
if !child.wait()?.success() {
return Err(io::Error::other("MCP failed"));
}
samples.sort_by(f64::total_cmp);
println!(
"resident-mcp,{format},{count},{},{:.2},{:.2}",
store.metadata()?.len(),
samples[15],
samples[29]
);
Ok(())
}
fn write_cached_vectors(path: &Path, count: usize) -> io::Result<()> {
let mut sidecar = BufWriter::new(File::create(path.with_extension("hxdb.when.bin"))?);
let vector = 0.25f32.to_le_bytes().repeat(768);
for i in 0..count {
let id = format!("fixture-{i}");
sidecar.write_all(&(id.len() as u16).to_le_bytes())?;
sidecar.write_all(id.as_bytes())?;
sidecar.write_all(&768u16.to_le_bytes())?;
sidecar.write_all(&vector)?;
}
sidecar.flush()
}
fn measure(engine: &Path, store: &Path, count: usize, offline_vectors: bool) -> io::Result<()> {
let mut writer = BufWriter::new(File::create(store)?);
for i in 0..count {
let cue = if i == 0 {
"approved headline".to_owned()
} else {
format!("delivery packing group{i} item{i}")
};
writeln!(
writer,
r#"{{"kind":"discovery","id":"fixture-{i}","title":"Task {i}","when":"{cue}","found":"The requested edit worked","how":"Use the accepted revision","evidence":"Checked the output","source":"banked","state":"candidate","scope_project":"studio"}}"#
)?;
}
writer.flush()?;
drop(writer);
let native = store.with_extension("hxdb");
let migration = Command::new(engine)
.arg("migrate")
.arg("--store")
.arg(store)
.arg("--to")
.arg(&native)
.output()?;
if !migration.status.success() {
return Err(io::Error::other(
String::from_utf8_lossy(&migration.stderr).to_string(),
));
}
let paths = [store, native.as_path()];
if offline_vectors {
resident(engine, &native, count, "helix-db-no-sidecar")?;
write_cached_vectors(&native, count)?;
return resident(engine, &native, count, "helix-db-with-sidecar");
}
let mut samples = [Vec::new(), Vec::new()];
for trial in 0..33 {
for step in 0..2 {
let arm = (trial + step) % 2;
let mut cmd = Command::new(engine);
for (key, _) in
env::vars_os().filter(|(k, _)| k.to_string_lossy().starts_with("INSTINCT_"))
{
cmd.env_remove(key);
}
cmd.env("INSTINCT_STORE", paths[arm]).args([
"decide",
"--project",
"studio",
"--q",
"Keep the approved headline",
]);
let start = Instant::now();
let output = cmd.output()?;
let elapsed = start.elapsed().as_secs_f64() * 1000.0;
let reply = String::from_utf8_lossy(&output.stdout);
if !output.status.success()
|| !reply.contains(r#""id":"fixture-0""#)
|| reply.matches(r#""id":"#).count() != 1
{
return Err(io::Error::other("unexpected fixture result"));
}
if trial >= 2 {
samples[arm].push(elapsed);
}
}
}
for (arm, times) in samples.iter_mut().enumerate() {
times.sort_by(f64::total_cmp);
println!(
"cold-cli,{},{},{},{:.2},{:.2}",
["jsonl", "helix-db"][arm],
count,
paths[arm].metadata()?.len(),
times[15],
times[29]
);
resident(engine, paths[arm], count, ["jsonl", "helix-db"][arm])?;
}
Ok(())
}
fn main() -> io::Result<()> {
let offline_vectors = match env::args_os().nth(2) {
None => false,
Some(arg) if arg == "--offline-vectors" => true,
_ => return Err(io::Error::other("expected optional --offline-vectors")),
};
let engine = env::args_os()
.nth(1)
.ok_or_else(|| io::Error::other("supply the path to the release instinct executable"))?;
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let scratch = env::temp_dir().join(format!("instinct-storage-{}-{stamp}", std::process::id()));
fs::create_dir(&scratch)?;
println!("mode,format,lessons,bytes,p50_ms,p95_ms");
let result = [100, 1000, 10000].into_iter().try_for_each(|n| {
measure(
Path::new(&engine),
&scratch.join(format!("bank-{n}.jsonl")),
n,
offline_vectors,
)
});
fs::remove_dir_all(&scratch)?;
result
}