use std::sync::{Arc, Once};
use fathomdb_embedder_api::{Embedder, EmbedderError, EmbedderIdentity, Vector};
use fathomdb_engine::{Engine, EngineError};
use fathomdb_schema::{migrate_with_steps, MIGRATIONS};
use tempfile::TempDir;
const DIM: usize = 384;
const PROBE_IDENTITY_NAME: &str = "fathomdb-probe-test";
const PROBE_IDENTITY_REV: &str = "veq-slice5";
const BGE_NAME: &str = "fathomdb-bge-small-en-v1.5";
const BGE_REV: &str = "veq-slice5-mc";
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 RefEmbedder;
impl Embedder for RefEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
Ok(reference_vector(text))
}
}
#[derive(Debug)]
struct DivergentEmbedder;
impl Embedder for DivergentEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
Ok(reference_vector(text).into_iter().map(|x| -x).collect())
}
}
#[derive(Debug)]
struct NoiseEmbedder;
impl Embedder for NoiseEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
Ok(reference_vector(text)
.into_iter()
.enumerate()
.map(|(i, x)| x + if i % 2 == 0 { 1e-7 } else { -1e-7 })
.collect())
}
}
#[derive(Debug)]
struct P2OnlyEmbedder;
impl Embedder for P2OnlyEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
Ok(reference_vector(text).into_iter().map(|x| x + 1e-3).collect())
}
}
#[derive(Debug)]
struct PanicEmbedder;
impl Embedder for PanicEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, _text: &str) -> Result<Vector, EmbedderError> {
panic!("probe embedder deliberately panics");
}
}
#[derive(Debug)]
struct ErrorEmbedder;
impl Embedder for ErrorEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(PROBE_IDENTITY_NAME, PROBE_IDENTITY_REV, DIM as u32)
}
fn embed(&self, _text: &str) -> Result<Vector, EmbedderError> {
Err(EmbedderError::Failed { message: "deterministic probe embed failure".to_string() })
}
}
#[derive(Debug)]
struct BgeRefEmbedder;
impl Embedder for BgeRefEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(BGE_NAME, BGE_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
Ok(reference_vector(text))
}
}
#[derive(Debug)]
struct BgeMeanReflectEmbedder;
impl Embedder for BgeMeanReflectEmbedder {
fn identity(&self) -> EmbedderIdentity {
EmbedderIdentity::new(BGE_NAME, BGE_REV, DIM as u32)
}
fn embed(&self, text: &str) -> Result<Vector, EmbedderError> {
Ok(reference_vector(text).into_iter().map(|x| 2.0 - x).collect())
}
}
fn db_path(dir: &TempDir) -> std::path::PathBuf {
dir.path().join("veq.sqlite")
}
fn register_sqlite_vec_once() {
static REGISTER: Once = Once::new();
REGISTER.call_once(|| unsafe {
let entrypoint: unsafe extern "C" fn(
*mut rusqlite::ffi::sqlite3,
*mut *mut std::os::raw::c_char,
*const rusqlite::ffi::sqlite3_api_routines,
) -> std::os::raw::c_int = std::mem::transmute(sqlite_vec::sqlite3_vec_init as *const ());
rusqlite::ffi::sqlite3_auto_extension(Some(entrypoint));
});
}
fn all_ones_mean_blob() -> Vec<u8> {
let mut blob = Vec::with_capacity(DIM * 4);
for _ in 0..DIM {
blob.extend_from_slice(&1.0f32.to_le_bytes());
}
blob
}
const VEQ_VERDICT_CACHE_KEY: &str = "vector_equivalence_verified_fingerprint";
fn force_probe_verdict_rerun(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 TC-68 verdict cache");
}
fn set_pinned_mean(path: &std::path::Path, mean: Option<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/un-pin mean_vec");
}
fn seed_bge_references_with_pinned_mean(path: &std::path::Path) {
let opened = Engine::open_with_embedder_for_test(path, Arc::new(BgeRefEmbedder))
.expect("bge session 1 open");
opened.engine.configure_vector_kind_for_test("note").expect("register vector kind");
opened.engine.close().expect("close bge session 1");
set_pinned_mean(path, Some(all_ones_mean_blob()));
let opened = Engine::open_with_embedder_for_test(path, Arc::new(BgeRefEmbedder))
.expect("bge session 2 open persists references");
assert!(!opened.report.dense_disabled, "first registration is never degraded");
opened.engine.close().expect("close bge session 2");
force_probe_verdict_rerun(path);
}
fn seed_references(path: &std::path::Path) {
let opened =
Engine::open_with_embedder_for_test(path, Arc::new(RefEmbedder)).expect("session 1 open");
opened.engine.configure_vector_kind_for_test("note").expect("register vector kind");
assert!(!opened.report.dense_disabled, "session 1 is never degraded");
opened.engine.close().expect("close session 1");
let opened = Engine::open_with_embedder_for_test(path, Arc::new(RefEmbedder))
.expect("session 2 open persists references");
assert!(!opened.report.dense_disabled, "first registration is never degraded");
opened.engine.close().expect("close session 2");
force_probe_verdict_rerun(path);
}
#[test]
fn probe_set_persisted_at_first_vector_kind_registration() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).expect("open");
opened.engine.configure_vector_kind_for_test("note").expect("register vector kind");
opened.engine.close().unwrap();
let conn0 = rusqlite::Connection::open(&path).unwrap();
let pre: i64 =
conn0.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(pre, 0, "no references persisted before a vector kind exists at open");
drop(conn0);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).expect("reopen");
opened.engine.close().unwrap();
let conn = rusqlite::Connection::open(&path).unwrap();
let rows: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 45, "exactly 45 probes must be persisted at first registration");
let (name, rev, dim): (String, String, i64) = conn
.query_row(
"SELECT embedder_name, embedder_revision, dim FROM _fathomdb_embed_probe WHERE probe_ordinal = 0",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap();
assert_eq!(name, PROBE_IDENTITY_NAME);
assert_eq!(rev, PROBE_IDENTITY_REV);
assert_eq!(dim, DIM as i64);
let ref_len: i64 = conn
.query_row(
"SELECT LENGTH(reference_vec) FROM _fathomdb_embed_probe WHERE probe_ordinal = 0",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(ref_len, (DIM * 4) as i64, "reference must be 4*dim f32 bytes, never packed bits");
}
#[test]
fn divergent_backend_trips_dense_refusal() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder))
.expect("open must SUCCEED (degraded), never fail");
let engine = opened.engine;
assert!(opened.report.dense_disabled, "divergent backend must degrade the open");
match engine.search("memory") {
Err(EngineError::VectorEquivalenceMismatch { .. }) => {}
other => panic!("hybrid search must refuse with VectorEquivalenceMismatch, got {other:?}"),
}
let fts = engine.search_text_only("memory").expect("FTS-only path must stay serviceable");
let _ = fts; engine.close().unwrap();
}
#[test]
fn same_backend_float_noise_does_not_trip() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(NoiseEmbedder))
.expect("open with float-noise backend");
let engine = opened.engine;
assert!(!opened.report.dense_disabled, "sub-epsilon float noise must NOT degrade the open");
match engine.search("memory") {
Ok(_) => {}
Err(EngineError::VectorEquivalenceMismatch { .. }) => {
panic!("float noise within the D4 floor must NOT refuse dense")
}
Err(other) => panic!("unexpected error: {other:?}"),
}
engine.close().unwrap();
}
#[test]
fn probe_p1_flip_count_matches_embedding_bin() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder)).unwrap();
assert!(opened.report.dense_disabled);
let reason = opened.report.dense_disabled_reason.clone().expect("degraded reason present");
assert!(
reason.contains("flips=17280"),
"P1 must count exactly 384*45=17280 sign flips, reason was: {reason}"
);
opened.engine.close().unwrap();
}
#[test]
fn probe_p2_l2_within_epsilon() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(P2OnlyEmbedder)).unwrap();
assert!(opened.report.dense_disabled, "P2 L2 over epsilon must degrade the open");
let reason = opened.report.dense_disabled_reason.clone().expect("reason present");
assert!(
reason.contains("flips=0"),
"P2-only divergence must NOT flip any P1 bit, reason was: {reason}"
);
opened.engine.close().unwrap();
}
#[test]
fn probe_respects_mean_centering_gate_non_mc_path() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).unwrap();
assert!(
!opened.report.dense_disabled,
"identical backend on the non-MC un-centered path must be 0 flips / 0 L2"
);
opened.engine.close().unwrap();
}
#[test]
fn divergent_open_is_degraded_not_failed() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder))
.expect("degraded open must SUCCEED");
assert!(opened.report.dense_disabled);
assert!(opened.engine.dense_disabled(), "engine accessor mirrors the report");
opened.engine.close().unwrap();
}
#[test]
fn every_vector_dependent_arm_refuses_with_typed_error() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder)).unwrap();
let engine = opened.engine;
let is_veq = |r: &Result<_, EngineError>| {
matches!(r, Err(EngineError::VectorEquivalenceMismatch { .. }))
};
assert!(is_veq(&engine.search("q")), "search must refuse");
assert!(is_veq(&engine.search_filtered("q", None)), "search_filtered must refuse");
assert!(
is_veq(&engine.search_reranked("q", None, 5, false, 1.0, 5)),
"search_reranked (CE) must refuse"
);
assert!(
is_veq(&engine.search_explained("q", None, 5, false, 1.0, 5)),
"search_explained (explain/rerank) must refuse"
);
assert!(
is_veq(&engine.search_reranked("q", None, 0, true, 0.3, 0)),
"graph-arm (use_graph_arm=true) must refuse"
);
assert!(
matches!(
engine.search_expand("q", None, 1),
Err(EngineError::VectorEquivalenceMismatch { .. })
),
"search_expand must refuse"
);
engine.close().unwrap();
}
#[test]
fn fts_only_path_still_serves_when_degraded() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder)).unwrap();
let engine = opened.engine;
assert!(engine.search_text_only("anything").is_ok(), "FTS-only path must serve when degraded");
assert!(engine.search("anything").is_err(), "the dense arm still refuses");
engine.close().unwrap();
}
#[test]
fn open_report_surfaces_dense_disabled_and_counter_and_reopen_stays_degraded() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder)).unwrap();
let engine = opened.engine;
assert!(opened.report.dense_disabled);
assert!(opened.report.dense_disabled_reason.is_some(), "reason surfaced on the report");
assert_eq!(engine.vector_equivalence_refusal_count(), 0, "counter starts at 0");
let _ = engine.search("q");
let _ = engine.search("q2");
assert_eq!(engine.vector_equivalence_refusal_count(), 2, "counter increments per refusal");
engine.close().unwrap();
let reopened = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder)).unwrap();
assert!(reopened.report.dense_disabled, "reopen with a divergent backend stays degraded");
reopened.engine.close().unwrap();
let healthy = Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).unwrap();
assert!(!healthy.report.dense_disabled, "reopen with a matching backend clears the degrade");
healthy.engine.close().unwrap();
}
#[test]
fn panicking_embedder_at_check_fails_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(PanicEmbedder))
.expect("a panicking probe embedder must NOT wedge open (open still succeeds)");
let engine = opened.engine;
assert!(
opened.report.dense_disabled,
"an un-verifiable (panicking) embedder must fail SAFE: dense refused"
);
assert!(opened.report.dense_disabled_reason.is_some(), "a refusal reason is surfaced");
match engine.search("memory") {
Err(EngineError::VectorEquivalenceMismatch { .. }) => {}
other => panic!("dense query must refuse with VectorEquivalenceMismatch, got {other:?}"),
}
assert!(engine.search_text_only("memory").is_ok(), "FTS-only path must still serve");
engine.close().unwrap();
}
#[test]
fn erroring_embedder_at_check_fails_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(ErrorEmbedder))
.expect("an erroring probe embedder must NOT wedge open");
let engine = opened.engine;
assert!(
opened.report.dense_disabled,
"an un-verifiable (erroring) embedder must fail SAFE: dense refused"
);
match engine.search("memory") {
Err(EngineError::VectorEquivalenceMismatch { .. }) => {}
other => panic!("dense query must refuse with VectorEquivalenceMismatch, got {other:?}"),
}
assert!(engine.search_text_only("memory").is_ok(), "FTS-only path must still serve");
engine.close().unwrap();
}
#[test]
fn population_failure_fails_safe_and_persists_no_partial_baseline() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).expect("open");
opened.engine.configure_vector_kind_for_test("note").expect("register vector kind");
opened.engine.close().unwrap();
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(PanicEmbedder))
.expect("population failure must NOT wedge open");
assert!(
opened.report.dense_disabled,
"a baseline that cannot be established must fail SAFE: dense refused"
);
match opened.engine.search("q") {
Err(EngineError::VectorEquivalenceMismatch { .. }) => {}
other => panic!("dense query must refuse, got {other:?}"),
}
opened.engine.close().unwrap();
let conn = rusqlite::Connection::open(&path).unwrap();
let rows: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 0, "a failed population must persist NO probe rows (no partial baseline)");
}
#[test]
fn post_open_registration_serves_in_session_and_baselines_at_next_open() {
use fathomdb_engine::PreparedWrite;
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).expect("open");
let engine = opened.engine;
assert!(!opened.report.dense_disabled, "a vector-less open is not degraded");
engine.configure_vector_kind_for_test("note").expect("register vector kind post-open");
engine
.write(&[PreparedWrite::Node {
kind: "note".to_string(),
body: "post-open registration body".to_string(),
source_id: fathomdb_engine::SourceId::new("test:fixture").expect("test source id"),
logical_id: None,
state: fathomdb_engine::InitialState::Active,
reason: None,
valid_from: None,
valid_until: None,
}])
.expect("write must not block on / be gated by the probe");
assert!(!engine.dense_disabled(), "in-session serving is safe (same live backend)");
assert!(engine.search("post-open").is_ok(), "in-session dense query is served");
engine.close().unwrap();
let conn = rusqlite::Connection::open(&path).unwrap();
let pre: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(pre, 0, "the write path must not embed/establish the baseline");
drop(conn);
let reopened =
Engine::open_with_embedder_for_test(&path, Arc::new(RefEmbedder)).expect("reopen");
assert!(!reopened.report.dense_disabled, "baseline establishment at reopen is not degraded");
reopened.engine.close().unwrap();
let conn = rusqlite::Connection::open(&path).unwrap();
let rows: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 45, "the next open must establish the 45-probe baseline (identity-gated)");
drop(conn);
force_probe_verdict_rerun(&path);
let divergent = Engine::open_with_embedder_for_test(&path, Arc::new(DivergentEmbedder))
.expect("divergent reopen (degraded)");
assert!(divergent.report.dense_disabled, "forward drift is caught after the reopen baseline");
divergent.engine.close().unwrap();
}
#[test]
fn mc_required_with_pin_same_backend_does_not_trip() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_bge_references_with_pinned_mean(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(BgeRefEmbedder))
.expect("bge same-backend reopen");
assert!(
!opened.report.dense_disabled,
"the MC-with-pin same-backend path must be 0 flips / 0 L2 (dense served)"
);
match opened.engine.search("q") {
Ok(_) | Err(EngineError::EmbedderNotConfigured) => {}
Err(EngineError::VectorEquivalenceMismatch { .. }) => {
panic!("the same-backend MC path must NOT refuse dense")
}
Err(other) => panic!("unexpected error: {other:?}"),
}
opened.engine.close().unwrap();
}
#[test]
fn mc_required_with_pin_centered_flip_trips_dense() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_bge_references_with_pinned_mean(&path);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(BgeMeanReflectEmbedder))
.expect("bge reflect reopen (degraded)");
assert!(
opened.report.dense_disabled,
"a mean-centered sign flip must degrade the open on the MC-with-pin path"
);
let reason = opened.report.dense_disabled_reason.clone().expect("reason present");
assert!(
!reason.contains("flips=0 "),
"centering must be applied (flips > 0) with the pinned mean, reason was: {reason}"
);
opened.engine.close().unwrap();
}
#[test]
fn mc_reflect_without_pin_takes_uncentered_path_zero_flips() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_bge_references_with_pinned_mean(&path);
set_pinned_mean(&path, None);
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(BgeMeanReflectEmbedder))
.expect("bge reflect reopen (un-pinned)");
assert!(opened.report.dense_disabled, "the reflect backend still trips P2 (L2) un-centered");
let reason = opened.report.dense_disabled_reason.clone().expect("reason present");
assert!(
reason.contains("flips=0 "),
"un-centered, the reflect backend must show 0 raw-sign flips, reason was: {reason}"
);
opened.engine.close().unwrap();
}
#[test]
fn upgrade_from_v18_with_kind_and_pinned_mean_establishes_baseline_and_checks() {
register_sqlite_vec_once();
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
{
let conn = rusqlite::Connection::open(&path).unwrap();
let steps_to_18: Vec<_> = MIGRATIONS.iter().filter(|m| m.step_id <= 18).cloned().collect();
migrate_with_steps(&conn, &steps_to_18).expect("migrate to v18");
let ver: u32 = conn.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();
assert_eq!(ver, 18, "precondition: DB is at v18");
conn.execute(
"INSERT INTO _fathomdb_embedder_profiles(profile, name, revision, dimension, mean_vec)
VALUES('default', ?1, ?2, ?3, ?4)",
rusqlite::params![BGE_NAME, BGE_REV, DIM as u32, all_ones_mean_blob()],
)
.expect("seed bge profile with a pinned mean");
conn.execute(
"INSERT INTO _fathomdb_vector_kinds(kind, profile, created_at) VALUES('note','default',0)",
[],
)
.expect("seed pre-existing vector kind");
drop(conn);
}
let opened = Engine::open_with_embedder_for_test(&path, Arc::new(BgeRefEmbedder))
.expect("open must upgrade v18→v19 and establish the baseline");
assert!(
!opened.report.dense_disabled,
"establishing the baseline at the upgrade open is never degraded"
);
assert_eq!(opened.report.schema_version_before, 18, "upgrade started at v18");
assert_eq!(opened.report.schema_version_after, 26, "upgrade reached head (v26)");
opened.engine.close().unwrap();
let conn = rusqlite::Connection::open(&path).unwrap();
let rows: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 45, "the upgrade open must establish the 45-probe baseline");
drop(conn);
let same = Engine::open_with_embedder_for_test(&path, Arc::new(BgeRefEmbedder))
.expect("same-backend reopen");
assert!(!same.report.dense_disabled, "same identity-matched backend ⇒ dense served");
same.engine.close().unwrap();
force_probe_verdict_rerun(&path);
let divergent = Engine::open_with_embedder_for_test(&path, Arc::new(BgeMeanReflectEmbedder))
.expect("divergent reopen (degraded)");
assert!(
divergent.report.dense_disabled,
"a mean-centered divergent backend ⇒ dense refused (fail-SAFE)"
);
divergent.engine.close().unwrap();
}
fn encode_le_f32(v: &[f32]) -> Vec<u8> {
let mut b = Vec::with_capacity(v.len() * 4);
for x in v {
b.extend_from_slice(&x.to_le_bytes());
}
b
}
fn assert_degraded_but_fts_serves(path: &std::path::Path) {
let opened = Engine::open_with_embedder_for_test(path, Arc::new(RefEmbedder))
.expect("a corrupt/partial baseline must NOT wedge open (open still succeeds)");
let engine = opened.engine;
assert!(
opened.report.dense_disabled,
"an incomplete/tampered stored baseline must fail SAFE: dense refused"
);
assert!(opened.report.dense_disabled_reason.is_some(), "a refusal reason is surfaced");
match engine.search("memory") {
Err(EngineError::VectorEquivalenceMismatch { .. }) => {}
other => panic!("dense query must refuse with VectorEquivalenceMismatch, got {other:?}"),
}
assert!(engine.search_text_only("memory").is_ok(), "FTS-only path must still serve");
engine.close().unwrap();
}
#[test]
fn partial_baseline_missing_one_row_fails_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute("DELETE FROM _fathomdb_embed_probe WHERE probe_ordinal = 44", [])
.expect("delete one probe row");
let rows: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 44, "precondition: the stored baseline is now partial (44 of 45)");
}
assert_degraded_but_fts_serves(&path);
}
#[test]
fn substituted_probe_text_verifying_against_itself_fails_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
{
let foreign = "this-is-not-a-committed-probe";
let foreign_vec = encode_le_f32(&reference_vector(foreign));
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute(
"UPDATE _fathomdb_embed_probe SET probe_text = ?1, reference_vec = ?2 \
WHERE probe_ordinal = 5",
rusqlite::params![foreign, foreign_vec],
)
.expect("substitute a self-consistent foreign probe");
}
assert_degraded_but_fts_serves(&path);
}
#[test]
fn re_attributed_embedder_identity_fails_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute("UPDATE _fathomdb_embed_probe SET embedder_name = 'a-different-embedder'", [])
.expect("re-attribute the stored embedder identity");
}
assert_degraded_but_fts_serves(&path);
}
#[test]
fn non_contiguous_ordinals_fail_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute(
"UPDATE _fathomdb_embed_probe SET probe_ordinal = 45 WHERE probe_ordinal = 44",
[],
)
.expect("introduce an ordinal gap");
let rows: i64 =
conn.query_row("SELECT COUNT(*) FROM _fathomdb_embed_probe", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 45, "precondition: the row COUNT is still 45 (only the ordinal moved)");
}
assert_degraded_but_fts_serves(&path);
}
#[test]
fn mangled_reference_blob_wrong_length_fails_safe_not_open() {
let dir = TempDir::new().unwrap();
let path = db_path(&dir);
seed_references(&path);
{
let conn = rusqlite::Connection::open(&path).unwrap();
let full: Vec<u8> = conn
.query_row(
"SELECT reference_vec FROM _fathomdb_embed_probe WHERE probe_ordinal = 7",
[],
|r| r.get(0),
)
.expect("read the reference blob to mangle");
assert_eq!(full.len(), DIM * 4, "precondition: the stored blob is a full 4*dim f32 blob");
let truncated = full[..full.len() - 1].to_vec(); conn.execute(
"UPDATE _fathomdb_embed_probe SET reference_vec = ?1 WHERE probe_ordinal = 7",
rusqlite::params![truncated],
)
.expect("truncate one reference blob");
let len: i64 = conn
.query_row(
"SELECT LENGTH(reference_vec) FROM _fathomdb_embed_probe WHERE probe_ordinal = 7",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(
len,
(DIM * 4 - 1) as i64,
"precondition: the stored blob is now the wrong length (not a multiple of 4)"
);
}
assert_degraded_but_fts_serves(&path);
}