Files
0pt/src/er/entity-resolution-service.ts
T
Simon AxelssonandClaude Opus 5 9267576b7c
CI (SIAX Cloud) / integration (push) Successful in 42s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / security (push) Successful in 46s
Security Scan (SIAX Cloud) / security (push) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 27s
feat(data-os): P060-P068 durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill
BEFORE_STATE (verified, with evidence):

* P060 PARTIAL/BROKEN. The registry persisted rights/provenance/health/
  freshness to Postgres, but carried no authorization, no schedule, no
  checkpoint, no schema and no owner distinct from created_by — and the
  activation DoD was inverted: postgres-source-repository.ts wrote
  `${input.status ?? "active"}`, so a source with no rights, no provenance
  and no authorization was ACTIVE the instant it was registered. No
  activation operation existed at all.
* P061 MISSING. services/api/sources/connectors.py had per-source fetch_*()
  functions only — no lifecycle, no cursor, no resume, no health, no
  conformance suite.
* P062 MISSING, already documented as such in
  services/api/tests/test_known_gaps.py:10-19 (no CDC pipeline anywhere;
  workers/pipeline.py has no persistence at all).
* P063 MISSING. schema_version existed as a free string; no comparison,
  no policy, no versioned source schema.
* P064 PARTIAL. Rules/runs/issues/scores existed, but a failing rule only
  opened an issue and the data flowed on. No quarantine anywhere.
* P065 DUPLICATE (confirmed). Two ER engines: src/er/entity-resolution-
  service.ts (canonical) and services/api/workers/resolve.py (simplified,
  still called by pipeline.py:110).
* P067 PARTIAL. Lineage was emitted to AUD0 but nothing here could ANSWER a
  lineage question — no store, no query, no route.
