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
+64
View File
@@ -0,0 +1,64 @@
/**
* app/api/0pt/quality/bridge-run/route.ts
* ==========================================
* The P010 TS/Python split-brain bridge (BEFORE_STATE.md §2). This is the
* ONE route the production Python engine
* (services/api/workers/quality_bridge.py, called from
* services/api/workers/pipeline.py) talks to. It:
*
* 1. auto-provisions a deterministic, tenant-scoped baseline rule set for
* (tenant_id, dataset_id) the first time it's seen (src/quality/quality-bridge.ts) --
* the Python engine never has to pre-register rules through the CRUD
* surface just to get a quality read on an order's already-produced rows;
* 2. runs QualityService.runQuality synchronously against the rows the
* pipeline already produced (delivered, post the Python filter --
* this is an ADVISORY second opinion, not a gate, until Simon decides
* to wire per-row gating -- see quality_bridge.py's docstring for why
* that isn't done in this pass);
* 3. returns the run + any open issues.
*
* This does not replace, call, or block on the Python filter in any way --
* it is purely additive. If this route is unreachable, times out, or 500s,
* the Python side is required to fail open (never raise into the pipeline).
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, qualityBridgeRunSchema } from "@/src/validation/0pt-schemas";
import { qualityService } from "@/src/services/quality";
import { ensureBaselineRules } from "@/src/quality/quality-bridge";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function POST(request: NextRequest) {
try {
const __raw = await request.json();
const __parsed = parseBody(qualityBridgeRunSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const body = __parsed.data;
await ensureBaselineRules(qualityService, {
tenant_id: body.tenant_id,
project_id: body.project_id,
dataset_id: body.dataset_id,
});
const run = await qualityService.runQuality({
tenant_id: body.tenant_id,
project_id: body.project_id,
dataset_id: body.dataset_id,
dataset_version: body.dataset_version,
rows: body.rows,
correlation_id: body.correlation_id,
});
const issues = qualityService.listIssues({
tenant_id: body.tenant_id,
dataset_id: body.dataset_id,
status: "open",
});
return NextResponse.json({ run, issues }, { status: 201 });
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+28
View File
@@ -0,0 +1,28 @@
/**
* app/api/0pt/quality/issues/route.ts
* ======================================
* quality.list_issues (GET) -- issues opened by finished quality runs
* (human-review handoff, Master-DoD §10).
*/
import { NextRequest, NextResponse } from "next/server";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import type { DataQualityIssue } from "@/src/quality/quality-types";
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const issues = qualityService.listIssues({
tenant_id: tenantId,
dataset_id: searchParams.get("dataset_id") ?? undefined,
status: (searchParams.get("status") as DataQualityIssue["status"]) ?? undefined,
});
return NextResponse.json(issues);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -0,0 +1,56 @@
/**
* app/api/0pt/quality/rules/[ruleId]/route.ts
* ===============================================
* quality.get_rule (GET) + quality.update_rule (PUT, versioned -- bumps
* `version`, records the superseded row). Cross-tenant reads are NOT_FOUND
* (no existence oracle), matching QualityService.getRule's own contract.
*/
import { NextRequest, NextResponse } from "next/server";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { z } from "zod";
const updateQualityRuleSchema = z.object({
tenant_id: z.string().min(1),
name: z.string().min(1).optional(),
expectation: z.object({ expectation_type: z.string().min(1), kwargs: z.record(z.string(), z.unknown()) }).optional(),
severity: z.enum(["info", "warning", "error", "critical"]).optional(),
status: z.enum(["active", "disabled", "superseded"]).optional(),
});
export async function GET(request: NextRequest, { params }: { params: Promise<{ ruleId: string }> }) {
try {
const { ruleId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const versions = searchParams.get("versions") === "true";
if (versions) {
return NextResponse.json(qualityService.getRuleVersions(ruleId, tenantId));
}
return NextResponse.json(qualityService.getRule(ruleId, tenantId));
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ ruleId: string }> }) {
try {
const { ruleId } = await params;
const raw = await request.json();
const parsed = updateQualityRuleSchema.safeParse(raw);
if (!parsed.success) {
return NextResponse.json(
{ error: "validation_error", issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })) },
{ status: 400 }
);
}
const { tenant_id, ...patch } = parsed.data;
const rule = await qualityService.updateRule(ruleId, tenant_id, patch);
return NextResponse.json(rule);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+47
View File
@@ -0,0 +1,47 @@
/**
* app/api/0pt/quality/rules/route.ts
* ====================================
* quality.create_rule (POST) + quality.list_rules (GET) -- the CRUD surface
* over QualityService's versioned rule registry (src/quality/quality-service.ts,
* Master-DoD §10). Uses the shared singleton from src/services/quality.ts,
* not a fresh `new QualityService()` per route module -- see that file's
* doc comment (and BEFORE_STATE.md §1, which found and fixed the same
* per-module-instance defect for the Source Registry).
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, createQualityRuleSchema } from "@/src/validation/0pt-schemas";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import type { DataQualityRule } from "@/src/quality/quality-types";
export async function POST(request: NextRequest) {
try {
const __raw = await request.json();
const __parsed = parseBody(createQualityRuleSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const rule = await qualityService.createRule(__parsed.data);
return NextResponse.json(rule, { status: 201 });
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const rules = qualityService.listRules({
tenant_id: tenantId,
dataset_id: searchParams.get("dataset_id") ?? undefined,
status: (searchParams.get("status") as DataQualityRule["status"]) ?? undefined,
});
return NextResponse.json(rules);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* app/api/0pt/quality/runs/[runId]/route.ts
* =============================================
* quality.get_run (GET). Cross-tenant reads are NOT_FOUND.
*/
import { NextRequest, NextResponse } from "next/server";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function GET(request: NextRequest, { params }: { params: Promise<{ runId: string }> }) {
try {
const { runId } = await params;
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
return NextResponse.json(qualityService.getRun(runId, tenantId));
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+44
View File
@@ -0,0 +1,44 @@
/**
* app/api/0pt/quality/runs/route.ts
* ====================================
* quality.run (POST) + quality.list_runs (GET). POST executes all active
* rules for a dataset against caller-supplied rows -- runs synchronously
* when every active rule's expectation is locally executable, otherwise
* delegates to the GE backend via N0D (QualityService.runQuality never
* fabricates a result for a check it couldn't run).
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, createQualityRunSchema } from "@/src/validation/0pt-schemas";
import { qualityService } from "@/src/services/quality";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
export async function POST(request: NextRequest) {
try {
const __raw = await request.json();
const __parsed = parseBody(createQualityRunSchema, __raw);
if (!__parsed.ok) {
return NextResponse.json(__parsed.body, { status: __parsed.status });
}
const run = await qualityService.runQuality(__parsed.data);
return NextResponse.json(run, { status: 201 });
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const runs = qualityService.listRuns({
tenant_id: tenantId,
dataset_id: searchParams.get("dataset_id") ?? undefined,
});
return NextResponse.json(runs);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}