Cotton code
557 lines · 20.0 KB · RustRaw
//! The semantic lane, with 25 vectors pinning the answers.//!//! # What came over, and what could not//!//! The TypeScript file opened a REAL SQLite file and created `_embeddings` "the//! way the SERVER creates it". This crate opens no database, so the eleven cases//! in its third block — *the lane inside search-everything* — have no home here://! they are cases about the SEARCH, not about the lane, and they belong wherever//! the search's own fold over one visibility rule, one hit per record and one hit//! per document is tested.//!//! Everything that is the LANE's own — the arithmetic block and the//! `semanticChunkScan` block — comes over in full. The two cases that were//! statements about SQL (`ignores every vector of another generation`, and//! `answers empty on a database that has no vectors table at all`) become//! assertions about the statements this module now declares, pinned against//! the SQL the running TypeScript actually issued to a recording driver.//!//! The fixture generators (`vectorOf`, `blend`, `floatCosine`) are the//! TypeScript test file's own, ported line for line: a seeded Lehmer generator//! rather than `sin(seed + i)`, because a phase-shifted wave gives two//! "different" seeds a cosine near 1 and a fixture where nothing is unrelated//! cannot show a floor doing its job. Every intermediate stays under 2^53, so//! `i64` reproduces the JavaScript doubles exactly — proven by the//! `fixture_generator_matches_nodes` vectors below.use crate::transforms::quantize::{dequantize_embedding, quantize_embedding, EMBED_DIMS};use super::*;const MODEL: &str = "openai:text-embedding-3-small:512";/// A deterministic, never-zero vector — the quantiser refuses a zero one.fn vector_of(seed: i64) -> Vec<f64> {    let mut state = (seed * 2_654_435_761) % 2_147_483_647;    if state == 0 {        state = 1;    }    let mut values = Vec::with_capacity(EMBED_DIMS);    for _ in 0..EMBED_DIMS {        state = (state * 48271) % 2_147_483_647;        values.push(state as f64 / 2_147_483_647.0 - 0.5 + 0.0001);    }    values}/// A vector `mix` of the way from `a` towards `b` — a controlled neighbour.fn blend(a: &[f64], b: &[f64], mix: f64) -> Vec<f64> {    a.iter()        .zip(b)        .map(|(value, other)| value * (1.0 - mix) + other * mix)        .collect()}fn quantised(values: &[f64]) -> Vec<u8> {    quantize_embedding(values).expect("a vector with a direction")}/// Float cosine over the DEQUANTISED vectors — what the scan approximates.fn float_cosine(a: &[f64], b: &[f64]) -> f64 {    let left = dequantize_embedding(&quantised(a)).expect("512 bytes");    let right = dequantize_embedding(&quantised(b)).expect("512 bytes");    left.iter().zip(&right).map(|(l, r)| l * r).sum()}fn row(source: &str, row_id: &str, values: &[f64]) -> EmbeddingChunkRow {    EmbeddingChunkRow {        source: source.to_string(),        row_id: row_id.to_string(),        chunk_ix: 0,        vec: quantised(values),        text_head: Some("some stored prose".to_string()),    }}fn head(mut row: EmbeddingChunkRow, text_head: &str) -> EmbeddingChunkRow {    row.text_head = Some(text_head.to_string());    row}fn options<'a>(vector: &'a [u8], min_score: Option<f64>) -> SemanticScanOptions<'a> {    SemanticScanOptions {        vector,        model: MODEL,        sources: None,        per_source: None,        min_score,    }}// ── the scan's arithmetic ────────────────────────────────────────────────────#[test]fn ranks_exactly_the_way_float_cosine_over_the_same_bytes_does() {    let query = vector_of(1);    let candidates: Vec<Vec<f64>> = (0..24)        .map(|i| blend(&query, &vector_of(100 + i), (i + 1) as f64 / 26.0))        .collect();    let query_bytes = quantised(&query);    let mut by_integer: Vec<(usize, f64)> = candidates        .iter()        .enumerate()        .map(|(i, values)| {            (                i,                quantized_cosine(                    as_stored_vector(&query_bytes).expect("512 bytes"),                    as_stored_vector(&quantised(values)).expect("512 bytes"),                ),            )        })        .collect();    by_integer.sort_by(|a, b| b.1.total_cmp(&a.1));    let mut by_float: Vec<(usize, f64)> = candidates        .iter()        .enumerate()        .map(|(i, values)| (i, float_cosine(&query, values)))        .collect();    by_float.sort_by(|a, b| b.1.total_cmp(&a.1));    assert_eq!(        by_integer.iter().map(|entry| entry.0).collect::<Vec<_>>(),        by_float.iter().map(|entry| entry.0).collect::<Vec<_>>()    );}#[test]fn agrees_with_float_cosine_to_within_the_quantisation_step() {    let query = vector_of(3);    let query_bytes = quantised(&query);    for i in 0..8 {        let other = blend(&query, &vector_of(200 + i), i as f64 / 10.0);        let integer = quantized_cosine(            as_stored_vector(&query_bytes).expect("512 bytes"),            as_stored_vector(&quantised(&other)).expect("512 bytes"),        );        assert!(            (integer - float_cosine(&query, &other)).abs() < 0.01,            "step {i}"        );    }}/// Not exactly 1: rounding 512 small components to whole int8 steps adds a/// percent or so of length back. This is the approximation D6 declares, and it/// reorders near-ties only — pinning it to 1.000 would be pinning a property/// the format does not have.#[test]fn scores_a_vector_against_itself_at_about_1_and_its_negation_at_about_minus_1() {    let values = vector_of(9);    let self_bytes = quantised(&values);    let negated: Vec<f64> = values.iter().map(|v| -v).collect();    let flipped = quantised(&negated);    let selff = as_stored_vector(&self_bytes).expect("512 bytes");    assert!((quantized_cosine(selff, selff) - 1.0).abs() < 0.05);    assert!(        (quantized_cosine(selff, as_stored_vector(&flipped).expect("512 bytes")) + 1.0).abs()            < 0.05    );    assert_eq!(EMBED_DOT_SCALE, 127.0 * 127.0);}/// The TypeScript's failure here is silent and plausible: better-sqlite3 hands/// back a view into a shared pool, so ignoring the offset scores some other/// row's bytes as this one's. A Rust `&[u8]` carries its own start, so the/// mistake is unspellable — the test comes over anyway, as a sub-slice of a/// larger buffer scoring identically to the standalone one.#[test]fn reads_a_slice_at_its_own_start_not_its_buffers() {    let bytes = quantised(&vector_of(5));    let mut pool = vec![0_u8; bytes.len() + 64];    pool[64..].copy_from_slice(&bytes);    let shifted = &pool[64..];    let view = as_stored_vector(shifted).expect("512 bytes");    let plain = as_stored_vector(&bytes).expect("512 bytes");    assert_eq!(        quantized_cosine(view, plain),        quantized_cosine(plain, plain)    );}/// One corrupt row must not take down a search over sixty thousand good ones./// The TypeScript's "not bytes at all" cases (`"not bytes"`, `null`) are the/// Rust type here.#[test]fn refuses_a_blob_that_is_not_a_whole_vector_rather_than_scoring_it() {    assert!(as_stored_vector(&[0_u8; 11]).is_none());    assert!(as_stored_vector(&[]).is_none());    assert!(as_stored_vector(&[0_u8; 511]).is_none());    assert!(as_stored_vector(&[0_u8; 513]).is_none());    assert!(as_stored_vector(&[0_u8; 512]).is_some());}// ── semanticChunkScan ────────────────────────────────────────────────────────/// The TypeScript asks a real driver; the Rust half of that question is "the/// caller found no table, so it has no rows", and the answer is an empty/// result rather than an error. The other half — that ASKING did not bring a/// table into being — is a property of the statement, and it is pinned below.#[test]fn answers_empty_on_a_database_that_has_no_vectors_table_at_all() {    let query = quantised(&vector_of(1));    assert_eq!(        semantic_chunk_scan(&[], &options(&query, None)),        Ok(Vec::new())    );}/// Looking at a database must never be what brings a table into being.#[test]fn the_presence_statement_only_reads_and_never_creates() {    assert_eq!(        EMBEDDINGS_PRESENT_SQL,        "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_embeddings'"    );    let shouted = EMBEDDINGS_PRESENT_SQL.to_uppercase();    for forbidden in ["CREATE", "INSERT", "UPDATE", "DELETE", "DROP", "PRAGMA"] {        assert!(!shouted.contains(forbidden), "{forbidden} in the probe");    }}#[test]fn keeps_a_top_k_per_source_so_one_source_cannot_crowd_out_another() {    let query = vector_of(1);    // Ten near-perfect message chunks, one middling note.    let mut rows: Vec<EmbeddingChunkRow> = (0..10)        .map(|i| {            row(                "message",                &format!("m{i}"),                &blend(&query, &vector_of(300 + i), 0.02),            )        })        .collect();    rows.push(row("note", "n1", &blend(&query, &vector_of(400), 0.5)));    let query_bytes = quantised(&query);    let hits = semantic_chunk_scan(        &rows,        &SemanticScanOptions {            per_source: Some(3),            ..options(&query_bytes, Some(-1.0))        },    )    .expect("a 512-byte query");    let count = |source: &str| hits.iter().filter(|hit| hit.source == source).count();    assert_eq!(count("message"), 3);    // The note survives on its own partition despite losing to every message.    assert_eq!(count("note"), 1);}#[test]fn ranks_best_first_within_a_source_and_carries_the_stored_head() {    let query = vector_of(1);    let rows = [        head(            row("note", "far", &blend(&query, &vector_of(500), 0.6)),            "far prose",        ),        head(            row("note", "near", &blend(&query, &vector_of(501), 0.05)),            "near prose",        ),    ];    let query_bytes = quantised(&query);    let hits =        semantic_chunk_scan(&rows, &options(&query_bytes, Some(-1.0))).expect("a 512-byte query");    assert_eq!(        hits.iter()            .map(|hit| hit.row_id.as_str())            .collect::<Vec<_>>(),        ["near", "far"]    );    assert_eq!(hits[0].text_head, "near prose");    assert!(hits[0].score > hits[1].score);}/// During a model change the table holds two generations at once, and vectors/// from different geometries are not comparable. That filter is the SQL's, and/// this is the assertion that it is IN the SQL — the Rust scan deliberately/// does not re-apply it, because the row struct carries no `model` and so/// cannot.#[test]fn ignores_every_vector_of_another_generation() {    let query = quantised(&vector_of(1));    let (sql, params) = embeddings_scan_query(&options(&query, None)).expect("a query");    assert!(sql.contains("WHERE model = ?"), "{sql}");    assert_eq!(params, [MODEL]);    assert!(EmbeddingChunkRow {        source: String::new(),        row_id: String::new(),        chunk_ix: 0,        vec: Vec::new(),        text_head: None,    }    .vec    .is_empty());}#[test]fn drops_everything_under_the_floor_rather_than_answering_with_noise() {    let query = vector_of(1);    let rows = [row("note", "unrelated", &vector_of(999))];    let query_bytes = quantised(&query);    assert_eq!(        semantic_chunk_scan(&rows, &options(&query_bytes, Some(0.9))),        Ok(Vec::new())    );}#[test]fn refuses_a_query_vector_that_is_not_512_bytes() {    let short = [0_u8; 8];    let err = semantic_chunk_scan(&[], &options(&short, None)).unwrap_err();    assert_eq!(err, SemanticLaneError::QueryVectorBytes(8));    assert_eq!(        err.to_string(),        "semantic query vector is 8 bytes, expected 512"    );}/// A caller that names no sources at all asked for nothing, and gets nothing —/// distinct from `None`, which is every source. The TypeScript decides this/// BEFORE the presence check, which is why it is decided here before the rows/// are looked at.#[test]fn an_explicitly_empty_source_list_asks_for_nothing_and_runs_no_query() {    let query = quantised(&vector_of(1));    let empty: [String; 0] = [];    let asked = SemanticScanOptions {        sources: Some(&empty),        ..options(&query, Some(-1.0))    };    assert!(embeddings_scan_query(&asked).is_none());    let rows = [row("note", "n1", &vector_of(1))];    assert_eq!(semantic_chunk_scan(&rows, &asked), Ok(Vec::new()));}/// A row whose blob is the wrong length is skipped, not scored and not fatal.#[test]fn steps_over_a_corrupt_row_rather_than_losing_the_whole_search() {    let query = vector_of(1);    let mut broken = row("note", "corrupt", &vector_of(2));    broken.vec.truncate(200);    let rows = [broken, row("note", "good", &query)];    let query_bytes = quantised(&query);    let hits =        semantic_chunk_scan(&rows, &options(&query_bytes, Some(-1.0))).expect("a 512-byte query");    assert_eq!(        hits.iter()            .map(|hit| hit.row_id.as_str())            .collect::<Vec<_>>(),        ["good"]    );}/// `text_head` is nullable in the schema; the TypeScript's/// `typeof … === "string" ? … : ""` becomes an empty string here too, so a/// renderer never has to ask.#[test]fn a_null_text_head_reads_as_an_empty_string() {    let query = vector_of(1);    let mut without = row("note", "n1", &query);    without.text_head = None;    let query_bytes = quantised(&query);    let hits = semantic_chunk_scan(&[without], &options(&query_bytes, Some(-1.0)))        .expect("a 512-byte query");    assert_eq!(hits[0].text_head, "");}/// Sources come back in the order the scan MET them, each already ranked. An/// insertion-ordered `Vec` rather than a `HashMap`, because a hasher's seed/// must not be what decides which kind a reader sees first.#[test]fn hands_the_sources_back_in_the_order_the_scan_met_them() {    let query = vector_of(1);    let rows = [        row("note", "n1", &query),        row("person", "p1", &query),        row("note", "n2", &blend(&query, &vector_of(700), 0.1)),    ];    let query_bytes = quantised(&query);    let hits =        semantic_chunk_scan(&rows, &options(&query_bytes, Some(-1.0))).expect("a 512-byte query");    assert_eq!(        hits.iter()            .map(|hit| hit.source.as_str())            .collect::<Vec<_>>(),        ["note", "note", "person"]    );}#[test]fn a_per_source_of_zero_still_keeps_one() {    let query = vector_of(1);    let rows = [row("note", "n1", &query), row("note", "n2", &query)];    let query_bytes = quantised(&query);    let hits = semantic_chunk_scan(        &rows,        &SemanticScanOptions {            per_source: Some(0),            ..options(&query_bytes, Some(-1.0))        },    )    .expect("a 512-byte query");    assert_eq!(hits.len(), 1);}// ── vectors read out of Node ─────────────────────────────────────────────────/// The SQL the running TypeScript issued to a recording driver, captured for/// four source shapes. Whitespace included: it is the statement byte for byte,/// so a caller comparing an EXPLAIN plan or a query log against this crate sees/// the same text.#[test]fn the_scan_query_is_the_statement_the_typescript_issues() {    let query = quantised(&vector_of(1));    let base = "SELECT source, row_id, chunk_ix, vec, text_head\n       FROM _embeddings\n      WHERE model = ?";    let none = embeddings_scan_query(&options(&query, None)).expect("a query");    assert_eq!(none.0, base);    assert_eq!(none.1, [MODEL]);    let one_source = [String::from("note")];    let one = embeddings_scan_query(&SemanticScanOptions {        sources: Some(&one_source),        ..options(&query, None)    })    .expect("a query");    assert_eq!(one.0, format!("{base} AND source IN (?)"));    assert_eq!(one.1, [MODEL, "note"]);    // `[...new Set(sources)]` — a source named twice binds ONE placeholder.    let repeated = [        String::from("note"),        String::from("message"),        String::from("note"),    ];    let deduped = embeddings_scan_query(&SemanticScanOptions {        sources: Some(&repeated),        ..options(&query, None)    })    .expect("a query");    assert_eq!(deduped.0, format!("{base} AND source IN (?, ?)"));    assert_eq!(deduped.1, [MODEL, "note", "message"]);    let four = [        String::from("a"),        String::from("b"),        String::from("c"),        String::from("d"),    ];    let many = embeddings_scan_query(&SemanticScanOptions {        sources: Some(&four),        ..options(&query, None)    })    .expect("a query");    assert_eq!(many.0, format!("{base} AND source IN (?, ?, ?, ?)"));    assert_eq!(many.1, [MODEL, "a", "b", "c", "d"]);}/// The test file's own generator, proven to be the same one: the first eight/// quantised bytes of six seeds, read out of Node. If `i64` had lost a bit/// where a JavaScript double did not, this is where it would show.#[test]fn fixture_generator_matches_nodes() {    let vectors: &[(i64, [i8; 8])] = &[        (1, [-5, 7, 0, 5, -2, 6, 4, 5]),        (2, [-1, 4, -9, 1, 5, 3, -1, 1]),        (3, [4, 1, 1, -3, -7, 0, -7, -3]),        (9, [-7, 3, 5, -10, -3, 0, 0, -9]),        (100, [4, -6, 0, 9, -6, -7, -9, -8]),        (999, [8, -9, 1, 5, -1, 3, 7, -5]),    ];    for (seed, expected) in vectors {        let bytes = quantised(&vector_of(*seed));        let head: Vec<i8> = bytes[..8].iter().map(|byte| *byte as i8).collect();        assert_eq!(head, expected, "for seed {seed}");    }}/// Nine cosine readings from Node, to the last bit. `quantized_cosine` sums in/// `i64` where the TypeScript sums in a `number`; every partial sum is an exact/// integer well under 2^53, so the two are bit-identical, and these are the/// proof.#[test]fn quantized_cosine_vectors_read_out_of_node() {    let vectors: &[(i64, i64, f64, f64)] = &[        (1, 100, 0.0, 0.995_721_991_443_982_9),        (1, 100, 0.02, 0.995_349_990_699_981_4),        (1, 100, 0.1, 0.991_257_982_515_965_1),        (1, 100, 0.5, 0.711_451_422_902_845_8),        (1, 100, 1.0, -0.032_798_065_596_131_194),        (3, 200, 0.25, 0.945_501_891_003_782),        (9, 999, 0.75, 0.288_610_577_221_154_46),    ];    for (seed_a, seed_b, mix, expected) in vectors {        let a = vector_of(*seed_a);        let b = if *mix == 0.0 {            a.clone()        } else {            blend(&a, &vector_of(*seed_b), *mix)        };        let left = quantised(&a);        let right = quantised(&b);        assert_eq!(            quantized_cosine(                as_stored_vector(&left).expect("512 bytes"),                as_stored_vector(&right).expect("512 bytes")            ),            *expected,            "for {seed_a}/{seed_b} at {mix}"        );    }    let values = vector_of(9);    let self_bytes = quantised(&values);    let negated: Vec<f64> = values.iter().map(|v| -v).collect();    let flipped = quantised(&negated);    let selff = as_stored_vector(&self_bytes).expect("512 bytes");    assert_eq!(quantized_cosine(selff, selff), 0.997_705_995_411_990_8);    assert_eq!(        quantized_cosine(selff, as_stored_vector(&flipped).expect("512 bytes")),        -0.997_705_995_411_990_8    );}#[test]fn the_declared_constants_are_the_typescripts() {    assert_eq!(EMBED_DOT_SCALE, 16129.0);    assert_eq!(SEMANTIC_MIN_SCORE, 0.28);    assert_eq!(SEMANTIC_PER_SOURCE_DEFAULT, 20);    assert_eq!(        EMBEDDINGS_SCAN_COLUMNS,        ["source", "row_id", "chunk_ix", "vec", "text_head"]    );}/// The hit shape is a wire shape: the TypeScript's object is camelCase and a/// server handing one to the app must not rename a field on the way.#[test]fn a_hit_serialises_the_typescripts_own_keys() {    let hit = SemanticChunkHit {        source: "note".into(),        row_id: "n1".into(),        chunk_ix: 2,        score: 0.5,        text_head: "prose".into(),    };    assert_eq!(        serde_json::to_string(&hit).unwrap(),        r#"{"source":"note","rowId":"n1","chunkIx":2,"score":0.5,"textHead":"prose"}"#    );}