Identity Resolution & Reconciliation: resolve, and route duplicates
This guide covers how IdentityResolver and ReconciliationTask in engine/identity_resolution.py implement identity handling for the four entity types: Order, Material, Qualification and Schedule identity. Each is resolved explicit-first, with inferred matching as a conservative fallback. An inferred match is never silently assumed.
1. Resolve an observation
from engine.activity_log import ActivityLog
from engine.identity_resolution import (
EntityType,
IdentityObservation,
IdentityStore,
IdentityResolver,
)
store = IdentityStore() # production default table name: identity_records
store.ensure_schema()
resolver = IdentityResolver(store, ActivityLog(), node_type="ERP", node_instance_id="erp-1")
result = resolver.resolve(IdentityObservation(entity_type=EntityType.ORDER, reference_id="MO-1001"))
result.outcome is one of IdentityResolutionOutcome:
RESOLVED_EXPLICIT:reference_idmatched an existing record.result.recordis that existing record (sameid), not a new row. This is what "two records with matching explicit reference IDs resolve as the same entity" means in practice.NEW: there was nothing to match against. Either an explicitreference_idwas seen for the first time, or an inferred observation had no candidate above the matcher's threshold. A fresh canonical record is created.PENDING_INFERRED: there was noreference_id, but the matcher found a candidate. This never auto-resolves, regardless of how strong the match score is. The inferred branch always routes to Mandatory-Human Status, whatever the matcher's confidence, because the fallback path is conservative by design.- A new
PENDINGrecord is created, carryingmatched_record_idandmatch_scorepointing at the candidate, andorigin="inferred_match". - A person later confirms or rejects it with
IdentityStore.resolve_pending(section 5). The resolver itself only ever sets the status.
- A new
NOT_CANONICAL:reference_idmatched a record a person already rejected, or merged into another record. It is neither a resolved match nor one awaiting a decision, so nothing is resolved onto it.ReconciliationTaskreports the same outcome for such a reference and merges nothing into the row.
The explicit-versus-inferred split is built as a Gate (engine/gate.py, EvaluationMode.RULE). It is the one Gate instance named directly for Identity Resolution. It is a plain, fixed two-way branch (evaluate never returns anything but the two branch names), so it declares no branches or fallback set, per Gate's docstring.
2. The inferred matcher is pluggable
from engine.identity_resolution import attribute_overlap_matcher
resolver = IdentityResolver(
store, activity_log, "Training & Certification", "tnc-1", matcher=my_splink_backed_matcher
) # same Callable shape
InferredMatcher is Callable[[IdentityObservation, list[IdentityRecord]], InferredMatch | None].
The default, attribute_overlap_matcher(), is a deterministic stand-in. It checks literal agreement across attributes both records share, which is not genuine probabilistic record linkage. It is good enough to exercise the Pending-routing policy above without adding a record-linkage library (such as Splink) to the engine's dependency set. A matcher backed by one plugs in through the same callable shape.
The candidate pool a matcher sees is always IdentityStore.list_resolved. It excludes:
PENDINGrecords, because a match still awaiting human confirmation isn't itself a canonical identity to match new observations against;MERGEDandREJECTEDrecords, because a person's decision has already been made about them.
3. Reconciliation: a known reference_id updates in place, not a duplicate
from engine.identity_resolution import ReconciliationTask
reconciliation = ReconciliationTask(store, activity_log, "ERP", "erp-1")
result = reconciliation.run(EntityType.ORDER, "MO-2002", {"status": "completed"})
This is not a new trigger mechanism. The IdentityStore.get_by_reference_id lookup that explicit resolution already needs also decides whether a reference_id is fresh or revisiting something on file.
| The lookup finds | What happens | Outcome |
|---|---|---|
| A record | IdentityStore.merge_attributes_if_open merges the event's attributes onto it in one atomic UPDATE. |
RECONCILED, same id |
| A row a person has already rejected or merged into another | Nothing is merged. The status test is in the UPDATE's own WHERE, which returns None. |
NOT_CANONICAL |
| Nothing | There is nothing to reconcile against yet, so it resolves as NEW instead, the same as IdentityResolver's explicit-miss path. |
NEW |
run raises ValueError for an empty reference_id. Reconciliation only ever applies to events that carry one. An observation with none belongs to IdentityResolver.resolve's inferred branch.
Concurrent merges
merge_attributes (and merge_attributes_if_open) uses Postgres's jsonb || concat operator (SET attributes = attributes || %s::jsonb) rather than a client-side read, merge and write.
Two concurrent reconciliations of the same record are a realistic race. Reconciliation exists specifically to handle late-arriving or duplicate events, which can themselves race with each other. With the || operator, both contribute their own attributes, instead of one UPDATE silently overwriting the other's merged result wholesale.
4. Concurrent resolution of the same new reference_id is race-safe
TriggerQueue.claim (engine/trigger_queue.py) already assumes concurrent dispatch workers exist. Two workers resolving the same brand-new reference_id at once (two events both naming an Order for the first time) is therefore a real scenario, not a hypothetical.
The mechanism:
IdentityStore.ensure_schemacreates a partial unique index over(entity_type, reference_id). It excludesNULLreference_ids, because inferred-branch rows have no natural key to deduplicate on.IdentityStore.saveinserts throughON CONFLICT ... DO NOTHINGagainst it, and returnsFalsewhen it loses the race.IdentityStore.save_or_get_existingwraps that. It returns the record itself when its insert won, or the already-on-file winner when it lost.IdentityResolver._resolveandReconciliationTask._reconcileboth call it and compare by identity (is).
What a losing call does:
- A losing
resolve()re-fetches and returns the winner's record asRESOLVED_EXPLICIT. It never creates a duplicate row. - A losing
reconcile()re-fetches the winner and merges its own attributes onto it (RECONCILED), so the event that lost the race doesn't silently drop its own data.
Activity Log
Both IdentityResolver.resolve and ReconciliationTask.run are wired through log_task_execution (see wiring-task-execution-to-activity-log.md). Each writes exactly one ActivityLogEntry:
task_typeis"ingestion-time classification"for resolution, and"Reconciliation"(the formal, capitalized Task type) for reconciliation.reference_idsalways carriesidentity_record_id, plusreference_idandmatched_record_idwhenever the record has them.
5. A person decides a Pending record
from engine.identity_resolution import IdentityDecision
transition = store.resolve_pending(
record.id, IdentityDecision.CONFIRMED, reviewer="alice-token", action_id=action_id
)
transition.record.status # MERGED, RESOLVED or REJECTED
transition.changed_keys # keys a merge added or replaced; None if this call did not decide it
resolve_pending is one atomic, first-writer-wins transition (UPDATE ... WHERE status = 'pending'). It records who decided, when, and the caller's action_id. A later call, whether a retry or another reviewer, finds the row settled and gets its stored state back unchanged.
What "confirm" does depends on which creator wrote the record (origin), because the two mean different things:
| Origin | Written by | Confirming it | Rejecting it |
|---|---|---|---|
inferred_match |
IdentityResolver |
Merges the record's attributes onto its candidate (the record's value wins where both have a key) and marks the record MERGED, in one transaction. |
Marks it REJECTED. The candidate is untouched. |
first_article |
FirstArticleInspectionTask |
Marks it RESOLVED, so the next observation of its reference is a clean match. |
Marks it REJECTED. It stays flagged on its next observation. |
Re-opening a rejection
A rejection is a decision and stays as it was decided, but it can be undone by making a new record. store.reopen(record.id, reviewer=..., action_id=...) clones a rejected record as a new PENDING one:
- The clone has the same attributes, candidate, score and kind.
reopens_idnames the rejected record, andreopened_byandreopen_action_idrecord who re-opened it and by which request.- A reference belongs to one row, so a rejected record that carries one gives it to the clone in the same transaction. The Node then finds a pending first article by that reference.
- The rejected record changes in nothing else, except that one with no stored
originis given the kind it was shown as, since without its reference that kind could no longer be worked out. - Like the decision, it is first-writer-wins:
appliedisFalsefor a later call, which gets the clone back. - It raises
NotRejectedErrorfor a record in any other state. - The clone can be confirmed, rejected or re-opened in turn.
Rows from before origin existed
A row written before the origin column existed has none stored. It is classified by classify_pending: a reference-less row with a candidate is an inferred match, and anything else is a first article. The management API reports a row's kind with the same function, so what a reviewer was shown is what is done. A reference-less first-article placeholder that matched a candidate cannot be told apart from a resolver match, and is treated as one.
Schema changes
origin, the three resolution columns and the three re-opening columns are added to an existing table by the Node's own IdentityStore.ensure_schema, leaving rows in place. The re-opening columns are reopens_id, reopened_by and reopen_action_id, with a unique index on reopens_id so a record is re-opened once.
- Columns are added only when one is missing. Adding a column takes an exclusive lock on the table even when it already exists, so a start that finds every column present takes none. One that must add a column gives up after a lock timeout instead of queueing every other query behind it.
- A service that is not the Node never alters the table.
resolve_pendingagainst one that has not been upgraded raisesIdentityTableNotUpgradedErrorand writes nothing.
Queries the management API reads with
IdentityStore.list_pending_page(limit=, after=, entity_type=, origin=, kind=, status=)returns aPendingIdentityPage:matches, each aPendingIdentityMatchof record, candidate and optional columns, plusnext_cursor.- A cursor it did not issue raises
InvalidCursorError. - Pending rows come oldest first, and decided ones newest decision first.
- It never creates or alters the table.
- A cursor it did not issue raises
IdentityStore.pending_summary()returns(count, earliest created_at)without loading attributes. It returns(0, None)when the table does not exist.resolve_pendingraisesUnknownIdentityRecordErrorfor an id with no record. It raisesCandidateUnavailableErrorwhen an inferred match's candidate is gone or no longer canonical. Nothing is written in that case: the match stays Pending and can be rejected.- For the first-article flow,
get_pending_by_attributefinds a still-Pending, reference-less record by one attribute.upgrade_pending_referencegives it its reference, returningNoneand writing nothing if a reviewer settled it meanwhile.
Pitfalls
- A
PENDINGrecord is a new row, not an edit of the matched candidate.result.record.id != result.record.matched_record_idon aPENDING_INFERREDoutcome. The candidate is left untouched until the Mandatory-Human Sign-off Mechanism's approve or reject resolves the Pending record against it. - The inferred matcher's candidate pool never includes
PENDINGrows. Two ambiguous observations arriving back to back each get their own independent Pending record against the one realRESOLVEDcandidate, rather than matching against each other. ReconciliationTask.runneeds a non-emptyreference_id, and raises otherwise. It isn't a general-purpose "resolve or update" entry point. UseIdentityResolver.resolvefor an observation that might have no explicit reference at all.- The inferred branch's own race is deliberately not closed the same way. Two concurrent observations that both lack a
reference_idcan each miss seeing the other as aRESOLVEDcandidate, and both land asNEW. Unlike the explicit branch, there is no natural key a database constraint could enforce uniqueness on. That is exactly the ambiguity Splink and a human's later confirmation exist to resolve, not something to paper over with a lock. - A confirmed, merged or rejected row keeps its place.
- A rejected first article that carries a
reference_idkeeps its slot in the unique index. Its next observation finds it and is flagged again, never re-inserted and never returned to the review queue by the Node. A person puts it back by re-opening it, which hands the reference to a newPENDINGrow. - A rejected or merged inferred match has no reference, so nothing deduplicates it. The same pair can come back as a new
PENDINGrow on a further observation.
- A rejected first article that carries a
- A first-article placeholder confirmed before its reference arrives is flagged again. The placeholder is a reference-less row. Once it is
RESOLVED,get_pending_by_attributeno longer finds it, so the later observation that carries the reference does not fold into it, and a secondPENDINGrow is written for the same real event. - Only a
QUALIFICATIONrecord isPENDINGwith areference_id. The read paths that look a record up by reference (order status, work in progress for a material, genealogy) do not check status. That is safe only because an order, material or schedule record that carries a reference is alwaysRESOLVED. The order trail does check, and refuses anything else by name.
Release: v0.11.0