TL;DR: Duplicate chunks in vector search are usually an identity problem before they are a similarity problem. For a B2B SaaS listing aggregator, derive each vector ID from the source listing, a normalized content fingerprint, and a stable chunk ordinal; record the intended generation before bulk ingestion; upsert on retry; then expose a generation only after its complete manifest is durable. This does not create magical exactly-once delivery. It makes repeated delivery converge to one auditable state while preventing old and new listing chunks from appearing together.
A nearest-neighbor index is expected to return semantically similar records. Retrieval-augmented generation depends on that retrieval step, so duplicate evidence is not cosmetic: repeated listing text can crowd distinct evidence out of a small result set and make downstream answers look more certain than the corpus warrants. The useful debugging question is therefore not merely "why are two strings equal?" It is "which identity or publication invariant allowed both records to become eligible?"
How should you debug duplicate chunks in vector search results?
Start with one suspect result pair and compare four fields: source key, content fingerprint, chunk ordinal, and ingestion generation. Equal fingerprints with different vector IDs indicate nondeterministic identity, commonly caused by assigning a fresh identifier on each attempt. Equal source keys with different fingerprints and generations indicate stale publication. Different source keys with equal fingerprints may be legitimate syndication across listing sources, so deleting one blindly can erase provenance that reconciliation needs.
The distinction matters because bulk jobs are retried at inconvenient boundaries. A worker may send 500 records, lose the acknowledgement, and send the same 500 again. If IDs are random, the index has no basis for recognizing the second delivery as the same logical write. If IDs are deterministic and the storage operation is an upsert keyed by that ID, the retry targets the existing record. Idempotency is a property of the key and state transition, not of the queue's good intentions.
Retries happen.
Do not begin by tuning similarity thresholds. Two byte-identical chunks have the same semantic content regardless of the threshold, while two versions of a listing can remain close enough to compete after an address, price, or availability field changes. Threshold tuning can hide the symptom and retain the stale record.
Step 1: Make chunk identity reproducible
Choose a canonical source key from facts that survive retries, such as source_system plus the source's listing identifier. Normalize only representation noise: line endings, Unicode whitespace that your ingestion contract declares insignificant, and repeated horizontal spaces. Do not lowercase identifiers or remove punctuation merely to increase deduplication; those transformations can merge distinct suite numbers, product codes, or legal names.
Then chunk deterministically. The same normalized document and configuration must yield the same boundaries and ordinals. Store the chunking policy version because changing a 900-byte window to a 1,200-byte window creates a new interpretation of the document even when the source is unchanged. The following complete Go program produces a stable identifier and shows that a retry converges on the same key:
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"regexp"
"strings"
)
var horizontalSpace = regexp.MustCompile(`[\t ]+`)
func normalize(s string) string {
s = strings.ReplaceAll(s, "\r\n", "\n")
s = strings.ReplaceAll(s, "\r", "\n")
return strings.TrimSpace(horizontalSpace.ReplaceAllString(s, " "))
}
func digest(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
func vectorID(source, listingID, policy string, ordinal int, chunk string) string {
material := fmt.Sprintf("%s\x1f%s\x1f%s\x1f%d\x1f%s",
source, listingID, policy, ordinal, digest(normalize(chunk)))
return digest(material)
}
func main() {
chunk := "ACME 42\r\nSuite 300"
first := vectorID("partner-a", "L-1842", "chunk-v3", 0, chunk)
retry := vectorID("partner-a", "L-1842", "chunk-v3", 0, chunk)
fmt.Println(first == retry)
}
The SHA-256 digest here is an identifier construction, not a claim that hash equality proves business equivalence. Preserve the original source key, normalized-content digest, policy version, ordinal, and generation as metadata. A digest alone cannot explain why a record exists.
There is a deliberate trade-off in including the content fingerprint in the ID. An unchanged retry overwrites the same vector, while changed content obtains a new ID and can be staged beside the active version. That supports safe publication, but it also means cleanup is mandatory after the new generation becomes active. Omitting the fingerprint makes updates overwrite in place and reduces cleanup, yet readers can observe a partially replaced multi-chunk listing during a bulk run. For freshness-sensitive aggregation, staging is the more defensible choice.
Step 2: Publish generations, not individual vectors
A listing with eight chunks is one logical document, not eight independently publishable facts. Assign every ingestion attempt a generation, build an expected manifest of its deterministic vector IDs, and write those vectors in bounded batches. After all writes are acknowledged, read back or otherwise verify the manifest according to the index's consistency contract. Only then change the listing's active-generation pointer. Query filters must require that active generation.
This small state machine provides a clean recovery rule:
| State | Query eligible | Retry action |
|---|---|---|
| Prepared | No | Reuse generation and IDs |
| Written, unverified | No | Verify or repeat upserts |
| Active | Yes | No-op if manifest matches |
| Superseded | No | Delete after retention policy permits |
The activation record belongs in a transactional system of record with a uniqueness constraint on (source_key, generation) and an idempotency key for the ingestion request. The vector index remains a derived projection. This boundary is important: many indexes can upsert individual records, but a multi-record batch and a separate metadata write should not be assumed to commit atomically unless the chosen system explicitly guarantees it.
Exactly once is the wrong operational promise. The useful invariant is narrower: at most one complete generation per listing is query eligible, and replaying a committed request does not change its manifest. Delivery may occur more than once. Effects converge.
That boundary is testable.
Step 3: Reconcile evidence instead of counting requests
Request success is weak evidence. Reconciliation should compare the source-of-truth manifest with the indexed projection and emit counts for missing IDs, unexpected IDs, duplicate fingerprints within one source key, and multiple eligible generations. Keep cardinality labels bounded; place individual listing IDs in sampled logs or an audit table rather than metric labels.
Each transition should append an audit event containing the idempotency key, source key, generation, chunking policy, expected count, acknowledged count, manifest digest, actor or worker identity, and timestamp. Retention is a compliance and legal-policy decision, so do not hard-code a universal duration into the worker. The event needs to answer who requested the change, what set was intended, and which generation became visible.
A useful acceptance test injects failure after every external boundary: before the first upsert, midway through a batch, after the final upsert but before activation, and after activation but before acknowledgement. Run the same request again each time. The assertions are concrete: one active generation, an identical manifest digest, no duplicate vector IDs, and no search hit from a prepared or superseded generation. Then repeat with changed listing content and verify that readers see either the complete old generation or the complete new one, never a mixture.
Be careful with cross-source duplicates. If three partners carry the same listing description, a global content-only ID would collapse three provenance records into one and make takedown or correction ambiguous. Keep source identity in the vector ID, retrieve candidates, and perform an explicit business-level merge later using authoritative attributes. Search deduplication and entity resolution are separate controls.
Provenance wins.
Roll out without a flag day
Introduce the new metadata first and dual-write deterministic IDs into a shadow generation while existing reads continue. Reconcile source counts and manifest digests, then enable active-generation filtering for a small partition of source keys. Watch the four discrepancy classes rather than a single "duplicate rate," because a falling aggregate can conceal a rise in stale generations.
Once the new path is stable, backfill source by source, activate only verified manifests, and retire old IDs through the same audited workflow. Keep rollback simple: move the active pointer to the last complete generation; do not reconstruct it from whatever vectors happen to remain.
The durable fix is compact: deterministic identity makes retries idempotent, generation gating makes freshness atomic at the document boundary, and reconciliation demonstrates that the derived index still matches intent. A clean result set is the consequence of those invariants, not a post-query deduplication trick.
Top comments (0)