cache.embedding_cache

chunktuner.cache.embedding_cache

SQLite-backed embedding cache (SHA256 key).

EmbeddingCache

EmbeddingCache(db_path, model)

Persistent cache: SHA256(model + '|' + text) → float vector.

Source code in src/chunktuner/cache/embedding_cache.py
def __init__(self, db_path: Path, model: str):
    self.db_path = Path(db_path).resolve()
    self.model = model
    self.db_path.parent.mkdir(parents=True, exist_ok=True)
    self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
    self._conn.execute("PRAGMA journal_mode=WAL")
    self._conn.execute(
        """
        CREATE TABLE IF NOT EXISTS embeddings (
            k TEXT PRIMARY KEY,
            dim INTEGER NOT NULL,
            vec BLOB NOT NULL,
            model TEXT
        )
        """
    )
    # Migrate pre-0.3 tables (no ``model`` column); legacy rows keep ``model`` NULL.
    cols = {row[1] for row in self._conn.execute("PRAGMA table_info(embeddings)")}
    if "model" not in cols:
        self._conn.execute("ALTER TABLE embeddings ADD COLUMN model TEXT")
    self._conn.commit()

clear

clear(model=None)

Delete all rows, or only rows written for model.

Rows from older versions have no recorded model and are only removed by clear().

Source code in src/chunktuner/cache/embedding_cache.py
def clear(self, model: str | None = None) -> None:
    """Delete all rows, or only rows written for ``model``.

    Rows from older versions have no recorded model and are only removed by ``clear()``.
    """
    if model is None:
        self._conn.execute("DELETE FROM embeddings")
    else:
        self._conn.execute("DELETE FROM embeddings WHERE model = ?", (model,))
    self._conn.commit()

stats

stats(model=None)

Row count and approximate size for all rows, or only rows written for model.

Source code in src/chunktuner/cache/embedding_cache.py
def stats(self, model: str | None = None) -> dict:
    """Row count and approximate size for all rows, or only rows written for ``model``."""
    sql = "SELECT COUNT(*), COALESCE(SUM(LENGTH(vec)+32),0) FROM embeddings"
    if model is None:
        row = self._conn.execute(sql).fetchone()
    else:
        row = self._conn.execute(sql + " WHERE model = ?", (model,)).fetchone()
    return {"rows": int(row[0] or 0), "approx_bytes": int(row[1] or 0)}