* P068 MISSING, documented in test_known_gaps.py:44-52 ("no delivery-store
  persistence layer exists to dedupe a backfill against").

BUILT (only what was PARTIAL/BROKEN/MISSING):

* P060 sql/007_ingestion_plane.sql adds authorization/schedule/schemas/
  checkpoints/ledger/quarantine/lineage tables, owner_id, and flips the
  opt_sources status DEFAULT to 'pending' so even a raw psql INSERT cannot
  produce an unclassified-but-active source. SourceRegistryService gains
  classifySource/activateSource/deactivateSource + authorization/schedule
  accessors; registration NEVER activates (asking for status:"active" goes
  through the gate, not around it); a service identity cannot authorize a
  source. Routes: activate (GET classification / POST activate),
  authorization, schedule.
* P061 src/connectors/connector.ts — all nine operations on one interface.
  src/connectors/conformance.ts — a runnable suite (15 checks, no "skip"
  verdict). HttpJsonConnector (real HTTP, opaque cursor) and
  JsonlFileConnector (real file, line offsets, CDC deletes) both pass it.
  The suite caught a real defect while being written: an API that drops
  next_cursor at the end left the connector unable to resume, which is why
  HttpJsonConnectorConfig has cursor_field.
* P062 src/types/ingestion.ts + src/ingestion/{envelope,ingestion-runner}.ts.
  One envelope for batch/stream/cdc; durable per-(source,partition)
  checkpoints; resume proven by killing a run inside the sink.
* P063 src/schema/{record-schema,compatibility,schema-registry}.ts. Two
  enforcement points, both upstream of any consumer write: a discovery gate
  before the first read, and per-record conformance before the page reaches
  the sink. A producer cannot widen its own policy retroactively.
* P064 src/quality/quality-policy.ts composes the EXISTING ExpectationEngine
  (not a second engine) and adds the missing consequence: block /
  quarantine / warn, with quarantine durable and recoverable. No policy is
  reported as "none_declared", never as a pass; an unexecutable expectation
  counts as a violation, never a silent pass.
* P067 src/lineage/{lineage-edge,lineage-store}.ts + GET /api/0pt/lineage.
  AUD0 stays the system of record; this is 0pt's own queryable projection.
* P068 opt_ingestion_ledger + IngestionRunner.backfill: bounded, idempotent
  on repeat, leaves the live checkpoint alone, still re-emits real changes.

A BUG THIS PASS WROTE AND CAUGHT: the first IngestionRepository draft
combined the idempotency check and its recording into one atomic call
BEFORE the sink. The crash/resume test then delivered 7 of 10 records — the
page in flight when the sink died was already marked delivered, so the
resumed run skipped it as a duplicate. Permanent, silent data loss. Fixed by
splitting peekDeliveries/commitDeliveries and committing both the ledger and
the checkpoint only after the sink resolves.

NOT DONE, stated rather than deferred quietly:

* P065 is NOT met. resolve.py is still a second simplified production
  engine. Closing it means rewriting it as an adapter over the canonical
  service, which cannot be verified from this repo today: services/api is
  not built by this repo's Dockerfile, api.0pt.app answers 404, and NO CI
  workflow runs its pytest suite. The duplication is now stated at both
  sites in code and the removal plan is in STATUS.md. The new ingestion
  plane performs no ER, so it adds no third engine.
* P066 (Iceberg) untouched — ST0RE is owned by another workflow. Contract
  read only.
* Delivery is AT-LEAST-ONCE, not exactly-once (no per-partition run lock).
* No CDC *source* exists; the contract is met, a CDC connector is not built.
* 0pt does not schedule itself — the schedule row is a declaration ACT0
  would read.

VERIFIED: pnpm typecheck clean; pnpm test 365 passed / 25 skipped (was
311/18); pnpm build clean with all four new routes in the route table; lint
unchanged at 12 pre-existing errors. Real Postgres 16
(tests/p0/ingestion-plane-postgres.realinfra.test.ts, 7 passed) plus a real
`docker restart` of that container with an identical read-back through the
production code path — that is P060's "a restart preserves all sources",
measured.

DEPLOYMENT REALITY (curl, 2026-09-04): 0pt.app/api/health returns 200 from
Vercel with db:not_configured; 0pt.app/api/0pt/sources returns 404;
api.0pt.app/health returns 404; cd.yml still guards on a placeholder Coolify
app id. None of the capability layer runs in production. Nothing here is
LIVE_VERIFIED and STATUS.md says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 17:03:14 +02:00

321 lines
12 KiB
TypeScript

/**
* 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).
*
* 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.
*/
import crypto from "crypto";
import { SiaxError } from "../platform/errors";
import type { N0dClient, N0dJob } from "../clients/n0d-client";
/** An opaque record supplied by the calling product. */
export interface ErRecord {
record_id: string;
fields: Record<string, string | number | null | undefined>;
}
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;
}
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;
}
export type ErCandidateStatus = "match" | "pending_review" | "non_match";
export interface ErFieldExplanation {
field: string;
a: string | null;
b: string | null;
similarity: number;
weight: number;
}
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;
}
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 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 {
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.records.length < 2) {
throw new SiaxError("INVALID_REQUEST", "0pt.er", "at least two records are required");
}
if (req.blocking_fields.length === 0) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.er",
"blocking_fields must not be empty — unblocked all-pairs comparison is refused (quadratic + §46)"
);
}
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");
}
// 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("|");
const bucket = blocks.get(key) ?? [];
bucket.push(rec);
blocks.set(key, bucket);
}
const pairs: ErCandidatePair[] = [];
let blockedComparisons = 0;
for (const [key, bucket] of blocks) {
if (key.replace(/\|/g, "") === "") continue; // empty blocking key never blocks together
for (let i = 0; i < bucket.length; i++) {
for (let j = i + 1; j < bucket.length; j++) {
blockedComparisons++;
pairs.push(this.comparePair(bucket[i], bucket[j], req, autoThreshold, reviewThreshold, key));
}
}
}
const n = req.records.length;
return {
request_id: `errq_${crypto.randomUUID()}`,
tenant_id: req.tenant_id,
pairs,
review_queue: pairs.filter((p) => p.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> {
if (!this.opts.n0dClient) {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "n0d", "no N0D client configured for batch ER");
}
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",
input_artifact_ids: [input.records_artifact_ref],
output_artifact_type: "er_candidate_set",
requires_backbone: false,
requires_gpu: false,
required_node_roles: ["compute_general"],
resource_profile: "large",
risk_level: "L3",
correlation_id: input.correlation_id,
});
}
// -----------------------------------------------------------------------
private comparePair(
a: ErRecord,
b: ErRecord,
req: ErCandidateRequest,
autoThreshold: number,
reviewThreshold: number,
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") {
return {
candidate_id: `erc_${crypto.randomUUID()}`,
record_a: a.record_id,
record_b: b.record_id,
score: decision === "force_match" ? 1 : 0,
status: decision === "force_match" ? "match" : "non_match",
decided_by: rule.rule_id,
explanation: this.explain(a, b, req),
blocking_key: blockingKey,
};
}
}
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 rounded = Math.round(score * 1000) / 1000;
const status: ErCandidateStatus =
rounded >= autoThreshold ? "match" : rounded >= reviewThreshold ? "pending_review" : "non_match";
return {
candidate_id: `erc_${crypto.randomUUID()}`,
record_a: a.record_id,
record_b: b.record_id,
score: rounded,
status,
decided_by: "score",
explanation,
blocking_key: blockingKey,
};
}
private explain(a: ErRecord, b: ErRecord, req: ErCandidateRequest): ErFieldExplanation[] {
return req.compare_fields.map(({ field, weight }) => {
const av = a.fields[field] === null || a.fields[field] === undefined ? null : String(a.fields[field]);
const bv = b.fields[field] === null || b.fields[field] === undefined ? null : String(b.fields[field]);
return {
field,
a: av,
b: bv,
similarity: similarity(av, bv),
weight: weight ?? 1,
};
});
}
}
// ---------------------------------------------------------------------------
// 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()
.replace(/ø/g, "o")
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.replace(/[^a-z0-9 ]/g, " ")
.replace(/\s+/g, " ")
.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);
const nb = normalize(b);
if (na === "" && nb === "") return 0;
if (na === nb) return 1;
return Math.max(tokenJaccard(na, nb), 1 - normalizedLevenshtein(na, nb));
}
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 union = new Set([...ta, ...tb]).size;
return union === 0 ? 0 : intersection / union;
}
function normalizedLevenshtein(a: string, b: string): number {
const maxLen = Math.max(a.length, b.length);
if (maxLen === 0) return 0;
return levenshtein(a, b) / maxLen;
}
function levenshtein(a: string, b: string): number {
const m = a.length;
const n = b.length;
if (m === 0) return n;
if (n === 0) return m;
let prev = new Array<number>(n + 1);
let curr = new Array<number>(n + 1);
for (let j = 0; j <= n; j++) prev[j] = j;
for (let i = 1; i <= m; i++) {
curr[0] = i;
for (let j = 1; j <= n; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
}
[prev, curr] = [curr, prev];
}
return prev[n];
}