Cotton code
260 lines · 10.2 KB · RustRaw
//! `_embeddings` and `_embed_state` — the two server-local tables, and the//! bookkeeping the indexer keeps in the second one.//!//! Both tables carry a leading underscore and are created here with//! `CREATE TABLE IF NOT EXISTS`, exactly like `_ai_logs`, `_devices` and the//! rest — so there is no `MIGRATIONS` entry, no `SCHEMA_VERSION` bump and no//! adopt entry owed for them: the op fold cannot see them and the outbox cannot//! queue them.//!//! WHY THE DDL IS HERE AND NOT IN `cotton-store`. In the TypeScript it sat in//! the store package beside the format it describes, because the PHONE's//! chunker shares that file. Nothing on this side of the port has a second//! reader: the vectors are written by this server's indexer and read by this//! server's lane, and the brief's rule for a server-local `_` table is that the//! worker creates it on first use exactly as the TypeScript's `ensure*` did.//! If a Rust phone ever grows a reader, this constant moves to `cotton-store`//! and this module imports it — one declaration either way.use cotton_store::driver::Driver;use cotton_store::Result;use rusqlite::types::Value as SqlValue;use cotton_core::rules::chunk::EMBED_SOURCES;/// The two tables, created by the server on first use (D3, D7).////// Issued with `CREATE TABLE IF NOT EXISTS`, so this list is the ONE statement/// of their shape — and because `IF NOT EXISTS` adds no column to a table that/// already exists, a later widening of either table is a real job (drop and/// rebuild, or an explicit ALTER), not an edit to this array.pub const EMBEDDINGS_DDL: &[&str] = &[    r#"CREATE TABLE IF NOT EXISTS _embeddings (     source      TEXT NOT NULL,     row_id      TEXT NOT NULL,     chunk_ix    INTEGER NOT NULL,     model       TEXT NOT NULL,     content_sha TEXT NOT NULL,     vec         BLOB NOT NULL,     text_head   TEXT NOT NULL,     created_at  TEXT NOT NULL,     PRIMARY KEY (source, row_id, chunk_ix, model)   )"#,    // The lane's own query: `WHERE model = ? AND source IN (…)`.    "CREATE INDEX IF NOT EXISTS idx_embeddings_model_source ON _embeddings (model, source)",    // The indexer's: every chunk of one row, to compare content_sha and to    // delete an orphan whose domain row is gone.    "CREATE INDEX IF NOT EXISTS idx_embeddings_row ON _embeddings (source, row_id)",    r#"CREATE TABLE IF NOT EXISTS _embed_state (     source          TEXT PRIMARY KEY,     cursor          TEXT,     last_full_at    TEXT,     failures        INTEGER NOT NULL DEFAULT 0,     next_attempt_at TEXT,     last_error      TEXT,     active_model    TEXT,     building_model  TEXT   )"#,];/// One `_embed_state` row, as the indexer and `GET /v1/search/status` read it.////// `active_model` is what the lane answers on; `building_model` is the/// generation being filled in behind it (D14). They are per-SOURCE columns/// because every other column here already is, but the indexer moves them/// together — a lane that answered half on one model and half on another would/// be comparing vectors from two different geometries.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct EmbedSourceState {    pub source: String,    pub cursor: Option<String>,    pub last_full_at: Option<String>,    pub failures: i64,    pub next_attempt_at: Option<String>,    pub last_error: Option<String>,    pub active_model: Option<String>,    pub building_model: Option<String>,}fn empty_state(source: &str) -> EmbedSourceState {    EmbedSourceState {        source: source.to_string(),        ..EmbedSourceState::default()    }}fn to_state(row: &cotton_store::driver::Row) -> EmbedSourceState {    EmbedSourceState {        source: row.text("source").unwrap_or_default().to_string(),        cursor: row.text("cursor").map(str::to_string),        last_full_at: row.text("last_full_at").map(str::to_string),        failures: row.int("failures").unwrap_or(0),        next_attempt_at: row.text("next_attempt_at").map(str::to_string),        last_error: row.text("last_error").map(str::to_string),        active_model: row.text("active_model").map(str::to_string),        building_model: row.text("building_model").map(str::to_string),    }}/// Are the two tables in this file?////// Asked rather than assumed by every READER — `GET /v1/search/status` on a/// workspace that has never turned the switch on must answer "nothing indexed"/// without creating a table as a side effect of being looked at. Only/// [`ensure_embed_tables`] creates, and only the indexer calls it.pub fn embed_tables_present(db: &Driver) -> bool {    db.get(        "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_embeddings'",        &[],    )    .ok()    .flatten()    .is_some()}/// Every source's state, defaulted for the sources that have no row yet.pub fn read_embed_state(db: &Driver) -> Vec<EmbedSourceState> {    if !embed_tables_present(db) {        return EMBED_SOURCES            .iter()            .map(|source| empty_state(source.source))            .collect();    }    let rows = db        .all("SELECT * FROM _embed_state", &[])        .unwrap_or_default();    EMBED_SOURCES        .iter()        .map(|source| {            rows.iter()                .find(|row| row.text("source") == Some(source.source))                .map(to_state)                .unwrap_or_else(|| empty_state(source.source))        })        .collect()}pub fn read_source_state(db: &Driver, source: &str) -> EmbedSourceState {    db.get(        "SELECT * FROM _embed_state WHERE source = ?",        &[SqlValue::Text(source.to_string())],    )    .ok()    .flatten()    .map(|row| to_state(&row))    .unwrap_or_else(|| empty_state(source))}/// The generation the meaning lane answers on — `None` before the first pass.////// The indexer moves `active_model` across every source together, so the first/// source's column speaks for the table. Declared ONCE here rather than/// restated at each reader: `GET /v1/search/status` and the query lane must/// agree on what "the current generation" means, and two copies of "read/// source[0]" is how they would eventually stop agreeing.////// `None` is the honest answer before anything is indexed. It is NOT the pinned/// model id: "this server would index with this model" is not "these vectors/// exist".pub fn active_embed_model(db: &Driver) -> Option<String> {    read_embed_state(db)        .into_iter()        .next()        .and_then(|state| state.active_model)}/// The columns a patch may name. Every field is `Option`: absent means "leave/// this column alone", which is not the same as writing NULL — hence the double/// option on the three nullable columns the failure path clears.#[derive(Debug, Clone, Default)]pub struct SourceStatePatch {    pub cursor: Option<Option<String>>,    pub last_full_at: Option<Option<String>>,    pub failures: Option<i64>,    pub next_attempt_at: Option<Option<String>>,    pub last_error: Option<Option<String>>,    pub active_model: Option<Option<String>>,    pub building_model: Option<Option<String>>,}fn nullable(value: &Option<Option<String>>) -> Option<SqlValue> {    value.as_ref().map(|inner| match inner {        Some(text) => SqlValue::Text(text.clone()),        None => SqlValue::Null,    })}/// Upsert the columns named, leaving the rest of the row alone.////// A patch rather than a whole-row write because the two halves of this row/// have different owners and different clocks: the scan advances `cursor` and/// `last_full_at`, the failure path owns `failures` / `next_attempt_at` //// `last_error`, and D14's flip owns the two model columns. A whole-row write/// from any one of them would clobber whichever of the others ran last.////// The INSERT always supplies `failures` (defaulting to 0) while the UPDATE/// only assigns the named columns — the TypeScript's own shape, kept: a fresh/// row needs the `NOT NULL` column filled, and an existing row's failure count/// is not this patch's to reset unless it said so.pub fn patch_source_state(db: &Driver, source: &str, patch: &SourceStatePatch) -> Result<()> {    let mut names: Vec<&str> = Vec::new();    let mut values: Vec<SqlValue> = Vec::new();    let mut push = |name: &'static str, value: Option<SqlValue>| {        if let Some(value) = value {            names.push(name);            values.push(value);        }    };    push("cursor", nullable(&patch.cursor));    push("last_full_at", nullable(&patch.last_full_at));    push("failures", patch.failures.map(SqlValue::Integer));    push("next_attempt_at", nullable(&patch.next_attempt_at));    push("last_error", nullable(&patch.last_error));    push("active_model", nullable(&patch.active_model));    push("building_model", nullable(&patch.building_model));    if names.is_empty() {        return Ok(());    }    let assignments = names        .iter()        .map(|name| format!("{name} = excluded.{name}"))        .collect::<Vec<_>>()        .join(", ");    let placeholders = names.iter().map(|_| "?").collect::<Vec<_>>().join(", ");    let columns = names.join(", ");    let mut params = vec![        SqlValue::Text(source.to_string()),        SqlValue::Integer(patch.failures.unwrap_or(0)),    ];    params.extend(values);    db.run(        &format!(            "INSERT INTO _embed_state (source, failures, {columns})               VALUES (?, ?, {placeholders})             ON CONFLICT(source) DO UPDATE SET {assignments}"        ),        &params,    )?;    Ok(())}/// `String.prototype.slice(0, n)` counts UTF-16 code units; a Rust byte slice/// would panic on a multi-byte boundary. Chars are the nearest honest cut for a/// message a person reads, and the column is server-local text.pub fn clip(text: &str, limit: usize) -> String {    text.chars().take(limit).collect()}/// Every vector this row holds at this model, gone — the row lost its text.pub fn delete_row_vectors(db: &Driver, source: &str, row_id: &str, model: &str) -> Result<()> {    db.run(        "DELETE FROM _embeddings WHERE source = ? AND row_id = ? AND model = ?",        &[            SqlValue::Text(source.to_string()),            SqlValue::Text(row_id.to_string()),            SqlValue::Text(model.to_string()),        ],    )?;    Ok(())}