# Verified index snapshot <store>.idx [GAMMA-Codon/S]. A hook that fires on every prompt must not re-read, re-verify and re-tokenize the whole bank.
# Key: the bank's byte length, a 128-bit hash of all its bytes, the lexical field weights, the synonym switch and the engine version. Any mismatch, short read, bad checksum or
# out-of-range offset means the snapshot is ignored and the cold path runs and rewrites it. Written 0600 through a temp file and a rename.
# Contents: every lesson as load() leaves it (scope fields included, scoping stays at use time), then BM25 lengths and postings per term.
AAC # use std::{collections::{BTreeMap, HashMap}, fs, io::{Read, Write}, path::{Path, PathBuf}}
AAC # use super::{Discovery, eligibility::Meta, rehearsal::StandingInstruction}
AAA # pub(super) fn enabled() -> bool
TAC # std::env::var("INSTINCT_INDEX").map_or(true, |v| v != "0")
TTT # end
# Fast non-cryptographic hash: four 64-bit lanes over 32-byte blocks, 128 bits out. It detects change and damage, not an adversary who can also write the store.
AAA # fn feed(h: &mut [u64; 4], blocks: &[u8])
AGA # for c in blocks.chunks_exact(32)
AGA # for j in 0..4
AAC # let w = u64::from_le_bytes([c[j * 8], c[j * 8 + 1], c[j * 8 + 2], c[j * 8 + 3], c[j * 8 + 4], c[j * 8 + 5], c[j * 8 + 6], c[j * 8 + 7]])
AAC # h[j] = (h[j].rotate_left(5) ^ w).wrapping_mul(0x517CC1B727220A95)
TTT # end
TTT # end
TTT # end
AAA # fn seed() -> [u64; 4]
TAC # [0x9E3779B97F4A7C15, 0xC2B2AE3D27D4EB4F, 0x165667B19E3779F9, 0x27D4EB2F165667C5]
TTT # end
AAA # fn finish(mut h: [u64; 4], tail: &[u8], total: u64) -> (u64, u64)
AAC # let mut block = [0u8; 32]
AAC # block[..tail.len()].copy_from_slice(tail)
AAC # feed(&mut h, &block)
AAC # h[0] ^= total
AAC # let mut a = (h[0] ^ h[1].rotate_left(17)).wrapping_mul(0xFF51AFD7ED558CCD)
AAC # let mut b = (h[2] ^ h[3].rotate_left(23)).wrapping_mul(0xC4CEB9FE1A85EC53)
AAC # a ^= a >> 32
AAC # b ^= b >> 29
TAC # (a, b)
TTT # end
AAA # fn mix(bytes: &[u8]) -> (u64, u64)
AAC # let mut h = seed()
AAC # let whole = bytes.len() - bytes.len() % 32
AAC # feed(&mut h, &bytes[..whole])
TAC # finish(h, &bytes[whole..], bytes.len() as u64)
TTT # end
TAG # #[derive(Clone, Copy, PartialEq, Eq, Debug)]
GCA # pub(super) struct Key
GCC # len: u64
GCC # a: u64
GCC # b: u64
GCC # weights: [u8; 4]
TTT # end
AAA # pub(super) fn key(path: &Path) -> Option<Key>
CAA # if !enabled()
TAC # return None
TTT # end
AAC # let mut file = fs::File::open(path).ok()?
AAC # let mut buf = vec![0u8; 65536]
AAC # let mut h = seed()
AAC # let mut total = 0u64
AAC # let mut tail: Vec<u8> = Vec::new()
AGA # for _ in 0..u64::MAX
AAC # let mut got = 0usize
AGA # for _ in 0..buf.len()
CAA # if got == buf.len()
TAC # break
TTT # end
AAC # let n = file.read(&mut buf[got..]).ok()?
CAA # if n == 0
TAC # break
TTT # end
AAC # got += n
TTT # end
AAC # let whole = got - got % 32
AAC # feed(&mut h, &buf[..whole])
AAC # total += got as u64
CAA # if got < buf.len()
AAC # tail = buf[whole..got].to_vec()
TAC # break
TTT # end
TTT # end
AAC # let (a, b) = finish(h, &tail, total)
AAC # let (w, t, body) = super::lex_weights()
TAC # Some(Key { len: total, a, b, weights: [w as u8, t as u8, body as u8, super::concepts::enabled() as u8] })
TTT # end
AAA # fn idx_path(path: &Path) -> PathBuf
AAC # let mut s = path.as_os_str().to_owned()
AAC # s.push(".idx")
TAC # PathBuf::from(s)
TTT # end
AAA # fn put_u32(o: &mut Vec<u8>, v: u32)
TAC # o.extend_from_slice(&v.to_le_bytes())
TTT # end
AAA # fn put_u64(o: &mut Vec<u8>, v: u64)
TAC # o.extend_from_slice(&v.to_le_bytes())
TTT # end
AAA # fn put_str(o: &mut Vec<u8>, s: &str)
AAC # put_u32(o, s.len() as u32)
TAC # o.extend_from_slice(s.as_bytes())
TTT # end
AAA # fn header(key: &Key) -> Vec<u8>
AAC # let mut o = b"INSTIDX2".to_vec()
AAC # put_str(&mut o, env!("CARGO_PKG_VERSION"))
AAC # put_u64(&mut o, key.len)
AAC # put_u64(&mut o, key.a)
AAC # put_u64(&mut o, key.b)
AAC # o.extend_from_slice(&key.weights)
TAC # o
TTT # end
AAA # fn put_entry(o: &mut Vec<u8>, d: &Discovery)
AAC # let at = o.len()
AAC # put_u32(o, 0)
AGA # for s in [&d.meta.source, &d.meta.state, &d.meta.evidence_status, &d.meta.project, &d.meta.persona, &d.meta.harness, &d.meta.version, &d.meta.machine]
AAC # put_str(o, s)
TTT # end
AAC # put_u64(o, d.meta.valid_until)
AGA # for s in [&d.id, &d.title, &d.when, &d.found, &d.how, &d.evidence, &d.reconsider, &d.tags]
AAC # put_str(o, s)
TTT # end
AAC # put_u64(o, d.ts)
AAC # put_u32(o, d.hits)
AAC # put_u32(o, d.misses)
AAC # put_u32(o, d.embedding.len() as u32)
AGA # for f in &d.embedding
AAC # put_u32(o, f.to_bits())
TTT # end
CAA # if let Some(s) = &d.standing
AAC # o.push(1)
AAC # put_str(o, &s.text)
AAC # put_str(o, &s.reference)
CAC # else
AAC # o.push(0)
TTT # end
AAC # let len = (o.len() - at - 4) as u32
AAC # o[at..at + 4].copy_from_slice(&len.to_le_bytes())
TTT # end
# Entries as load() returned them, then per-lesson token counts, then the sorted vocabulary with its postings (lesson, term frequency).
AAA # fn encode(key: &Key, all: &[Discovery]) -> Vec<u8>
AAC # let mut o = header(key)
AAC # put_u32(&mut o, all.len() as u32)
AGA # for d in all
AAC # put_entry(&mut o, d)
TTT # end
AAC # let mut lens: Vec<u32> = Vec::with_capacity(all.len())
AAC # let mut vocab: BTreeMap<String, Vec<(u32, u32)>> = BTreeMap::new()
AGA # for (i, d) in all.iter().enumerate()
AAC # let words = super::tokens(&d.lex_text())
AAC # lens.push(words.len() as u32)
AAC # let mut counts: HashMap<String, u32> = HashMap::new()
AGA # for w in words
AAC # *counts.entry(w).or_insert(0) += 1
TTT # end
AGA # for (w, tf) in counts
AAC # vocab.entry(w).or_default().push((i as u32, tf))
TTT # end
TTT # end
AGA # for l in &lens
AAC # put_u32(&mut o, *l)
TTT # end
AAC # let mut blob: Vec<u8> = Vec::new()
AAC # let mut voff: Vec<u32> = vec![0]
AAC # let mut poff: Vec<u32> = vec![0]
AAC # let mut pdoc: Vec<u32> = Vec::new()
AAC # let mut ptf: Vec<u32> = Vec::new()
AGA # for (w, list) in &vocab
AAC # blob.extend_from_slice(w.as_bytes())
AAC # voff.push(blob.len() as u32)
AGA # for &(doc, tf) in list
AAC # pdoc.push(doc)
AAC # ptf.push(tf)
TTT # end
AAC # poff.push(pdoc.len() as u32)
TTT # end
AAC # put_u32(&mut o, vocab.len() as u32)
AGA # for v in &voff
AAC # put_u32(&mut o, *v)
TTT # end
AAC # o.extend_from_slice(&blob)
AGA # for v in poff.iter().chain(pdoc.iter()).chain(ptf.iter())
AAC # put_u32(&mut o, *v)
TTT # end
AAC # let mut per: Vec<Vec<String>> = Vec::with_capacity(all.len())
AAC # let mut avocab: BTreeMap<String, u32> = BTreeMap::new()
AGA # for d in all
AAC # let mut seen = super::anchors(&d.when)
AAC # seen.extend(super::anchors(&d.title))
AGA # for t in d.tags.split(';')
AAC # seen.extend(super::anchors(t))
TTT # end
AAC # let mut v: Vec<String> = seen.into_iter().collect()
AAC # v.sort()
AGA # for a in &v
AAC # avocab.entry(a.clone()).or_insert(0)
TTT # end
AAC # per.push(v)
TTT # end
AAC # let idmap: HashMap<&str, u32> = avocab.keys().enumerate().map(|(i, s)| (s.as_str(), i as u32)).collect()
AAC # put_u32(&mut o, avocab.len() as u32)
AAC # let mut ablob: Vec<u8> = Vec::new()
AAC # let mut aoff: Vec<u32> = vec![0]
AGA # for s in avocab.keys()
AAC # ablob.extend_from_slice(s.as_bytes())
AAC # aoff.push(ablob.len() as u32)
TTT # end
AGA # for v in &aoff
AAC # put_u32(&mut o, *v)
TTT # end
AAC # o.extend_from_slice(&ablob)
AAC # let mut aloff: Vec<u32> = vec![0]
AAC # let mut aids: Vec<u32> = Vec::new()
AGA # for v in &per
AGA # for a in v
AAC # aids.push(idmap[a.as_str()])
TTT # end
AAC # aloff.push(aids.len() as u32)
TTT # end
AGA # for v in aloff.iter().chain(aids.iter())
AAC # put_u32(&mut o, *v)
TTT # end
AAC # let (a, b) = mix(&o)
AAC # put_u64(&mut o, a)
AAC # put_u64(&mut o, b)
TAC # o
TTT # end
# The body length when the checksum holds and the header names this key; None otherwise.
AAA # fn check(buf: &[u8], key: &Key) -> Option<usize>
AAC # let n = buf.len().checked_sub(16)?
AAC # let (a, b) = mix(&buf[..n])
CAA # if buf[n..n + 8] != a.to_le_bytes() || buf[n + 8..] != b.to_le_bytes()
TAC # return None
TTT # end
AAC # let h = header(key)
CAA # if buf.get(..h.len()) != Some(&h[..])
TAC # return None
TTT # end
TAC # Some(n)
TTT # end
# Write only when no valid snapshot for this bank exists. A bank that moved while it was being read is not pinned.
AAA # pub(super) fn store(path: &Path, key: &Key, all: &[Discovery])
CAA # if !enabled()
TAC # return
TTT # end
AAC # let target = idx_path(path)
CAA # if fs::read(&target).ok().is_some_and(|b| check(&b, key).is_some())
TAC # return
TTT # end
CAA # if key_now(path) != Some(*key)
TAC # return
TTT # end
AAC # let bytes = encode(key, all)
AAC # let mut tmp = target.as_os_str().to_owned()
AAC # tmp.push(format!(".tmp{}", std::process::id()))
AAC # let tmp = PathBuf::from(tmp)
AAC # let ok = super::journal::private_options().create(true).truncate(true).write(true).open(&tmp).and_then(|mut f| f.write_all(&bytes)).and_then(|_| fs::rename(&tmp, &target)).is_ok()
CAA # if !ok
AAC # let _ = fs::remove_file(&tmp)
TTT # end
TTT # end
AAA # fn key_now(path: &Path) -> Option<Key>
TAC # key(path)
TTT # end
TAC # struct Rd<'a> { b: &'a [u8], o: usize }
AAA # fn take<'a>(r: &mut Rd<'a>, n: usize) -> Option<&'a [u8]>
AAC # let e = r.o.checked_add(n)?
AAC # let s = r.b.get(r.o..e)?
AAC # r.o = e
TAC # Some(s)
TTT # end
AAA # fn r_u32(r: &mut Rd) -> Option<u32>
AAC # let s = take(r, 4)?
TAC # Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
TTT # end
AAA # fn r_u64(r: &mut Rd) -> Option<u64>
AAC # let s = take(r, 8)?
TAC # Some(u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
TTT # end
AAA # fn r_str(r: &mut Rd) -> Option<String>
AAC # let n = r_u32(r)? as usize
TAC # String::from_utf8(take(r, n)?.to_vec()).ok()
TTT # end
AAA # fn r_meta(r: &mut Rd) -> Option<Meta>
AAC # let source = r_str(r)?
AAC # let state = r_str(r)?
AAC # let evidence_status = r_str(r)?
AAC # let project = r_str(r)?
AAC # let persona = r_str(r)?
AAC # let harness = r_str(r)?
AAC # let version = r_str(r)?
AAC # let machine = r_str(r)?
AAC # let valid_until = r_u64(r)?
TAC # Some(Meta { source, state, evidence_status, project, persona, harness, version, machine, valid_until })
TTT # end
AAA # fn r_rest(r: &mut Rd, meta: Meta) -> Option<Discovery>
AAC # let id = r_str(r)?
AAC # let title = r_str(r)?
AAC # let when = r_str(r)?
AAC # let found = r_str(r)?
AAC # let how = r_str(r)?
AAC # let evidence = r_str(r)?
AAC # let reconsider = r_str(r)?
AAC # let tags = r_str(r)?
AAC # let ts = r_u64(r)?
AAC # let hits = r_u32(r)?
AAC # let misses = r_u32(r)?
AAC # let dims = r_u32(r)? as usize
AAC # let raw = take(r, dims.checked_mul(4)?)?
AAC # let embedding: Vec<f32> = raw.chunks_exact(4).map(|c| f32::from_bits(u32::from_le_bytes([c[0], c[1], c[2], c[3]]))).collect()
AAC # let standing = if take(r, 1)?[0] == 1 { Some(StandingInstruction { text: r_str(r)?, reference: r_str(r)? }) } else { None }
TAC # Some(Discovery { id, ts, title, when, found, how, evidence, reconsider, tags, embedding, hits, misses, outcomes: HashMap::new(), standing, meta })
TTT # end
# The read side keeps the snapshot bytes and reads lengths, vocabulary and postings in place; only lessons are decoded.
TAC # pub(super) struct Index { buf: Vec<u8>, lens: usize, vn: usize, voff: usize, vblob: usize, poff: usize, pdoc: usize, ptf: usize, avn: usize, aoff: usize, ablob: usize, aloff: usize, aids: usize }
AAA # fn word(buf: &[u8], at: usize) -> usize
TAC # u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) as usize
TTT # end
# `scope` and `now` keep a lesson exactly when load_scoped would: the lessons come back in bank order with `pos` mapping each snapshot lesson to its scoped position (u32::MAX when left out).
AAA # pub(super) fn open(path: &Path, key: &Key, scope: &super::eligibility::Scope, now: u64) -> Option<(Vec<Discovery>, Vec<u32>, Index)>
CAA # if !enabled()
TAC # return None
TTT # end
AAC # let buf = fs::read(idx_path(path)).ok()?
AAC # let end = check(&buf, key)?
AAC # let mut r = Rd { b: &buf[..end], o: header(key).len() }
AAC # let n = r_u32(&mut r)? as usize
CAA # if n > end / 64
TAC # return None
TTT # end
AAC # let mut all = Vec::with_capacity(n)
AAC # let mut pos = Vec::with_capacity(n)
AGA # for _ in 0..n
AAC # let len = r_u32(&mut r)? as usize
AAC # let stop = r.o.checked_add(len)?
CAA # if stop > end
TAC # return None
TTT # end
AAC # let meta = r_meta(&mut r)?
CAA # if super::eligibility::scope_check(&meta, scope, now).is_ok()
AAC # pos.push(all.len() as u32)
AAC # all.push(r_rest(&mut r, meta)?)
CAC # else
AAC # pos.push(u32::MAX)
AAC # r.o = stop
TTT # end
CAA # if r.o != stop
TAC # return None
TTT # end
TTT # end
AAC # let lens = r.o
AAC # take(&mut r, n.checked_mul(4)?)?
AAC # let vn = r_u32(&mut r)? as usize
AAC # let voff = r.o
AAC # take(&mut r, vn.checked_add(1)?.checked_mul(4)?)?
AAC # let blob = word(&buf, voff + vn * 4)
AAC # let vblob = r.o
AAC # take(&mut r, blob)?
AAC # let poff = r.o
AAC # take(&mut r, vn.checked_add(1)?.checked_mul(4)?)?
AAC # let total = word(&buf, poff + vn * 4)
AAC # let pdoc = r.o
AAC # take(&mut r, total.checked_mul(4)?)?
AAC # let ptf = r.o
AAC # take(&mut r, total.checked_mul(4)?)?
AAC # let avn = r_u32(&mut r)? as usize
AAC # let aoff = r.o
AAC # take(&mut r, avn.checked_add(1)?.checked_mul(4)?)?
AAC # let ablob_len = word(&buf, aoff + avn * 4)
AAC # let ablob = r.o
AAC # take(&mut r, ablob_len)?
AAC # let aloff = r.o
AAC # take(&mut r, n.checked_add(1)?.checked_mul(4)?)?
AAC # let atotal = word(&buf, aloff + n * 4)
AAC # let aids = r.o
AAC # take(&mut r, atotal.checked_mul(4)?)?
CAA # if r.o != end
TAC # return None
TTT # end
AGA # for i in 0..vn
CAA # if word(&buf, voff + i * 4) > word(&buf, voff + i * 4 + 4) || word(&buf, voff + i * 4 + 4) > blob || word(&buf, poff + i * 4) > word(&buf, poff + i * 4 + 4) || word(&buf, poff + i * 4 + 4) > total
TAC # return None
TTT # end
TTT # end
AGA # for i in 0..total
CAA # if word(&buf, pdoc + i * 4) >= n
TAC # return None
TTT # end
TTT # end
AGA # for i in 0..avn
CAA # if word(&buf, aoff + i * 4) > word(&buf, aoff + i * 4 + 4) || word(&buf, aoff + i * 4 + 4) > ablob_len
TAC # return None
TTT # end
TTT # end
AGA # for i in 0..n
CAA # if word(&buf, aloff + i * 4) > word(&buf, aloff + i * 4 + 4) || word(&buf, aloff + i * 4 + 4) > atotal
TAC # return None
TTT # end
TTT # end
AGA # for i in 0..atotal
CAA # if word(&buf, aids + i * 4) >= avn
TAC # return None
TTT # end
TTT # end
TAC # Some((all, pos, Index { buf, lens, vn, voff, vblob, poff, pdoc, ptf, avn, aoff, ablob, aloff, aids }))
TTT # end
# Okapi BM25 (k1 1.2, b 0.75) over the lessons in scope, in the same term and summation order as bm25() so the floats match bit for bit.
# `pos[i]` is the scoped position of snapshot lesson i, or u32::MAX when scope or expiry left it out.
AAA # pub(super) fn scores(ix: &Index, pos: &[u32], count: usize, query: &str) -> Vec<f32>
AAC # let mut terms = super::tokens(query)
AAC # terms.sort()
AAC # terms.dedup()
CAA # if terms.is_empty() || count == 0
TAC # return vec![0.0; count]
TTT # end
AAC # let b = &ix.buf
AAC # let mut total_length = 0usize
AGA # for i in 0..pos.len()
CAA # if pos[i] != u32::MAX
AAC # total_length += word(b, ix.lens + i * 4)
TTT # end
TTT # end
AAC # let n = count as f32
AAC # let avgdl = (total_length as f32 / n).max(1.0)
AAC # let mut out = vec![0.0f32; count]
AGA # for term in &terms
AAC # let (mut lo, mut hi) = (0usize, ix.vn)
AGA # for _ in 0..40
CAA # if lo >= hi
TAC # break
TTT # end
AAC # let mid = (lo + hi) / 2
AAC # let word_at = &b[ix.vblob + word(b, ix.voff + mid * 4)..ix.vblob + word(b, ix.voff + mid * 4 + 4)]
CAA # if word_at < term.as_bytes()
AAC # lo = mid + 1
CAC # else
AAC # hi = mid
TTT # end
TTT # end
CAA # if lo >= ix.vn || &b[ix.vblob + word(b, ix.voff + lo * 4)..ix.vblob + word(b, ix.voff + lo * 4 + 4)] != term.as_bytes()
TAC # continue
TTT # end
AAC # let (from, to) = (word(b, ix.poff + lo * 4), word(b, ix.poff + lo * 4 + 4))
AAC # let df = (from..to).filter(|&j| pos[word(b, ix.pdoc + j * 4)] != u32::MAX).count() as f32
AAC # let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln()
AGA # for j in from..to
AAC # let doc = word(b, ix.pdoc + j * 4)
CAA # if pos[doc] != u32::MAX
AAC # let tf = word(b, ix.ptf + j * 4) as f32
AAC # let length = word(b, ix.lens + doc * 4) as f32
AAC # out[pos[doc] as usize] += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / avgdl))
TTT # end
TTT # end
TTT # end
TAC # out
TTT # end
# Anchors in more than a tenth of the in-scope lessons' trigger texts (when, title, tags): what common_anchors() counts, without re-tokenizing the bank.
AAA # pub(super) fn common_anchors(ix: &Index, pos: &[u32], count: usize) -> std::collections::HashSet<String>
AAC # let b = &ix.buf
AAC # let mut df = vec![0usize; ix.avn]
AGA # for doc in 0..pos.len()
CAA # if pos[doc] != u32::MAX
AGA # for j in word(b, ix.aloff + doc * 4)..word(b, ix.aloff + doc * 4 + 4)
AAC # df[word(b, ix.aids + j * 4)] += 1
TTT # end
TTT # end
TTT # end
AAC # let mut out = std::collections::HashSet::new()
AGA # for (i, c) in df.iter().enumerate()
CAA # if c * 10 > count
AAC # out.insert(String::from_utf8_lossy(&b[ix.ablob + word(b, ix.aoff + i * 4)..ix.ablob + word(b, ix.aoff + i * 4 + 4)]).into_owned())
TTT # end
TTT # end
TAC # out
TTT # end
# Previously consolidated entries can differ even when the file, weights and crate version all match.
TAC # #[test]
AAA # fn legacy_snapshot_with_a_valid_checksum_is_rejected()
AAC # let key = Key { len: 0, a: 10, b: 20, weights: [1, 2, 1, 1] }
AAC # let current = encode(&key, &[])
AAC # let n = check(¤t, &key).expect("current snapshot is valid")
AAC # let mut previous = current[..n].to_vec()
AAC # previous[..8].copy_from_slice(b"INSTIDX1")
AAC # let (a, b) = mix(&previous)
AAC # put_u64(&mut previous, a)
AAC # put_u64(&mut previous, b)
AAC # assert_eq!(check(&previous, &key), None)
TTT # end