Cotton code
315 lines · 14.3 KB · RustRaw
//! The meaning lane's scan — the dot product, and the top-k heap per source.//! The port of `packages/core/src/engine/semanticLane.ts`.//!//! [`crate::transforms::quantize`] is the FORMAT — floats in, bytes out. This is//! the SCAN. Both halves of the comparison were unit-normalised before//! quantisation, so cosine similarity is the plain integer dot product//! `Σ qᵢ·dᵢ` — no division, no stored norm, no float column — and dividing once//! at the end by `127²` puts the answer back on the −1…1 scale a reader//! expects.//!//! NO NATIVE SQLITE EXTENSION, EVER (D8). There is no `sqlite-vec`, no `vec0`//! virtual table and no compile flag; the scan is a loop over a byte slice,//! which at personal scale (~60k chunks, ~30M multiply-adds) costs tens of//! milliseconds — the same order as the network round-trip that had to embed//! the query before this function could be called at all. The repo has already//! paid for the alternative once: a native SQLite compile flag in the wrong//! manifest held the owner's phone on the splash for two TestFlight builds.//! Guarded by `crates/cotton-server/tests/it/embed.rs`.//!//! # What changed in the port, and why//!//! The TypeScript takes a `SqlDriver` and issues two statements. This crate//! opens no database — so the split is: the caller runs the SQL, this module//! owns everything the SQL cannot decide. To keep the query from being//! re-derived at each call site (which is how a `model` filter goes missing and//! two generations of vectors get compared), the two statements are declared//! HERE — [`EMBEDDINGS_PRESENT_SQL`] and [`embeddings_scan_query`] — and pinned//! by vectors captured from the running TypeScript.//!//! [`semantic_chunk_scan`] therefore does NOT re-apply the `model` or `source`//! filter: the TypeScript's in-memory loop does not either, because the `WHERE`//! already did it. Feed it the rows [`embeddings_scan_query`] asked for and the//! two answer identically; feed it rows from a query of your own and you are//! the one holding the generation rule. `EmbeddingChunkRow` carries exactly the//! five columns the SELECT list names, and no `model`, so the temptation to//! filter twice is not expressible.use serde::{Deserialize, Serialize};use crate::transforms::quantize::{EMBED_QUANTIZE_SCALE, EMBED_VECTOR_BYTES};/// The largest an int8 dot product component can be — `127 × 127`.////// Dividing the summed dot product by this is the ONLY division in the scan,/// and it is what turns an integer nobody can read into the cosine similarity/// every caller thresholds on.pub const EMBED_DOT_SCALE: f64 = EMBED_QUANTIZE_SCALE * EMBED_QUANTIZE_SCALE;/// How many chunks one source keeps, before the caller's own cap.pub const SEMANTIC_PER_SOURCE_DEFAULT: usize = 20;/// The floor a chunk must clear to be called a hit at all.////// A brute-force scan ALWAYS returns something: every vector has some cosine/// with every other, so a top-k with no floor answers a query about nothing/// with twenty confident-looking rows. `text-embedding-3-small` puts unrelated/// short English text somewhere around 0.1–0.2, and genuinely related text well/// above 0.3. This is a quality floor, not a correctness one, and a caller that/// wants every neighbour passes its own.pub const SEMANTIC_MIN_SCORE: f64 = 0.28;/// Is `_embeddings` in this file at all?////// Asked by every reader, and the answer is usually no: the tables are created/// by the SERVER's indexer on first use, only after the owner turned the switch/// on, and a workspace that never did has neither. **Looking at a database must/// never be what brings a table into being**, which is why this is a `SELECT`/// against `sqlite_master` and not a `CREATE TABLE IF NOT EXISTS` — the lane/// answers empty rather than calling the indexer's `ensureEmbedTables`.////// One row back means present; no row means absent, and the lane's answer is an/// empty result rather than an error.pub const EMBEDDINGS_PRESENT_SQL: &str =    "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_embeddings'";/// One chunk the scan kept — a fragment of a row, not the row itself.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SemanticChunkHit {    /// The `_embeddings.source` this chunk came from — the partition.    pub source: String,    /// The DOMAIN row's own id, as the indexer stamped it.    pub row_id: String,    /// 0-based within the row.    pub chunk_ix: i64,    /// Cosine similarity, −1…1. Bigger is closer.    pub score: f64,    /// The first ~160 characters of the chunk — the lane's only snippet.    pub text_head: String,}/// One `_embeddings` row as [`embeddings_scan_query`] selects it — those five/// columns, in that order, and nothing else.#[derive(Debug, Clone, PartialEq, Eq)]pub struct EmbeddingChunkRow {    pub source: String,    /// The TypeScript coerces with `String(row.row_id)` because SQLite will    /// hand back an integer for a numeric-looking id; a Rust caller does that    /// coercion at its own row boundary.    pub row_id: String,    pub chunk_ix: i64,    /// The stored blob. A row whose `vec` is NULL, or is not    /// [`EMBED_VECTOR_BYTES`] long, is SKIPPED rather than scored — one corrupt    /// row must not take down a search over sixty thousand good ones — so the    /// caller maps a NULL column to an empty vector and the length check does    /// the rest.    pub vec: Vec<u8>,    /// `text_head` is nullable in the schema; the TypeScript guards with    /// `typeof row.text_head === "string" ? … : ""`, which `Option` says    /// directly.    pub text_head: Option<String>,}/// What the caller asks the lane for.#[derive(Debug, Clone)]pub struct SemanticScanOptions<'a> {    /// The QUERY vector, quantised exactly as the stored ones were    /// ([`crate::transforms::quantize::quantize_embedding`]). Passed in rather than    /// embedded here on purpose: turning text into a vector is a network    /// round-trip to a third party, and this engine is pure and synchronous    /// like everything beside it.    pub vector: &'a [u8],    /// The generation to compare against — `_embed_state.active_model`, never    /// the model this server would index with today. During a model change the    /// table holds two generations at once and vectors from different    /// geometries are not comparable.    pub model: &'a str,    /// Restrict to these `_embeddings.source` values. `None` for every source.    pub sources: Option<&'a [String]>,    /// Chunks kept PER SOURCE (default [`SEMANTIC_PER_SOURCE_DEFAULT`]).    pub per_source: Option<usize>,    /// Minimum cosine similarity (default [`SEMANTIC_MIN_SCORE`]).    pub min_score: Option<f64>,}/// Why the lane refused. `Display` is the TypeScript's thrown sentence/// verbatim, so a handler can pass it to the error envelope unchanged.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum SemanticLaneError {    #[error("semantic query vector is {0} bytes, expected 512")]    QueryVectorBytes(usize),}/// The statement and bound parameters that fetch the rows/// [`semantic_chunk_scan`] scans.////// `None` means "do not run a query at all, the answer is empty" — the/// TypeScript's `if (sources && sources.length === 0) return []`, which fires/// BEFORE the presence check because an explicit empty source list is a caller/// that asked for nothing rather than a database that holds nothing.////// Sources are deduped keeping first-appearance order (`[...new Set(sources)]`)/// so a caller that names one twice binds one placeholder, not two.pub fn embeddings_scan_query(options: &SemanticScanOptions<'_>) -> Option<(String, Vec<String>)> {    let sources: Option<Vec<&str>> = options.sources.map(|sources| {        let mut unique: Vec<&str> = Vec::new();        for source in sources {            if !unique.contains(&source.as_str()) {                unique.push(source);            }        }        unique    });    if sources.as_ref().is_some_and(|unique| unique.is_empty()) {        return None;    }    let filter = match &sources {        None => String::new(),        Some(unique) => format!(" AND source IN ({})", vec!["?"; unique.len()].join(", ")),    };    let sql = format!(        "SELECT source, row_id, chunk_ix, vec, text_head\n       FROM _embeddings\n      WHERE model = ?{filter}"    );    let mut params = vec![options.model.to_string()];    if let Some(unique) = sources {        params.extend(unique.into_iter().map(str::to_string));    }    Some((sql, params))}/// A stored `vec` BLOB as the bytes it is, or `None` when it is not one.////// The TypeScript's `byteOffset` care has no Rust analogue and needs none: a/// `&[u8]` carries its own start, where a Node `Buffer` is a view into a shared/// allocation pool and `new Int8Array(buf.buffer)` would read from the START of/// that pool — scoring a neighbouring row's bytes as this row's vector,/// silently and with plausible numbers. The Rust type makes that mistake/// unspellable; the test that pinned it is ported anyway, as a sub-slice of a/// larger buffer scoring identically.////// A wrong-length blob answers `None` rather than failing: one corrupt row must/// not take down a search over sixty thousand good ones. The TypeScript's/// "value is not bytes at all" case (`ArrayBuffer.isView`) is the type here.////// The bytes are SIGNED — `-1` is stored as `0xFF` — and the sign is applied at/// the multiply, exactly as [`crate::transforms::quantize::dequantize_embedding`]/// does. Returning `&[u8]` keeps the module free of `unsafe`.pub fn as_stored_vector(value: &[u8]) -> Option<&[u8]> {    (value.len() == EMBED_VECTOR_BYTES).then_some(value)}/// Cosine similarity between two quantised unit vectors.////// Both were L2-normalised before quantisation, so this is the dot product and/// nothing else. The accumulation is exact: the maximum magnitude is/// `512 × 127²` ≈ 8.3M, nowhere near either integer ceiling, so summing in/// `i64` and dividing once in `f64` is bit-for-bit what the TypeScript's/// number-typed accumulator produces.////// Both slices are [`EMBED_VECTOR_BYTES`] long by the time they get here/// ([`as_stored_vector`] is the gate on each); `zip` is the faithful reading of/// the TypeScript's `for (i < query.length)` over two equal-length arrays.pub fn quantized_cosine(query: &[u8], stored: &[u8]) -> f64 {    let mut dot: i64 = 0;    for (q, d) in query.iter().zip(stored) {        dot += i64::from(*q as i8) * i64::from(*d as i8);    }    dot as f64 / EMBED_DOT_SCALE}/// Every chunk in the file that means what was asked, best first, capped PER/// SOURCE.////// The cap is per source rather than overall because that is where "ranked/// within a kind and never across kinds" comes from — the engine's oldest rule/// falls out of the partition instead of being imposed on the result. One/// conversation's forty near-identical messages cannot crowd out the note that/// answers the question, because the two are not competing for the same slots.////// Brute force, one pass, no index beyond `idx_embeddings_model_source` doing/// the `WHERE`. The keep-list per source is a bounded insertion sort rather/// than a heap: k is at most a few dozen, the comparison against the current/// floor rejects almost every row in one branch, and a sorted array hands back/// a ranked answer with no drain step.////// Returns an empty vector rather than an error when there are no rows — the/// absent-table case, which is the ordinary state of a database whose owner/// never turned this on.////// Sources come back in the order the scan MET them (the TypeScript's `Map`/// insertion order), each already ranked — the caller groups by kind and never/// sorts across sources. An insertion-ordered `Vec` rather than a `HashMap`,/// because a hasher's seed must not be what decides which kind a reader sees/// first.pub fn semantic_chunk_scan(    rows: &[EmbeddingChunkRow],    options: &SemanticScanOptions<'_>,) -> Result<Vec<SemanticChunkHit>, SemanticLaneError> {    let Some(query) = as_stored_vector(options.vector) else {        return Err(SemanticLaneError::QueryVectorBytes(options.vector.len()));    };    if embeddings_scan_query(options).is_none() {        return Ok(Vec::new());    }    let per_source = options        .per_source        .unwrap_or(SEMANTIC_PER_SOURCE_DEFAULT)        .max(1);    let min_score = options.min_score.unwrap_or(SEMANTIC_MIN_SCORE);    let mut kept: Vec<(String, Vec<SemanticChunkHit>)> = Vec::new();    for row in rows {        let Some(stored) = as_stored_vector(&row.vec) else {            continue;        };        let score = quantized_cosine(query, stored);        if score < min_score {            continue;        }        let lane = match kept.iter().position(|(source, _)| *source == row.source) {            Some(at) => &mut kept[at].1,            None => {                kept.push((row.source.clone(), Vec::new()));                &mut kept.last_mut().expect("just pushed").1            }        };        // The floor test first: past the first `per_source` rows this rejects        // the overwhelming majority in one comparison, which is what keeps a        // scan of sixty thousand chunks a scan rather than sixty thousand        // insertions.        if lane.len() >= per_source && score <= lane[lane.len() - 1].score {            continue;        }        let hit = SemanticChunkHit {            source: row.source.clone(),            row_id: row.row_id.clone(),            chunk_ix: row.chunk_ix,            score,            text_head: row.text_head.clone().unwrap_or_default(),        };        let mut at = lane.len();        while at > 0 && lane[at - 1].score < score {            at -= 1;        }        lane.insert(at, hit);        if lane.len() > per_source {            lane.pop();        }    }    Ok(kept.into_iter().flat_map(|(_, lane)| lane).collect())}/// The `_embeddings` SELECT list, in order — the one place the scan's column/// order is written down, so a caller building [`EmbeddingChunkRow`]s from a/// driver's positional results cannot transpose two of them.pub const EMBEDDINGS_SCAN_COLUMNS: [&str; 5] = ["source", "row_id", "chunk_ix", "vec", "text_head"];#[cfg(test)]#[path = "semantic_lane_tests.rs"]mod tests;