-- Migration 007: one current edge per (source, target, type). -- The seed upsert previously conflicted on (source_id, target_id, type, -- valid_from) — valid_from is now() at insert, so the conflict never fired -- and every re-ingest duplicated all current edges. Dedupe (keep earliest -- valid_from), then enforce uniqueness on current edges with a partial -- unique index the upsert can target. DELETE FROM relationships r USING relationships keep WHERE r.valid_to IS NULL AND keep.valid_to IS NULL AND r.source_id = keep.source_id AND r.target_id = keep.target_id AND r.type = keep.type AND r.valid_from > keep.valid_from; CREATE UNIQUE INDEX IF NOT EXISTS uq_rel_current ON relationships(source_id, target_id, type) WHERE valid_to IS NULL;