Retain commits document tracking (deletes previous units, overwrites original_text) even when chunk extraction failed, leaving 0-unit documents
Summary
A retain that fails part-way (e.g. embeddings outage) still commits "document tracking" for the document — previous memory units are deleted and documents.original_text is overwritten — and only then raises. The result is a document with memory_unit_count = 0 and no chunk rows. We found 883 such documents after an embeddings quota outage.
Version
hindsight-api-slim 1.0.0.
Where (hindsight_api/engine/retain/orchestrator.py, _streaming_retain_batch)
- ~L2821-2827: the producer gathers chunk extraction with
return_exceptions=True, stores failures inproducer_error, and still pushes the end sentinel. - ~L1322: chunks that extract 0 facts return before calling embeddings, so during an embeddings outage only fact-bearing chunks fail.
- ~L2993-3050: the consumer's first batch (even with 0 facts) runs
lock_document_for_write→handle_document_tracking(delete existing units, upsertoriginal_text) and commits. - ~L3466-3467:
if producer_error: raise producer_error[0]runs only after the consumer has finished.
Reproduction
- Retain document
D(gets N memory units). - Make the embeddings backend raise for the next call; re-retain
Dwith a body >3000 chars whose second chunk extracts 0 facts. - The operation fails as expected, but
GET /documents/Dnow showsmemory_unit_count = 0and the neworiginal_text. The old N units are gone.
Expected
If any chunk extraction failed, the document must not be replaced; the previous units and text should survive until a successful retain.
Reference fix
https://github.com/choi138/hindsight/tree/fix/retain-atomic-document-tracking (commit 62052e551): producer records failures as they happen; the consumer checks producer_error at every commit point and discards instead of committing. Includes a DB-backed test that fails on current main with the failed retain deleted the document's previous memory units — assert 0 == 1.