Skip to content

feat(duplicate-detection): two-tier duplicate document detection with operator review integration #411

Closed

Description

@duguankui

Background

Operators regularly encounter re-uploaded documents (receipts, invoices, etc.) that are semantically equivalent to an already-processed document but with a different binary (re-scanned from the same physical paper). Byte-level deduplication is already in place; this issue adds a second tier that catches these semantic duplicates.

Existing: Tier 1 — File hash (already implemented)

FileOrigin.ContentHash (SHA-256 hex) is stored at upload time and checked before the document is persisted. A collision throws a BusinessException:

  • Extract:DocumentDuplicate — an active document with the same bytes exists (error includes ExistingDocumentId)
  • Extract:DocumentInRecycleBin — the duplicate is soft-deleted in the recycle bin

This is a hard-reject at upload, not a review-queue entry. Nothing to change here.

New: Tier 2 — Field fingerprint (to implement)

Configuration — on FieldDefinition, not DocumentType

Add a boolean flag "Include in unique key" to the FieldDefinition edit form. When checked, this field's extracted value participates in the business identity fingerprint for its document type. This is co-located with the field itself rather than a separate multi-select on the type, which is more discoverable and consistent with the existing field-editing UX.

The flag follows the existing dual-layer design: Host admin controls it for Host-layer types; Tenant admin controls it for their own tenant-layer types.

Detection — FieldFingerprint on Document

After field extraction:

  1. Collect the values of all FieldDefinitions flagged as unique-key for this document's type
  2. Normalize (trim, lowercase) and hash them → FieldFingerprint (new nullable column on Document)
  3. Query for (TenantId, DocumentTypeId, FieldFingerprint) collision against existing documents

Re-extraction consistency

Re-extraction fires FieldsExtractedEto again. The fingerprint recalculation lives in the same FieldsExtracted handler, so the fingerprint is always recomputed alongside the field values with no special handling.

Review queue integration

A FieldFingerprint collision (different bytes, same business identity) enters the existing operator review queue with a new ReviewReason = DuplicateSuspected. The collision candidates are carried as review-entry metadata (DuplicateCandidateDocumentIds) — they do NOT go into ETO payloads to keep event contracts lean.

The operator sees: "疑似重复" with a list of candidate documents. No distinction is shown between byte-level and semantic-level duplicates (Tier 1 already hard-rejects byte-level at upload, so anything reaching the queue is by definition a semantic duplicate).

Resolution follows the existing Ready Gate:

DuplicateSuspected in review queue
        │
        ├── Operator: "Allow (not a duplicate / legitimate re-upload)"
        │       └── DocumentReadyEto fires  → downstream consumes normally
        │
        └── Operator: "Discard (confirmed duplicate)"
                └── DocumentDeletedEto fires

No new lifecycle states are introduced.

Edge case: re-extraction after DocumentReadyEto already fired

If a document is already Ready and re-extraction produces a new FieldFingerprint that collides with another document, the document re-enters the review queue. If the operator allows it, DocumentReadyEto fires again. Downstream consumers already have an at-least-once + EventTime idempotency contract, so this is handled correctly without any new mechanism — but should be explicitly called out in the downstream integration docs.

Schema additions

Entity New field Notes
Document FieldFingerprint (nullable string) Set after field extraction; null when no unique-key fields are configured for the type
FieldDefinition IsUniqueKey (bool, default false) Whether this field participates in the business identity fingerprint

Angular UI

  • FieldDefinition edit form: add "Include in unique key" checkbox
  • Review panel for DuplicateSuspected entries:
    • Action: Allow → document proceeds to Ready
    • Action: Discard → document is soft-deleted
    • Show DuplicateCandidateDocumentIds as clickable links for side-by-side comparison

Out of scope

  • Cross-type duplicate detection (a document classified into the wrong type is a classification problem, not a deduplication problem)
  • Automatic merge or replacement of duplicate records (operator confirms; the channel does not auto-act)
  • Byte-level deduplication (already implemented via FileOrigin.ContentHash)

Activity

  1. duguankui commented on Jun 23, 2026

    @duguankui
    MemberAuthor

    Design decision: Ready-gating (chosen over non-blocking alert)

    While implementing, the pipeline ordering forced a design decision. field-extraction is currently a non-key, lifecycle-neutral pipeline (ExtractPipelines.KeyPipelines = { text-extraction, classification }), so DocumentReadyEto fires at classification completion — before field extraction runs. Since FieldFingerprint depends on extracted fields, fingerprint-based duplicate detection is fundamentally a post-Ready signal: by the time a collision is detectable, downstream has already received the document.

    Two options:

    1. Non-blocking alert + discard-retracts: let it go Ready, alert the operator; on "discard" → DocumentDeletedEto → downstream retracts. Small change, consistent with the existing MissingRequiredFields pattern, but downstream briefly sees the suspected duplicate.
    2. Ready-gating (chosen): withhold DocumentReadyEto until the duplicate check passes, so downstream never receives a suspected duplicate.

    Decision: option 2. This requires overturning the documented lifecycle-neutrality of field-extraction.

    Implementation approach

    • field-extraction becomes a key pipeline (added to ExtractPipelines.KeyPipelines). DeriveLifecycleAsync now withholds Ready until field extraction succeeds, so DocumentReadyEto fires only after fields are extracted and no duplicate is suspected.
    • The classification→field-extraction cascade is routed through DocumentFieldExtractionBackgroundJob (the event handler now enqueues the job instead of calling the service inline) so the cascade path also creates a DocumentPipelineRun — required for the run to participate in the Ready gate.
    • Containers are exempted from the field-extraction requirement in DeriveLifecycleAsync (a container runs no field extraction and must still reach Ready lifecycle).
    • DuplicateSuspected is added to DocumentReviewReasons as a blocking reason (ReviewReasonPolicy.Blocking). A collision sets it during field extraction; the document stays out of Ready and enters the operator review queue.
    • Document.FieldFingerprint (nullable) stores the SHA-256 of normalized unique-key field values; computed only when all IsUniqueKey fields for the type have values (partial keys → null, to avoid false positives).
    • Document.DuplicateAllowed (bool) is a durable operator override so a re-extraction (Document reprocessing (reclassification / field re-extraction) batch mechanism — design and implementation plan #289 bulk / manual reclassify) does not re-flag a document the operator already cleared.
    • Operator actions: Allow → new AllowDuplicateAsync (sets DuplicateAllowed, clears DuplicateSuspected, re-derives lifecycle → Ready). Discard → existing DeleteAsync (soft-delete → DocumentDeletedEto).
    • Candidate documents are recomputed on read at DTO assembly (BuildReviewReasonDetailsAsync) by re-querying the fingerprint collision — no separate candidate storage.

    Consequence (documented)

    Bulk re-extraction (#289) of an already-Ready document now bounces Ready → Processing → Ready and re-fires DocumentReadyEto; downstream absorbs the re-delivery via the existing at-least-once + EventTime idempotency contract. This reverses the #289 "field-extraction is lifecycle-neutral" property by design.

  2. added 3 commits that reference this issue on Jun 23, 2026
  3. added a commit that references this issue on Jul 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions