Volver al blog
SQLite para agentes de IA: vectores, memoria y los límites que nadie mide

SQLite para agentes de IA: vectores, memoria y los límites que nadie mide

Every agent ends at the same question: where does the memory live? SQLite answers with one file — copyable, inspectable from a CLI, no server. What it does not answer cleanly is vector search. The extension everyone cites sits at v0.1.9, still brute force and still pre-1.0 as of 2026-10-28, while the developments that matter landed elsewhere: SQLite shipped its own ANN index, and the fix for single-writer contention arrived as a VFS, not a fork.

Todo agente acaba preguntando dónde vive la memoria. SQLite responde con un archivo, copiable e inspeccionable desde la CLI. Lo que no resuelve igual de bien es el vector search: la extensión que todos citan sigue en la v0.1.9, en fuerza bruta y por debajo de 1.0 a 2026-10-28, mientras los avances que importan llegaron por otro lado: SQLite publicó su propio índice ANN y la contención de escritor se resolvió como VFS, no como fork.

sqlite-vec Is Still Pre-1.0, and Still Brute Force

sqlite-vec sigue por debajo de 1.0 y sigue en fuerza bruta

sqlite-vec (Alex Garcia, asg017; 8,224 stars; Apache-2.0/MIT dual) is the default recommendation and it is unfinished. Stable is v0.1.9 (2026-03-31), a fix for DELETEs on long-text metadata. The real work sits in v0.1.10-alpha.4 (2026-05-18), which PyPI and npm do not resolve to, and the README carries a pre-v1 warning. ANN landed on 2026-03-31 in alpha.1 as rescore (quantized scan plus float rerank), ivf (experimental, compiled out by default), and diskann.

sqlite-vec (Alex Garcia, asg017; 8,224 estrellas; Apache-2.0/MIT) es la recomendación por defecto y no está terminado: la estable es la v0.1.9 (2026-03-31), un arreglo de DELETE sobre metadatos de texto largo. El trabajo real está en la v0.1.10-alpha.4 (2026-05-18), a la que PyPI y npm no apuntan, con aviso pre-v1 en el README. El ANN llegó el 2026-03-31 en la alpha.1: rescore, ivf (experimental, compilado fuera por defecto) y diskann.

The alpha.2 notes are the project’s most honest document: they add a tuning command column, INSERT OR REPLACE and ALTER TABLE RENAME, then admit data leaking through un-deleted compressed neighbor vectors in DiskANN, expensive DELETEs, and UPDATEs blocked on DiskANN and IVF. Distances are vec_distance_L2, vec_distance_cosine, vec_distance_hamming; vec0 defaults to L2 per column. And benchmarks/README.md is empty — benchmarks-ann/ ships Cohere 1M/10M and NYT harnesses that write to results.db without publishing a table. Every performance claim here is unbenchmarked.

Las notas de la alpha.2 son lo más honesto del proyecto: añaden una columna de comandos, INSERT OR REPLACE y ALTER TABLE RENAME, y reconocen fuga de datos por vectores comprimidos sin borrar en DiskANN, DELETE caros y UPDATEs bloqueados en DiskANN e IVF. Distancias: vec_distance_L2, vec_distance_cosine, vec_distance_hamming. Y benchmarks/README.md está vacío: los arneses Cohere 1M/10M y NYT escriben en results.db sin publicar tablas, así que toda cifra de rendimiento carece de medición.

What the Memory Math Says Before You Benchmark

Lo que dicen las cuentas de memoria antes de medir

The arithmetic decides the design before latency does. A million 768-dimension float32 vectors take 2,930 MB; int8 takes 740 MB; binary lands near 99 MB. At 1536 dimensions float32 costs 6.144 GB per million, plus ~5% page overhead. Compression buys memory with recall, and the trade is not linear: brute force is 100% recall at about 3 KB scanned per vector; int8 holds near 99.5% recall at 12.9× compression; one bit gives ~10% recall on uniform-random data at 195× faster, so treat it as a filter for a float rerank.

La aritmética decide antes que la latencia. Un millón de vectores de 768 dimensiones ocupa 2,930 MB en float32; en int8, 740 MB; en binario, unos 99 MB. Con 1536 dimensiones, float32 cuesta 6.144 GB por millón. Comprimir cambia memoria por recall, no de forma lineal: la fuerza bruta da 100% de recall a unos 3 KB recorridos por vector; int8 conserva cerca del 99.5% con 12.9× de compresión; un bit da ~10% de recall con datos aleatorios a 195× más velocidad, así que es un filtro para rerank en float.

