Incremental Embeddings in SQLite: Test Deduplication and Crash Recovery
A complete-snapshot index reuses vectors, checkpoints completed batches and publishes source links atomically. Seven recovery checks and a fresh live embedding sequence verify its limits.

Build incremental embeddings with two separate stages: persist validated vectors as checkpoints, then atomically publish the complete document-to-vector map. If an embedding batch fails, the previous searchable source map should remain intact.
Crazyrouter is the gateway used in this SQLite index test: the first snapshot created two vectors, an identical rerun created zero, and an edited snapshot created one.
By Jeff M · Tested November 3, 2026
How do incremental embeddings handle deduplication and crash recovery?#
Hash normalized text inside a namespace containing model, dimensions and normalization revision. Store completed vector batches durably and replace source links only after all required vectors are ready. Reopening the database after a simulated interruption reused the completed checkpoint and embedded only the missing text.
The source input is a complete snapshot#
The sync input maps stable source IDs to full nonempty text. A missing ID means deletion from the active source map. An empty dictionary intentionally clears that namespace. Passing only changed documents would incorrectly delete all unchanged source links, so a delta feed needs a different contract with explicit upsert and delete events.
The normalization converts Unicode to NFC and normalizes line endings while preserving meaningful whitespace. Equal normalized text shares a digest even when source IDs differ. The namespace includes model, dimensions and revision so a configuration change does not accidentally reuse incompatible vectors.
November 3 test results#
The tests ran on Windows with Python 3.10.2 and synthetic inputs. The API host was https://api.crazyrouter.com; the complete request path, model and parameters appear in the runnable code below. These are dated observations, not a guarantee of future behavior.
| Snapshot | Sources | Unique text | New vectors |
|---|---|---|---|
| First | 3 | 2 | 2 |
| Identical | 3 | 2 | 0 |
| Edited | 2 | 2 | 1 |
Local fixtures: 7 passed. The live-response criteria are evaluated separately.
Observed response or request IDs (including failed-output responses):
1793713104008901
1793713104868722
Embedding body response IDs were absent; the listed values are observed x-request-id headers.

