fix: Make documents.source_id a unique key for idempotent upserts #19
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR refactors the document ingestion logic to use a proper UNIQUE constraint on
documents.source_id, enabling atomic upsert-by-sourceId semantics that are safe under concurrent writes.Problem
The previous implementation used a "delete existing document by source_id, then insert" pattern. This approach is NOT safe under concurrent writes - if two ingest calls for the same sourceId run simultaneously, both could delete and then both insert, resulting in duplicate documents.
Solution
documents.source_idin the database schemaON CONFLICT (source_id) DO UPDATEfor atomic upsertupsert()to return{ documentId: string }- the canonical (stable) document IDdocument_idafter upserting the document, instead of deleting documents bysource_idChanges
Schema Updates
documents.source_idnow requires a UNIQUE constraintStore Adapters (all updated with same pattern)
drizzle-postgres-pgvectorprisma-postgres-pgvectorraw-sql-postgres-pgvectorCore
ingest.ts: Uses the canonicaldocumentIdreturned fromstore.upsert()types.ts: UpdatedVectorStore.upsert()signature to return{ documentId: string }Doctor Command
db-sourceid-unique- Verifies UNIQUE constraint exists ondocuments.source_iddb-sourceid-duplicates- Detects duplicate source_id values that must be resolved before adding the constraintDocumentation
unrag.md)Tests
Migration Notes
Existing users will need to:
source_idvalues:SELECT source_id, COUNT() FROM documents GROUP BY source_id HAVING COUNT() > 1;