fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# 0pt data engine — workers package (router + pipeline).
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
Adaptive router — per-market compliant-source planner.
|
||||
|
||||
P014 CORRECTION: this file's previous docstring read "all methods, no
|
||||
compliance restrictions. See b0ts for scraping." That phrasing directly
|
||||
contradicts this product's own compliance stance (CLAUDE.md §1: official
|
||||
API/bulk -> authorized public web -> licensed partner data -> otherwise
|
||||
level 0, never a bypass) and, worse, pointed a future reader at `b0ts` -- a
|
||||
SEPARATE repo that does non-compliant scraping and is out of scope/forbidden
|
||||
to touch from here. Nothing in this file ever called b0ts or any bypass
|
||||
path; the line was simply wrong and is corrected, not extended.
|
||||
|
||||
What this file actually does: `plan_for_market(market)` returns the ordered
|
||||
list of registered source_ids `pipeline.py._fetch` tries, in priority order,
|
||||
for a given market. Every entry is a name pipeline.py may or may not have an
|
||||
implemented connector for (see sources/connectors.py's CONNECTORS dict) --
|
||||
an unimplemented source_id is simply skipped by `_fetch`, it is never a
|
||||
license to build a bypass in its place.
|
||||
|
||||
P014 ADDITION: `record_blocked` / `is_blocked` give this planner a memory of
|
||||
which (market, source_id) pairs recently told the engine to stop (HTTP
|
||||
401/403/429/451 -- see sources/connectors.py's SourceBlockedError). Before
|
||||
this pass, a source that started rate-limiting or blocking the engine mid-run
|
||||
was retried on every subsequent record with no memory at all -- not a
|
||||
compliance bypass, but not "respecting the block as a stop signal" either
|
||||
(the same principle 0pt-motor's AdaptiveRouter documents for its own,
|
||||
separate method-tier selector). `plan_for_market` now filters a currently-
|
||||
blocked source out of the plan for the rest of the block's cooldown window,
|
||||
so the engine backs off instead of hammering it. This is process-local,
|
||||
in-memory state (matches every other piece of in-memory state this engine
|
||||
documents honestly elsewhere, e.g. orchestrator/main.py's _ORDERS/_JOBS) --
|
||||
not a persistent, cross-process reputation system.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
MARKET_SOURCES: dict[str, list[str]] = {
|
||||
"NO": ["brreg", "brreg_under", "proff", "1881", "gulesider", "flowfirma", "selskapssok", "regnskapsbasen", "okonomi", "visverdi", "gleif"],
|
||||
"GB": ["companies_house", "gleif"],
|
||||
"FI": ["prh", "gleif"],
|
||||
"DK": ["cvr", "krak", "proff_dk", "118", "degulesider", "companydata", "grundigt", "datafordeler", "virk", "gleif"],
|
||||
"DE": ["northdata", "handelsregister", "unternehmensregister", "moneyhouse", "creditreform", "bundesanzeiger", "registercheck", "personensuche", "whitepages", "companyhouse", "gleif"],
|
||||
"SE": ["gleif"],
|
||||
}
|
||||
|
||||
# How long a (market, source_id) pair is excluded from plan_for_market after
|
||||
# being reported blocked. A fixed cooldown, not exponential backoff -- this
|
||||
# is a planner, not a retry/backoff controller; a source is free to be tried
|
||||
# again on the next run once the window elapses.
|
||||
DEFAULT_BLOCK_COOLDOWN_SECONDS = 300.0
|
||||
|
||||
|
||||
class AdaptiveRouter:
|
||||
"""Tracks which (market, source_id) pairs are currently in a block cooldown."""
|
||||
|
||||
def __init__(self, cooldown_seconds: float = DEFAULT_BLOCK_COOLDOWN_SECONDS):
|
||||
self._cooldown = cooldown_seconds
|
||||
self._blocked_until: dict[tuple[str, str], float] = {}
|
||||
|
||||
def record_blocked(self, market: str, source_id: str, *, now: float | None = None) -> None:
|
||||
"""Mark (market, source_id) as blocked starting now."""
|
||||
self._blocked_until[(market, source_id)] = (now if now is not None else time.monotonic()) + self._cooldown
|
||||
|
||||
def is_blocked(self, market: str, source_id: str, *, now: float | None = None) -> bool:
|
||||
deadline = self._blocked_until.get((market, source_id))
|
||||
if deadline is None:
|
||||
return False
|
||||
current = now if now is not None else time.monotonic()
|
||||
if current >= deadline:
|
||||
# Cooldown elapsed -- clear it so the map doesn't grow forever.
|
||||
del self._blocked_until[(market, source_id)]
|
||||
return False
|
||||
return True
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Test/process-reset hook -- forgets every recorded block."""
|
||||
self._blocked_until.clear()
|
||||
|
||||
|
||||
# Process-wide singleton, mirroring the in-memory-state convention already
|
||||
# used elsewhere in this engine (e.g. orchestrator/main.py's _ORDERS/_JOBS).
|
||||
# Injectable in `plan_for_market` for tests rather than only reachable via
|
||||
# global mutable state.
|
||||
default_router = AdaptiveRouter()
|
||||
|
||||
|
||||
def plan_for_market(market: str, *, router: AdaptiveRouter | None = None) -> list[str]:
|
||||
"""
|
||||
Return the ordered source plan for a market, minus any source_id
|
||||
currently in a block cooldown for that market. `router` defaults to the
|
||||
process-wide `default_router`; tests inject their own instance so they
|
||||
never share state with each other or with production.
|
||||
"""
|
||||
r = router if router is not None else default_router
|
||||
plan = MARKET_SOURCES.get(market, ["gleif"])
|
||||
return [source_id for source_id in plan if not r.is_blocked(market, source_id)]
|
||||
@@ -0,0 +1,217 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Literal
|
||||
from urllib.parse import urlparse
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from rapidfuzz.fuzz import ratio
|
||||
|
||||
EntityType = Literal["organization", "person"]
|
||||
|
||||
|
||||
class ResolutionDecision(str, Enum):
|
||||
EXACT_LINK = "exact_link"
|
||||
REVIEW = "review"
|
||||
DISTINCT = "distinct"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntityCandidate:
|
||||
entity_id: str
|
||||
entity_type: EntityType
|
||||
name: str
|
||||
source_ref: str
|
||||
registration_country: str | None = None
|
||||
registration_number: str | None = None
|
||||
email: str | None = None
|
||||
website: str | None = None
|
||||
organization_id: str | None = None
|
||||
city: str | None = None
|
||||
metadata: dict[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolutionResult:
|
||||
left_id: str
|
||||
right_id: str
|
||||
decision: ResolutionDecision
|
||||
score: float
|
||||
reasons: tuple[str, ...]
|
||||
requires_human_review: bool
|
||||
algorithm_version: str = "entity-resolution-v1"
|
||||
|
||||
|
||||
def _norm(value: str | None) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
normalized = unicodedata.normalize("NFKD", value)
|
||||
ascii_text = "".join(char for char in normalized if not unicodedata.combining(char))
|
||||
return re.sub(r"[^a-z0-9]+", " ", ascii_text.lower()).strip()
|
||||
|
||||
|
||||
def _norm_registration_number(value: str | None) -> str:
|
||||
return re.sub(r"[^0-9a-z]+", "", (value or "").lower())
|
||||
|
||||
|
||||
def _norm_email(value: str | None) -> str:
|
||||
return (value or "").strip().lower()
|
||||
|
||||
|
||||
def _domain(value: str | None) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
raw = value.strip().lower()
|
||||
if "@" in raw and "://" not in raw:
|
||||
raw = raw.rsplit("@", 1)[-1]
|
||||
if "://" not in raw:
|
||||
raw = f"https://{raw}"
|
||||
host = (urlparse(raw).hostname or "").lower()
|
||||
return host.removeprefix("www.")
|
||||
|
||||
|
||||
def _exact_organization(left: EntityCandidate, right: EntityCandidate) -> ResolutionResult | None:
|
||||
left_number = _norm_registration_number(left.registration_number)
|
||||
right_number = _norm_registration_number(right.registration_number)
|
||||
left_country = _norm(left.registration_country)
|
||||
right_country = _norm(right.registration_country)
|
||||
if left_number and right_number and left_country and right_country:
|
||||
if left_country == right_country and left_number == right_number:
|
||||
return ResolutionResult(
|
||||
left.entity_id,
|
||||
right.entity_id,
|
||||
ResolutionDecision.EXACT_LINK,
|
||||
1.0,
|
||||
("same registration country and registration number",),
|
||||
False,
|
||||
)
|
||||
if left_country == right_country and left_number != right_number:
|
||||
return ResolutionResult(
|
||||
left.entity_id,
|
||||
right.entity_id,
|
||||
ResolutionDecision.DISTINCT,
|
||||
0.0,
|
||||
("different registration numbers in the same country",),
|
||||
False,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _exact_person(left: EntityCandidate, right: EntityCandidate) -> ResolutionResult | None:
|
||||
left_email = _norm_email(left.email)
|
||||
right_email = _norm_email(right.email)
|
||||
if left_email and right_email:
|
||||
if left_email == right_email:
|
||||
return ResolutionResult(
|
||||
left.entity_id,
|
||||
right.entity_id,
|
||||
ResolutionDecision.EXACT_LINK,
|
||||
1.0,
|
||||
("same normalized email address",),
|
||||
False,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def resolve_entity_pair(left: EntityCandidate, right: EntityCandidate) -> ResolutionResult:
|
||||
if left.entity_type != right.entity_type:
|
||||
return ResolutionResult(
|
||||
left.entity_id,
|
||||
right.entity_id,
|
||||
ResolutionDecision.DISTINCT,
|
||||
0.0,
|
||||
("different entity types",),
|
||||
False,
|
||||
)
|
||||
|
||||
exact = _exact_organization(left, right) if left.entity_type == "organization" else _exact_person(left, right)
|
||||
if exact is not None:
|
||||
return exact
|
||||
|
||||
left_name = _norm(left.name)
|
||||
right_name = _norm(right.name)
|
||||
if not left_name or not right_name:
|
||||
return ResolutionResult(
|
||||
left.entity_id,
|
||||
right.entity_id,
|
||||
ResolutionDecision.REVIEW,
|
||||
0.0,
|
||||
("missing normalized name prevents deterministic comparison",),
|
||||
True,
|
||||
)
|
||||
|
||||
name_similarity = ratio(left_name, right_name) / 100.0
|
||||
reasons = [f"name similarity {name_similarity:.3f}"]
|
||||
score = name_similarity * 0.65
|
||||
|
||||
if left.entity_type == "organization":
|
||||
left_domain = _domain(left.website or left.email)
|
||||
right_domain = _domain(right.website or right.email)
|
||||
if left_domain and right_domain:
|
||||
if left_domain == right_domain:
|
||||
score += 0.25
|
||||
reasons.append("same normalized domain")
|
||||
else:
|
||||
score -= 0.1
|
||||
reasons.append("different normalized domains")
|
||||
if _norm(left.registration_country) and _norm(left.registration_country) == _norm(right.registration_country):
|
||||
score += 0.05
|
||||
reasons.append("same registration country")
|
||||
if _norm(left.city) and _norm(left.city) == _norm(right.city):
|
||||
score += 0.05
|
||||
reasons.append("same city")
|
||||
else:
|
||||
if left.organization_id and right.organization_id:
|
||||
if left.organization_id == right.organization_id:
|
||||
score += 0.25
|
||||
reasons.append("same known organization")
|
||||
else:
|
||||
score -= 0.1
|
||||
reasons.append("different known organizations")
|
||||
left_domain = _domain(left.email)
|
||||
right_domain = _domain(right.email)
|
||||
if left_domain and right_domain and left_domain == right_domain:
|
||||
score += 0.1
|
||||
reasons.append("same email domain")
|
||||
|
||||
score = max(0.0, min(1.0, score))
|
||||
|
||||
# Only strong identifiers auto-link. Similarity-based matches remain operator-review candidates.
|
||||
if score >= 0.72:
|
||||
decision = ResolutionDecision.REVIEW
|
||||
review = True
|
||||
elif score <= 0.3:
|
||||
decision = ResolutionDecision.DISTINCT
|
||||
review = False
|
||||
else:
|
||||
decision = ResolutionDecision.REVIEW
|
||||
review = True
|
||||
|
||||
return ResolutionResult(
|
||||
left.entity_id,
|
||||
right.entity_id,
|
||||
decision,
|
||||
round(score, 6),
|
||||
tuple(reasons),
|
||||
review,
|
||||
)
|
||||
|
||||
|
||||
def rank_resolution_candidates(
|
||||
query: EntityCandidate,
|
||||
candidates: list[EntityCandidate],
|
||||
*,
|
||||
limit: int = 20,
|
||||
) -> list[ResolutionResult]:
|
||||
results = [resolve_entity_pair(query, candidate) for candidate in candidates if candidate.entity_id != query.entity_id]
|
||||
decision_order = {
|
||||
ResolutionDecision.EXACT_LINK: 0,
|
||||
ResolutionDecision.REVIEW: 1,
|
||||
ResolutionDecision.DISTINCT: 2,
|
||||
}
|
||||
return sorted(
|
||||
results,
|
||||
key=lambda result: (decision_order[result.decision], -result.score, result.right_id),
|
||||
)[: max(0, limit)]
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Production pipeline: sourcing -> extraction -> canonical ER -> QA -> quality.
|
||||
|
||||
Identity decisions are owned by src/er/entity-resolution-service.ts. The
|
||||
Python worker only applies canonical `match` decisions returned by its
|
||||
internal bridge. If tenant context or the canonical bridge is unavailable,
|
||||
records remain unmerged: false identity merges are never used as fallback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from workers.resolve import resolve
|
||||
from workers.quality_bridge import run_quality_bridge
|
||||
from sources.connectors import (
|
||||
CompanyResult,
|
||||
SourceBlockedError,
|
||||
brreg_by_orgnr,
|
||||
companies_house_by_number,
|
||||
cvr_by_number,
|
||||
gleif_by_lei,
|
||||
prh_by_businessid,
|
||||
)
|
||||
from workers.adaptive_router import default_router, plan_for_market
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
PIPELINE_VERSION = "0pt-pipeline@2"
|
||||
|
||||
DEMO_SEEDS: dict[str, list[str]] = {
|
||||
"NO": ["923609016"],
|
||||
"GB": ["00000006"],
|
||||
}
|
||||
|
||||
|
||||
async def _fetch(source_id: str, key: str) -> CompanyResult | None:
|
||||
if source_id == "gleif": return await gleif_by_lei(key)
|
||||
if source_id == "brreg": return await brreg_by_orgnr(key)
|
||||
if source_id == "companies_house": return await companies_house_by_number(key)
|
||||
if source_id == "prh": return await prh_by_businessid(key)
|
||||
if source_id == "cvr": return await cvr_by_number(key)
|
||||
return None
|
||||
|
||||
|
||||
async def run_job(order_id: str, config: dict[str, Any]) -> dict[str, Any]:
|
||||
markets: list[str] = config.get("markets", []) or ["NO"]
|
||||
threshold = float(config.get("confidence", 92)) / 100.0
|
||||
seeds: dict[str, list[str]] = config["seeds"] if config.get("seeds") is not None else DEMO_SEEDS
|
||||
tenant_id = config.get("tenant_id")
|
||||
project_id = config.get("project_id", "p_default")
|
||||
correlation_id = config.get("correlation_id")
|
||||
|
||||
records: list[dict[str, Any]] = []
|
||||
per_market: dict[str, int] = {}
|
||||
|
||||
for market in markets:
|
||||
keys = seeds.get(market, [])
|
||||
got = 0
|
||||
for key in keys:
|
||||
plan = plan_for_market(market)
|
||||
for source_id in plan:
|
||||
try:
|
||||
res = await _fetch(source_id, key)
|
||||
except SourceBlockedError:
|
||||
default_router.record_blocked(market, source_id)
|
||||
res = None
|
||||
except Exception:
|
||||
res = None
|
||||
if res and res.name:
|
||||
records.append({
|
||||
"market": market,
|
||||
"name": res.name,
|
||||
"status": res.status,
|
||||
"lei": res.lei,
|
||||
"org_nr": res.org_nr,
|
||||
"source": res.source,
|
||||
"provenance": [p.__dict__ for p in res.provenance],
|
||||
"confidence": max((p.confidence for p in res.provenance), default=0.0),
|
||||
})
|
||||
got += 1
|
||||
break
|
||||
per_market[market] = got
|
||||
|
||||
# Canonical ER is tenant-bound. Missing tenant context must never be
|
||||
# papered over with a synthetic tenant or the removed Python scorer.
|
||||
if tenant_id:
|
||||
deduped = await resolve(
|
||||
records,
|
||||
tenant_id=tenant_id,
|
||||
project_id=project_id,
|
||||
correlation_id=correlation_id,
|
||||
)
|
||||
er_mode = "canonical_ts"
|
||||
else:
|
||||
deduped = [dict(r) for r in records]
|
||||
er_mode = "fail_closed_unmerged_missing_tenant"
|
||||
|
||||
delivered = [r for r in deduped if r["confidence"] >= threshold]
|
||||
dropped = len(deduped) - len(delivered)
|
||||
avg_conf = round(sum(r["confidence"] for r in delivered) / len(delivered), 3) if delivered else 0.0
|
||||
|
||||
artifact_ref = f"0pt:pipeline_delivery:{order_id}"
|
||||
for r in delivered:
|
||||
for p in r.get("provenance", []):
|
||||
p["artifact_ref"] = artifact_ref
|
||||
|
||||
quality_bridge_metrics: dict[str, Any]
|
||||
if not tenant_id:
|
||||
quality_bridge_metrics = {
|
||||
"status": "not_configured",
|
||||
"detail": "config.tenant_id missing — quality bridge not called",
|
||||
}
|
||||
else:
|
||||
bridge_result = await run_quality_bridge(
|
||||
tenant_id=tenant_id,
|
||||
project_id=project_id,
|
||||
dataset_id=f"0pt-order-{order_id}",
|
||||
rows=delivered,
|
||||
correlation_id=correlation_id,
|
||||
)
|
||||
quality_bridge_metrics = bridge_result.as_metrics()
|
||||
if bridge_result.status == "ok":
|
||||
quality_info = {
|
||||
"score": bridge_result.score,
|
||||
"run_id": bridge_result.run_id,
|
||||
"run_status": bridge_result.run_status,
|
||||
"checked_by": "0pt-quality-bridge",
|
||||
}
|
||||
for r in delivered:
|
||||
for p in r.get("provenance", []):
|
||||
p["quality"] = quality_info
|
||||
elif bridge_result.status != "disabled":
|
||||
logger.warning(
|
||||
"0pt.quality_bridge did not complete for order %s: %s (%s)",
|
||||
order_id, bridge_result.status, bridge_result.detail,
|
||||
)
|
||||
|
||||
return {
|
||||
"stage": "qa",
|
||||
"pct": 100,
|
||||
"state": "done",
|
||||
"metrics": {
|
||||
"rows": len(delivered),
|
||||
"dropped_below_threshold": dropped,
|
||||
"per_market": per_market,
|
||||
"avg_confidence": avg_conf,
|
||||
"pipeline_version": PIPELINE_VERSION,
|
||||
"entity_resolution": er_mode,
|
||||
"quality_bridge": quality_bridge_metrics,
|
||||
},
|
||||
"records": delivered,
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
"""
|
||||
services/api/workers/quality_bridge.py
|
||||
=========================================
|
||||
P010: the TS/Python split-brain bridge (BEFORE_STATE.md §2). The production
|
||||
order pipeline (workers/pipeline.py) has always run its own one-line QA
|
||||
filter (`[r for r in deduped if r["confidence"] >= threshold]`) and never
|
||||
touched this repo's sophisticated, versioned TS QualityService (393 lines:
|
||||
rule registry, GE delegation, OpenLineage) — "noll bryggor mellan sig", per
|
||||
BEFORE_STATE.md.
|
||||
|
||||
This module is the ADDITIVE bridge, called optionally from pipeline.py. It
|
||||
is NOT a replacement for the Python filter and cannot become a silent one:
|
||||
|
||||
* Feature-flagged OFF by default (OPT_QUALITY_BRIDGE_ENABLED unset/"false").
|
||||
A disabled bridge makes zero network calls and returns immediately.
|
||||
* FAILS OPEN. Any failure mode (bridge URL unset, connection refused,
|
||||
timeout, non-2xx, malformed JSON) is caught here and reported back as
|
||||
`{"status": "unavailable", ...}` — it NEVER raises into pipeline.run_job,
|
||||
and it never changes which rows get delivered. `run_job` remains the
|
||||
single source of truth for delivery; this bridge is read-only/advisory.
|
||||
* ADVISORY ONLY, not a second gate — and this is a real limitation, not a
|
||||
choice made lightly: ExpectationEngine's execute() returns per-rule
|
||||
PASS/FAIL COUNTS and up to 20 unexpected-value SAMPLES
|
||||
(src/quality/expectation-engine.ts), not a per-row boolean array. There
|
||||
is no way, from a dataset-level score + a handful of samples, to know
|
||||
*which* of the N rows in this batch failed which rule — so per-row
|
||||
gating against the TS engine's result cannot be implemented honestly
|
||||
without first extending that engine's output contract (out of scope for
|
||||
this pass; flagged, not worked around with a guess). A future
|
||||
`OPT_QUALITY_BRIDGE_GATE_ENABLED` flag is deliberately NOT implemented
|
||||
here for that reason — see the docstring on `BridgeResult` below.
|
||||
|
||||
Transport: a direct HTTP call to the Next.js edge's
|
||||
POST /api/0pt/quality/bridge-run (app/api/0pt/quality/bridge-run/route.ts),
|
||||
reusing the same `X-Internal-Token` shared-secret convention lib/engine.ts
|
||||
already uses for the (opposite-direction) edge -> engine call, for
|
||||
consistency. This was chosen over an N0D job dispatch (the other option the
|
||||
brief raised) because: the TS QualityService instance the pipeline needs to
|
||||
reach lives in-process inside the Next.js app (src/services/quality.ts, an
|
||||
in-memory singleton, same pattern as the Source Registry before its Postgres
|
||||
persistence landed) — there is no durable store an N0D job could read/write
|
||||
through today, and dispatching a job whose only effect is "call this
|
||||
in-process singleton" would add a queue hop for no isolation benefit. A
|
||||
synchronous HTTP call, wrapped in a short timeout and a hard fail-open, is
|
||||
the simpler and more honest choice for a first cut; nothing here blocks a
|
||||
later move to N0D once the quality state has real (Postgres) persistence.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
_TIMEOUT = httpx.Timeout(4.0, connect=2.0) # short — this must never meaningfully slow delivery
|
||||
|
||||
|
||||
def _enabled() -> bool:
|
||||
return os.getenv("OPT_QUALITY_BRIDGE_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _bridge_url() -> str | None:
|
||||
base = os.getenv("OPT_QUALITY_BRIDGE_URL") or os.getenv("EDGE_URL")
|
||||
if not base:
|
||||
return None
|
||||
return f"{base.rstrip('/')}/api/0pt/quality/bridge-run"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BridgeResult:
|
||||
"""
|
||||
Outcome of one bridge-run attempt. `status`:
|
||||
- "disabled": OPT_QUALITY_BRIDGE_ENABLED is not set — no call made.
|
||||
- "not_configured": enabled, but no OPT_QUALITY_BRIDGE_URL/EDGE_URL set.
|
||||
- "unavailable": enabled + configured, but the call failed (timeout,
|
||||
connection error, non-2xx, malformed body). Never raises.
|
||||
- "ok": a real run completed; `score`/`run_id`/`issue_count` are populated.
|
||||
|
||||
There is deliberately no `gated`/`dropped_rows` field — see the module
|
||||
docstring's "ADVISORY ONLY" section for why per-row gating isn't
|
||||
implementable against the current TS engine contract.
|
||||
"""
|
||||
status: str
|
||||
score: float | None = None
|
||||
run_id: str | None = None
|
||||
run_status: str | None = None
|
||||
issue_count: int | None = None
|
||||
detail: str | None = None
|
||||
|
||||
def as_metrics(self) -> dict[str, Any]:
|
||||
return {
|
||||
"status": self.status,
|
||||
"score": self.score,
|
||||
"run_id": self.run_id,
|
||||
"run_status": self.run_status,
|
||||
"issue_count": self.issue_count,
|
||||
**({"detail": self.detail} if self.detail else {}),
|
||||
}
|
||||
|
||||
|
||||
async def run_quality_bridge(
|
||||
*,
|
||||
tenant_id: str,
|
||||
project_id: str,
|
||||
dataset_id: str,
|
||||
rows: list[dict[str, Any]],
|
||||
correlation_id: str | None = None,
|
||||
) -> BridgeResult:
|
||||
"""Ask the TS QualityService to grade `rows`. Never raises — see module docstring."""
|
||||
if not _enabled():
|
||||
return BridgeResult(status="disabled")
|
||||
|
||||
url = _bridge_url()
|
||||
if not url:
|
||||
return BridgeResult(status="not_configured", detail="OPT_QUALITY_BRIDGE_URL/EDGE_URL not set")
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"tenant_id": tenant_id,
|
||||
"project_id": project_id,
|
||||
"dataset_id": dataset_id,
|
||||
"rows": rows,
|
||||
}
|
||||
if correlation_id:
|
||||
payload["correlation_id"] = correlation_id
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"X-Internal-Token": os.getenv("INTERNAL_TOKEN", ""),
|
||||
}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
|
||||
r = await client.post(url, json=payload, headers=headers)
|
||||
if r.status_code not in (200, 201):
|
||||
return BridgeResult(status="unavailable", detail=f"HTTP {r.status_code}")
|
||||
body = r.json()
|
||||
run = body.get("run") or {}
|
||||
issues = body.get("issues") or []
|
||||
return BridgeResult(
|
||||
status="ok",
|
||||
score=run.get("score"),
|
||||
run_id=run.get("run_id"),
|
||||
run_status=run.get("status"),
|
||||
issue_count=len(issues),
|
||||
)
|
||||
except httpx.TimeoutException:
|
||||
return BridgeResult(status="unavailable", detail="timeout")
|
||||
except httpx.HTTPError as exc:
|
||||
return BridgeResult(status="unavailable", detail=f"{type(exc).__name__}: {exc}")
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
# Malformed/unexpected response body — treat exactly like network
|
||||
# unavailability, never propagate into the pipeline.
|
||||
return BridgeResult(status="unavailable", detail=f"malformed response: {type(exc).__name__}")
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
Lightweight in-process job queue (docs/02). Adequate for single-worker dev; swap
|
||||
the backend for Redis/Celery at scale without changing callers.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
Job = Callable[..., Awaitable[Any]]
|
||||
|
||||
|
||||
class JobQueue:
|
||||
def __init__(self) -> None:
|
||||
self._q: "asyncio.Queue[tuple[Job, tuple[Any, ...]]]" = asyncio.Queue()
|
||||
|
||||
async def enqueue(self, fn: Job, *args: Any) -> None:
|
||||
await self._q.put((fn, args))
|
||||
|
||||
async def worker(self) -> None:
|
||||
while True:
|
||||
fn, args = await self._q.get()
|
||||
try:
|
||||
await fn(*args)
|
||||
except Exception as e: # keep the worker alive on a failed job
|
||||
print("job failed:", repr(e))
|
||||
finally:
|
||||
self._q.task_done()
|
||||
|
||||
|
||||
queue = JobQueue()
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Thin adapter from the Python pipeline to 0pt's canonical TS ER engine.
|
||||
|
||||
Python no longer scores identity. It sends opaque records to
|
||||
/api/0pt/internal/er/candidates, then applies only explicit hard-rule `match`
|
||||
decisions. Score/fuzzy decisions are review evidence only and can never merge
|
||||
records in this adapter, even if an older or compromised bridge returns
|
||||
`status=match, decided_by=score`.
|
||||
|
||||
If the canonical engine is unavailable, records are returned UNMERGED (fail
|
||||
closed against false identity merges).
|
||||
|
||||
A canonical hard non-match is also a cluster-wide constraint: transitive
|
||||
matches are never allowed to pull two records with conflicting stable identity
|
||||
evidence into the same entity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
_TIMEOUT = httpx.Timeout(6.0, connect=2.0)
|
||||
|
||||
|
||||
def _url() -> str | None:
|
||||
base = os.getenv("OPT_ER_BRIDGE_URL") or os.getenv("EDGE_URL")
|
||||
return f"{base.rstrip('/')}/api/0pt/internal/er/candidates" if base else None
|
||||
|
||||
|
||||
def _record_id(record: dict[str, Any]) -> str:
|
||||
stable = {
|
||||
"market": record.get("market"),
|
||||
"name": record.get("name"),
|
||||
"status": record.get("status"),
|
||||
"lei": record.get("lei"),
|
||||
"org_nr": record.get("org_nr"),
|
||||
"source": record.get("source"),
|
||||
"provenance": record.get("provenance", []),
|
||||
}
|
||||
raw = json.dumps(stable, sort_keys=True, separators=(",", ":"), default=str).encode()
|
||||
return "erp_" + hashlib.sha256(raw).hexdigest()[:32]
|
||||
|
||||
|
||||
def _unique_record_ids(records: list[dict[str, Any]]) -> list[str]:
|
||||
seen: dict[str, int] = {}
|
||||
unique_ids: list[str] = []
|
||||
for record in records:
|
||||
rid = _record_id(record)
|
||||
n = seen.get(rid, 0)
|
||||
seen[rid] = n + 1
|
||||
unique_ids.append(rid if n == 0 else f"{rid}_{n}")
|
||||
return unique_ids
|
||||
|
||||
|
||||
def _apply_matches(records: list[dict[str, Any]], pairs: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if not records:
|
||||
return []
|
||||
|
||||
unique_ids = _unique_record_ids(records)
|
||||
known_ids = set(unique_ids)
|
||||
parent = {rid: rid for rid in unique_ids}
|
||||
members = {rid: {rid} for rid in unique_ids}
|
||||
|
||||
hard_non_matches: set[frozenset[str]] = set()
|
||||
for pair in pairs:
|
||||
a, b = pair.get("record_a"), pair.get("record_b")
|
||||
if a not in known_ids or b not in known_ids:
|
||||
continue
|
||||
if pair.get("status") == "non_match" and pair.get("decided_by") not in (None, "score"):
|
||||
hard_non_matches.add(frozenset((a, b)))
|
||||
|
||||
def find(x: str) -> str:
|
||||
while parent[x] != x:
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
return x
|
||||
|
||||
def components_conflict(left: set[str], right: set[str]) -> bool:
|
||||
return any(frozenset((a, b)) in hard_non_matches for a in left for b in right)
|
||||
|
||||
def union(a: str, b: str) -> bool:
|
||||
ra, rb = find(a), find(b)
|
||||
if ra == rb:
|
||||
return True
|
||||
left, right = members[ra], members[rb]
|
||||
if components_conflict(left, right):
|
||||
return False
|
||||
keep, drop = (ra, rb) if ra < rb else (rb, ra)
|
||||
parent[drop] = keep
|
||||
members[keep] = members[ra] | members[rb]
|
||||
members.pop(drop, None)
|
||||
return True
|
||||
|
||||
# Defence in depth: only stable-identifier hard rules may create canonical
|
||||
# identity links. Score/fuzzy "match" responses are ignored at the consumer
|
||||
# boundary even if an upstream/legacy route emits one.
|
||||
match_pairs = [
|
||||
p for p in pairs
|
||||
if p.get("status") == "match"
|
||||
and p.get("decided_by") not in (None, "score")
|
||||
and p.get("record_a") in known_ids
|
||||
and p.get("record_b") in known_ids
|
||||
]
|
||||
match_pairs.sort(
|
||||
key=lambda p: (
|
||||
-float(p.get("score") or 0.0),
|
||||
str(p.get("candidate_id") or ""),
|
||||
)
|
||||
)
|
||||
accepted_edges: list[dict[str, Any]] = []
|
||||
for pair in match_pairs:
|
||||
a, b = str(pair["record_a"]), str(pair["record_b"])
|
||||
if union(a, b):
|
||||
accepted_edges.append(pair)
|
||||
|
||||
groups: dict[str, list[tuple[str, dict[str, Any]]]] = {}
|
||||
for rid, record in zip(unique_ids, records):
|
||||
groups.setdefault(find(rid), []).append((rid, copy.deepcopy(record)))
|
||||
|
||||
out: list[dict[str, Any]] = []
|
||||
for group in groups.values():
|
||||
group.sort(key=lambda item: (-float(item[1].get("confidence", 0.0)), item[0]))
|
||||
_, anchor = group[0]
|
||||
sources = sorted({str(r.get("source")) for _, r in group if r.get("source")})
|
||||
anchor["agreed_sources"] = len(sources) or 1
|
||||
anchor["confidence"] = min(
|
||||
0.99,
|
||||
float(anchor.get("confidence", 0.0)) + 0.1 * max(0, len(sources) - 1),
|
||||
)
|
||||
anchor["merged_from"] = [r.get("source") for _, r in group[1:] if r.get("source")]
|
||||
|
||||
provenance = list(anchor.get("provenance", []))
|
||||
keys = {(p.get("field_name"), p.get("source_id")) for p in provenance}
|
||||
for _, record in group[1:]:
|
||||
for p in record.get("provenance", []):
|
||||
key = (p.get("field_name"), p.get("source_id"))
|
||||
if key not in keys:
|
||||
provenance.append(copy.deepcopy(p))
|
||||
keys.add(key)
|
||||
|
||||
member_ids = {rid for rid, _ in group}
|
||||
edges = [
|
||||
p for p in accepted_edges
|
||||
if p.get("record_a") in member_ids and p.get("record_b") in member_ids
|
||||
]
|
||||
er_info = {
|
||||
"method": "canonical_ts_entity_resolution",
|
||||
"merged_sources": sources,
|
||||
"matched_edges": [
|
||||
{
|
||||
"candidate_id": p.get("candidate_id"),
|
||||
"score": p.get("score"),
|
||||
"decided_by": p.get("decided_by"),
|
||||
}
|
||||
for p in edges
|
||||
],
|
||||
}
|
||||
if len(group) > 1:
|
||||
for p in provenance:
|
||||
p["entity_resolution"] = er_info
|
||||
anchor["provenance"] = provenance
|
||||
out.append(anchor)
|
||||
|
||||
return sorted(out, key=lambda r: (_record_id(r), str(r.get("source") or "")))
|
||||
|
||||
|
||||
async def resolve(
|
||||
records: list[dict[str, Any]],
|
||||
*,
|
||||
tenant_id: str,
|
||||
project_id: str,
|
||||
correlation_id: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return canonically resolved records; never falls back to local scoring."""
|
||||
if len(records) < 2:
|
||||
return [copy.deepcopy(r) for r in records]
|
||||
|
||||
url = _url()
|
||||
token = os.getenv("INTERNAL_TOKEN", "")
|
||||
if not url or not token or not tenant_id or not project_id:
|
||||
return [copy.deepcopy(r) for r in records]
|
||||
|
||||
unique_ids = _unique_record_ids(records)
|
||||
er_records = []
|
||||
for rid, record in zip(unique_ids, records):
|
||||
name = str(record.get("name") or "")
|
||||
market = record.get("market")
|
||||
er_records.append({
|
||||
"record_id": rid,
|
||||
"fields": {
|
||||
"market": market,
|
||||
"registration_country": market,
|
||||
"block_initial": name[:1].upper(),
|
||||
"name": name,
|
||||
"status": record.get("status"),
|
||||
"lei": record.get("lei"),
|
||||
"org_nr": record.get("org_nr"),
|
||||
},
|
||||
})
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"tenant_id": tenant_id,
|
||||
"project_id": project_id,
|
||||
"records": er_records,
|
||||
"blocking_fields": ["market", "block_initial"],
|
||||
"compare_fields": [{"field": "name", "weight": 1}],
|
||||
"auto_match_threshold": 0.92,
|
||||
"review_threshold": 0.72,
|
||||
}
|
||||
if correlation_id:
|
||||
payload["correlation_id"] = correlation_id
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=_TIMEOUT) as client:
|
||||
response = await client.post(
|
||||
url,
|
||||
json=payload,
|
||||
headers={"Content-Type": "application/json", "X-Internal-Token": token},
|
||||
)
|
||||
if response.status_code not in (200, 201):
|
||||
return [copy.deepcopy(r) for r in records]
|
||||
body = response.json()
|
||||
pairs = body.get("pairs")
|
||||
if not isinstance(pairs, list):
|
||||
return [copy.deepcopy(r) for r in records]
|
||||
return _apply_matches(records, pairs)
|
||||
except (httpx.HTTPError, ValueError, TypeError, KeyError):
|
||||
return [copy.deepcopy(r) for r in records]
|
||||
|
||||
|
||||
__all__ = ["resolve", "_apply_matches"]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
Worker entrypoint. In production this drains a queue of order jobs and runs the
|
||||
compliant pipeline. For now it exposes a CLI to run a single job locally.
|
||||
python -m workers.run <order_id>
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from workers.pipeline import run_job
|
||||
|
||||
|
||||
async def _main() -> None:
|
||||
order_id = sys.argv[1] if len(sys.argv) > 1 else "demo"
|
||||
result = await run_job(order_id, {"markets": ["NO", "GB"], "confidence": 90})
|
||||
print(result["metrics"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(_main())
|
||||
Reference in New Issue
Block a user