Recovery is demonstrated with a real temporary SQLite file#
The local recovery test first publishes an old source. A replacement run saves one new vector and deliberately throws on the second batch. The original document map remains readable. After closing and reopening the SQLite connection, the retry uses the saved vector and embeds only the other text.
Other checks cover snapshot deletion, orphan-vector collection, invalid boolean vector elements, preserving the map after validation failure, and a changed normalization namespace. These are seven executed checks. The exception is injected between batches, not an operating-system power-loss simulation.
Know the single-writer and billing boundaries#
This reference implementation assumes one writer per database. It does not coordinate competing workers, handle distributed locks or implement a tenant access layer. For a service that contains multiple users, add trusted tenant scope to storage and retrieval rather than relying on content hashes as authorization.
The vector checkpoint commits after the API returns. If the process loses the result before committing, retrying can call the API again. This is resumable work, not exactly-once billing. Garbage collection should follow a successful sync: deleting orphan checkpoints during an interrupted run would discard useful recovery work.
The earlier October 11 example used another origin. This revision was actually rerun November 3 against the public API origin; it does not relabel the old measurements.
Reproduce the test#
Install requests, set CRAZYROUTER_API_KEY in the process environment, save the complete script below, and run it with Python. It sends the synthetic requests shown in the code using your own authorized credential. It does not print authorization headers. Output includes the observed fixture outcomes; completing the script does not mean every model answer passed.
"""Single-writer SQLite reference index; sync accepts a COMPLETE source snapshot."""
import hashlib
import json
import math
import os
import sqlite3
import unicodedata
from pathlib import Path
import requests
def normalize(text):
# Keep whitespace meaningful; only normalize Unicode and line endings.
return unicodedata.normalize("NFC", text.replace("\r\n", "\n").replace("\r", "\n"))
class Index:
def __init__(self, path, embed, *, model="text-embedding-3-small", dimensions=512,
revision="nfc-lines-v1", batch_size=16):
if batch_size < 1 or dimensions < 1:
raise ValueError("batch_size and dimensions must be positive")
self.db = sqlite3.connect(path)
self.db.execute("PRAGMA foreign_keys = ON")
self.db.executescript('''
CREATE TABLE IF NOT EXISTS vectors (
namespace TEXT NOT NULL, digest TEXT NOT NULL, vector TEXT NOT NULL,
PRIMARY KEY(namespace, digest));
CREATE TABLE IF NOT EXISTS documents (
namespace TEXT NOT NULL, source_id TEXT NOT NULL, digest TEXT NOT NULL,
PRIMARY KEY(namespace, source_id),
FOREIGN KEY(namespace,digest) REFERENCES vectors(namespace,digest));
''')
self.ns = json.dumps([model, dimensions, revision], separators=(",", ":"))
self.embed, self.dimensions, self.batch_size = embed, dimensions, batch_size
def sync(self, snapshot):
"""A dict of stable source/chunk IDs to text. Empty dict deletes this namespace."""
if not isinstance(snapshot, dict):
raise TypeError("snapshot must be a complete ID-to-text dictionary")
links, unique = {}, {}
for source_id, text in snapshot.items():
if not isinstance(source_id, str) or not isinstance(text, str) or not text.strip():
raise ValueError("IDs must be strings; texts must be nonempty strings")
normalized = normalize(text)
digest = hashlib.sha256(normalized.encode()).hexdigest()
links[source_id] = digest
unique[digest] = normalized
present = {x[0] for x in self.db.execute(
"SELECT digest FROM vectors WHERE namespace=?", (self.ns,))}
missing = [(d, t) for d, t in unique.items() if d not in present]
for start in range(0, len(missing), self.batch_size):
batch = missing[start:start+self.batch_size]
vectors = self.embed([text for _, text in batch])
if len(vectors) != len(batch):
raise ValueError("wrong vector count")
for vector in vectors:
if len(vector) != self.dimensions or not all(type(v) in (int, float) and math.isfinite(v) for v in vector):
raise ValueError("invalid vector dimensions or nonfinite values")
# Each completed batch is a durable checkpoint. Source links stay intact.
with self.db:
self.db.executemany("INSERT INTO vectors VALUES (?,?,?)", [
(self.ns, d, json.dumps(v)) for (d, _), v in zip(batch, vectors)])
# Publish the new source map atomically only after all vectors are durable.
with self.db:
self.db.execute("DELETE FROM documents WHERE namespace=?", (self.ns,))
self.db.executemany("INSERT INTO documents VALUES (?,?,?)", [
(self.ns, source_id, digest) for source_id, digest in links.items()])
return {"sources": len(links), "unique_texts": len(unique), "new_vectors": len(missing)}
def gc(self):
# Call only after successful sync; an interrupted run may need orphan vectors.
with self.db:
cur = self.db.execute('''DELETE FROM vectors WHERE namespace=?
AND digest NOT IN (SELECT digest FROM documents WHERE namespace=?)''',
(self.ns, self.ns))
return cur.rowcount
def close(self):
self.db.close()
import json
import math
import os
import time
import requests
ENDPOINT="https://api.crazyrouter.com/v1/embeddings"
def embed(texts,dimensions,receipts):
client=requests.Session();client.trust_env=False
payload={"model":"text-embedding-3-small","dimensions":dimensions,"encoding_format":"float","input":texts}
start=time.perf_counter()
try:
r=client.post(ENDPOINT,headers={"Authorization":"Bearer "+os.environ["CRAZYROUTER_API_KEY"]},json=payload,timeout=(10,45),allow_redirects=False)
r.raise_for_status();data=r.json();rows=sorted(data["data"],key=lambda x:x["index"])
assert [x["index"] for x in rows]==list(range(len(texts)))
vectors=[x["embedding"] for x in rows]
assert all(len(v)==dimensions and all(type(n) in (int,float) and math.isfinite(n) for n in v) for v in vectors)
receipts.append({"http":r.status_code,"request":payload,"response_id":data.get("id"),"request_id":r.headers.get("x-request-id"),"usage":data.get("usage",{}),"seconds":round(time.perf_counter()-start,3),"vectors":len(vectors),"dimensions":dimensions,"validated":True})
return vectors
finally:client.close()
import tempfile
def main():
tests=[]
def checked(name,condition):
assert condition,name
tests.append({"case":name,"passed":True})
with tempfile.TemporaryDirectory() as folder:
path=Path(folder)/"recovery.sqlite"
index=Index(path,lambda texts:[[1.0,0.0] for _ in texts],dimensions=2,batch_size=1)
index.sync({"old":"old source"})
calls=[0]
def crash(texts):
calls[0]+=1
if calls[0]==2:raise RuntimeError("synthetic interruption")
return [[0.0,1.0] for _ in texts]
index.embed=crash
try:index.sync({"a":"first new source","b":"second new source"})
except RuntimeError:pass
checked("old snapshot retained",index.db.execute("SELECT source_id FROM documents").fetchall()==[("old",)])
index.close()
calls=[0]
def resume(texts):calls[0]+=len(texts);return [[0.0,1.0] for _ in texts]
index=Index(path,resume,dimensions=2,batch_size=1)
index.sync({"a":"first new source","b":"second new source"})
checked("reopen reuses checkpoint",calls[0]==1)
index.sync({"a":"first new source"})
checked("snapshot deletion",index.db.execute("SELECT COUNT(*) FROM documents").fetchone()[0]==1)
checked("garbage collection",index.gc()==2)
index.embed=lambda texts:[[True,0.0] for _ in texts]
try:index.sync({"x":"invalid vector"});raise AssertionError("accepted boolean")
except ValueError:tests.append({"case":"invalid vector rejected","passed":True})
checked("failed validation preserves map",index.db.execute("SELECT source_id FROM documents").fetchall()==[("a",)])
index.close()
other=Index(path,resume,dimensions=2,revision="new-normalization")
result=other.sync({"a":"first new source"})
checked("new namespace embeds again",result["new_vectors"]==1);other.close()
receipts=[]
live=Index(Path(folder)/"live.sqlite",lambda texts:embed(texts,512,receipts),dimensions=512)
first=live.sync({"a":"Reset an account password.","b":"Download a payment invoice.","c":"Reset an account password."})
repeat=live.sync({"a":"Reset an account password.","b":"Download a payment invoice.","c":"Reset an account password."})
edit=live.sync({"a":"Reset an account password.","b":"Download an annual billing invoice."})
live.close()
assert [first["new_vectors"],repeat["new_vectors"],edit["new_vectors"]]==[2,0,1]
print(json.dumps({"endpoint":ENDPOINT,"local_tests":tests,"requests":receipts,"syncs":[first,repeat,edit]}))
if __name__=="__main__":main()

