💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
fix(recovery): verify recovered checkpoint batches against the current run's ids (#1293)
Ashfaqc60c7a0c9314
diff --git a/src/python/txtai/vectors/base.py b/src/python/txtai/vectors/base.pyindex d90dc2ae..3e947fcb 100644--- a/src/python/txtai/vectors/base.py+++ b/src/python/txtai/vectors/base.py@@ -2,10 +2,12 @@Vectors module"""+import contextlibimport jsonimport osimport tempfileimport uuid+import zlibfrom ..pipeline import Tokenizer@@ -137,7 +139,7 @@ class Vectors:recovery = Recovery(checkpoint, vectorsid, self.loadembeddings) if checkpoint else None# Convert all documents to embedding arrays, stream embeddings to disk to control memory usage- with self.spool(checkpoint, vectorsid) as output:+ with self.spool(checkpoint, vectorsid) as output, self.checksumspool(checkpoint, vectorsid) as checksums:stream = output.namebatch = []for document in documents:@@ -145,7 +147,7 @@ class Vectors:if len(batch) == batchsize:# Convert batch to embeddings- uids, dimensions = self.batch(batch, output, recovery)+ uids, dimensions = self.batch(batch, output, checksums, recovery)ids.extend(uids)batches += 1@@ -153,7 +155,7 @@ class Vectors:# Final batchif batch:- uids, dimensions = self.batch(batch, output, recovery)+ uids, dimensions = self.batch(batch, output, checksums, recovery)ids.extend(uids)batches += 1@@ -288,31 +290,87 @@ class Vectors:# Spool to temporary filereturn tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False)- def batch(self, documents, output, recovery):+ def checksumspool(self, checkpoint, vectorsid):+ """+ Opens a companion file to store each batch's checksum alongside a checkpoint, used by a+ future recovery attempt to confirm a checkpointed batch still matches. Kept separate from+ the embeddings checkpoint file so that file's format is unchanged - a checkpoint from+ before this file existed is still read normally, just without checksum verification.++ Args:+ checkpoint: optional checkpoint directory, enables indexing restart+ vectorsid: vectors uid for current configuration++ Returns:+ checksum spool file, or a no-op context when checkpointing is disabled+ """++ if checkpoint:+ return open(f"{checkpoint}/{vectorsid}.checksums", "w", encoding="utf-8")++ return contextlib.nullcontext()++ def checksum(self, ids, data):+ """+ Computes a stable checksum for a batch's ids and raw document content, as a single+ value. Used to confirm a recovered checkpoint batch still matches the batch currently being+ built at that position - matching ids alone isn't enough, since the same id can carry+ different content across runs (an updated row from the source, for example).++ Args:+ ids: ids for this batch+ data: raw document content for this batch, prior to any model-specific preparation++ Returns:+ checksum identifying this batch's ids and content. Not a security use case, just a+ change-detection check against the current batch, so a fast CRC32 is used in place of+ a cryptographic hash.+ """++ try:+ encoded = json.dumps([ids, data], sort_keys=True, default=str).encode("utf-8")+ except TypeError:+ encoded = str((ids, data)).encode("utf-8")++ return format(zlib.crc32(encoded), "08x")++ def batch(self, documents, output, checksums, recovery):"""Builds a batch of embeddings.Args:documents: list of documents used to build embeddingsoutput: output temp file to store embeddings+ checksums: output file to store this batch's checksum, only used when recovery is enabledrecovery: optional recovery instanceReturns:(ids, dimensions) list of ids and number of dimensions in embeddings"""- # Extract ids and prepare input documents for vectors modelids = [uid for uid, _, _ in documents]- documents = [self.prepare(data, "data") for _, data, _ in documents]dimensions = None- # Attempt to read embeddings from a recovery file- embeddings = recovery() if recovery else None- embeddings = self.vectorize(documents, "data") if embeddings is None else embeddings+ # Only compute a checksum when recovery is enabled (checkpoint is set) - it's only ever read+ # back in that case, so there's no reason to pay for it otherwise+ checksum = self.checksum(ids, [data for _, data, _ in documents]) if recovery is not None else None++ # Prepare input documents for vectors model+ prepared = [self.prepare(data, "data") for _, data, _ in documents]++ # Attempt to read embeddings from a recovery file, only trusting a batch whose recorded+ # checksum matches this one+ embeddings = recovery(checksum) if recovery else None+ embeddings = self.vectorize(prepared, "data") if embeddings is None else embeddingsif embeddings is not None:dimensions = embeddings.shape[1]self.saveembeddings(output, embeddings)+ # Only record the checksum once its embeddings are fully written, so a checksum is+ # never found without a matching batch on a later recovery attempt+ if checksum is not None:+ checksums.write(checksum + "\n")+return (ids, dimensions)def prepare(self, data, category=None):diff --git a/src/python/txtai/vectors/dense/words.py b/src/python/txtai/vectors/dense/words.pyindex 55833f0e..67c3df03 100644--- a/src/python/txtai/vectors/dense/words.py+++ b/src/python/txtai/vectors/dense/words.py@@ -172,14 +172,14 @@ class WordVectors(Vectors):# Convert all documents to embedding arrays, stream embeddings to disk to control memory usagewith Pool(parallel, initializer=create, initargs=args) as pool:- with self.spool(checkpoint, vectorsid) as output:+ with self.spool(checkpoint, vectorsid) as output, self.checksumspool(checkpoint, vectorsid) as checksums:stream = output.namebatch = []for document in documents:batch.append(document)if len(batch) == batchsize:- uids, dimensions = self.parallelbatch(pool, batch, output, recovery)+ uids, dimensions = self.parallelbatch(pool, batch, output, checksums, recovery)ids.extend(uids)batches += 1@@ -187,13 +187,13 @@ class WordVectors(Vectors):# Final batchif batch:- uids, dimensions = self.parallelbatch(pool, batch, output, recovery)+ uids, dimensions = self.parallelbatch(pool, batch, output, checksums, recovery)ids.extend(uids)batches += 1return (ids, dimensions, batches, stream)- def parallelbatch(self, pool, documents, output, recovery):+ def parallelbatch(self, pool, documents, output, checksums, recovery):"""Builds a batch of embeddings using the multiprocessing pool, honoring a recoverycheckpoint if one is available for this batch.@@ -202,6 +202,7 @@ class WordVectors(Vectors):documents: list of documents used to build embeddingspool: multiprocessing pool used to transform documents not served from recoveryoutput: output stream to store embeddings+ checksums: output file to store this batch's checksum, only used when recovery is enabledrecovery: optional recovery instanceReturns:@@ -210,14 +211,24 @@ class WordVectors(Vectors):ids = [uid for uid, _, _ in documents]- # Attempt to read embeddings from a recovery file- embeddings = recovery() if recovery else None+ # Only compute a checksum when recovery is enabled (checkpoint is set) - it's only ever read+ # back in that case, so there's no reason to pay for it otherwise+ checksum = self.checksum(ids, [data for _, data, _ in documents]) if recovery is not None else None++ # Attempt to read embeddings from a recovery file, only trusting a batch whose recorded+ # checksum matches this one+ embeddings = recovery(checksum) if recovery else Noneif embeddings is None:embeddings = np.array([embedding for _, embedding in pool.imap(transform, documents, self.encodebatch)], dtype=np.float32)dimensions = embeddings.shape[1]self.saveembeddings(output, embeddings)+ # Only record the checksum once its embeddings are fully written, so a checksum is never+ # found without a matching batch on a later recovery attempt+ if checksum is not None:+ checksums.write(checksum + "\n")+return (ids, dimensions)def lookup(self, tokens):diff --git a/src/python/txtai/vectors/recovery.py b/src/python/txtai/vectors/recovery.pyindex f0dfb7c8..1b8d1953 100644--- a/src/python/txtai/vectors/recovery.py+++ b/src/python/txtai/vectors/recovery.py@@ -8,7 +8,8 @@ import shutilclass Recovery:"""- Vector embeddings recovery. This class handles streaming embeddings from a vector checkpoint file.+ Vector embeddings recovery. Streams embeddings from a checkpoint file, verifying each batch+ against an optional companion checksum file before trusting it."""def __init__(self, checkpoint, vectorsid, load):@@ -21,7 +22,9 @@ class Recovery:load: load embeddings method"""- self.spool, self.path, self.load = None, None, load+ self.spool, self.path = None, None+ self.checksums, self.checksumspath = None, None+ self.load = load# Get unique file idpath = f"{checkpoint}/{vectorsid}"@@ -32,26 +35,68 @@ class Recovery:# Copy current checkpoint to recoveryshutil.copyfile(path, self.path)- # Open file an return+ # Open file and return# pylint: disable=R1732self.spool = open(self.path, "rb")- def __call__(self):+ # Checksums are optional - a checkpoint from before this file existed has none, so its+ # batches are trusted without verification+ checksumspath = f"{checkpoint}/{vectorsid}.checksums"+ if os.path.exists(checksumspath):+ self.checksumspath = f"{checkpoint}/recovery.checksums"+ shutil.copyfile(checksumspath, self.checksumspath)++ # pylint: disable=R1732+ self.checksums = open(self.checksumspath, encoding="utf-8")++ def __call__(self, checksum):"""- Reads and returns the next batch of embeddings.+ Reads and returns the next batch of embeddings. When a checksums file is present, the batch is+ only returned once its recorded checksum matches the checksum of the batch about to be built.++ Args:+ checksum: checksum for the batch about to be built, used to confirm the recovered batch's+ ids and content weren't changed since the checkpoint was writtenReturns- batch of embeddings+ batch of embeddings, or None if unavailable or the checkpoint no longer lines up"""+ if not self.spool:+ return None+try:- return self.load(self.spool) if self.spool else None+ if self.checksums:+ line = self.checksums.readline()+ if not line:+ raise EOFError++ if line.strip() != checksum:+ # The document stream no longer lines up with the checkpoint, either a different+ # document (id) or the same id with changed content (checksum). Every later batch+ # position is unreliable too once this happens, so stop trusting the recovery file+ # for the rest of this run.+ self.cleanup()+ return None++ return self.load(self.spool)except EOFError:# End of spool file, cleanup+ self.cleanup()+ return None++ def cleanup(self):+ """+ Closes and removes the recovery spool and checksums files.+ """++ if self.spool:self.spool.close()os.remove(self.path)- # Clear parameters- self.spool, self.path = None, None+ if self.checksums:+ self.checksums.close()+ os.remove(self.checksumspath)- return None+ self.spool, self.path = None, None+ self.checksums, self.checksumspath = None, Nonediff --git a/test/python/testvectors/testdense/testvectors.py b/test/python/testvectors/testdense/testvectors.pyindex e3cb0dc9..6d6f5c42 100644--- a/test/python/testvectors/testdense/testvectors.py+++ b/test/python/testvectors/testdense/testvectors.py@@ -16,15 +16,17 @@ class TestVectors(unittest.TestCase):Vectors tests."""- def testNotImplemented(self):+ def testChecksumUnserializable(self):"""- Test exceptions for non-implemented methods+ Test that checksum falls back to str() when a batch's ids/data can't be JSON-serialized+ (for example, a dict with mixed key types can't be sorted by json.dumps(sort_keys=True)),+ producing a deterministic checksum instead of raising"""vectors = Vectors(None, None, None)- self.assertRaises(NotImplementedError, vectors.load, None)- self.assertRaises(NotImplementedError, vectors.encode, None)+ data = [{1: "a", "b": "c"}]+ self.assertEqual(vectors.checksum([1], data), vectors.checksum([1], data))def testNormalize(self):"""@@ -49,6 +51,16 @@ class TestVectors(unittest.TestCase):self.assertTrue(np.allclose(data1, data2))self.assertFalse(np.allclose(data1, original))+ def testNotImplemented(self):+ """+ Test exceptions for non-implemented methods+ """++ vectors = Vectors(None, None, None)++ self.assertRaises(NotImplementedError, vectors.load, None)+ self.assertRaises(NotImplementedError, vectors.encode, None)+def testRecovery(self):"""Test vectors recovery failure@@ -59,10 +71,112 @@ class TestVectors(unittest.TestCase):os.makedirs(checkpoint, exist_ok=True)# Create empty file- # pylint: disable=R1732- f = open(os.path.join(checkpoint, "id"), "w", encoding="utf-8")- f.close()+ self.write(os.path.join(checkpoint, "id"))# Create the recovery instance with an empty checkpoint filerecovery = Recovery(checkpoint, "id", np.load)- self.assertIsNone(recovery())+ self.assertIsNone(recovery("checksum-a"))++ def testRecoveryChecksumsExhausted(self):+ """+ Test that recovery stops trusting the checkpoint once the checksums file runs out of lines,+ even though the embeddings spool file still has data - a truncated or corrupted companion+ file must not be read past its end+ """++ checkpoint = os.path.join(tempfile.gettempdir(), "recovery-checksums-exhausted")+ os.makedirs(checkpoint, exist_ok=True)++ embeddings = np.random.rand(2, 4).astype(np.float32)++ # Checksums file exists but has no lines, while the spool file still has embeddings+ self.write(os.path.join(checkpoint, "id"), checksums=[], embeddings=embeddings)++ recovery = Recovery(checkpoint, "id", np.load)+ self.assertIsNone(recovery("checksum-a"))++ def testRecoveryContentMismatch(self):+ """+ Test that recovery rejects a batch whose ids match but whose content checksum doesn't - the+ same id can carry different content across runs (an updated row from the source, for+ example), and matching ids alone must not be trusted in that case. The checksum covers both+ ids and content, so this looks identical to any other checksum mismatch from here+ """++ checkpoint = os.path.join(tempfile.gettempdir(), "recovery-content-mismatch")+ os.makedirs(checkpoint, exist_ok=True)++ embeddings = np.random.rand(2, 4).astype(np.float32)+ self.write(os.path.join(checkpoint, "id"), checksums=["checksum-ab"], embeddings=embeddings)++ # Same ids as the checkpoint, but content changed means the checksum won't match+ recovery = Recovery(checkpoint, "id", np.load)+ self.assertIsNone(recovery("checksum-ab-changed"))++ def testRecoveryLegacyCheckpoint(self):+ """+ Test that a checkpoint written before checksum tracking existed (no companion checksums+ file) is still read back and trusted as-is+ """++ checkpoint = os.path.join(tempfile.gettempdir(), "recovery-legacy")+ os.makedirs(checkpoint, exist_ok=True)++ embeddings = np.random.rand(2, 4).astype(np.float32)+ self.write(os.path.join(checkpoint, "id"), embeddings=embeddings)++ # No companion checksums file present+ recovery = Recovery(checkpoint, "id", np.load)+ result = recovery("checksum-a")+ self.assertTrue(np.allclose(result, embeddings))++ def testRecoveryMatch(self):+ """+ Test that recovery returns the checkpointed embeddings when their recorded checksum matches+ the current run's checksum+ """++ checkpoint = os.path.join(tempfile.gettempdir(), "recovery-match")+ os.makedirs(checkpoint, exist_ok=True)++ embeddings = np.random.rand(2, 4).astype(np.float32)+ self.write(os.path.join(checkpoint, "id"), checksums=["checksum-ab"], embeddings=embeddings)++ recovery = Recovery(checkpoint, "id", np.load)+ result = recovery("checksum-ab")+ self.assertTrue(np.allclose(result, embeddings))++ def testRecoveryMismatch(self):+ """+ Test that recovery rejects a batch whose checkpointed checksum doesn't match the current+ run's checksum for that batch+ """++ checkpoint = os.path.join(tempfile.gettempdir(), "recovery-mismatch")+ os.makedirs(checkpoint, exist_ok=True)++ embeddings = np.random.rand(2, 4).astype(np.float32)+ self.write(os.path.join(checkpoint, "id"), checksums=["checksum-a"], embeddings=embeddings)++ recovery = Recovery(checkpoint, "id", np.load)+ self.assertIsNone(recovery("checksum-b"))++ def write(self, path, checksums=None, embeddings=None):+ """+ Writes a checkpoint and an optional companion checksums file.++ Args:+ path: checkpoint file to write+ checksums: list of checksums to write to a companion file, or None to omit it (simulating+ a checkpoint written before checksums existed)+ embeddings: embeddings array to write, or None to write an empty checkpoint file+ """++ with open(path, "wb") as f:+ if embeddings is not None:+ np.save(f, embeddings, allow_pickle=False)++ if checksums is not None:+ with open(f"{path}.checksums", "w", encoding="utf-8") as f:+ for checksum in checksums:+ f.write(checksum + "\n")diff --git a/test/python/testvectors/testdense/testwordvectors.py b/test/python/testvectors/testdense/testwordvectors.pyindex b2732ce8..efe39748 100644--- a/test/python/testvectors/testdense/testwordvectors.py+++ b/test/python/testvectors/testdense/testwordvectors.py@@ -81,69 +81,82 @@ class TestWordVectors(unittest.TestCase):self.assertEqual(np.load(queue).shape, (512, 300))self.assertEqual(np.load(queue).shape, (488, 300))- def testIndexSerial(self):+ def testIndexCheckpoint(self):"""- Test word vector indexing in single process mode+ Test word vector indexing writes a checkpoint file and a second run over the same+ documents is served entirely from it"""- # Generate data- documents = [(x, "This is a test", None) for x in range(1000)]+ checkpoint = os.path.join(tempfile.gettempdir(), "wordvectors-checkpoint")+ shutil.rmtree(checkpoint, ignore_errors=True)+ documents = [(x, "This is a test", None) for x in range(10)]model = VectorsFactory.create({"path": self.path, "parallel": False}, None)- ids, dimension, batches, stream = model.index(documents, 1)-- self.assertEqual(len(ids), 1000)- self.assertEqual(dimension, 300)- self.assertEqual(batches, 1000)- self.assertIsNotNone(os.path.exists(stream))+ # First run builds the checkpoint+ model.index(documents, 5, checkpoint)+ self.assertTrue(os.path.exists(os.path.join(checkpoint, model.vectorsid())))- # Test shape of serialized embeddings- with open(stream, "rb") as queue:- self.assertEqual(np.load(queue).shape, (1, 300))+ # Second run over the same documents must be fully served from the checkpoint+ with patch.object(WordVectors, "encode", wraps=model.encode) as encode:+ model.index(documents, 5, checkpoint)+ encode.assert_not_called()- def testIndexSerialBatch(self):+ def testIndexCheckpointContentEdit(self):"""- Test word vector indexing in single process mode with batch size set+ Test that a resumed run where a document's id is unchanged but its content was edited+ (e.g. an updated row from the source) re-encodes that document instead of reusing the+ checkpoint's stale embedding for the old content under the same id"""- # Generate data- documents = [(x, "This is a test", None) for x in range(1000)]+ checkpoint = os.path.join(tempfile.gettempdir(), "wordvectors-checkpoint-content-changed")+ shutil.rmtree(checkpoint, ignore_errors=True)+ documents = [(x, f"document number {x}", None) for x in range(10)]model = VectorsFactory.create({"path": self.path, "parallel": False}, None)- ids, dimension, batches, stream = model.index(documents, 512)+ # First run builds the checkpoint+ model.index(documents, 5, checkpoint)- self.assertEqual(len(ids), 1000)- self.assertEqual(dimension, 300)- self.assertEqual(batches, 2)- self.assertIsNotNone(os.path.exists(stream))+ # Resume with the same id at the same batch position, but edited content+ resumed = list(documents)+ resumed[7] = (7, "document number 7 has been edited since the last run", None)- # Test shape of serialized embeddings- with open(stream, "rb") as queue:- self.assertEqual(np.load(queue).shape, (512, 300))- self.assertEqual(np.load(queue).shape, (488, 300))+ buffer = os.path.join(tempfile.gettempdir(), "wordvectors-checkpoint-content-changed.buffer")+ ids, _, embeddings = model.vectors(resumed, 5, checkpoint, buffer=buffer, dtype=np.float32)- def testIndexCheckpoint(self):+ # The edited document's embedding must match a fresh encoding of its new text, not the+ # checkpoint's stale embedding recorded for id 7's old content+ expected = model.transform((7, "document number 7 has been edited since the last run", None))+ self.assertTrue(np.allclose(embeddings[ids.index(7)], expected))++ def testIndexCheckpointMismatch(self):"""- Test word vector indexing writes a checkpoint file and a second run over the same- documents is served entirely from it+ Test that a resumed run with a different document at the same batch position re-encodes+ that document instead of reusing the checkpoint's embedding for whoever previously sat+ in that position"""- checkpoint = os.path.join(tempfile.gettempdir(), "wordvectors-checkpoint")+ checkpoint = os.path.join(tempfile.gettempdir(), "wordvectors-checkpoint-mismatch")shutil.rmtree(checkpoint, ignore_errors=True)- documents = [(x, "This is a test", None) for x in range(10)]+ documents = [(x, f"document number {x}", None) for x in range(10)]model = VectorsFactory.create({"path": self.path, "parallel": False}, None)# First run builds the checkpointmodel.index(documents, 5, checkpoint)- self.assertTrue(os.path.exists(os.path.join(checkpoint, model.vectorsid())))- # Second run over the same documents must be fully served from the checkpoint- with patch.object(WordVectors, "encode", wraps=model.encode) as encode:- model.index(documents, 5, checkpoint)- encode.assert_not_called()+ # Resume with one document swapped out at the same batch position (index 7)+ resumed = list(documents)+ resumed[7] = (999, "a completely different sentence", None)++ buffer = os.path.join(tempfile.gettempdir(), "wordvectors-checkpoint-mismatch.buffer")+ ids, _, embeddings = model.vectors(resumed, 5, checkpoint, buffer=buffer, dtype=np.float32)++ # The swapped document's embedding must match a fresh encoding of its own text, not the+ # checkpoint's stale embedding for whatever occupied that batch position previously+ expected = model.transform((999, "a completely different sentence", None))+ self.assertTrue(np.allclose(embeddings[ids.index(999)], expected))@patch("os.cpu_count")def testIndexCheckpointParallel(self, cpucount):@@ -163,6 +176,49 @@ class TestWordVectors(unittest.TestCase):model.index(documents, 5, checkpoint)self.assertTrue(os.path.exists(os.path.join(checkpoint, model.vectorsid())))+ def testIndexSerial(self):+ """+ Test word vector indexing in single process mode+ """++ # Generate data+ documents = [(x, "This is a test", None) for x in range(1000)]++ model = VectorsFactory.create({"path": self.path, "parallel": False}, None)++ ids, dimension, batches, stream = model.index(documents, 1)++ self.assertEqual(len(ids), 1000)+ self.assertEqual(dimension, 300)+ self.assertEqual(batches, 1000)+ self.assertIsNotNone(os.path.exists(stream))++ # Test shape of serialized embeddings+ with open(stream, "rb") as queue:+ self.assertEqual(np.load(queue).shape, (1, 300))++ def testIndexSerialBatch(self):+ """+ Test word vector indexing in single process mode with batch size set+ """++ # Generate data+ documents = [(x, "This is a test", None) for x in range(1000)]++ model = VectorsFactory.create({"path": self.path, "parallel": False}, None)++ ids, dimension, batches, stream = model.index(documents, 512)++ self.assertEqual(len(ids), 1000)+ self.assertEqual(dimension, 300)+ self.assertEqual(batches, 2)+ self.assertIsNotNone(os.path.exists(stream))++ # Test shape of serialized embeddings+ with open(stream, "rb") as queue:+ self.assertEqual(np.load(queue).shape, (512, 300))+ self.assertEqual(np.load(queue).shape, (488, 300))+def testLookup(self):"""Test word vector lookup