use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use fathomdb_embedder_api::{Embedder, EmbedderError, EmbedderIdentity, Vector};
use fathomdb_engine::{Engine, EngineError};
use tempfile::TempDir;
const DIM: usize = 384;
const PROBE_IDENTITY_NAME: &str = "fathomdb-probe-test";
const PROBE_IDENTITY_REV: &str = "veq-tc68";
const BGE_NAME: &str = "fathomdb-bge-small-en-v1.5";
const BGE_REV: &str = "veq-tc68-mc";
const PROBE_COUNT: u64 = 45;
const VEQ_VERDICT_CACHE_KEY: &str = "vector_equivalence_verified_fingerprint";
fn reference_vector(text: &str) -> Vec<f32> {
let mut out = Vec::with_capacity(DIM);
for i in 0..DIM {
let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ (i as u64).wrapping_mul(0x0100_0000_01b3);
for b in text.bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
let frac = (h % 1000) as f32 / 1000.0;
out.push(0.5 + frac);
}
out
}
#[derive(Debug)]
struct CountingRefEmbedder {
calls: Arc<AtomicU64>,
}
impl Embedder for CountingRefEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(reference_vector(text))
}
}
#[derive(Debug)]
struct CountingDivergentEmbedder {
calls: Arc<AtomicU64>,
}
impl Embedder for CountingDivergentEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(reference_vector(text).into_iter().map(|x| -x).collect())
}
}
#[derive(Debug)]
struct CountingBgeRefEmbedder {
calls: Arc<AtomicU64>,
}
impl Embedder for CountingBgeRefEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(BGE_NAME, BGE_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(reference_vector(text))
}
}
fn db_path(dir: &TempDir) -> std::path::PathBuf {
dir.path().join("tc68.sqlite")
}
fn counter() -> Arc<AtomicU64> {
Arc::new(AtomicU64::new(0))
}
fn mean_blob(value: f32) -> Vec<u8> {
let mut blob = Vec::with_capacity(DIM * 4);
for _ in 0..DIM {
blob.extend_from_slice(&value.to_le_bytes());
}
blob
}
fn set_pinned_mean(path: &std::path::Path, mean: Vec<u8>) {
let conn = rusqlite::Connection::open(path).unwrap();
conn.execute(
"UPDATE _fathomdb_embedder_profiles SET mean_vec = ?1 WHERE profile = 'default'",
rusqlite::params![mean],
)
.expect("pin mean_vec");
}
fn encode_vector_blob(vector: &[f32]) -> Vec<u8> {
vector.iter().flat_map(|x| x.to_le_bytes()).collect()
}
fn read_verdict_marker(path: &std::path::Path) -> Option<String> {
let conn = rusqlite::Connection::open(path).unwrap();
conn.query_row(
"SELECT value FROM _fathomdb_open_state WHERE key = ?1",
[VEQ_VERDICT_CACHE_KEY],
|row| row.get::<_, String>(0),
)
.ok()
}
fn install_verdict_marker(path: &std::path::Path, value: &str) {
let conn = rusqlite::Connection::open(path).unwrap();
conn.execute(
"INSERT INTO _fathomdb_open_state(key, value) VALUES(?1, ?2)
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
rusqlite::params![VEQ_VERDICT_CACHE_KEY, value],
)
.expect("install the verdict marker");
}
fn clear_verdict_marker(path: &std::path::Path) {
let conn = rusqlite::Connection::open(path).unwrap();
conn.execute("DELETE FROM _fathomdb_open_state WHERE key = ?1", [VEQ_VERDICT_CACHE_KEY])
.expect("clear the verdict marker");
}
fn forge_stored_baseline(path: &std::path::Path, f: impl Fn(&str) -> Vec<f32>) {
let conn = rusqlite::Connection::open(path).unwrap();
let rows: Vec<(i64, String, usize)> = {
let mut stmt = conn
.prepare(
"SELECT probe_ordinal, probe_text, length(reference_vec) \
FROM _fathomdb_embed_probe ORDER BY probe_ordinal",
)
.unwrap();
let rows = stmt
.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get::<_, i64>(2)? as usize)))
.unwrap()
.collect::<rusqlite::Result<Vec<_>>>()
.unwrap();
rows
};
assert_eq!(rows.len() as u64, PROBE_COUNT, "the baseline must be the full committed set");
for (ordinal, text, blob_len) in rows {
let blob = encode_vector_blob(&f(&text));
assert_eq!(blob.len(), blob_len, "the forgery must preserve the blob length");
conn.execute(
"UPDATE _fathomdb_embed_probe SET reference_vec = ?1 WHERE probe_ordinal = ?2",
rusqlite::params![blob, ordinal],
)
.expect("forge one reference row");
}
}
fn open_count_close(
path: &std::path::Path,
embedder: Arc<dyn Embedder>,
calls: &Arc<AtomicU64>,
) -> (u64, bool) {
let before = calls.load(Ordering::SeqCst);
let opened = Engine::open_with_embedder_for_test(path, embedder).expect("open must succeed");
let embeds = calls.load(Ordering::SeqCst) - before;
let dense_disabled = opened.report.dense_disabled;
opened.engine.close().expect("close");
(embeds, dense_disabled)
}
fn enrol_kind(path: &std::path::Path, calls: &Arc<AtomicU64>, kind: &str) {
let opened = Engine::open_with_embedder_for_test(
path,
Arc::new(CountingRefEmbedder { calls: calls.clone() }),
)
.expect("enrolment open");
opened.engine.configure_vector_kind_for_test(kind).expect("enrol vector kind");
opened.engine.close().expect("close enrolment session");
}
fn seed_verified_workspace(path: &std::path::Path, calls: &Arc<AtomicU64>) {
enrol_kind(path, calls, "note");
let (embeds, degraded) =
open_count_close(path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), calls);
assert_eq!(embeds, 2 * PROBE_COUNT, "the POPULATION open is 45 persist + 45 confirm");
assert!(!degraded, "a faithful population open is never degraded");
}
#[test]
fn measured_zero_enrolled_kinds_costs_zero_probe_embeds() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
let (first, _) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
let (second, _) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(first, 0, "no vector kind ⇒ no dense arm to guard ⇒ no probe embeds");
assert_eq!(second, 0, "…and the same on reopen");
}
#[test]
fn measured_population_open_cost_is_flat_in_the_enrolled_kind_count() {
let one_dir = TempDir::new().unwrap();
let one_path = db_path(&one_dir);
let one_calls = counter();
enrol_kind(&one_path, &one_calls, "note");
let (one_kind_open, _) = open_count_close(
&one_path,
Arc::new(CountingRefEmbedder { calls: one_calls.clone() }),
&one_calls,
);
let many_dir = TempDir::new().unwrap();
let many_path = db_path(&many_dir);
let many_calls = counter();
{
let opened = Engine::open_with_embedder_for_test(
&many_path,
Arc::new(CountingRefEmbedder { calls: many_calls.clone() }),
)
.expect("enrolment open");
for kind in ["note", "email", "article", "paper", "meeting", "todo"] {
opened.engine.configure_vector_kind_for_test(kind).expect("enrol vector kind");
}
opened.engine.close().expect("close");
}
let (six_kind_open, _) = open_count_close(
&many_path,
Arc::new(CountingRefEmbedder { calls: many_calls.clone() }),
&many_calls,
);
assert_eq!(one_kind_open, 2 * PROBE_COUNT, "population open = 45 persist + 45 confirm");
assert_eq!(six_kind_open, one_kind_open, "probe cost never scaled with the kind count");
}
#[test]
fn verified_reopen_performs_zero_probe_embeds() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
let (third, third_degraded) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
let (fourth, fourth_degraded) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(third, 0, "a verified workspace must not re-embed the probe set on reopen");
assert_eq!(fourth, 0, "…and the cached verdict must persist, not be one-shot");
assert!(!third_degraded, "the cached verdict is PASS, so dense stays enabled");
assert!(!fourth_degraded, "…on every subsequent open too");
}
#[test]
fn a_rewritten_pinned_mean_reruns_the_full_probe() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
{
let opened = Engine::open_with_embedder_for_test(
&path,
Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }),
)
.expect("bge enrolment open");
opened.engine.configure_vector_kind_for_test("note").expect("enrol vector kind");
opened.engine.close().expect("close");
}
set_pinned_mean(&path, mean_blob(1.0));
let (population, _) =
open_count_close(&path, Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(population, 2 * PROBE_COUNT, "population open under a pinned mean");
let (cached, cached_degraded) =
open_count_close(&path, Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(cached, 0, "unchanged fingerprint ⇒ zero probe embeds");
assert!(!cached_degraded);
set_pinned_mean(&path, mean_blob(0.9));
let (after_mean_change, after_degraded) =
open_count_close(&path, Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(
after_mean_change, PROBE_COUNT,
"a rewritten mean_vec must re-run the FULL probe, not reuse the cached verdict"
);
assert!(!after_degraded, "a faithful backend still passes the re-run");
let (recached, _) =
open_count_close(&path, Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(recached, 0, "the fresh verdict must be cached under the new fingerprint");
}
#[test]
fn a_tampered_reference_baseline_reruns_the_probe_and_refuses_dense() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
let (cached, _) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(cached, 0, "verified workspace reopens free");
{
let conn = rusqlite::Connection::open(&path).unwrap();
let blob: Vec<u8> = conn
.query_row(
"SELECT reference_vec FROM _fathomdb_embed_probe WHERE probe_ordinal = 0",
[],
|r| r.get(0),
)
.expect("read reference 0");
let flipped: Vec<u8> = blob
.chunks_exact(4)
.flat_map(|c| {
let v = f32::from_le_bytes([c[0], c[1], c[2], c[3]]);
(-v).to_le_bytes()
})
.collect();
assert_eq!(flipped.len(), blob.len(), "tamper must preserve the blob length");
conn.execute(
"UPDATE _fathomdb_embed_probe SET reference_vec = ?1 WHERE probe_ordinal = 0",
rusqlite::params![flipped],
)
.expect("tamper reference 0");
}
let before = calls.load(Ordering::SeqCst);
let opened = Engine::open_with_embedder_for_test(
&path,
Arc::new(CountingRefEmbedder { calls: calls.clone() }),
)
.expect("open must SUCCEED (degraded), never fail");
let embeds = calls.load(Ordering::SeqCst) - before;
assert_eq!(embeds, PROBE_COUNT, "a mutated baseline must force a full re-run");
assert!(
opened.report.dense_disabled,
"the tampered reference diverges ⇒ dense must be REFUSED (fail-safe, R-VEQ-4)"
);
match opened.engine.search("memory") {
Err(EngineError::VectorEquivalenceMismatch { .. }) => {}
other => panic!("dense arm must refuse with VectorEquivalenceMismatch, got {other:?}"),
}
opened.engine.close().unwrap();
}
#[test]
fn an_unreadable_cache_entry_falls_back_to_running_the_probe() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
let (cached, _) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(cached, 0, "verified workspace reopens free");
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute(
"UPDATE _fathomdb_open_state SET value = 'not-a-fingerprint'
WHERE key NOT IN ('projection_cursor',
'search_index_tokenizer_reproject_complete',
'tc33_edge_vector_prune_complete',
'tc33_reserved_write_cursor')",
[],
)
.expect("garble the cached verdict");
}
let (after_garble, degraded) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(
after_garble, PROBE_COUNT,
"an unreadable cached verdict must RUN the probe, never be trusted"
);
assert!(!degraded, "…and running it on a faithful backend passes, so dense stays enabled");
}
#[test]
fn a_missing_cache_entry_falls_back_to_running_the_probe() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute(
"DELETE FROM _fathomdb_open_state
WHERE key NOT IN ('projection_cursor',
'search_index_tokenizer_reproject_complete',
'tc33_edge_vector_prune_complete',
'tc33_reserved_write_cursor')",
[],
)
.expect("delete the cached verdict");
}
let (after_delete, degraded) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(after_delete, PROBE_COUNT, "no cached verdict ⇒ run the probe");
assert!(!degraded);
let (recached, _) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(recached, 0, "…and the fresh verdict is cached again");
}
#[test]
fn a_divergence_on_a_rerun_still_disables_dense() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute(
"DELETE FROM _fathomdb_open_state
WHERE key NOT IN ('projection_cursor',
'search_index_tokenizer_reproject_complete',
'tc33_edge_vector_prune_complete',
'tc33_reserved_write_cursor')",
[],
)
.expect("delete the cached verdict");
}
let (embeds, degraded) = open_count_close(
&path,
Arc::new(CountingDivergentEmbedder { calls: calls.clone() }),
&calls,
);
assert_eq!(embeds, PROBE_COUNT, "the probe must actually run");
assert!(degraded, "divergence on a re-run must still refuse the dense arm");
let (rerun, rerun_degraded) = open_count_close(
&path,
Arc::new(CountingDivergentEmbedder { calls: calls.clone() }),
&calls,
);
assert_eq!(rerun, PROBE_COUNT, "a failing verdict must never be cached");
assert!(rerun_degraded);
}
#[test]
fn residual_same_identity_backend_drift_is_not_caught_on_a_cached_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
let honest_marker =
read_verdict_marker(&path).expect("the honest population open records its own verdict");
let (embeds, degraded) = open_count_close(
&path,
Arc::new(CountingDivergentEmbedder { calls: calls.clone() }),
&calls,
);
assert_eq!(embeds, 0, "the cached verdict answers, so the drifted backend is never asked");
assert!(
!degraded,
"RESIDUAL: same-identity backend drift is NOT caught on a cached open — \
it is caught only at the next open whose fingerprint changed"
);
assert_eq!(
read_verdict_marker(&path).as_deref(),
Some(honest_marker.as_str()),
"fix-2 (§8.5): the drifted backend was served off the ENGINE'S OWN marker, \
unchanged — no forgery was involved, so a forged marker buys nothing here"
);
}
#[test]
fn a_forged_stored_baseline_defeats_the_probe_even_when_it_fully_runs() {
let control_dir = TempDir::new().unwrap();
let control_path = db_path(&control_dir);
let control_calls = counter();
seed_verified_workspace(&control_path, &control_calls);
clear_verdict_marker(&control_path);
let (control_embeds, control_degraded) = open_count_close(
&control_path,
Arc::new(CountingDivergentEmbedder { calls: control_calls.clone() }),
&control_calls,
);
assert_eq!(control_embeds, PROBE_COUNT, "control: the probe must actually run");
assert!(control_degraded, "control: un-forged baseline + drifted backend ⇒ dense REFUSED");
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
forge_stored_baseline(&path, |text| reference_vector(text).into_iter().map(|x| -x).collect());
clear_verdict_marker(&path);
assert_eq!(read_verdict_marker(&path), None, "the cache must play NO part in this leg");
let before = calls.load(Ordering::SeqCst);
let opened = Engine::open_with_embedder_for_test(
&path,
Arc::new(CountingDivergentEmbedder { calls: calls.clone() }),
)
.expect("open must succeed");
let embeds = calls.load(Ordering::SeqCst) - before;
assert_eq!(embeds, PROBE_COUNT, "the FULL pre-slice check ran — nothing was skipped");
assert!(
!opened.report.dense_disabled,
"PRE-EXISTING: a forged stored baseline defeats the probe on the pre-slice path — \
the probe is a correctness self-check against backend drift, NOT an integrity \
boundary against an actor with write access to the database file"
);
if let Err(EngineError::VectorEquivalenceMismatch { .. }) = opened.engine.search("memory") {
panic!("the dense arm must be SERVING — that is the point of this measurement");
}
opened.engine.close().unwrap();
}
#[test]
fn a_marker_matching_the_current_state_serves_a_drifted_backend() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
let digest = read_verdict_marker(&path).expect("a verified workspace carries a marker");
clear_verdict_marker(&path);
let (caught_embeds, caught_degraded) = open_count_close(
&path,
Arc::new(CountingDivergentEmbedder { calls: calls.clone() }),
&calls,
);
assert_eq!(caught_embeds, PROBE_COUNT, "no marker ⇒ the probe runs");
assert!(caught_degraded, "no marker ⇒ the drifted backend is CAUGHT");
assert_eq!(read_verdict_marker(&path), None, "a failing verdict is never cached");
install_verdict_marker(&path, &digest);
let (forged_embeds, forged_degraded) = open_count_close(
&path,
Arc::new(CountingDivergentEmbedder { calls: calls.clone() }),
&calls,
);
assert_eq!(forged_embeds, 0, "a matching marker skips the 45-probe verification");
assert!(
!forged_degraded,
"codex §9 round-2 [P1]: a marker matching the current state serves a drifted \
backend — the marker proves the fingerprint inputs are unchanged since SOME \
engine recorded a pass, not that THIS engine verified THIS backend"
);
}
#[test]
fn a_replayed_verdict_marker_is_defeated_by_a_mutated_baseline() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
seed_verified_workspace(&path, &calls);
let digest = read_verdict_marker(&path).expect("a verified workspace carries a marker");
{
let conn = rusqlite::Connection::open(&path).unwrap();
let blob: Vec<u8> = conn
.query_row(
"SELECT reference_vec FROM _fathomdb_embed_probe WHERE probe_ordinal = 0",
[],
|r| r.get(0),
)
.expect("read reference 0");
let flipped: Vec<u8> = blob
.chunks_exact(4)
.flat_map(|c| (-f32::from_le_bytes([c[0], c[1], c[2], c[3]])).to_le_bytes())
.collect();
conn.execute(
"UPDATE _fathomdb_embed_probe SET reference_vec = ?1 WHERE probe_ordinal = 0",
rusqlite::params![flipped],
)
.expect("mutate reference 0");
}
install_verdict_marker(&path, &digest);
let (embeds, degraded) =
open_count_close(&path, Arc::new(CountingRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(embeds, PROBE_COUNT, "the stale digest cannot keep the probe skipped");
assert!(degraded, "…and the re-run catches the mutated reference (fail-safe, R-VEQ-4)");
}
#[test]
fn a_replayed_verdict_marker_is_defeated_by_a_rewritten_pinned_mean() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let calls = counter();
{
let opened = Engine::open_with_embedder_for_test(
&path,
Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }),
)
.expect("bge enrolment open");
opened.engine.configure_vector_kind_for_test("note").expect("enrol vector kind");
opened.engine.close().expect("close");
}
set_pinned_mean(&path, mean_blob(1.0));
let (population, _) =
open_count_close(&path, Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(population, 2 * PROBE_COUNT, "population open under a pinned mean");
let digest = read_verdict_marker(&path).expect("a verified workspace carries a marker");
set_pinned_mean(&path, mean_blob(0.9));
install_verdict_marker(&path, &digest);
let (embeds, degraded) =
open_count_close(&path, Arc::new(CountingBgeRefEmbedder { calls: calls.clone() }), &calls);
assert_eq!(embeds, PROBE_COUNT, "a rewritten mean invalidates the replayed digest");
assert!(!degraded, "…and a faithful backend still passes the forced re-run");
}