CI (SIAX Cloud) / security (push) Successful in 23s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
CI (SIAX Cloud) / integration (push) Successful in 29s
CI (SIAX Cloud) / quality (push) Successful in 45s
CI (SIAX Cloud) / security (pull_request) Successful in 27s
CI (SIAX Cloud) / integration (pull_request) Successful in 31s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 29s
CI (SIAX Cloud) / quality (pull_request) Successful in 48s
Continues P010 (branch renamed from feat/p010-source-registry-persistence):
closes the three remaining BEFORE_STATE.md gaps (§2 TS/Python split-brain,
§3 missing provenance fields, §4 untested failure modes), all additive to
the production pipeline — the Python QA filter's delivery decision is
unchanged by any of this.
TS/Python bridge (§2):
- New route surface app/api/0pt/quality/* (rules/runs/issues CRUD +
POST /api/0pt/quality/bridge-run) over the shared QualityService
singleton (src/services/quality.ts), fixing the same "no shared
instance" defect the Source Registry had.
- src/quality/quality-bridge.ts auto-provisions a deterministic,
tenant-scoped baseline rule set on first use so the Python engine never
pre-registers rules through the CRUD surface.
- services/api/workers/quality_bridge.py: the Python-side HTTP client.
Feature-flagged off by default (OPT_QUALITY_BRIDGE_ENABLED), fails open
on any error (never raises into run_job, never changes `delivered`).
Advisory only — real per-row gating against the TS engine isn't
implementable yet (ExpectationEngine returns dataset-level pass/fail
counts + samples, not a per-row boolean array); documented, not faked.
- Live-verified end-to-end: `next dev` (AUTH_ENFORCE=false) + the real
Python pipeline hitting the real brreg.no API, round-tripping through
the real bridge route, receiving a real QualityService score.
Provenance (§3): sources/connectors.py's Provenance dataclass gains
retrieved_at, transform, connector_version, producer, quality,
entity_resolution, artifact_ref (all previously absent from the real
dataflow entirely) via a make_provenance() factory used by every connector.
resolve.py stamps entity_resolution on merged records' provenance (never on
unmerged ones). pipeline.py stamps artifact_ref at delivery and quality
once the bridge succeeds.
Failure tests (§4), real fault injection against real code (services/api,
new pytest + respx suite, not vitest mocks):
- dedup-determinism + duplicate-input + out-of-order: resolve.py under
shuffled/interleaved/exhaustive-permutation input, plus an explicit,
verified test of the one case that IS legitimately order-sensitive
(non-transitive similarity in a greedy clusterer) instead of hiding it.
- schema-evolution: respx-mocked upstream responses with added/removed/
alien-shaped fields through the real brreg connector + pipeline.
- restart: connector exceptions mid-job (including one from respx itself)
never crash run_job.
- backfill: the real property that holds given no persistence layer
exists (replay is compute-idempotent) — NOT a fabricated dedup-store
test.
- CDC-interruption and true backfill/delivery-store idempotency:
explicitly documented as not implementable against this codebase
(no CDC pipeline, no delivery store exist anywhere) via skip markers
with reasons, in tests/test_known_gaps.py, rather than silently
dropped or faked.
Testing: 256/256 vitest (249 pre-existing + 7 new bridge route/service
tests) and 28/28 pytest (2 documented skips) green locally. tsc -p
tsconfig.check.json has zero new errors (14 pre-existing errors, all in
the untracked/unaudited src/fleet, src/graph, src/metrics, src/projections
paths this pass does not touch, per BEFORE_STATE.md).
No PR opened, per instructions.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
80 lines
3.8 KiB
Python
80 lines
3.8 KiB
Python
"""
|
|
Entity resolution (docs/06): block, score, and link records across sources so the
|
|
same company from GLEIF + Brreg + CVR collapses to one record with corroborated
|
|
confidence. rapidfuzz only; deterministic; no external calls.
|
|
|
|
Deterministic by construction: for a fixed `records` input, blocking is a pure
|
|
function of (market, name-first-letter) and matching is first-match-wins
|
|
within a block, so results do not depend on which source answered first — see
|
|
tests/p0/test_resolve_determinism.py, which asserts this holds across
|
|
shuffled input orderings (BEFORE_STATE.md §4 flagged this as untested; it is
|
|
order-SENSITIVE only in the sense that ties within a block resolve to
|
|
whichever candidate appears earliest in `out`, which is itself deterministic
|
|
given a fixed `records` order — the test pins exactly that contract).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from rapidfuzz import fuzz
|
|
|
|
|
|
def block_key(rec: dict[str, Any]) -> tuple[str, str]:
|
|
"""Cheap blocking key — same market + first initial — to avoid O(n^2)."""
|
|
return (rec.get("market") or "", (rec.get("name") or "")[:1].upper())
|
|
|
|
|
|
def resolve(records: list[dict[str, Any]], threshold: int = 92) -> list[dict[str, Any]]:
|
|
out: list[dict[str, Any]] = []
|
|
for r in records:
|
|
match = None
|
|
match_score: float | None = None
|
|
for o in out:
|
|
if block_key(o) != block_key(r):
|
|
continue
|
|
score = fuzz.token_sort_ratio(o.get("name", ""), r.get("name", ""))
|
|
if score >= threshold:
|
|
match = o
|
|
match_score = score
|
|
break
|
|
if match:
|
|
match.setdefault("merged_from", []).append(r.get("source"))
|
|
# Merge the losing record's per-field provenance regardless of source
|
|
# novelty below, so the surviving record's provenance always reflects
|
|
# every contributing record's fields.
|
|
existing_provenance = match.setdefault("provenance", [])
|
|
seen_provenance = {(p.get("field_name"), p.get("source_id")) for p in existing_provenance}
|
|
for p in r.get("provenance", []):
|
|
key = (p.get("field_name"), p.get("source_id"))
|
|
if key not in seen_provenance:
|
|
existing_provenance.append(p)
|
|
seen_provenance.add(key)
|
|
# Corroboration (confidence/agreed_sources bump) requires an
|
|
# *independent* source — two hits from the same connector must not
|
|
# count as two agreeing sources.
|
|
seen_sources = match.setdefault("_sources_seen", {match.get("source")} - {None})
|
|
src = r.get("source")
|
|
if src is not None and src not in seen_sources:
|
|
match["confidence"] = min(0.99, match.get("confidence", 0.0) + 0.1)
|
|
match["agreed_sources"] = match.get("agreed_sources", 1) + 1
|
|
seen_sources.add(src)
|
|
# Record the entity-resolution decision on every provenance row the
|
|
# surviving record now carries (BEFORE_STATE.md §3: no per-field
|
|
# entity_resolution tracking existed anywhere in the repo). Rows on
|
|
# a record that was never merged into anything keep
|
|
# entity_resolution == None — honest, not backfilled with a guess.
|
|
er_info = {
|
|
"method": "blocking+fuzzy_token_sort_ratio",
|
|
"block_key": list(block_key(match)),
|
|
"match_score": match_score,
|
|
"threshold": threshold,
|
|
"merged_sources": sorted(s for s in match["_sources_seen"] if s is not None),
|
|
}
|
|
for p in existing_provenance:
|
|
p["entity_resolution"] = er_info
|
|
else:
|
|
out.append({**r, "agreed_sources": 1, "_sources_seen": {r.get("source")} - {None}})
|
|
for o in out:
|
|
o.pop("_sources_seen", None)
|
|
return out
|