Sources and related implementation guides#
Official references checked November 3, 2026: Python SQLite transaction documentation, OpenAI embeddings guide. Their documented behavior is distinct from the gateway results measured here.
- text-embedding-3-small Dimensions: A 256, 512 and 1536 Retrieval Test
- AI API Retries in Python: Retry-After, Timeouts, and Safe Replay
- AI API Response Caching in Python: TTL, Isolation, and a Live Test
- Authorize LLM Tool Calls: Tenant Isolation with a Tested Python Executor
- AI SaaS Unit Economics: Calculate Cost per Usable Output
FAQ#
Can I pass only the changed records to sync?#
No. This function consumes a complete snapshot; missing IDs are removed from the active map.
What counts as duplicate text?#
Text with the same NFC and line-ending normalization, within the same model/dimension/revision namespace.
Does the old map survive an interrupted batch?#
Yes in the tested exception-and-reopen case. Source links are replaced only after all necessary vectors have been validated and saved.
Does deletion erase the stored vector immediately?#
No. It removes the source link; gc removes unreferenced vectors in the namespace after a successful sync.
Can this guarantee no repeated API charges?#
No. A returned result can be lost before the local checkpoint commits, leading to a repeated request.
Is it ready for multiple simultaneous writers?#
No. It is a single-writer reference implementation; concurrency control and tenant access need separate design.
Last actually tested: November 3, 2026. This API-dependent article is due for review December 3, 2026.
Estimating API spend? See the current text-embedding-3-small price and token cost calculator.
Implementation Guides
Podcast
AI Dev Tools: The Crazyrouter Podcast
Short episodes for developers on AI APIs, gateways, cost control and coding tools.
Latest episodes
EP196 · Oct 29, 2026 · 6:53
AI API Security Posture — Turn Controls Into Continuous Evidence
A practical guide to AI API security posture: inventory exposure, verify controls continuously, protect keys and data, constrain tools, and turn security assumptions into evidence that operators can act on.
EP195 · Oct 28, 2026 · 7:21
AI API Policy Drift — Detect When Production Rules Stop Matching Intent
A practical guide to policy drift in AI APIs: version routing and safety rules, detect stale enforcement, compare intended and observed behavior, and restore control before small gaps become incidents.





