feat: harden canonical ER service and idempotent batch submission

This commit is contained in:
2026-09-07 18:17:52 +02:00
parent 9782eaf42c
commit 243918a255
+86 -90
View File
@@ -1,44 +1,18 @@
/**
* src/er/entity-resolution-service.ts
* ====================================
* Generic Entity Resolution capability (Master-DoD §10 Entity Resolution:
* candidate API, generic probability, blocking, explanation, product
* hard-rule hook, human review handoff).
* Canonical generic Entity Resolution capability.
*
* Division of labour, stated plainly:
* - THIS service is the GENERIC candidate API: deterministic blocking +
* a transparent similarity scorer (token Jaccard + normalized Levenshtein)
* producing an explainable per-pair score. It is the reference
* implementation and the contract.
* - HEAVY/statistical ER (Splink probabilistic linkage, §11 ER) is
* 0pt-motor's job — `submitBatchResolution` creates the N0D job
* ("0pt.er.batch_resolution") and never fakes its output.
* - PRODUCTS own domain judgement via the HARD-RULE HOOK: e.g. VehIQ
* registers VIN-equality rules that FORCE match/non-match regardless of
* the generic score (Master-DoD §24 "VIN hard rules ... negative
* identity evidence"). Hard rules always win over probabilities.
* - Pairs in the configurable "review band" are handed off to humans
* (status pending_review) — never auto-merged.
*
* GENERIC means GENERIC: no person-matching logic, no Ratsit/PII pipelines —
* records are opaque field maps supplied by the calling product under its
* own legal basis; this module implements comparison mechanics only.
*
* P065 STATUS — THIS IS THE CANONICAL ENGINE, AND IT IS NOT YET THE ONLY ONE.
* `services/api/workers/resolve.py` is a second, simplified ER engine (fuzzy
* threshold, auto-merge, no hard rules, no review band) that
* `services/api/workers/pipeline.py` still calls. P065's DoD ("no second
* simplified duplicated production engine remains") is therefore NOT met.
* See that file's header for why it was not rewritten blind in the
* P060-P068 pass and STATUS.md for the removal plan. The ingestion plane
* added in that pass (src/ingestion/*) deliberately does no ER of its own —
* it stops at the sink, so it adds no THIRD engine.
* - synchronous candidate generation is deterministic, explainable and
* review-aware;
* - product hard rules may override probabilities in either direction;
* - heavy/statistical ER is delegated to 0pt-motor through N0D;
* - the legacy Python production scorer has been removed: Python is now only
* an adapter to this canonical decision engine.
*/
import crypto from "crypto";
import { SiaxError } from "../platform/errors";
import type { N0dClient, N0dJob } from "../clients/n0d-client";
import { SiaxError } from "../platform/errors";
import { isResourceRef } from "../platform/resource-ref";
/** An opaque record supplied by the calling product. */
export interface ErRecord {
record_id: string;
fields: Record<string, string | number | null | undefined>;
@@ -46,7 +20,6 @@ export interface ErRecord {
export type HardRuleDecision = "force_match" | "force_non_match" | "abstain";
/** Product-supplied hard rule (the §10 hook). */
export interface HardRule {
rule_id: string;
decide(a: ErRecord, b: ErRecord): HardRuleDecision;
@@ -56,13 +29,9 @@ export interface ErCandidateRequest {
tenant_id: string;
project_id: string;
records: ErRecord[];
/** Fields whose normalized values form the blocking key. */
blocking_fields: string[];
/** Fields compared for similarity (weight defaults to 1). */
compare_fields: { field: string; weight?: number }[];
/** Score ≥ auto_match_threshold → match (unless a hard rule vetoes). Default 0.9. */
auto_match_threshold?: number;
/** Score ≥ review_threshold (< auto) → pending_review. Default 0.6. */
review_threshold?: number;
correlation_id?: string;
}
@@ -81,12 +50,9 @@ export interface ErCandidatePair {
candidate_id: string;
record_a: string;
record_b: string;
/** Generic similarity score 0..1. */
score: number;
status: ErCandidateStatus;
/** Which mechanism decided: hard rule id, or "score". */
decided_by: string;
/** Per-field breakdown — the §10 explanation. */
explanation: ErFieldExplanation[];
blocking_key: string;
}
@@ -95,49 +61,77 @@ export interface ErCandidateResult {
request_id: string;
tenant_id: string;
pairs: ErCandidatePair[];
/** Pairs handed to human review (subset of pairs). */
review_queue: ErCandidatePair[];
blocked_comparisons: number;
total_possible_comparisons: number;
}
export interface SubmitBatchResolutionInput {
tenant_id: string;
project_id: string;
records_artifact_ref: string;
actor_id?: string;
correlation_id?: string;
idempotency_key?: string;
}
export class EntityResolutionService {
private readonly hardRules: HardRule[] = [];
constructor(private readonly opts: { n0dClient?: N0dClient } = {}) {}
/** The product hard-rule hook (§10). Rules run in registration order. */
registerHardRule(rule: HardRule): void {
if (!rule.rule_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "hard rule requires rule_id");
if (this.hardRules.some((existing) => existing.rule_id === rule.rule_id)) {
throw new SiaxError("CONFLICT", "0pt.er", `hard rule ${rule.rule_id} is already registered`);
}
this.hardRules.push(rule);
}
// -----------------------------------------------------------------------
// Candidate API (synchronous, generic)
// -----------------------------------------------------------------------
generateCandidates(req: ErCandidateRequest): ErCandidateResult {
if (!req.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "tenant_id is required");
if (!req.tenant_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "tenant_id is required");
if (!req.project_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "project_id is required");
if (req.records.length < 2 || req.records.length > 5_000) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "records must contain between 2 and 5000 items");
}
if (req.records.length < 2) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "at least two records are required");
if (new Set(req.records.map((record) => record.record_id)).size !== req.records.length) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "record_id values must be unique");
}
if (req.blocking_fields.length === 0) {
if (req.blocking_fields.length < 1 || req.blocking_fields.length > 20) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.er",
"blocking_fields must not be empty — unblocked all-pairs comparison is refused (quadratic + §46)"
"blocking_fields must contain 1-20 fields — unblocked all-pairs comparison is refused",
);
}
if (req.compare_fields.length < 1 || req.compare_fields.length > 50) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "compare_fields must contain 1-50 fields");
}
for (const { field, weight = 1 } of req.compare_fields) {
if (!field?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "compare field name is required");
if (!Number.isFinite(weight) || weight < 0 || weight > 100) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", `invalid weight for compare field ${field}`);
}
}
const autoThreshold = req.auto_match_threshold ?? 0.9;
const reviewThreshold = req.review_threshold ?? 0.6;
if (reviewThreshold >= autoThreshold) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "review_threshold must be < auto_match_threshold");
if (
!Number.isFinite(autoThreshold) || autoThreshold < 0 || autoThreshold > 1 ||
!Number.isFinite(reviewThreshold) || reviewThreshold < 0 || reviewThreshold > 1 ||
reviewThreshold >= autoThreshold
) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.er",
"thresholds must be within 0..1 and review_threshold must be lower than auto_match_threshold",
);
}
// Blocking: bucket records by normalized blocking key.
const blocks = new Map<string, ErRecord[]>();
for (const rec of req.records) {
const key = req.blocking_fields.map((f) => normalize(String(rec.fields[f] ?? ""))).join("|");
if (!rec.record_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "every record requires record_id");
const key = req.blocking_fields.map((field) => normalize(String(rec.fields[field] ?? ""))).join("|");
const bucket = blocks.get(key) ?? [];
bucket.push(rec);
blocks.set(key, bucket);
@@ -146,10 +140,10 @@ export class EntityResolutionService {
const pairs: ErCandidatePair[] = [];
let blockedComparisons = 0;
for (const [key, bucket] of blocks) {
if (key.replace(/\|/g, "") === "") continue; // empty blocking key never blocks together
if (key.replace(/\|/g, "") === "") continue;
for (let i = 0; i < bucket.length; i++) {
for (let j = i + 1; j < bucket.length; j++) {
blockedComparisons++;
blockedComparisons += 1;
pairs.push(this.comparePair(bucket[i], bucket[j], req, autoThreshold, reviewThreshold, key));
}
}
@@ -160,32 +154,38 @@ export class EntityResolutionService {
request_id: `errq_${crypto.randomUUID()}`,
tenant_id: req.tenant_id,
pairs,
review_queue: pairs.filter((p) => p.status === "pending_review"),
review_queue: pairs.filter((pair) => pair.status === "pending_review"),
blocked_comparisons: blockedComparisons,
total_possible_comparisons: (n * (n - 1)) / 2,
};
}
// -----------------------------------------------------------------------
// Batch/statistical path — 0pt-motor via N0D (contract only, never faked)
// -----------------------------------------------------------------------
async submitBatchResolution(input: {
tenant_id: string;
project_id: string;
/** ST0RE artifact ref of the record dataset. */
records_artifact_ref: string;
correlation_id?: string;
}): Promise<N0dJob> {
/** Heavy/statistical path — an idempotent N0D job executed by 0pt-motor. */
async submitBatchResolution(input: SubmitBatchResolutionInput): Promise<N0dJob> {
if (!input.tenant_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "tenant_id is required");
if (!input.project_id?.trim()) throw new SiaxError("INVALID_REQUEST", "0pt.er", "project_id is required");
if (!isResourceRef(input.records_artifact_ref, "st0re", "artifact")) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.er",
"records_artifact_ref must be a canonical st0re:artifact:... reference",
);
}
if (!this.opts.n0dClient) {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "n0d", "no N0D client configured for batch ER");
}
const idempotencyKey = input.idempotency_key?.trim() || crypto
.createHash("sha256")
.update(`0pt.er.batch.v1|${input.tenant_id}|${input.project_id}|${input.records_artifact_ref}`)
.digest("hex");
return this.opts.n0dClient.createJob({
tenant_id: input.tenant_id,
project_id: input.project_id,
job_type: "0pt.er.batch_resolution",
capability_id: "0pt.er.batch.v1",
requested_by_app_id: "0pt",
requested_by_actor_id: "svc_0pt",
requested_by_actor_id: input.actor_id ?? "svc_0pt",
input_artifact_ids: [input.records_artifact_ref],
output_artifact_type: "er_candidate_set",
requires_backbone: false,
@@ -194,19 +194,20 @@ export class EntityResolutionService {
resource_profile: "large",
risk_level: "L3",
correlation_id: input.correlation_id,
idempotency_key: idempotencyKey,
timeout_seconds: 3_600,
max_retries: 2,
});
}
// -----------------------------------------------------------------------
private comparePair(
a: ErRecord,
b: ErRecord,
req: ErCandidateRequest,
autoThreshold: number,
reviewThreshold: number,
blockingKey: string
blockingKey: string,
): ErCandidatePair {
// Hard rules first — they always win (§10/§24).
for (const rule of this.hardRules) {
const decision = rule.decide(a, b);
if (decision !== "abstain") {
@@ -224,12 +225,16 @@ export class EntityResolutionService {
}
const explanation = this.explain(a, b, req);
const weightSum = explanation.reduce((s, e) => s + e.weight, 0);
const score = weightSum === 0 ? 0 : explanation.reduce((s, e) => s + e.similarity * e.weight, 0) / weightSum;
const weightSum = explanation.reduce((sum, item) => sum + item.weight, 0);
const score = weightSum === 0
? 0
: explanation.reduce((sum, item) => sum + item.similarity * item.weight, 0) / weightSum;
const rounded = Math.round(score * 1000) / 1000;
const status: ErCandidateStatus =
rounded >= autoThreshold ? "match" : rounded >= reviewThreshold ? "pending_review" : "non_match";
const status: ErCandidateStatus = rounded >= autoThreshold
? "match"
: rounded >= reviewThreshold
? "pending_review"
: "non_match";
return {
candidate_id: `erc_${crypto.randomUUID()}`,
record_a: a.record_id,
@@ -257,14 +262,6 @@ export class EntityResolutionService {
}
}
// ---------------------------------------------------------------------------
// Transparent similarity primitives (deterministic; the "generic probability")
// ---------------------------------------------------------------------------
/**
* Case-fold, DIACRITIC-FOLD (ö→o, é→e — deliberate: "Göteborg" and
* "Goteborg" must land in the same block), strip punctuation, collapse
* whitespace. ø has no NFKD decomposition and is mapped explicitly.
*/
export function normalize(s: string): string {
return s
.toLowerCase()
@@ -276,7 +273,6 @@ export function normalize(s: string): string {
.trim();
}
/** Combined similarity: max(token Jaccard, 1 - normalized Levenshtein). */
export function similarity(a: string | null, b: string | null): number {
if (a === null || b === null) return 0;
const na = normalize(a);
@@ -289,7 +285,7 @@ export function similarity(a: string | null, b: string | null): number {
function tokenJaccard(a: string, b: string): number {
const ta = new Set(a.split(" "));
const tb = new Set(b.split(" "));
const intersection = [...ta].filter((t) => tb.has(t)).length;
const intersection = [...ta].filter((token) => tb.has(token)).length;
const union = new Set([...ta, ...tb]).size;
return union === 0 ? 0 : intersection / union;
}