second-brain-core 0.13.3

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
use anyhow::Result;
use chrono::Utc;
use rusqlite::{OptionalExtension, Transaction, params};
use serde::Serialize;
use uuid::Uuid;

use super::SqliteStore;
use super::delete::DeleteScope;

/// One delete run on this store, and how far each floor neighbour has
/// acknowledged this store's log past it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DeleteStatus {
    pub id: Uuid,
    pub scope: String,
    pub target: String,
    /// The highest log seq the delete's tombstones took.
    pub seq: u64,
    /// Wall-clock µs.
    pub deleted_at: i64,
    pub peers: Vec<PeerDeleteAck>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PeerDeleteAck {
    pub peer_id: String,
    pub acked_seq: Option<u64>,
    /// The peer acknowledged this store's log at or past the delete's seq,
    /// so it holds the tombstones.
    pub acked: bool,
    pub live: bool,
}

impl SqliteStore {
    /// The delete `key` names, by its id or, newest first, by its target.
    pub fn delete_status(&self, key: &str) -> Result<Option<DeleteStatus>> {
        let row: Option<(String, String, String, i64, i64)> = self
            .reader()
            .query_row(
                "SELECT id, scope, target, seq, deleted_at FROM deletes \
                 WHERE id = ?1 OR target = ?1 ORDER BY id = ?1 DESC, deleted_at DESC LIMIT 1",
                params![key],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
            )
            .optional()?;
        let Some((id, scope, target, seq, deleted_at)) = row else {
            return Ok(None);
        };
        let seq = u64::try_from(seq)?;
        let peers = self
            .peer_acks()?
            .into_iter()
            .map(|ack| PeerDeleteAck {
                acked: ack.acked_seq.is_some_and(|acked| acked >= seq),
                peer_id: ack.peer_id,
                acked_seq: ack.acked_seq,
                live: ack.live,
            })
            .collect();
        Ok(Some(DeleteStatus {
            id: Uuid::parse_str(&id)?,
            scope,
            target,
            seq,
            deleted_at,
            peers,
        }))
    }
}

/// Records a delete that logged its tombstones in `tx`, at the log's head.
pub(super) fn record(tx: &Transaction<'_>, scope: &DeleteScope) -> Result<(Uuid, u64)> {
    let (name, target) = match scope {
        DeleteScope::Memory(id) => ("memory", id.to_string()),
        DeleteScope::Session(key) => ("session", key.clone()),
        DeleteScope::Project(path) => ("project", path.clone()),
    };
    let seq: i64 = tx.query_row(
        "SELECT COALESCE(MAX(local_seq), 0) FROM sync_log",
        [],
        |r| r.get(0),
    )?;
    let id = Uuid::new_v4();
    tx.execute(
        "INSERT INTO deletes (id, scope, target, seq, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5)",
        params![
            id.to_string(),
            name,
            target,
            seq,
            Utc::now().timestamp_micros()
        ],
    )?;
    Ok((id, u64::try_from(seq)?))
}