SQLite Shipped Its Own ANN: Vec1

SQLite publicó su propio ANN: Vec1

The under-covered story is that SQLite has an official vector extension. sqlite.org/vec1 is a single C file (vec1.c), v0.7 announced 2026-07-07 by Dan Kennedy, documentation at 0.8, doing real ANN through IVFADC with OPQ plus an untrained RabitQ quantizer added in 0.7. L2 and cosine, AVX2 and NEON, no dependencies, vec1_train() and rebuild, filtered and streaming queries, metadata columns.

Lo poco cubierto: SQLite tiene extensión vectorial oficial. sqlite.org/vec1 es un solo archivo C, v0.7 anunciada el 2026-07-07 por Dan Kennedy, docs en 0.8, con ANN real mediante IVFADC y OPQ y un cuantizador RabitQ sin entrenamiento añadido en la 0.7. L2 y coseno, AVX2 y NEON, sin dependencias, vec1_train(), consultas filtradas y en streaming.

Published sift1m results (1M × 128d) are what nobody quotes: at nprobe=32, K=10, recall@10 of 0.916 at 3,537 QPS single-threaded; at nprobe=64, 0.977 at 2,175 QPS. Training takes 1.28 s, the index builds in 622 ms with 16 threads. Kennedy frames it carefully — “in the ballpark competitive with most ANN vector-search implementations” for trainable, static datasets — and the untrained online mode is still roadmap. If embeddings change continuously, that training step decides whether Vec1 fits.

Los resultados publicados de sift1m (1M × 128d) son lo que nadie cita: con nprobe=32 y K=10, recall@10 de 0.916 a 3,537 QPS en un hilo; con nprobe=64, 0.977 a 2,175 QPS. El entrenamiento tarda 1.28 s; el índice, 622 ms con 16 hilos. Kennedy lo formula con cuidado: competitivo con la mayoría de implementaciones ANN para conjuntos entrenables y estáticos. Y el modo online sigue en el roadmap: si los embeddings cambian sin parar, ese entrenamiento decide si Vec1 sirve.

The Rest of the Field, Honestly

El resto del panorama, sin adornos

vectorlite (Apache-2.0, ~360 stars, active 2026-10-10) is the pragmatic pick for a real HNSW index: hnswlib underneath, knn_search() and knn_param() in SQL, Rust core with C++ only for hnswlib and SIMD. sqlite-vss (MIT, ~2,005 stars, last push 2024-05-05) is dead — it wrapped FAISS, installed badly, and now points at sqlite-vec. Turso/libSQL carries vectors in the core: vector32/64, vector8, vector1bit, vector32_sparse, and a DiskANN index via libsql_vector_idx(embedding).

vectorlite (Apache-2.0, ~360 estrellas, activo a 2026-10-10) es la opción pragmática para un HNSW real: hnswlib por debajo, knn_search()/knn_param() en SQL, núcleo en Rust con C++ solo para SIMD. sqlite-vss (MIT, ~2,005 estrellas, último push 2024-05-05) está muerto: envolvía FAISS, se instalaba mal y remite a sqlite-vec. Turso/libSQL lleva los vectores en el núcleo, con índice DiskANN vía libsql_vector_idx(embedding).

Chroma is SQLite-backed for metadata (chroma.sqlite3) but keeps vectors in its own index: SQLite is the catalog, not the ANN. LanceDB (0.41.0-beta, 2026-10-28) is columnar Lance files — better above roughly 10M vectors and on object storage, worse for one file and zero ops. And SQLite AI’s sqlite-vector is a direct competitor from an unrelated codebase: vectors as ordinary BLOB columns, vector_init() required, exhaustive only (“zero preindexing”) — while the same company sponsors sqlite-vec. It shipped without a LICENSE file until 2026-09-10.

Chroma usa SQLite para metadatos (chroma.sqlite3) pero guarda los vectores en su propio índice: SQLite es el catálogo, no el ANN. LanceDB (0.41.0-beta, 2026-10-28) son archivos Lance — mejor por encima de 10M de vectores y en object storage, peor para un archivo y cero operaciones. Y sqlite-vector de SQLite AI compite desde otro código: columnas BLOB, vector_init() obligatorio, solo exhaustivo, mientras la misma empresa patrocina sqlite-vec. Salió sin LICENSE hasta el 2026-09-10.

