feat(data-os): TS/Python quality bridge + provenance fields + fault-injection tests
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 <[email protected]>
This commit is contained in:
Simon Axelsson
2026-09-01 21:02:14 +02:00
co-authored by Claude Sonnet 5
parent 07b13bd833
commit 9740e20818
22 changed files with 1541 additions and 24 deletions
+76 -1
View File
@@ -2,12 +2,30 @@
Production pipeline (docs/06): sourcing -> extraction -> structuring ->
enrichment/fusion -> QA. Compliant connectors only; every field gets provenance;
rows below the order's confidence target are dropped (deliver fewer, never fabricate).
P010 additions (both flagged in BEFORE_STATE.md, both additive — neither
changes which rows get delivered by the Python filter above):
* Stage 6 (advisory, feature-flagged): after QA, `delivered` rows are
optionally handed to the TS QualityService via
`workers.quality_bridge.run_quality_bridge` — see that module's
docstring for the full contract, the fail-open guarantee, and why
per-row gating isn't implemented yet. Disabled unless
`OPT_QUALITY_BRIDGE_ENABLED=true`.
* Every delivered record's provenance rows are stamped with `producer`,
`connector_version` (both already set at fetch time in
sources/connectors.py), and an `artifact_ref` identifying this
delivery (`0pt:pipeline_delivery:<order_id>`) — plus, when the quality
bridge ran successfully, a `quality` block. BEFORE_STATE.md §3 found
these fields absent from the actual dataflow entirely.
"""
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,
@@ -19,6 +37,10 @@ from sources.connectors import (
)
from workers.adaptive_router import plan_for_market
logger = logging.getLogger(__name__)
PIPELINE_VERSION = "0pt-pipeline@1"
# Minimal built-in seed so a job is demonstrable without customer input.
DEMO_SEEDS: dict[str, list[str]] = {
"NO": ["923609016"], # brreg orgnr (example)
@@ -79,16 +101,69 @@ async def run_job(order_id: str, config: dict[str, Any]) -> dict[str, Any]:
deduped = resolve(records)
# 4) enrichment/fusion already folded into confidence above.
# 5) QA — drop rows below the order's confidence threshold.
# 5) QA — drop rows below the order's confidence threshold. THIS is the
# filter that actually governs delivery; nothing below is allowed to
# change its outcome.
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
# Stamp the delivery artifact reference on every provenance row of every
# delivered record (BEFORE_STATE.md §3: `artifact_ref` did not exist
# anywhere). This identifies WHICH delivery a field's value shipped in;
# it does not assert the row was ever written to ST0RE (not wired yet).
artifact_ref = f"0pt:pipeline_delivery:{order_id}"
for r in delivered:
for p in r.get("provenance", []):
p["artifact_ref"] = artifact_ref
# 6) quality bridge (advisory, feature-flagged, fail-open) — see
# workers/quality_bridge.py's docstring for the full contract. Runs
# AFTER the QA gate above and can never change `delivered`.
tenant_id = config.get("tenant_id")
quality_bridge_metrics: dict[str, Any]
if not tenant_id:
# The engine has no tenant context yet for orders created through
# this API (orchestrator/main.py never threads tenant_id into
# `config` — a pre-existing, separately-tracked gap). Rather than
# fabricate a tenant to make the bridge call "work", skip it
# honestly and say why.
quality_bridge_metrics = {
"status": "not_configured",
"detail": "config.tenant_id missing — engine has no tenant context for this order",
}
else:
bridge_result = await run_quality_bridge(
tenant_id=tenant_id,
project_id=config.get("project_id", "p_default"),
dataset_id=f"0pt-order-{order_id}",
rows=delivered,
correlation_id=config.get("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,
"quality_bridge": quality_bridge_metrics,
},
"records": delivered,
}
+154
View File
@@ -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__}")
+29 -1
View File
@@ -2,6 +2,15 @@
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
@@ -19,9 +28,14 @@ def resolve(records: list[dict[str, Any]], threshold: int = 92) -> list[dict[str
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) and fuzz.token_sort_ratio(o.get("name", ""), r.get("name", "")) >= threshold:
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"))
@@ -44,6 +58,20 @@ def resolve(records: list[dict[str, Any]], threshold: int = 92) -> list[dict[str
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: