#![cfg(unix)]
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
fn bin() -> &'static str {
env!("CARGO_BIN_EXE_instinct")
}
fn run(store: &Path, args: &[&str], stdin: &str, env: &[(&str, &str)]) -> (i32, String) {
let mut c = Command::new(bin());
c.args(args)
.env("INSTINCT_STORE", store)
.env_remove("INSTINCT_EXPLORE")
.env_remove("INSTINCT_INDEX")
.env_remove("INSTINCT_PROJECT")
.env_remove("INSTINCT_W_WHEN")
.env_remove("INSTINCT_W_TITLE")
.env_remove("INSTINCT_W_BODY");
for (k, v) in env {
c.env(k, v);
}
let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes());
let out = child.wait_with_output().unwrap();
let mut text = String::from_utf8(out.stdout).unwrap();
if !out.status.success() {
text.push_str(&String::from_utf8_lossy(&out.stderr));
}
(out.status.code().unwrap(), text)
}
fn temp(name: &str, file: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("instinct-snapshot-{}-{}-{name}", std::process::id(), uniq()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir.join(file)
}
fn idx(store: &Path) -> PathBuf {
let mut s = store.as_os_str().to_owned();
s.push(".idx");
PathBuf::from(s)
}
fn bank(store: &Path, title: &str, when: &str, found: &str, how: &str, extra: &[&str]) -> String {
let mut a = vec!["bank", "--title", title, "--when", when, "--found", found, "--how", how, "--evidence", "seen twice"];
a.extend_from_slice(extra);
let (code, out) = run(store, &a, "", &[]);
assert_eq!(code, 0, "{out}");
out.split_whitespace().nth(1).unwrap().to_owned()
}
fn fixture(name: &str) -> (PathBuf, Vec<String>) {
let store = temp(name, "bank.hxdb");
let ids = vec![
bank(&store, "Pin the lockfile", "A release build resolves dependencies on CI", "Cargo picked a newer crate", "Pass --locked to every cargo build", &[]),
bank(&store, "Warm the registry", "The build host has no network access", "Cargo tried to refresh the index", "Fetch once then build with --offline", &[]),
bank(&store, "Thin LTO on small runners", "The linker is killed with signal 9 on a small runner", "Full LTO needed six gigabytes", "Use lto thin and sixteen codegen units", &[]),
bank(&store, "Replica restart order", "Restarting the postgres replica after a primary failover", "Replica started before the primary", "Restart the primary first and wait for it", &["--project", "payments"]),
bank(&store, "Image layer cache", "The image build reinstalls every dependency on each commit", "Copy order busted the layer cache", "Copy the lockfile before the sources", &[]),
];
for id in &ids[..3] {
assert_eq!(run(&store, &["hit", id], "", &[]).0, 0);
}
assert_eq!(run(&store, &["miss", &ids[4]], "", &[]).0, 0);
(store, ids)
}
const QUERIES: &[&str] = &[
"release build resolves dependencies on CI",
"linker killed with signal 9 on the runner",
"restart the postgres replica after failover",
"the image build reinstalls every dependency",
"no network access on the build host",
"something nobody ever banked about kubernetes ingress",
];
fn answers(store: &Path, q: &str, env: &[(&str, &str)]) -> Vec<(String, String)> {
let esc = q.replace('\\', "\\\\").replace('"', "\\\"");
let prompt = format!("{{\"prompt\":\"{esc}\"}}");
let guard = format!("{{\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{esc}\"}}}}");
let mut off = env.to_vec();
off.push(("INSTINCT_INDEX", "0"));
let mut v = Vec::new();
for (args, stdin) in [(vec!["recall", "--q", q, "--k", "3"], String::new()), (vec!["prompt"], prompt), (vec!["guard"], guard)] {
let (c1, warm) = run(store, &args, &stdin, env);
let (c2, cold) = run(store, &args, &stdin, &off);
assert_eq!((c1, c2), (0, 0), "{args:?} {q}");
v.push((warm, cold));
}
v
}
fn assert_same(store: &Path, env: &[(&str, &str)]) -> usize {
let mut nonempty = 0;
for q in QUERIES {
for (warm, cold) in answers(store, q, env) {
assert_eq!(warm, cold, "snapshot and cold path disagree for {q:?}");
if !warm.trim().is_empty() {
nonempty += 1;
}
}
}
nonempty
}
fn header_len(path: &Path) -> u64 {
let b = std::fs::read(path).unwrap();
assert_eq!(&b[..8], b"INSTIDX2");
let version = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
assert_eq!(&b[12..12 + version], env!("CARGO_PKG_VERSION").as_bytes(), "the snapshot names the engine that wrote it");
u64::from_le_bytes(b[12 + version..20 + version].try_into().unwrap())
}
#[test]
fn answers_are_byte_identical_with_and_without_the_snapshot() {
let (store, _) = fixture("same");
let n = assert_same(&store, &[]);
assert!(n > 6, "the comparison must cover real answers, not only empty ones: {n}");
assert_same(&store, &[("INSTINCT_PROJECT", "payments")]);
assert_same(&store, &[("INSTINCT_PROJECT", "elsewhere")]);
let meta = std::fs::metadata(idx(&store)).unwrap();
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the snapshot is private like the bank");
}
#[test]
fn every_write_invalidates_and_the_next_lookup_rebuilds() {
let (store, ids) = fixture("writes");
let q = "release build resolves dependencies on CI";
let lookup = |store: &Path| run(store, &["recall", "--q", q, "--k", "3"], "", &[]);
lookup(&store);
let mut last = std::fs::read(idx(&store)).unwrap();
let steps: Vec<(&str, Vec<&str>)> = vec![
("bank", vec!["bank", "--title", "New lesson", "--when", "a brand new release trigger", "--found", "x", "--how", "y", "--evidence", "z"]),
("hit", vec!["hit", &ids[0]]),
("miss", vec!["miss", &ids[1]]),
("review", vec!["review", &ids[2], "--state", "quarantined", "--reason", "test", "--source-ref", "test"]),
];
for (name, args) in steps {
let (code, out) = run(&store, &args, "", &[]);
assert_eq!(code, 0, "{name}: {out}");
let (_, warm) = lookup(&store);
let (_, cold) = run(&store, &["recall", "--q", q, "--k", "3"], "", &[("INSTINCT_INDEX", "0")]);
assert_eq!(warm, cold, "after {name}");
let now = std::fs::read(idx(&store)).unwrap();
assert_ne!(now, last, "after {name} the snapshot must be rebuilt");
assert_eq!(header_len(&idx(&store)), std::fs::metadata(&store).unwrap().len(), "after {name} the snapshot names the new bank");
last = now;
}
assert_same(&store, &[]);
}
#[test]
fn an_external_append_or_replacement_gives_the_cold_answer() {
let store = temp("external", "bank.jsonl");
let lesson = |id: &str, when: &str| {
format!("{{\"kind\":\"discovery\",\"id\":\"{id}\",\"ts\":1,\"title\":\"{id} title\",\"when\":\"{when}\",\"found\":\"found\",\"how\":\"fix\",\"evidence\":\"seen\",\"tags\":\"\",\"reconsider\":\"\",\"embedding\":[],\"source\":\"banked\",\"state\":\"candidate\",\"evidence_status\":\"unverified\"}}\n")
};
std::fs::write(&store, lesson("in-aaaa001", "deploy lock timeout on staging") + &lesson("in-aaaa002", "database migration hangs on large table")).unwrap();
let ask = |env: &[(&str, &str)]| run(&store, &["recall", "--q", "deploy lock timeout on staging", "--k", "3"], "", env).1;
assert!(ask(&[]).contains("in-aaaa001"));
assert!(idx(&store).exists());
let mut f = std::fs::OpenOptions::new().append(true).open(&store).unwrap();
f.write_all(lesson("in-aaaa003", "deploy lock timeout on staging again").as_bytes()).unwrap();
drop(f);
let (warm, cold) = (ask(&[]), ask(&[("INSTINCT_INDEX", "0")]));
assert_eq!(warm, cold);
assert_eq!(header_len(&idx(&store)), std::fs::metadata(&store).unwrap().len());
run(&store, &["recall", "--q", "database migration stuck on large table", "--k", "3"], "", &[]);
let before = std::fs::read(&store).unwrap();
let swapped = String::from_utf8(before.clone()).unwrap().replace("migration hangs", "migration stuck");
assert_ne!(swapped.as_bytes(), &before[..]);
assert_eq!(swapped.len(), before.len(), "the swap keeps the byte length, so only the hash can notice it");
std::fs::write(&store, swapped).unwrap();
let q = ["recall", "--q", "database migration stuck on large table", "--k", "3"];
let (warm, cold) = (run(&store, &q, "", &[]).1, run(&store, &q, "", &[("INSTINCT_INDEX", "0")]).1);
assert_eq!(warm, cold);
assert!(warm.contains("in-aaaa002") && warm.contains("stuck"), "the replaced file is what gets answered: {warm}");
}
#[test]
fn a_damaged_or_foreign_snapshot_is_ignored_and_rebuilt() {
let (store, _) = fixture("damage");
assert_same(&store, &[]);
let good = std::fs::read(idx(&store)).unwrap();
let (other, _) = fixture("damage-other");
run(&other, &["recall", "--q", "anything about the build"], "", &[]);
let foreign = std::fs::read(idx(&other)).unwrap();
let mut flipped = good.clone();
let mid = flipped.len() / 2;
flipped[mid] ^= 0x40;
let mut flipped_tail = good.clone();
let last = flipped_tail.len() - 1;
flipped_tail[last] ^= 1;
let damaged: Vec<(&str, Vec<u8>)> = vec![
("flipped byte", flipped),
("flipped checksum", flipped_tail),
("truncated", good[..good.len() / 3].to_vec()),
("empty", Vec::new()),
("garbage", b"not a snapshot at all".to_vec()),
("another bank's snapshot", foreign),
];
for (what, bytes) in damaged {
std::fs::write(idx(&store), &bytes).unwrap();
assert_same(&store, &[]);
assert_eq!(std::fs::read(idx(&store)).unwrap(), good, "{what}: the snapshot is rewritten from the bank");
}
}
#[test]
fn index_zero_neither_reads_nor_writes_the_snapshot() {
let (store, _) = fixture("off");
let off = [("INSTINCT_INDEX", "0")];
let _ = std::fs::remove_file(idx(&store));
run(&store, &["recall", "--q", "release build"], "", &off);
run(&store, &["stats"], "", &off);
assert!(!idx(&store).exists(), "disabled means nothing is written");
std::fs::write(idx(&store), b"planted").unwrap();
run(&store, &["recall", "--q", "release build"], "", &off);
assert_eq!(std::fs::read(idx(&store)).unwrap(), b"planted", "disabled means the file is left alone");
}
#[test]
fn the_lexical_weights_belong_to_the_key() {
let (store, _) = fixture("weights");
assert_same(&store, &[]);
let before = std::fs::read(idx(&store)).unwrap();
assert_same(&store, &[("INSTINCT_W_WHEN", "1"), ("INSTINCT_W_TITLE", "4")]);
assert_ne!(std::fs::read(idx(&store)).unwrap(), before, "a different weighting writes a different snapshot");
}
#[test]
fn nothing_but_the_snapshot_is_left_behind() {
let (store, _) = fixture("litter");
assert_same(&store, &[]);
let names: Vec<String> = std::fs::read_dir(store.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
assert!(names.iter().all(|n| !n.contains(".tmp")), "{names:?}");
assert!(names.iter().any(|n| n == "bank.hxdb.idx"), "{names:?}");
}
#[test]
fn the_rare_word_gate_and_synonyms_match_the_cold_path() {
let store = temp("gate", "bank.jsonl");
let mut text = String::new();
for i in 0..40 {
let (when, title, tags) = match i {
0 => ("a release page that needs the memory limit raised", "Raise the pod memory limit", "release page"),
1 => ("a release page with a stale cache header", "Purge the edge cache", "release page"),
2 => ("the ram on a worker runs out during a release", "Add swap on workers", "worker ram"),
3 => ("the test suite hangs on the ci runner", "Fix the hanging suite", "suite hang"),
_ => ("the release page build number is wrong on a branch", "Rebuild the release page", "release page build"),
};
text.push_str(&format!("{{\"kind\":\"discovery\",\"id\":\"in-gate{i:03}\",\"ts\":1,\"title\":\"{title} {i}\",\"when\":\"{when} {i}\",\"found\":\"found {i}\",\"how\":\"how {i}\",\"evidence\":\"seen\",\"tags\":\"{tags}\",\"reconsider\":\"\",\"embedding\":[],\"source\":\"banked\",\"state\":\"candidate\",\"evidence_status\":\"unverified\"}}\n"));
}
std::fs::write(&store, text).unwrap();
for q in ["release page", "the release page is wrong", "release page memory limit", "worker memory runs out in a release", "stale cache header on the release page", "pod ram limit", "test suite", "the spec suite is slow", "test suite hangs on the runner"] {
for env in [vec![], vec![("INSTINCT_RARE", "0")], vec![("INSTINCT_CONCEPTS", "0")], vec![("INSTINCT_RARE", "0"), ("INSTINCT_CONCEPTS", "0")]] {
let esc = format!("{{\"prompt\":\"{q}\"}}");
let mut off = env.clone();
off.push(("INSTINCT_INDEX", "0"));
let warm = run(&store, &["prompt"], &esc, &env).1;
let cold = run(&store, &["prompt"], &esc, &off).1;
assert_eq!(warm, cold, "{q} {env:?}");
let warm = run(&store, &["recall", "--q", q, "--k", "3"], "", &env).1;
let cold = run(&store, &["recall", "--q", q, "--k", "3"], "", &off).1;
assert_eq!(warm, cold, "{q} {env:?}");
}
}
assert!(idx(&store).exists());
}
fn uniq() -> usize {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}