A Memory Schema That Survives Contact With Agents

Un esquema de memoria que aguanta el contacto con agentes

Start with plain tables; the extension is the last decision. Transcripts go in messages(id, conv_id, role, content, tokens, created_at) append-only. Episodic memory in events, semantic memory in facts(subject, predicate, object, confidence, src_msg_id), graph structure in edges(src, dst, rel, weight) traversed with recursive CTEs. Add one vector column used only for recall, fused with FTS5 bm25() ranks through reciprocal rank fusion.

Conviene empezar por tablas normales: la extensión es la última decisión. Las transcripciones van en messages(id, conv_id, role, content, tokens, created_at) como filas append-only; la memoria episódica en events, la semántica en facts(subject, predicate, object, confidence, src_msg_id), el grafo en edges(src, dst, rel, weight) recorrido con CTEs recursivos. Después, una columna vectorial solo para recall, fusionada con los rangos bm25() de FTS5 mediante reciprocal rank fusion.

Decay and dedup are where such schemas rot. Keep last_used_at and score exp(-λ·age) * similarity, or materialise a strength REAL incremented on access. UNIQUE(content_hash) stops exact repeats; a cosine threshold before insert stops near ones. Compaction is one statement plus one pragma: DELETE … WHERE created_at < ? AND pinned=0, then PRAGMA incremental_vacuum, with wal_autocheckpoint set. Pinning matters: a summarised fact that still matters tomorrow is what a naive TTL deletes.

El decaimiento y la deduplicación son donde estos esquemas se pudren. Basta last_used_at y puntuar exp(-λ·age) * similarity, o un strength REAL que sube al acceder. UNIQUE(content_hash) frena repeticiones exactas; un umbral de coseno antes del insert frena las cercanas. Compactar es una sentencia y un pragma: DELETE … WHERE created_at < ? AND pinned=0, luego PRAGMA incremental_vacuum, con wal_autocheckpoint fijado. El pinning importa: un hecho resumido que aún importa mañana es lo que un TTL ingenuo borra.

CREATE TABLE facts (
  id INTEGER PRIMARY KEY,
  subject TEXT, predicate TEXT, object TEXT,
  confidence REAL, src_msg_id INTEGER,
  embedding BLOB, last_used_at INTEGER,
  content_hash TEXT NOT NULL UNIQUE
);
CREATE VIRTUAL TABLE facts_vec USING vec0(embedding float[768]);

MCP Is Not Memory

MCP no es memoria

The official SQLite server from modelcontextprotocol/servers moved to servers-archived (last commit 2025-05-28). What replaced it: jparkerweb/mcp-sqlite (~130 stars), a read-only hannesrudolph explorer (~108 stars), and SQLite AI’s sqlite-mcp, which inverts the direction — an extension that calls MCP tools from SQL. The naming trap: most “SQLite MCP servers” are a thin sqlite3 wrapper exposing arbitrary SQL, with no decay, dedup, or consolidation. A model paging a log is not building memory. MCP is transport; the schema is the memory.

El servidor oficial de SQLite de modelcontextprotocol/servers pasó a servers-archived (último commit 2025-05-28). Lo que hay ahora: jparkerweb/mcp-sqlite (~130 estrellas), un explorador de solo lectura (~108) y el sqlite-mcp de SQLite AI, que invierte la dirección: una extensión que llama herramientas MCP desde SQL. La trampa: casi todos los “servidores MCP de SQLite” son un envoltorio fino de sqlite3 con SQL arbitrario, sin decaimiento ni consolidación. Un modelo hojeando un log no construye memoria: MCP es transporte; el esquema, la memoria.

Where It Breaks

Dónde se rompe

One writer is the structural limit. WAL gives concurrent readers and one writer; the docs say readers and writers do not block each other, while also stating that all processes must be on the same host and that WAL fails on network filesystems. N agents mean serialised commits and SQLITE_BUSY retries. The 2026 answer is sqlite-multiwriter (2026-10-11), a VFS that drops the write lock without changing the format. Vendor-reported: 16 threads from 8,630 to 49,277 tx/s, retries 189 → 0.2 per 100 transactions, p99.9 from 157 ms to 2.08 ms. No independent run cited.

El escritor único es el límite estructural. WAL da lectores concurrentes y un escritor; la documentación dice que no se bloquean, y que todos los procesos deben estar en el mismo host y que WAL falla en sistemas de archivos de red. N agentes implican commits serializados y SQLITE_BUSY. La respuesta de 2026: sqlite-multiwriter (2026-10-11), un VFS que elimina el bloqueo de escritura sin cambiar el formato. Reportado por el proveedor: 16 hilos de 8,630 a 49,277 tx/s, reintentos de 189 a 0.2 por cada 100 transacciones, p99.9 de 157 ms a 2.08 ms. Sin corrida independiente.

Ops is the quiet failure. No built-in replication — backup API, VACUUM INTO, Litestream, LiteFS, rqlite or Turso embedded replicas; no online schema changes under load, and checkpoint stalls land in p99. Past roughly 5–10M vectors with tight latency, more than one sustained writer, or multi-region writers, move to pgvector 0.8.7 — a real HNSW graph index, build cost but no training set, plus halfvec/sparsevec and a proper VACUUM and replication story.

Las operaciones son el otro fallo. No hay replicación incorporada: API de backup, VACUUM INTO, Litestream, LiteFS, rqlite o réplicas de Turso; tampoco cambios de esquema en caliente, y las paradas de checkpoint se ven en el p99. Por encima de unos 5–10M de vectores con latencia exigente, con más de un escritor sostenido o varias regiones, conviene pgvector 0.8.7 — HNSW real, con coste de construcción pero sin entrenamiento, y una historia seria de VACUUM y replicación.

The rule is narrow and checkable: one host, one sustained writer, up to about ten million vectors, and an agent that benefits from a file it can copy, back up with VACUUM INTO, and inspect with sqlite3. Inside that box SQLite is not a compromise, it is the whole system. Outside it, no extension saves the design. The companion post on the 3.54 engine covers the rest.

La regla es estrecha y comprobable: un host, un escritor sostenido, hasta unos diez millones de vectores y un agente que gane algo con un archivo que puede copiar, respaldar con VACUUM INTO e inspeccionar con sqlite3. Dentro de esa caja SQLite no es un compromiso: es el sistema completo. Fuera, ninguna extensión salva el diseño. El artículo compañero sobre el motor 3.54 cubre el resto.


References

Referencias

  • Alex Garcia. sqlite-vec — a vector search SQLite extension. GitHub
  • Alex Garcia. sqlite-vec releases (v0.1.9, v0.1.10-alpha.*). GitHub
  • Alex Garcia. sqlite-vec ANN benchmark harness. GitHub
  • Alex Garcia. Binary quantization guide. GitHub
  • SQLite. Vec1 documentation. sqlite.org
  • SQLite. Vec1 benchmarks. sqlite.org
  • Dan Kennedy. Vec1 version 0.7. SQLite Forum
  • SQLite AI. sqlite-vector — vector search extension. GitHub
  • SQLite AI. sqlite-multiwriter — multi-writer VFS. GitHub
  • 1yefuwang1. vectorlite — HNSW vector search for SQLite. GitHub
  • SQLite Cloud. SQLite AI product map. sqlite.ai
  • Turso. AI and embeddings in libSQL. docs.turso.tech
  • SQLite. Write-Ahead Logging (concurrency limits). sqlite.org
  • pgvector. Open-source vector similarity search for Postgres. GitHub
  • Alex Garcia. sqlite-vec — extensión de búsqueda vectorial para SQLite. GitHub
  • Alex Garcia. Versiones de sqlite-vec (v0.1.9, v0.1.10-alpha.*). GitHub
  • Alex Garcia. Arnés de benchmark ANN de sqlite-vec. GitHub
  • Alex Garcia. Guía de cuantización binaria. GitHub
  • SQLite. Documentación de Vec1. sqlite.org
  • SQLite. Benchmarks de Vec1. sqlite.org
  • Dan Kennedy. Vec1 versión 0.7. Foro de SQLite
  • SQLite AI. sqlite-vector — extensión de búsqueda vectorial. GitHub
  • SQLite AI. sqlite-multiwriter — VFS multi-escritor. GitHub
  • 1yefuwang1. vectorlite — búsqueda vectorial HNSW para SQLite. GitHub
  • SQLite Cloud. Mapa de productos de SQLite AI. sqlite.ai
  • Turso. IA y embeddings en libSQL. docs.turso.tech
  • SQLite. Write-Ahead Logging (límites de concurrencia). sqlite.org
  • pgvector. Búsqueda vectorial de código abierto para Postgres. GitHub
Compartir