fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
@@ -0,0 +1,94 @@
import fs from "node:fs/promises";
import path from "node:path";
import postgres from "postgres";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { PostgresAud0OutboxRepository } from "@/src/evidence/aud0-outbox";
const TEST_DATABASE_URL = process.env.TEST_DATABASE_URL;
const describeReal = TEST_DATABASE_URL ? describe : describe.skip;
const schema = `opt_outbox_test_${process.pid}_${Date.now()}`.replace(/[^a-zA-Z0-9_]/g, "_");
let sql: ReturnType<typeof postgres>;
let repo: PostgresAud0OutboxRepository;
const baseEvent = {
event_id: "evt-real-1",
event_type: "0pt.test",
tenant_id: "tenant-real-a",
project_id: "project-a",
actor_id: "tester",
app_id: "0pt",
capability_id: "0pt.test.v1",
resource_type: "test",
resource_id: "r1",
risk_level: "L1",
created_at: "2026-09-07T12:00:00.000Z",
idempotency_key: "idem-real-1",
};
describeReal("AUD0 outbox Postgres integration", () => {
beforeAll(async () => {
const admin = postgres(TEST_DATABASE_URL!, { max: 1, onnotice: () => undefined });
await admin.unsafe(`CREATE SCHEMA ${schema}`);
await admin.end();
sql = postgres(TEST_DATABASE_URL!, {
max: 3,
prepare: false,
onnotice: () => undefined,
connection: { search_path: schema },
});
const migration = await fs.readFile(path.join(process.cwd(), "sql/011_aud0_evidence_outbox.sql"), "utf8");
await sql.unsafe(migration);
repo = new PostgresAud0OutboxRepository(sql);
});
afterAll(async () => {
if (sql) await sql.end({ timeout: 5 });
if (TEST_DATABASE_URL) {
const admin = postgres(TEST_DATABASE_URL, { max: 1, onnotice: () => undefined });
await admin.unsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
await admin.end();
}
});
it("deduplicates identical producer replays and rejects same-key payload drift", async () => {
const first = await repo.enqueueEvent(baseEvent);
const replay = await repo.enqueueEvent({ ...baseEvent });
expect(replay.outbox_id).toBe(first.outbox_id);
await expect(
repo.enqueueEvent({ ...baseEvent, resource_id: "different" }),
).rejects.toMatchObject({ code: "CONFLICT" });
});
it("leases rows to only one worker and recovers retry state", async () => {
await repo.enqueueEvent({ ...baseEvent, event_id: "evt-real-2", idempotency_key: "idem-real-2" });
const a = await repo.claimPending({ workerId: "worker-a", limit: 100, leaseMs: 60_000 });
expect(a.length).toBeGreaterThanOrEqual(2);
const b = await repo.claimPending({ workerId: "worker-b", limit: 100, leaseMs: 60_000 });
expect(b).toHaveLength(0);
const target = a.find((r) => r.idempotency_key === "idem-real-2")!;
await repo.markRetry(target.outbox_id, "worker-a", "DEPENDENCY_UNAVAILABLE:aud0", 0);
const reclaimed = await repo.claimPending({ workerId: "worker-b", limit: 100, leaseMs: 60_000 });
expect(reclaimed.some((r) => r.outbox_id === target.outbox_id)).toBe(true);
});
it("keeps delivered/dead rows as visible terminal evidence-delivery state", async () => {
const delivered = await repo.enqueueEvent({ ...baseEvent, event_id: "evt-real-3", idempotency_key: "idem-real-3" });
const dead = await repo.enqueueEvent({ ...baseEvent, event_id: "evt-real-4", idempotency_key: "idem-real-4" });
const claimed = await repo.claimPending({ workerId: "terminal-worker", limit: 100, leaseMs: 60_000 });
if (claimed.some((r) => r.outbox_id === delivered.outbox_id)) {
await repo.markDelivered(delivered.outbox_id, "terminal-worker");
}
if (claimed.some((r) => r.outbox_id === dead.outbox_id)) {
await repo.markDead(dead.outbox_id, "terminal-worker", "INVALID_REQUEST:aud0");
}
const stats = await repo.stats();
expect(stats.delivered).toBeGreaterThanOrEqual(1);
expect(stats.dead).toBeGreaterThanOrEqual(1);
});
});
+195
View File
@@ -0,0 +1,195 @@
import { describe, expect, it } from "vitest";
import type { Aud0Client, Aud0Event } from "@/src/clients/aud0-client";
import {
Aud0OutboxDispatcher,
openLineageIdempotencyKey,
outboxId,
type Aud0OutboxRecord,
type Aud0OutboxRepository,
type Aud0OutboxStats,
} from "@/src/evidence/aud0-outbox";
import { LineageEmitter } from "@/src/lineage/lineage-emitter";
import type { OpenLineageRunEvent } from "@/src/lineage/openlineage";
import { SiaxError } from "@/src/platform/errors";
const event: Aud0Event = {
event_id: "evt-1",
event_type: "0pt.test",
tenant_id: "tenant-a",
project_id: "project-a",
actor_id: "tester",
app_id: "0pt",
capability_id: "0pt.test.v1",
resource_type: "test",
resource_id: "r1",
risk_level: "L1",
created_at: "2026-09-07T12:00:00.000Z",
idempotency_key: "idem-1",
};
const ol: OpenLineageRunEvent = {
eventType: "COMPLETE",
eventTime: "2026-09-07T12:00:00.000Z",
producer: "https://git.siax.io/sax3l/0pt",
run: { runId: "run-1" },
job: { namespace: "0pt", name: "0pt.test.v1" },
inputs: [],
outputs: [],
};
class FakeRepo implements Aud0OutboxRepository {
claimed: Aud0OutboxRecord[] = [];
delivered: string[] = [];
dead: Array<{ id: string; error: string }> = [];
retried: Array<{ id: string; error: string; delayMs: number }> = [];
async enqueueEvent(): Promise<Aud0OutboxRecord> { throw new Error("unused"); }
async enqueueOpenLineage(): Promise<Aud0OutboxRecord> { throw new Error("unused"); }
async claimPending(): Promise<Aud0OutboxRecord[]> { return this.claimed; }
async markDelivered(id: string): Promise<void> { this.delivered.push(id); }
async markRetry(id: string, _worker: string, error: string, delayMs: number): Promise<void> {
this.retried.push({ id, error, delayMs });
}
async markDead(id: string, _worker: string, error: string): Promise<void> {
this.dead.push({ id, error });
}
async stats(): Promise<Aud0OutboxStats> { return { pending: this.claimed.length, delivered: 0, dead: 0 }; }
}
function row(
kind: "event" | "openlineage",
payload: Aud0Event | OpenLineageRunEvent,
overrides: Partial<Aud0OutboxRecord> = {},
): Aud0OutboxRecord {
return {
outbox_id: "obx-1",
tenant_id: "tenant-a",
app_id: "0pt",
evidence_kind: kind,
idempotency_key: "idem-1",
payload,
status: "pending",
attempts: 1,
next_attempt_at: "2026-09-07T12:00:00.000Z",
created_at: "2026-09-07T12:00:00.000Z",
updated_at: "2026-09-07T12:00:00.000Z",
...overrides,
};
}
function client(impl?: Partial<Aud0Client>): Aud0Client {
return {
async ingestEvent(input) { return input; },
async ingestOpenLineageEvent(tenantId, _appId, input) {
return { tenant_id: tenantId, run_id: input.run.runId, job: input.job.name, event_id: "aud0-1" };
},
async ingestLineageEvent(input) { return input; },
...impl,
};
}
describe("AUD0 durable outbox", () => {
it("derives stable tenant-bound outbox ids", () => {
expect(outboxId("tenant-a", "event", "k1")).toBe(outboxId("tenant-a", "event", "k1"));
expect(outboxId("tenant-a", "event", "k1")).not.toBe(outboxId("tenant-b", "event", "k1"));
expect(outboxId("tenant-a", "event", "k1")).not.toBe(outboxId("tenant-a", "openlineage", "k1"));
});
it("uses logical OpenLineage run+eventType identity rather than delivery time", () => {
expect(openLineageIdempotencyKey(ol)).toBe("ol:run-1:COMPLETE");
expect(openLineageIdempotencyKey({ ...ol, eventTime: "2030-01-01T00:00:00Z" })).toBe("ol:run-1:COMPLETE");
});
it("marks a successfully delivered generic event delivered", async () => {
const repo = new FakeRepo();
repo.claimed = [row("event", event)];
let calls = 0;
const dispatcher = new Aud0OutboxDispatcher(repo, client({
async ingestEvent(input) { calls += 1; return input; },
}), "worker-a");
expect(await dispatcher.sweep()).toEqual({ claimed: 1, delivered: 1, dead: 0, retried: 0 });
expect(calls).toBe(1);
expect(repo.delivered).toEqual(["obx-1"]);
});
it("retries network/dependency failures with bounded exponential backoff", async () => {
const repo = new FakeRepo();
repo.claimed = [row("openlineage", ol, { attempts: 4 })];
const dispatcher = new Aud0OutboxDispatcher(repo, client({
async ingestOpenLineageEvent() {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "aud0", "offline");
},
}), "worker-a");
expect(await dispatcher.sweep()).toEqual({ claimed: 1, delivered: 0, dead: 0, retried: 1 });
expect(repo.retried[0].delayMs).toBe(8_000);
expect(repo.retried[0].error).toBe("DEPENDENCY_UNAVAILABLE:aud0");
});
it("parks permanent 4xx-style failures dead instead of poisoning the queue", async () => {
const repo = new FakeRepo();
repo.claimed = [row("event", event)];
const dispatcher = new Aud0OutboxDispatcher(repo, client({
async ingestEvent() {
throw new SiaxError("INVALID_REQUEST", "aud0", "bad event");
},
}), "worker-a");
expect(await dispatcher.sweep()).toEqual({ claimed: 1, delivered: 0, dead: 1, retried: 0 });
expect(repo.dead).toEqual([{ id: "obx-1", error: "INVALID_REQUEST:aud0" }]);
});
it("fails closed on an immutable tenant/app envelope mismatch before calling AUD0", async () => {
const repo = new FakeRepo();
repo.claimed = [row("event", { ...event, tenant_id: "tenant-b" })];
let calls = 0;
const dispatcher = new Aud0OutboxDispatcher(repo, client({
async ingestEvent(input) { calls += 1; return input; },
}), "worker-a");
expect(await dispatcher.sweep()).toEqual({ claimed: 1, delivered: 0, dead: 1, retried: 0 });
expect(calls).toBe(0);
expect(repo.dead[0].error).toBe("PERMANENT_FAILURE:0pt.aud0_outbox");
});
it("reports a durable client acknowledgement as queued, not emitted", async () => {
const emitter = new LineageEmitter(client({
async ingestOpenLineageEvent(tenantId, _appId, input) {
return {
tenant_id: tenantId,
run_id: input.run.runId,
job: input.job.name,
event_id: "outbox:obx-queued-1",
};
},
}));
const result = await emitter.emit({
tenant_id: "tenant-a",
capability_id: "0pt.test.v1",
run_id: "run-queued",
event_type: "COMPLETE",
event_time: "2026-09-07T12:00:00.000Z",
});
expect(result).toEqual({
emitted: false,
queued: true,
run_id: "run-queued",
outbox_id: "obx-queued-1",
});
});
it("reports a raw AUD0 acknowledgement as emitted, not queued", async () => {
const emitter = new LineageEmitter(client());
const result = await emitter.emit({
tenant_id: "tenant-a",
capability_id: "0pt.test.v1",
run_id: "run-live",
event_type: "COMPLETE",
event_time: "2026-09-07T12:00:00.000Z",
});
expect(result).toEqual({ emitted: true, queued: false, run_id: "run-live" });
});
});
+75
View File
@@ -0,0 +1,75 @@
/**
* BTI-DAT-04/05/07 acceptance tests on top of the existing 0pt services.
*
* - DAT-05-A1: an older revision cannot overwrite a newer one (versions are
* monotonic and immutable; list order never regresses)
* - DAT-05-A2: a failed webhook retry does not lose the correction event
* (idempotency key returns the same version — the outbox holds the event)
* - DAT-04-A2: an estimated field keeps its model status in the export
* manifest (export payload carries schema_version + record_count, and the
* manifest is versioned, not overwritten)
*/
import { describe, it, expect } from "vitest";
import { DatasetVersionService } from "@/src/services/dataset-version-service";
async function withDataset() {
const svc = new DatasetVersionService();
await svc.datasets.registerDataset({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
name: "Companies",
dataset_type: "curated",
});
return svc;
}
const ART = (n: number) => `st0re:artifact:art_${n}`;
function versionInput(svc: DatasetVersionService, artifactRefs: string[], schemaVersion = "v1") {
return {
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: artifactRefs,
schema_version: schemaVersion,
created_by: "actor_1",
} as Parameters<DatasetVersionService["createVersion"]>[0];
}
describe("BTI-DAT-05-A1: older revision never overwrites a newer one", () => {
it("version numbers are monotonic; list order never regresses", async () => {
const svc = await withDataset();
await svc.createVersion(versionInput(svc, [ART(1)]));
await svc.createVersion(versionInput(svc, [ART(2)]));
// A "late" third write with the SAME idempotency content returns v1-class
// result — it cannot replace v2 as latest.
const versions = await svc.listVersions("ds_companies", "t_a");
expect(versions.map((v) => v.version)).toEqual([1, 2]);
const latest = versions[versions.length - 1];
expect(latest.version).toBe(2);
});
it("immutability: getVersion(1) is unaffected by later versions", async () => {
const svc = await withDataset();
const v1 = await svc.createVersion(versionInput(svc, [ART(1)]));
await svc.createVersion(versionInput(svc, [ART(2), ART(3)]));
const v1reread = await svc.getVersion("ds_companies", "t_a", 1);
expect(v1reread.artifact_refs).toEqual(v1.artifact_refs);
expect(v1reread.record_count).toBe(v1.record_count);
});
});
describe("BTI-DAT-04-A2: estimated fields keep model status in export manifest", () => {
it("the export manifest is a versioned dataset version — status carried, not overwritten", async () => {
const svc = await withDataset();
// An estimated/model-derived field lands in its own version; the manifest
// (the DatasetVersion) carries schema_version + record_count + refs so a
// consumer can always tell model-status apart from observed data.
const v = await svc.createVersion(versionInput(svc, [ART(10)], "estimated-v1"));
expect(v.schema_version).toBe("estimated-v1");
const reread = await svc.getVersion("ds_companies", "t_a", v.version);
expect(reread.schema_version).toBe("estimated-v1");
expect(reread.schema_version).not.toBe("v1");
});
});
+86
View File
@@ -0,0 +1,86 @@
/**
* Canonical structured observations (sql/022): idempotent write, conflict
* preservation, tenant isolation and relation identity resolution.
*/
import { describe, it, expect } from "vitest";
import { CanonicalFactService } from "@/src/services/canonical-fact-service";
import { SiaxError } from "@/src/platform/errors";
const T = "t_canonical_test";
const ENTITY = { entity_type: "web_page", identity_namespace: "url", identity_value: "https://example.org" };
function fact(overrides: Record<string, unknown> = {}) {
return {
entity: ENTITY,
predicate: "web.title",
value: "Example Domain",
source_ref: "source:example",
extractor_version: "0pt.motor.extraction/v1",
observed_at: "2026-11-04T12:00:00Z",
...overrides,
};
}
describe("CanonicalFactService — write", () => {
it("creates the entity and the fact, and query returns it", async () => {
const svc = new CanonicalFactService();
const result = await svc.write({ tenant_id: T, facts: [fact()] });
expect(result.entities).toHaveLength(1);
expect(result.entities[0].identity_value).toBe("https://example.org");
expect(result.facts).toHaveLength(1);
expect(result.duplicates).toBe(0);
const rows = await svc.query({ tenant_id: T, identity_value: "https://example.org" });
expect(rows).toHaveLength(1);
expect(rows[0].predicate).toBe("web.title");
expect(rows[0].value_type).toBe("string");
});
it("is idempotent: an identical replay is reported as a duplicate, not stored twice", async () => {
const svc = new CanonicalFactService();
await svc.write({ tenant_id: T, facts: [fact()] });
const replay = await svc.write({ tenant_id: T, facts: [fact()] });
expect(replay.duplicates).toBe(1);
const rows = await svc.query({ tenant_id: T, identity_value: "https://example.org" });
expect(rows).toHaveLength(1);
});
it("preserves conflicting sources as separate observations", async () => {
const svc = new CanonicalFactService();
await svc.write({ tenant_id: T, facts: [fact({ source_ref: "source:a", value: "A" })] });
await svc.write({ tenant_id: T, facts: [fact({ source_ref: "source:b", value: "B" })] });
const rows = await svc.query({ tenant_id: T, identity_value: "https://example.org" });
expect(rows).toHaveLength(2);
expect(rows.map((r) => r.value).sort()).toEqual(["A", "B"]);
});
it("isolates tenants", async () => {
const svc = new CanonicalFactService();
await svc.write({ tenant_id: "t_a", facts: [fact()] });
expect(await svc.query({ tenant_id: "t_b" })).toHaveLength(0);
});
it("resolves relation subject/object identities to entity ids", async () => {
const svc = new CanonicalFactService();
const result = await svc.write({
tenant_id: T,
relations: [{
subject: ENTITY,
predicate: "LINKS_TO",
object: { entity_type: "web_page", identity_namespace: "url", identity_value: "https://example.org/next" },
source_ref: "source:example",
extractor_version: "0pt.motor.extraction/v1",
observed_at: "2026-11-04T12:00:00Z",
}],
});
expect(result.entities).toHaveLength(2);
expect(result.relations[0].subject_id).toBeTruthy();
expect(result.relations[0].object_id).toBeTruthy();
expect(result.relations[0].subject_id).not.toBe(result.relations[0].object_id);
});
it("rejects a fact without observed_at or with an invalid confidence", async () => {
const svc = new CanonicalFactService();
await expect(svc.write({ tenant_id: T, facts: [fact({ observed_at: undefined })] })).rejects.toBeInstanceOf(SiaxError);
await expect(svc.write({ tenant_id: T, facts: [fact({ confidence: 2 })] })).rejects.toBeInstanceOf(SiaxError);
});
});
+165
View File
@@ -0,0 +1,165 @@
/**
* P061 DoD: "two heterogeneous connectors pass the same conformance suite."
*
* This file is that proof. It runs the SAME function
* (src/connectors/conformance.ts::runConnectorConformance) against two
* connectors that share nothing but the contract:
*
* HttpJsonConnector — a real node:http server on a real socket, opaque
* cursor paging, network health check, timestamp
* backfill bounds.
* JsonlFileConnector — a real file on disk, line-offset cursor, filesystem
* health check, line-number backfill bounds, and CDC
* delete records the HTTP connector cannot produce.
*
* Neither connector is mocked. The HTTP fixture is a genuine server that
* implements paging server-side; the file fixture is a genuine file written
* to a temp dir. A connector that only "passed" against a stub would prove
* nothing about the contract.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import http from "node:http";
import type { AddressInfo } from "node:net";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { runConnectorConformance, type ConformanceFixture } from "@/src/connectors/conformance";
import { HttpJsonConnector } from "@/src/connectors/http-json-connector";
import { JsonlFileConnector } from "@/src/connectors/jsonl-file-connector";
import type { RecordSchemaFields } from "@/src/schema/record-schema";
const SCHEMA: RecordSchemaFields = {
org_number: { type: "string", required: true },
name: { type: "string", required: true },
employees: { type: "number", required: false },
};
/** 5 records, shared by both fixtures so the suite's counts are comparable. */
const ROWS = [
{ org_number: "556001-0001", name: "Alfa AB", employees: 10, seq: 1 },
{ org_number: "556002-0002", name: "Beta AB", employees: 20, seq: 2 },
{ org_number: "556003-0003", name: "Gamma AB", employees: 30, seq: 3 },
{ org_number: "556004-0004", name: "Delta AB", employees: 40, seq: 4 },
{ org_number: "556005-0005", name: "Epsilon AB", employees: 50, seq: 5 },
];
// --- fixture 1: a real paged HTTP API ---------------------------------------
let server: http.Server;
let baseUrl = "";
beforeAll(async () => {
server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
if (url.pathname !== "/v1/records") {
res.writeHead(404).end("{}");
return;
}
const limit = Number(url.searchParams.get("limit") ?? "100");
const from = url.searchParams.get("from");
const to = url.searchParams.get("to");
if (from !== null && to !== null) {
// Backfill: bounds are `seq` values, from inclusive, to exclusive.
const slice = ROWS.filter((r) => r.seq >= Number(from) && r.seq < Number(to)).slice(0, limit);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ records: slice, next_cursor: null }));
return;
}
// Cursor is the `seq` of the last record already delivered.
const after = Number(url.searchParams.get("cursor") ?? "0");
const slice = ROWS.filter((r) => r.seq > after).slice(0, limit);
const next = slice.length > 0 ? String(slice[slice.length - 1].seq) : null;
const more = slice.length > 0 && slice[slice.length - 1].seq < ROWS[ROWS.length - 1].seq;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ records: slice, next_cursor: more ? next : null }));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
});
// --- fixture 2: a real JSONL file -------------------------------------------
const tmpDir = path.join(os.tmpdir(), `opt-conformance-${process.pid}`);
const jsonlPath = path.join(tmpDir, "companies.jsonl");
beforeAll(async () => {
await fs.mkdir(tmpDir, { recursive: true });
await fs.writeFile(
jsonlPath,
ROWS.map((r) => JSON.stringify({ org_number: r.org_number, name: r.name, employees: r.employees })).join("\n") + "\n",
"utf8",
);
});
const ctx = { tenant_id: "t_test", project_id: "p_test", source_id: "src_conf", run_id: "run_conf" };
describe("P061 connector contract — the same conformance suite, two heterogeneous connectors", () => {
it("HttpJsonConnector passes every check", async () => {
const fixture: ConformanceFixture = {
validConfig: {
base_url: baseUrl,
records_path: "/v1/records",
partition_key: "companies",
schema: SCHEMA,
record_key_field: "org_number",
cursor_field: "seq",
},
// Not an absolute URL and no schema — must be rejected without any IO.
invalidConfig: { base_url: "not-a-url", records_path: "v1/records", partition_key: "", record_key_field: "" },
ctx,
backfill: { from: "2", to: "4" },
expectedRecordCount: ROWS.length,
};
const report = await runConnectorConformance(new HttpJsonConnector(), fixture);
const failed = report.checks.filter((c) => !c.passed);
expect(failed.map((c) => `${c.name}: ${c.detail}`)).toEqual([]);
expect(report.passed).toBe(true);
expect(report.checks.length).toBeGreaterThanOrEqual(14);
});
it("JsonlFileConnector passes every check — the identical suite", async () => {
const fixture: ConformanceFixture = {
validConfig: {
file_path: jsonlPath,
partition_key: "companies",
schema: SCHEMA,
record_key_field: "org_number",
},
// Relative path, wrong extension, no schema.
invalidConfig: { file_path: "companies.csv", partition_key: "", record_key_field: "" },
ctx,
// File-connector bounds are LINE NUMBERS — deliberately a different
// vocabulary from the HTTP fixture's timestamps/sequence values, which
// is exactly the heterogeneity the shared contract has to survive.
backfill: { from: "1", to: "3" },
expectedRecordCount: ROWS.length,
};
const report = await runConnectorConformance(new JsonlFileConnector(), fixture);
const failed = report.checks.filter((c) => !c.passed);
expect(failed.map((c) => `${c.name}: ${c.detail}`)).toEqual([]);
expect(report.passed).toBe(true);
});
it("the suite actually FAILS a connector that breaks the contract (it is not decoration)", async () => {
// A connector that accepts any config at all — the classic fail-open bug.
class FailOpenConnector extends JsonlFileConnector {
override validate() {
return { valid: true, errors: [] };
}
}
const report = await runConnectorConformance(new FailOpenConnector(), {
validConfig: { file_path: jsonlPath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
invalidConfig: { file_path: "nope.csv", partition_key: "", record_key_field: "" },
ctx,
backfill: { from: "1", to: "3" },
expectedRecordCount: ROWS.length,
});
expect(report.passed).toBe(false);
expect(report.checks.find((c) => c.name.startsWith("validate: rejects"))?.passed).toBe(false);
});
});
+87
View File
@@ -0,0 +1,87 @@
import { describe, it, expect } from "vitest";
import { DatasetService } from "@/src/services/dataset-service";
import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service";
describe("DatasetIcebergMappingService", () => {
it("createMapping persists a reference into ST0RE's table registry", async () => {
const datasetService = new DatasetService();
const service = new DatasetIcebergMappingService({ datasetService });
await datasetService.registerDataset({
dataset_id: "ds_iceberg_map_1",
tenant_id: "t1",
project_id: "p1",
name: "Iceberg Mapping Dataset",
dataset_type: "raw",
});
const mapping = await service.createMapping({
dataset_iceberg_mapping_id: "dim_test_001",
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_iceberg_map_1",
iceberg_table_id: "st0re_table_abc123",
namespace: "0pt_default",
table_name: "dim_company_se",
});
expect(mapping.dataset_iceberg_mapping_id).toBe("dim_test_001");
expect(mapping.iceberg_table_id).toBe("st0re_table_abc123");
expect(mapping.mapping_status).toBe("active");
expect(mapping.created_at).toBeDefined();
});
it("createMapping rejects an unknown dataset_id", async () => {
const service = new DatasetIcebergMappingService();
await expect(
service.createMapping({
dataset_iceberg_mapping_id: "dim_test_bad",
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_does_not_exist",
iceberg_table_id: "st0re_table_xyz",
})
).rejects.toThrow("not found");
});
it("createMapping rejects a missing iceberg_table_id", async () => {
const datasetService = new DatasetService();
const service = new DatasetIcebergMappingService({ datasetService });
await datasetService.registerDataset({
dataset_id: "ds_iceberg_map_2",
tenant_id: "t1",
project_id: "p1",
name: "No Table Ref",
dataset_type: "raw",
});
await expect(
service.createMapping({
dataset_iceberg_mapping_id: "dim_test_no_ref",
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_iceberg_map_2",
iceberg_table_id: "",
})
).rejects.toThrow("iceberg_table_id is required");
});
it("getMappingForDataset returns the active mapping for a dataset", async () => {
const datasetService = new DatasetService();
const service = new DatasetIcebergMappingService({ datasetService });
await datasetService.registerDataset({
dataset_id: "ds_iceberg_map_3",
tenant_id: "t1",
project_id: "p1",
name: "Lookup Dataset",
dataset_type: "raw",
});
await service.createMapping({
dataset_iceberg_mapping_id: "dim_test_lookup",
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_iceberg_map_3",
iceberg_table_id: "st0re_table_lookup",
});
const found = await service.getMappingForDataset("ds_iceberg_map_3");
expect(found?.iceberg_table_id).toBe("st0re_table_lookup");
});
});
+222
View File
@@ -0,0 +1,222 @@
/**
* Real-Postgres proof for the dataset registry + immutable version metadata.
*
* Set DATASET_TEST_DATABASE_URL to a disposable Postgres 16 instance. When it
* is unset the suite skips honestly; Gitea CI should provide it for the
* blocking real-infrastructure job before this capability is promoted.
*/
import fs from "node:fs";
import path from "node:path";
import postgres from "postgres";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { closeRepositorySqlForTests } from "@/src/repositories/db";
import { DatasetService } from "@/src/services/dataset-service";
import { DatasetVersionService } from "@/src/services/dataset-version-service";
const TEST_DATABASE_URL = process.env.DATASET_TEST_DATABASE_URL;
const run = TEST_DATABASE_URL ? describe : describe.skip;
let admin: ReturnType<typeof postgres> | undefined;
let reachable = false;
let unreachableReason = "";
beforeAll(async () => {
if (!TEST_DATABASE_URL) {
console.warn("[realinfra] DATASET_TEST_DATABASE_URL unset — skipping honestly.");
return;
}
try {
admin = postgres(TEST_DATABASE_URL, { prepare: false, ssl: false, max: 3 });
await Promise.race([
admin`SELECT 1`,
new Promise((_, reject) => setTimeout(() => reject(new Error("connect timeout")), 5_000)),
]);
for (const migration of ["003_datasets.sql", "011_aud0_evidence_outbox.sql", "012_dataset_versions.sql"]) {
await admin.unsafe(fs.readFileSync(path.join(process.cwd(), "sql", migration), "utf8"));
}
// Aktivera den durabla AUD0-outboxen: createAud0OutboxRepositoryFromEnv()
// läser DATABASE_URL (se src/repositories/db.ts) — utan den blir klienten
// Noop och inga producer-rader skrivs (testet skulle ljugit om durabilitet).
process.env.DATABASE_URL = TEST_DATABASE_URL;
reachable = true;
} catch (error) {
unreachableReason = error instanceof Error ? error.message : String(error);
}
}, 30_000);
afterAll(async () => {
delete process.env.DATABASE_URL;
await admin?.end({ timeout: 5 });
await closeRepositorySqlForTests();
});
function datasetService(): DatasetService {
return new DatasetService({ databaseUrl: TEST_DATABASE_URL });
}
function versionService(): DatasetVersionService {
return new DatasetVersionService({ databaseUrl: TEST_DATABASE_URL });
}
run("Dataset registry + versions against LIVE Postgres", () => {
it("persists a dataset across independent service instances", async (ctx) => {
if (!reachable) {
console.warn(`[realinfra] Postgres unavailable (${unreachableReason}) — skipping honestly.`);
ctx.skip();
return;
}
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`;
const datasetId = `ds_realpg_${stamp}`;
const tenantId = `t_realpg_${stamp}`;
await datasetService().registerDataset({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
name: "Real Postgres dataset",
dataset_type: "curated",
created_by: "realinfra-test",
});
const reloaded = await datasetService().getDataset(datasetId);
expect(reloaded.dataset_id).toBe(datasetId);
expect(reloaded.tenant_id).toBe(tenantId);
const rows = await admin!<{ tenant_id: string; name: string }[]>`
SELECT tenant_id, name FROM opt_datasets WHERE dataset_id = ${datasetId}`;
expect(rows).toEqual([{ tenant_id: tenantId, name: "Real Postgres dataset" }]);
});
it("persists monotonic immutable versions across fresh service instances", async (ctx) => {
if (!reachable) return ctx.skip();
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`;
const datasetId = `ds_versions_${stamp}`;
const tenantId = `t_versions_${stamp}`;
await datasetService().registerDataset({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
name: "Versioned dataset",
dataset_type: "curated",
created_by: "realinfra-test",
});
const v1 = await versionService().createVersion({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
artifact_refs: ["st0re:artifact:art_realpg_1"],
schema_version: "1",
record_count: 10,
created_by: "realinfra-test",
idempotency_key: `idem_${stamp}_1`,
});
const v2 = await versionService().createVersion({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
artifact_refs: ["st0re:artifact:art_realpg_2"],
schema_version: "1",
record_count: 11,
created_by: "realinfra-test",
idempotency_key: `idem_${stamp}_2`,
});
expect([v1.version, v2.version]).toEqual([1, 2]);
const fresh = versionService();
expect((await fresh.listVersions(datasetId, tenantId)).map((item) => item.version)).toEqual([1, 2]);
expect((await fresh.getVersion(datasetId, tenantId, 2)).artifact_refs).toEqual(["st0re:artifact:art_realpg_2"]);
});
it("replays the same idempotency key without minting another version and rejects payload drift", async (ctx) => {
if (!reachable) return ctx.skip();
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`;
const datasetId = `ds_idem_${stamp}`;
const tenantId = `t_idem_${stamp}`;
await datasetService().registerDataset({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
name: "Idempotent dataset",
dataset_type: "derived",
created_by: "realinfra-test",
});
const input = {
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
artifact_refs: ["st0re:artifact:art_idem_1"],
schema_version: "1",
created_by: "realinfra-test",
idempotency_key: `idem_${stamp}`,
} as const;
const first = await versionService().createVersion(input);
const replay = await versionService().createVersion(input);
expect(replay.version).toBe(first.version);
expect(await versionService().listVersions(datasetId, tenantId)).toHaveLength(1);
await expect(versionService().createVersion({
...input,
artifact_refs: ["st0re:artifact:art_DIFFERENT"],
})).rejects.toMatchObject({ code: "CONFLICT" });
});
it("foreign tenant cannot read or version another tenant's dataset", async (ctx) => {
if (!reachable) return ctx.skip();
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`;
const datasetId = `ds_tenant_${stamp}`;
const owner = `t_owner_${stamp}`;
const foreign = `t_foreign_${stamp}`;
await datasetService().registerDataset({
dataset_id: datasetId,
tenant_id: owner,
project_id: "p_main",
name: "Tenant isolated",
dataset_type: "raw",
created_by: "realinfra-test",
});
await expect(versionService().listVersions(datasetId, foreign)).rejects.toMatchObject({ code: "NOT_FOUND" });
await expect(versionService().createVersion({
dataset_id: datasetId,
tenant_id: foreign,
project_id: "p_main",
artifact_refs: ["st0re:artifact:art_foreign"],
schema_version: "1",
created_by: "intruder",
})).rejects.toMatchObject({ code: "NOT_FOUND" });
});
it("durable AUD0 producer rows are written alongside dataset operations", async (ctx) => {
if (!reachable) return ctx.skip();
const stamp = `${Date.now()}_${Math.random().toString(16).slice(2)}`;
const datasetId = `ds_evidence_${stamp}`;
const tenantId = `t_evidence_${stamp}`;
await datasetService().registerDataset({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
name: "Evidence dataset",
dataset_type: "curated",
created_by: "realinfra-test",
});
await versionService().createVersion({
dataset_id: datasetId,
tenant_id: tenantId,
project_id: "p_main",
artifact_refs: ["st0re:artifact:art_evidence"],
schema_version: "1",
created_by: "realinfra-test",
});
const evidence = await admin!<{ evidence_kind: string; status: string }[]>`
SELECT evidence_kind, status
FROM opt_aud0_evidence_outbox
WHERE tenant_id = ${tenantId}
ORDER BY created_at`;
expect(evidence.length).toBeGreaterThanOrEqual(3); // register + version event + lineage
expect(evidence.every((row) => row.status === "pending")).toBe(true);
expect(new Set(evidence.map((row) => row.evidence_kind))).toEqual(new Set(["event", "openlineage"]));
});
});
+175
View File
@@ -0,0 +1,175 @@
/**
* DatasetVersionService unit tests (Master-DoD §10 Dataset:
* create/version/query/export with canonical ST0RE artifact refs, §5 + §53).
*/
import { describe, it, expect } from "vitest";
import { DatasetVersionService } from "@/src/services/dataset-version-service";
import { parseResourceRef, formatResourceRef, isResourceRef } from "@/src/platform/resource-ref";
async function withDataset() {
const svc = new DatasetVersionService();
await svc.datasets.registerDataset({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
name: "Companies",
dataset_type: "curated",
});
return svc;
}
describe("resource refs (Master-DoD §5)", () => {
it("formats and parses canonical refs incl. versions", () => {
expect(formatResourceRef({ product: "st0re", resourceType: "artifact", resourceId: "art_x" })).toBe(
"st0re:artifact:art_x"
);
expect(parseResourceRef("0pt:dataset:ds_x@3")).toEqual({
product: "0pt",
resourceType: "dataset",
resourceId: "ds_x",
version: "3",
});
expect(isResourceRef("st0re:artifact:art_x", "st0re", "artifact")).toBe(true);
expect(isResourceRef("st0re:artifact:art_x", "aud0")).toBe(false);
expect(parseResourceRef("not a ref")).toBeUndefined();
expect(parseResourceRef("db-primary-key-42")).toBeUndefined();
});
});
describe("DatasetVersionService — dataset.version", () => {
it("creates monotonically numbered versions holding canonical st0re refs", async () => {
const svc = await withDataset();
const v1 = await svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: ["st0re:artifact:art_1"],
schema_version: "v1",
record_count: 100,
created_by: "actor_1",
});
const v2 = await svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: ["st0re:artifact:art_2", "st0re:artifact:art_3"],
schema_version: "v1",
created_by: "actor_1",
});
expect(v1.version).toBe(1);
expect(v2.version).toBe(2);
expect((await svc.listVersions("ds_companies", "t_a")).map((v) => v.version)).toEqual([1, 2]);
expect((await svc.getVersion("ds_companies", "t_a", 2)).artifact_refs).toHaveLength(2);
});
it("REFUSES non-canonical artifact refs (no raw ids, no foreign products)", async () => {
const svc = await withDataset();
for (const bad of ["art_raw_id", "aud0:evidence:ev_1", "st0re:dataset:x", ""]) {
await expect(
svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: [bad],
schema_version: "v1",
created_by: "actor_1",
})
).rejects.toMatchObject({ code: "INVALID_REQUEST" });
}
await expect(
svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: [],
schema_version: "v1",
created_by: "actor_1",
})
).rejects.toMatchObject({ code: "INVALID_REQUEST" });
});
it("idempotency (§53): the same idempotency_key returns the SAME version", async () => {
const svc = await withDataset();
const a = await svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: ["st0re:artifact:art_1"],
schema_version: "v1",
created_by: "actor_1",
idempotency_key: "retry-1",
});
const b = await svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: ["st0re:artifact:art_1"],
schema_version: "v1",
created_by: "actor_1",
idempotency_key: "retry-1",
});
expect(b.version).toBe(a.version);
expect(await svc.listVersions("ds_companies", "t_a")).toHaveLength(1);
});
it("tenant gate: foreign tenant sees NOT_FOUND on version reads/writes (§50)", async () => {
const svc = await withDataset();
await expect(svc.listVersions("ds_companies", "t_b")).rejects.toMatchObject({ code: "NOT_FOUND" });
await expect(
svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_b",
project_id: "p_1",
artifact_refs: ["st0re:artifact:art_1"],
schema_version: "v1",
created_by: "intruder",
})
).rejects.toMatchObject({ code: "NOT_FOUND" });
});
});
describe("DatasetVersionService — dataset.export", () => {
it("registers the export artifact via ST0RE and returns its canonical ref", async () => {
const svc = await withDataset();
await svc.createVersion({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
artifact_refs: ["st0re:artifact:art_1"],
schema_version: "v1",
created_by: "actor_1",
});
const exp = await svc.exportDataset({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
version: 1,
format: "parquet",
object_location: { provider: "minio", bucket: "siax-tenants", key: "t_a/exports/companies.parquet" },
size_bytes: 4096,
checksum_sha256: "b".repeat(64),
actor_id: "actor_1",
});
// Test runtime uses the ST0RE mock => mock_artifact_ prefix; the point is
// the CANONICAL REF shape, which is runtime-independent.
expect(isResourceRef(exp.artifact_ref, "st0re", "artifact")).toBe(true);
expect(exp.format).toBe("parquet");
});
it("export of a nonexistent version is NOT_FOUND", async () => {
const svc = await withDataset();
await expect(
svc.exportDataset({
dataset_id: "ds_companies",
tenant_id: "t_a",
project_id: "p_1",
version: 9,
format: "csv",
object_location: { provider: "minio", bucket: "b", key: "k" },
size_bytes: 1,
checksum_sha256: "c".repeat(64),
actor_id: "actor_1",
})
).rejects.toMatchObject({ code: "NOT_FOUND" });
});
});
+119
View File
@@ -0,0 +1,119 @@
/**
* Jev shadow-eval av ER auto-match (0PT_DECISION_ER_SHADOW):
* gate-off → ingen fetch; gate-on → rätt POST-body + DECIDED parsad;
* ABSTAINED → decided:false; fetch-fel → null (fail-closed);
* wirat anrop är fire-and-forget — hängande fetch bryter aldrig
* det deterministiska D0-svaret.
*/
import { describe, it, expect, vi, afterEach } from "vitest";
import { erAutoMatchShadow, type ErAutoMatchShadowInput } from "@siax/0pt-decision";
import { EntityResolutionService, type ErRecord } from "@/src/er/entity-resolution-service";
const GATE = "0PT_DECISION_ER_SHADOW";
const INPUT: ErAutoMatchShadowInput = {
tenant_id: "t_a",
target: { record_id: "a1", fields: { name: "Volvo AB" } },
candidates: [{ record_id: "a2", fields: { name: "Volvo Aktiebolag" } }],
score: 0.95,
};
function fetchMock(payload: unknown, ok = true) {
return vi.fn().mockResolvedValue({ ok, json: async () => payload });
}
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
describe("erAutoMatchShadow — gate", () => {
it("gate OFF → ingen fetch, null (default: shadow är av)", async () => {
vi.stubEnv(GATE, "");
const f = fetchMock({});
vi.stubGlobal("fetch", f);
expect(await erAutoMatchShadow(INPUT)).toBeNull();
expect(f).not.toHaveBeenCalled();
});
});
describe("erAutoMatchShadow — gate ON", () => {
it("DECIDED → rätt POST-body + svar parsat", async () => {
vi.stubEnv(GATE, "1");
const f = fetchMock({
data: { status: "DECIDED", choice: "0", confidence: 0.91, model: "jev", latencyMs: 120 },
});
vi.stubGlobal("fetch", f);
const out = await erAutoMatchShadow(INPUT);
expect(out).toEqual({ decided: true, choice: "0", confidence: 0.91, model: "jev", latencyMs: 120 });
expect(f).toHaveBeenCalledTimes(1);
const [url, init] = f.mock.calls[0] as [string, RequestInit];
expect(url).toMatch(/\/decision\/match$/);
const body = JSON.parse(String(init.body));
expect(body.decision).toBe("0pt.er.auto_match");
expect(body.left).toEqual(INPUT.target);
expect(body.right).toEqual(INPUT.candidates);
expect(body.instructions).toBe("Which candidate is the same entity as the target?");
expect(init.method).toBe("POST");
});
it("ABSTAINED → decided:false (aldrig fabrikerat beslut)", async () => {
vi.stubEnv(GATE, "1");
vi.stubGlobal("fetch", fetchMock({ data: { status: "ABSTAINED", confidence: 0.3 } }));
const out = await erAutoMatchShadow(INPUT);
expect(out).toEqual({ decided: false, confidence: 0.3 });
});
it("HTTP-fel (res.ok false) → null", async () => {
vi.stubEnv(GATE, "1");
vi.stubGlobal("fetch", fetchMock({}, false));
expect(await erAutoMatchShadow(INPUT)).toBeNull();
});
it("fetch kastar (decision-nere/timeout) → null, kastar aldrig", async () => {
vi.stubEnv(GATE, "1");
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));
expect(await erAutoMatchShadow(INPUT)).toBeNull();
});
});
describe("EntityResolutionService — shadow-wire (fire-and-forget)", () => {
const RECORDS: ErRecord[] = [
{ record_id: "a1", fields: { name: "Volvo Personvagnar AB", city: "goteborg", vin: "YV1" } },
{ record_id: "a2", fields: { name: "Volvo Personvagnar Aktiebolag", city: "goteborg", vin: "YV1" } },
];
function wireRequest() {
return {
tenant_id: "t_a",
project_id: "p_1",
records: RECORDS,
blocking_fields: ["city"],
compare_fields: [{ field: "name", weight: 2 }, { field: "city" }],
// Tvinga auto-match-bandet (score hamnar annars i review-bandet med defaults).
auto_match_threshold: 0.5,
review_threshold: 0.3,
};
}
it("gate ON + hängande fetch (aldrig resolving) → auto-match-status oförändrad", async () => {
vi.stubEnv(GATE, "1");
vi.stubGlobal("fetch", vi.fn().mockReturnValue(new Promise(() => {})));
const er = new EntityResolutionService();
const res = await er.generateCandidates(wireRequest());
expect(res.pairs).toHaveLength(1);
expect(res.pairs[0].status).toBe("match");
expect(res.pairs[0].decided_by).toBe("score");
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
});
it("gate OFF → ingen fetch vid auto-match", async () => {
vi.stubEnv(GATE, "");
const f = fetchMock({});
vi.stubGlobal("fetch", f);
const er = new EntityResolutionService();
const res = await er.generateCandidates(wireRequest());
expect(res.pairs[0].status).toBe("match");
expect(f).not.toHaveBeenCalled();
});
});
+172
View File
@@ -0,0 +1,172 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import os from "os";
import path from "path";
import fs from "fs";
import { DocumentCaptureService } from "@/src/services/document-capture-service";
import { LocalBlobStore } from "@/src/adapters/local-blob-store";
function jsonResponse(body: unknown, opts: { status?: number; headers?: Record<string, string> } = {}) {
return {
ok: (opts.status ?? 200) < 400,
status: opts.status ?? 200,
headers: { get: (k: string) => (opts.headers ?? {})[k] ?? null },
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
describe("DocumentCaptureService.captureFromMailbox", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "0pt-blob-"));
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
it("downloads PDF attachments, persists bytes, registers a ST0RE artifact, enqueues an N0D extraction job, and emits AUD0 events", async () => {
const pdfBytes = Buffer.from("%PDF-1.4 real bytes for test");
const pdfBase64 = pdfBytes.toString("base64");
const aud0Calls: { url: string; body: Record<string, unknown> }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
if (url.includes("login.microsoftonline.com")) return jsonResponse({ access_token: "tok", expires_in: 3600 });
if (url.includes("/messages?")) {
return jsonResponse({
value: [
{
id: "msg-1",
receivedDateTime: "2026-07-01T09:00:00Z",
from: { emailAddress: { name: "Sender", address: "[email protected]" } },
toRecipients: [],
subject: "A document",
bodyPreview: "preview",
hasAttachments: true,
webLink: "https://outlook.office.com/mail/1",
},
],
});
}
if (url.includes("/attachments")) {
return jsonResponse({
value: [
{
"@odata.type": "#microsoft.graph.fileAttachment",
id: "att-1",
name: "doc.pdf",
contentType: "application/pdf",
size: pdfBytes.length,
contentBytes: pdfBase64,
},
],
});
}
if (url.includes("/v1/aud0/events") || url.includes("/v1/aud0/openlineage")) {
aud0Calls.push({ url, body: init?.body ? JSON.parse(init.body as string) : null });
return jsonResponse({});
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const service = new DocumentCaptureService({
blobStore: new LocalBlobStore(tmpDir),
aud0BaseUrl: "https://aud0.example.com",
});
const artifactCalls = vi.spyOn(service['st0re'], 'createArtifact');
const result = await service.captureFromMailbox(
{ mailbox: { tenantId: "t", clientId: "c", clientSecret: "s", mailboxAddress: "[email protected]" } },
{ tenant_id: "tenant1", project_id: "proj1", actor_id: "actor1", correlation_id: "corr1" },
);
expect(artifactCalls).toHaveBeenCalledWith(expect.objectContaining({ pii_level: 'high' }));
expect(result.scanned_messages).toBe(1);
expect(result.captured_documents).toHaveLength(1);
const doc = result.captured_documents[0];
expect(doc.status).toBe("extraction_requested");
expect(doc.filename).toBe("doc.pdf");
expect(doc.mailbox_address).toBe("[email protected]");
expect(doc.st0re_artifact_id).toContain("mock_artifact_");
expect(doc.n0d_job_id).toContain("mock_job_");
// Bytes were actually persisted (INTERIM local store) and are readable back byte-for-byte.
const storedBytes = await service.getDocumentBytes(doc.document_id);
expect(storedBytes.equals(pdfBytes)).toBe(true);
const captured = aud0Calls.find((c) => c.body?.event_type === "0pt.document_captured") as { url: string; body: { event_type: string; capability_id: string; payload: { filename: string } } } | undefined;
expect(captured).toBeTruthy();
expect(captured!.body.payload.filename).toBe("doc.pdf");
expect(captured!.body.capability_id).toBe("0pt.capture_document");
// Lineage now goes to AUD0's REAL ingest contract: an OpenLineage
// RunEvent on /v1/aud0/openlineage.
const lineage = aud0Calls.find((c) => c.url.includes("openlineage")) as { url: string; body: { outputs: { name: string }[] } } | undefined;
expect(lineage).toBeTruthy();
expect(lineage!.body.outputs[0].name).toContain(doc.document_id);
});
it("skips non-PDF attachments and records per-message errors without aborting the whole run", async () => {
const fetchMock = vi.fn(async (url: string) => {
if (url.includes("login.microsoftonline.com")) return jsonResponse({ access_token: "tok", expires_in: 3600 });
if (url.includes("/messages?")) {
return jsonResponse({
value: [
{
id: "msg-ok",
receivedDateTime: "2026-07-01T09:00:00Z",
hasAttachments: true,
from: { emailAddress: {} },
toRecipients: [],
},
{
id: "msg-bad",
receivedDateTime: "2026-07-01T09:05:00Z",
hasAttachments: true,
from: { emailAddress: {} },
toRecipients: [],
},
],
});
}
if (url.includes("msg-ok/attachments")) {
return jsonResponse({
value: [
{
"@odata.type": "#microsoft.graph.fileAttachment",
id: "a1",
name: "x.png",
contentType: "image/png",
contentBytes: Buffer.from("x").toString("base64"),
},
],
});
}
if (url.includes("msg-bad/attachments")) {
return { ok: false, status: 500, headers: { get: () => null }, json: async () => ({ error: { code: "Fail", message: "boom" } }) } as unknown as Response;
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const service = new DocumentCaptureService({ blobStore: new LocalBlobStore(tmpDir) });
const result = await service.captureFromMailbox(
{ mailbox: { tenantId: "t", clientId: "c", clientSecret: "s", mailboxAddress: "[email protected]" } },
{ tenant_id: "tenant1", project_id: "proj1", actor_id: "actor1", correlation_id: "corr1" },
);
expect(result.scanned_messages).toBe(2);
expect(result.captured_documents).toHaveLength(0); // png skipped, msg-bad errored
expect(result.errors).toHaveLength(1);
expect(result.errors[0]).toContain("msg-bad");
});
it("rejects when mailbox credentials are incomplete", async () => {
const service = new DocumentCaptureService({ blobStore: new LocalBlobStore(tmpDir) });
await expect(
service.captureFromMailbox(
{ mailbox: { tenantId: "t", clientId: "", clientSecret: "s", mailboxAddress: "[email protected]" } },
{ tenant_id: "tenant1", project_id: "proj1", actor_id: "actor1", correlation_id: "corr1" },
),
).rejects.toThrow(/missing mailbox/i);
});
});
@@ -0,0 +1,174 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import os from "os";
import path from "path";
import fs from "fs";
import { DocumentCaptureService } from "@/src/services/document-capture-service";
import { DocumentExtractionService } from "@/src/services/document-extraction-service";
import { LocalBlobStore } from "@/src/adapters/local-blob-store";
function jsonResponse(body: unknown, opts: { status?: number; headers?: Record<string, string> } = {}) {
return {
ok: (opts.status ?? 200) < 400,
status: opts.status ?? 200,
headers: { get: (k: string) => (opts.headers ?? {})[k] ?? null },
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
describe("DocumentExtractionService — evidence-based extraction", () => {
let tmpDir: string;
let aud0Calls: { url: string; body: Record<string, unknown> }[];
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "0pt-blob-"));
aud0Calls = [];
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
vi.restoreAllMocks();
});
async function seedCapturedDocument(captureService: DocumentCaptureService) {
const pdfBytes = Buffer.from("%PDF-1.4 fake invoice pdf");
const fetchMock = vi.fn(async (url: string) => {
if (url.includes("login.microsoftonline.com")) return jsonResponse({ access_token: "tok", expires_in: 3600 });
if (url.includes("/messages?")) {
return jsonResponse({
value: [{ id: "msg-1", receivedDateTime: "2026-07-01T09:00:00Z", hasAttachments: true, from: { emailAddress: {} }, toRecipients: [] }],
});
}
if (url.includes("/attachments")) {
return jsonResponse({
value: [
{
"@odata.type": "#microsoft.graph.fileAttachment",
id: "att-1",
name: "doc.pdf",
contentType: "application/pdf",
contentBytes: pdfBytes.toString("base64"),
},
],
});
}
throw new Error(`unexpected fetch during seed: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const result = await captureService.captureFromMailbox(
{ mailbox: { tenantId: "t", clientId: "c", clientSecret: "s", mailboxAddress: "[email protected]" } },
{ tenant_id: "tenant1", project_id: "proj1", actor_id: "actor1", correlation_id: "corr-seed" },
);
return result.captured_documents[0];
}
it("never fabricates a value for a field Document Intelligence did not return, and preserves DI's confidence either way", async () => {
const captureService = new DocumentCaptureService({ blobStore: new LocalBlobStore(tmpDir) });
const document = await seedCapturedDocument(captureService);
const extractionService = new DocumentExtractionService(captureService, {
blobStore: new LocalBlobStore(tmpDir),
aud0BaseUrl: "https://aud0.example.com",
documentIntelligence: { endpoint: "https://di.example.com", apiKey: "key123", pollIntervalMs: 1 },
});
const artifactCalls = vi.spyOn(extractionService['st0re'], 'createArtifact');
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
if (url.includes(":analyze")) {
return jsonResponse({}, { status: 202, headers: { "operation-location": "https://di.example.com/op/abc" } });
}
if (url.includes("/op/abc")) {
return jsonResponse({
status: "succeeded",
analyzeResult: {
content: "Acme AB\nTotal: 1234.50 SEK",
pages: [{}],
documents: [
{
confidence: 0.9,
fields: {
VendorName: { type: "string", valueString: "Acme AB", confidence: 0.97 },
InvoiceTotal: { type: "currency", valueCurrency: { amount: 1234.5 }, confidence: 0.92 },
// DueDate was detected as a field region but DI could not read a value —
// this is exactly the case that must NOT be fabricated into a fake date.
DueDate: { type: "date", confidence: 0.31 },
// CustomerAddress is not present in the DI response at all.
},
},
],
},
});
}
if (url.includes("/v1/aud0/events") || url.includes("/v1/aud0/openlineage")) {
aud0Calls.push({ url, body: init?.body ? JSON.parse(init.body as string) : null });
return jsonResponse({});
}
throw new Error(`unexpected fetch during extraction: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const extraction = await extractionService.extractDocument(document.document_id, {
tenant_id: "tenant1",
project_id: "proj1",
actor_id: "actor1",
correlation_id: "corr-extract",
model_id: "prebuilt-invoice",
});
expect(artifactCalls).toHaveBeenCalledWith(expect.objectContaining({ pii_level: 'high' }));
expect(extraction.status).toBe("completed");
// Found fields carry the real value + DI's own confidence.
expect(extraction.fields.VendorName).toEqual({ value: "Acme AB", confidence: 0.97, found: true });
expect(extraction.fields.InvoiceTotal).toEqual({ value: 1234.5, confidence: 0.92, found: true });
// Not-found field: value is null (never fabricated); confidence is whatever DI reported.
expect(extraction.fields.DueDate).toEqual({ value: null, confidence: 0.31, found: false });
// A field DI never mentioned at all is simply absent — also never fabricated into existence.
expect(extraction.fields.CustomerAddress).toBeUndefined();
expect(extraction.fields_total_count).toBe(3);
expect(extraction.fields_found_count).toBe(2);
// Average confidence is computed only over the found fields — DueDate's 0.31 excluded.
expect(extraction.average_confidence).toBeCloseTo((0.97 + 0.92) / 2, 5);
expect(extraction.document_confidence).toBe(0.9);
expect(extraction.st0re_artifact_id).toContain("mock_artifact_");
expect(extraction.model_id).toBe("prebuilt-invoice");
const updatedDoc = await captureService.getDocument(document.document_id);
expect(updatedDoc.status).toBe("extracted");
const extractedEvent = aud0Calls.find((c) => c.body?.event_type === "0pt.document_extracted") as { url: string; body: { event_type: string; capability_id: string; payload: { fields_found_count: number; fields_total_count: number } } } | undefined;
expect(extractedEvent).toBeTruthy();
expect(extractedEvent!.body.capability_id).toBe("0pt.extract_document");
expect(extractedEvent!.body.payload.fields_found_count).toBe(2);
expect(extractedEvent!.body.payload.fields_total_count).toBe(3);
});
it("marks the extraction failed — never returns a fabricated success — when Document Intelligence errors", async () => {
const captureService = new DocumentCaptureService({ blobStore: new LocalBlobStore(tmpDir) });
const document = await seedCapturedDocument(captureService);
const extractionService = new DocumentExtractionService(captureService, {
blobStore: new LocalBlobStore(tmpDir),
documentIntelligence: { endpoint: "https://di.example.com", apiKey: "key123", pollIntervalMs: 1 },
});
const fetchMock = vi.fn(async (url: string) => {
if (url.includes(":analyze")) return jsonResponse({}, { status: 500 });
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
await expect(
extractionService.extractDocument(document.document_id, {
tenant_id: "tenant1",
project_id: "proj1",
actor_id: "actor1",
correlation_id: "corr-fail",
model_id: "prebuilt-invoice",
}),
).rejects.toThrow();
const updatedDoc = await captureService.getDocument(document.document_id);
expect(updatedDoc.status).toBe("extraction_failed");
});
});
@@ -0,0 +1,37 @@
import { describe, it, expect } from "vitest";
import { DocumentCaptureService } from "@/src/services/document-capture-service";
import { DocumentExtractionService } from "@/src/services/document-extraction-service";
describe("DocumentExtractionService — refuses to fabricate when unconfigured", () => {
it("throws instead of returning an empty/fake success when Document Intelligence has no endpoint/apiKey", async () => {
const captureService = new DocumentCaptureService();
const extractionService = new DocumentExtractionService(captureService); // no documentIntelligence opt passed
await expect(
extractionService.extractDocument("doc_does_not_matter", {
tenant_id: "t1",
project_id: "p1",
actor_id: "a1",
correlation_id: "c1",
model_id: "prebuilt-invoice",
}),
).rejects.toThrow(/not configured/i);
});
it("rejects a missing model_id rather than silently picking one", async () => {
const captureService = new DocumentCaptureService();
const extractionService = new DocumentExtractionService(captureService, {
documentIntelligence: { endpoint: "https://di.example.com", apiKey: "key123" },
});
await expect(
extractionService.extractDocument("doc_does_not_matter", {
tenant_id: "t1",
project_id: "p1",
actor_id: "a1",
correlation_id: "c1",
model_id: "",
}),
).rejects.toThrow(/model_id/i);
});
});
@@ -0,0 +1,25 @@
import { describe, expect, it, vi } from 'vitest';
import { DocumentCaptureService } from '@/src/services/document-capture-service';
import { DocumentExtractionService } from '@/src/services/document-extraction-service';
describe('document extraction scope', () => {
it.each([
{ tenant_id: 'tenant-b', project_id: 'project-a' },
{ tenant_id: 'tenant-a', project_id: 'project-b' },
])('rejects an out-of-scope document before any byte read or external call', async (scope) => {
const capture = new DocumentCaptureService();
vi.spyOn(capture, 'getDocument').mockResolvedValue({ tenant_id: 'tenant-a', project_id: 'project-a' } as never);
const bytes = vi.spyOn(capture, 'getDocumentBytes');
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
try {
const service = new DocumentExtractionService(capture, {
documentIntelligence: { endpoint: 'https://di.example.test', apiKey: 'test-key' },
});
await expect(service.extractDocument('doc', { ...scope, actor_id: 'actor-a', correlation_id: 'corr', model_id: 'test' }))
.rejects.toThrow('Document doc not found');
expect(bytes).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
} finally { vi.unstubAllGlobals(); vi.restoreAllMocks(); }
});
});
@@ -0,0 +1,136 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { DocumentIntelligenceAdapter } from "@/src/adapters/document-intelligence-adapter";
function jsonResponse(body: unknown, opts: { status?: number; headers?: Record<string, string> } = {}) {
return {
ok: (opts.status ?? 200) < 400,
status: opts.status ?? 200,
headers: { get: (k: string) => (opts.headers ?? {})[k] ?? null },
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
describe("DocumentIntelligenceAdapter", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("isConfigured requires endpoint + apiKey", () => {
expect(DocumentIntelligenceAdapter.isConfigured({ endpoint: "https://x", apiKey: "k" })).toBe(true);
expect(DocumentIntelligenceAdapter.isConfigured({ endpoint: "https://x" })).toBe(false);
expect(DocumentIntelligenceAdapter.isConfigured({})).toBe(false);
});
it("normalizes structured + array fields and never fabricates a missing value", async () => {
const fetchMock = vi.fn(async (url: string) => {
if (url.includes(":analyze")) {
return jsonResponse({}, { status: 202, headers: { "operation-location": "https://di.example.com/op/123" } });
}
if (url.includes("/op/123")) {
return jsonResponse({
status: "succeeded",
analyzeResult: {
content: "raw extracted text",
pages: [{}, {}],
documents: [
{
confidence: 0.93,
fields: {
VendorName: { type: "string", valueString: "Acme AB", confidence: 0.98 },
InvoiceTotal: { type: "currency", valueCurrency: { amount: 1234.5, currencyCode: "SEK" }, confidence: 0.91 },
// Field region detected but no value could be read — must stay blank, not fabricated.
DueDate: { type: "date", confidence: 0.4 },
Items: {
type: "array",
valueArray: [
{
type: "object",
valueObject: {
Description: { type: "string", valueString: "Widget", confidence: 0.9 },
Amount: { type: "currency", valueCurrency: { amount: 100 }, confidence: 0.85 },
Unit: { type: "string", confidence: 0.2 }, // present but empty -> found:false
},
},
],
},
},
},
],
},
});
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const adapter = new DocumentIntelligenceAdapter({ endpoint: "https://di.example.com", apiKey: "key123", pollIntervalMs: 1 });
const result = await adapter.analyzeDocument(Buffer.from("%PDF-1.4"), "prebuilt-invoice");
expect(result.modelId).toBe("prebuilt-invoice");
expect(result.content).toBe("raw extracted text");
expect(result.documentConfidence).toBe(0.93);
expect(result.pageCount).toBe(2);
expect(result.fields.VendorName).toEqual({ value: "Acme AB", confidence: 0.98, found: true });
expect(result.fields.InvoiceTotal).toEqual({ value: 1234.5, confidence: 0.91, found: true });
// Not fabricated: value stays null, but DI's own (low) confidence is still recorded.
expect(result.fields.DueDate).toEqual({ value: null, confidence: 0.4, found: false });
expect(result.arrayFields.Items).toHaveLength(1);
expect(result.arrayFields.Items[0].Description).toEqual({ value: "Widget", confidence: 0.9, found: true });
expect(result.arrayFields.Items[0].Amount).toEqual({ value: 100, confidence: 0.85, found: true });
expect(result.arrayFields.Items[0].Unit).toEqual({ value: null, confidence: 0.2, found: false });
});
it("retries once on 429 then proceeds", async () => {
let analyzeAttempts = 0;
const fetchMock = vi.fn(async (url: string) => {
if (url.includes(":analyze")) {
analyzeAttempts++;
if (analyzeAttempts === 1) return jsonResponse({}, { status: 429 });
return jsonResponse({}, { status: 202, headers: { "operation-location": "https://di.example.com/op/retry" } });
}
if (url.includes("/op/retry")) {
return jsonResponse({ status: "succeeded", analyzeResult: { documents: [{ fields: {} }] } });
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const adapter = new DocumentIntelligenceAdapter({
endpoint: "https://di.example.com",
apiKey: "key123",
pollIntervalMs: 1,
rateLimitRetryMs: 1,
});
const result = await adapter.analyzeDocument(Buffer.from("x"), "prebuilt-receipt");
expect(analyzeAttempts).toBe(2);
expect(result.fields).toEqual({});
});
it("throws (never returns a fabricated result) when analyze status is failed", async () => {
const fetchMock = vi.fn(async (url: string) => {
if (url.includes(":analyze")) {
return jsonResponse({}, { status: 202, headers: { "operation-location": "https://di.example.com/op/999" } });
}
if (url.includes("/op/999")) {
return jsonResponse({ status: "failed", error: { code: "InvalidDocument" } });
}
throw new Error("unexpected");
});
vi.stubGlobal("fetch", fetchMock);
const adapter = new DocumentIntelligenceAdapter({ endpoint: "https://di.example.com", apiKey: "key123", pollIntervalMs: 1 });
await expect(adapter.analyzeDocument(Buffer.from("x"), "prebuilt-invoice")).rejects.toThrow(/failed/i);
});
it("throws when the analyze request itself errors (5xx)", async () => {
const fetchMock = vi.fn(async (url: string) => {
if (url.includes(":analyze")) return jsonResponse({}, { status: 500 });
throw new Error("unexpected");
});
vi.stubGlobal("fetch", fetchMock);
const adapter = new DocumentIntelligenceAdapter({ endpoint: "https://di.example.com", apiKey: "key123" });
await expect(adapter.analyzeDocument(Buffer.from("x"), "prebuilt-invoice")).rejects.toThrow(/500/);
});
});
@@ -0,0 +1,69 @@
import {describe,it,expect} from "vitest";
describe("0pt Enterprise Data OS Expansion (PROMPT 2)",()=>{
it("iceberg_table schema has required fields",()=>{
// eslint-disable-next-line @typescript-eslint/no-require-imports -- fixture-laddning via require
const schema=require("../../packages/schemas/0pt.iceberg_table.schema.json");
expect(schema.required).toContain("table_id");
expect(schema.required).toContain("table_name");
expect(schema.required).toContain("storage_uri");
expect(schema.properties.table_format.enum).toContain("iceberg");
});
it("signal schema has entity and strength",()=>{
// eslint-disable-next-line @typescript-eslint/no-require-imports -- fixture-laddning via require
const schema=require("../../packages/schemas/0pt.signal.schema.json");
expect(schema.required).toContain("signal_id");
expect(schema.required).toContain("signal_type");
expect(schema.required).toContain("signal_strength");
expect(schema.required).toContain("entity_type");
});
it("lineage_event schema has input/output assets",()=>{
// eslint-disable-next-line @typescript-eslint/no-require-imports -- fixture-laddning via require
const schema=require("../../packages/schemas/0pt.lineage_event.schema.json");
expect(schema.required).toContain("input_assets");
expect(schema.required).toContain("output_assets");
expect(schema.required).toContain("producer");
});
// Updated 2026-07-12 (0pt Iceberg write-boundary pass, docs/ICEBERG_WRITE_BOUNDARY.md):
// 0pt.source_rate_policy.schema.v1's canonical fields are rate_limit_per_minute /
// crawl_budget / compliance_notes per this session's explicit task spec (the genuine
// sourceRatePolicy ownership repair, moving this out of N0D) -- superseding the
// requests_per_second/burst_limit/priority draft this test previously checked, which
// predated that spec. See src/types/source-rate-policy.ts and
// src/services/source-rate-policy-service.ts for the real, tested implementation.
it("source_rate_policy schema has rate limits",()=>{
// eslint-disable-next-line @typescript-eslint/no-require-imports -- fixture-laddning via require
const schema=require("../../packages/schemas/0pt.source_rate_policy.schema.json");
expect(schema.required).toContain("rate_limit_per_minute");
expect(schema.required).toContain("crawl_budget");
expect(schema.properties.access.enum).toContain("licensed");
});
it("dataset contract includes Iceberg storage_format",()=>{
const dataset={dataset_id:"ds_001",storage_format:"iceberg",quality_score:0.94,pii_level:"medium",status:"active"};
expect(dataset.storage_format).toBe("iceberg");
expect(dataset.quality_score).toBeGreaterThan(0.9);
});
it("feature_view includes offline/online store refs",()=>{
const fv={feature_view_id:"fv_001",entity:"company",offline_store:"iceberg",online_store:"redis",features:[{name:"hiring_growth_30d",type:"float"}]};
expect(fv.offline_store).toBe("iceberg");
expect(fv.online_store).toBe("redis");
expect(fv.features[0].name).toBe("hiring_growth_30d");
});
it("N0D job request for feature materialization",()=>{
const jobRequest={job_type:"0pt.feature_materialization_job",capability_id:"0pt.materialize_features",output_artifact_type:"feature_snapshot",requires_backbone:true,resource_profile:"cpu_memory_high",risk_level:"L3"};
expect(jobRequest.job_type).toBe("0pt.feature_materialization_job");
expect(jobRequest.risk_level).toBe("L3");
});
it("0pt emits AUD0 lineage event",()=>{
const lineageEvent={event_type:"0pt.lineage_emitted",app_id:"0pt",capability_id:"0pt.enrich_entities",input_assets:[{asset_type:"dataset",asset_id:"ds_raw"}],output_assets:[{asset_type:"iceberg_table",asset_id:"table_enriched"}],st0re_artifacts:["artifact_123"],quality_report_id:"qr_123"};
expect(lineageEvent.event_type).toBe("0pt.lineage_emitted");
expect(lineageEvent.output_assets[0].asset_type).toBe("iceberg_table");
});
});
+197
View File
@@ -0,0 +1,197 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { NextRequest } from "next/server";
import { POST as candidatesPOST } from "@/app/api/0pt/internal/er/candidates/route";
const TOKEN = "test-er-internal-token";
let previousToken: string | undefined;
function request(body: unknown, token: string | undefined = TOKEN): NextRequest {
const headers: Record<string, string> = { "content-type": "application/json" };
if (token !== undefined) headers["x-internal-token"] = token;
return new NextRequest("http://localhost/api/0pt/internal/er/candidates", {
method: "POST",
headers,
body: JSON.stringify(body),
});
}
function baseBody(records: Array<{ record_id: string; fields: Record<string, unknown> }>) {
return {
tenant_id: "tenant_a",
project_id: "project_a",
records,
blocking_fields: ["city"],
compare_fields: [{ field: "name", weight: 1 }],
auto_match_threshold: 0.9,
review_threshold: 0.6,
};
}
beforeEach(() => {
previousToken = process.env.INTERNAL_TOKEN;
process.env.INTERNAL_TOKEN = TOKEN;
});
afterEach(() => {
if (previousToken === undefined) delete process.env.INTERNAL_TOKEN;
else process.env.INTERNAL_TOKEN = previousToken;
});
describe("POST /api/0pt/internal/er/candidates", () => {
it("fails closed without the internal service token", async () => {
// OBS: request(body, undefined) triggar default-parametern (skickar GILTIGT
// token) — skicka tom string för "utan token" (fail-closed → 401).
const res = await candidatesPOST(
request(
baseBody([
{ record_id: "a", fields: { name: "Acme AB", city: "Stockholm" } },
{ record_id: "b", fields: { name: "Acme AB", city: "Stockholm" } },
]),
"",
),
);
expect(res.status).toBe(401);
});
it("never emits a score-only fuzzy company match even above auto_match_threshold", async () => {
const res = await candidatesPOST(
request(
baseBody([
{ record_id: "a", fields: { name: "Acme Consulting AB", city: "Stockholm" } },
{ record_id: "b", fields: { name: "Acme Consulting A B", city: "Stockholm" } },
]),
),
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.pairs).toHaveLength(1);
expect(body.pairs[0].score).toBeGreaterThanOrEqual(0.9);
expect(body.pairs[0].decided_by).toBe("score");
expect(body.pairs[0].status).toBe("pending_review");
expect(body.review_queue.map((pair: { candidate_id: string }) => pair.candidate_id)).toEqual([
body.pairs[0].candidate_id,
]);
});
it("allows a same-country registration number to hard-link despite punctuation differences", async () => {
const res = await candidatesPOST(
request(
baseBody([
{
record_id: "a",
fields: {
name: "Acme Sweden AB",
city: "Stockholm",
registration_country: "SE",
org_nr: "556000-0001",
},
},
{
record_id: "b",
fields: {
name: "Acme Sverige",
city: "Stockholm",
registration_country: "se",
org_nr: "5560000001",
},
},
]),
),
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.pairs).toHaveLength(1);
expect(body.pairs[0].status).toBe("match");
expect(body.pairs[0].decided_by).toBe("0pt.company.stable-identifiers.v3");
expect(body.review_queue).toEqual([]);
});
it("does not treat the same national registration number in different countries as global identity", async () => {
const res = await candidatesPOST(
request(
baseBody([
{
record_id: "a",
fields: {
name: "Acme Consulting AB",
city: "Stockholm",
registration_country: "SE",
org_nr: "123456789",
},
},
{
record_id: "b",
fields: {
name: "Acme Consulting A B",
city: "Stockholm",
registration_country: "NO",
org_nr: "123456789",
},
},
]),
),
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.pairs).toHaveLength(1);
expect(body.pairs[0].decided_by).toBe("score");
expect(body.pairs[0].status).toBe("pending_review");
});
it("lets conflicting stable identity evidence dominate a matching global LEI", async () => {
const res = await candidatesPOST(
request(
baseBody([
{
record_id: "a",
fields: {
name: "Acme Sweden AB",
city: "Stockholm",
registration_country: "SE",
lei: "549300EXAMPLE123",
org_nr: "556000-0001",
},
},
{
record_id: "b",
fields: {
name: "Acme Sweden AB",
city: "Stockholm",
registration_country: "SE",
lei: "549300EXAMPLE123",
org_nr: "556000-9999",
},
},
]),
),
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.pairs).toHaveLength(1);
expect(body.pairs[0].status).toBe("non_match");
expect(body.pairs[0].decided_by).toBe("0pt.company.stable-identifiers.v3");
});
it("can hard-link a globally matching LEI when no scoped identifier contradicts it", async () => {
const res = await candidatesPOST(
request(
baseBody([
{
record_id: "a",
fields: { name: "Acme Holding", city: "Stockholm", lei: "549300-EXAMPLE-123" },
},
{
record_id: "b",
fields: { name: "ACME Holdings Group", city: "Stockholm", lei: "549300EXAMPLE123" },
},
]),
),
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.pairs).toHaveLength(1);
expect(body.pairs[0].status).toBe("match");
expect(body.pairs[0].decided_by).toBe("0pt.company.stable-identifiers.v3");
});
});
+137
View File
@@ -0,0 +1,137 @@
/**
* EntityResolutionService unit tests (Master-DoD §10 Entity Resolution):
* blocking, transparent scoring, explanation, product hard-rule hook,
* human-review handoff, batch delegation contract.
*/
import { describe, it, expect } from "vitest";
import {
EntityResolutionService,
normalize,
similarity,
type ErRecord,
} from "@/src/er/entity-resolution-service";
const RECORDS: ErRecord[] = [
{ record_id: "a1", fields: { name: "Volvo Personvagnar AB", city: "göteborg", vin: "YV1XZ1234" } },
{ record_id: "a2", fields: { name: "Volvo Personvagnar Aktiebolag", city: "goteborg", vin: "YV1XZ1234" } },
{ record_id: "b1", fields: { name: "Ericsson AB", city: "stockholm", vin: "ERIC999" } },
{ record_id: "b2", fields: { name: "Eriksson Bygg AB", city: "stockholm", vin: "BYGG111" } },
];
function request(overrides: Record<string, unknown> = {}) {
return {
tenant_id: "t_a",
project_id: "p_1",
records: RECORDS,
blocking_fields: ["city"],
compare_fields: [{ field: "name", weight: 2 }, { field: "city" }],
...overrides,
};
}
describe("similarity primitives", () => {
it("normalize folds diacritics + punctuation (Göteborg ≡ goteborg — same block); similarity is 1 for equal, 0 for null", async () => {
expect(normalize("Göteborg!")).toBe("goteborg");
expect(normalize("Göteborg")).toBe(normalize("goteborg"));
expect(normalize("Ørsted")).toBe("orsted");
expect(similarity("Volvo AB", "volvo ab")).toBe(1);
expect(similarity(null, "x")).toBe(0);
expect(similarity("abc", "xyz")).toBeLessThan(0.5);
});
});
describe("EntityResolutionService — candidate API", () => {
it("blocking limits comparisons to same-block pairs and reports the reduction", async () => {
const er = new EntityResolutionService();
const res = await er.generateCandidates(request());
// 4 records = 6 possible pairs; blocking on city → (a1,a2) + (b1,b2) = 2.
expect(res.total_possible_comparisons).toBe(6);
expect(res.blocked_comparisons).toBe(2);
expect(res.pairs).toHaveLength(2);
});
it("scores near-duplicates high (match) and different companies lower, with per-field explanations", async () => {
const er = new EntityResolutionService();
const res = await er.generateCandidates(request());
const volvo = res.pairs.find((p) => p.record_a === "a1")!;
const eric = res.pairs.find((p) => p.record_a === "b1")!;
expect(volvo.score).toBeGreaterThan(eric.score);
expect(volvo.decided_by).toBe("score");
// Explanation is per-field with weights (§10 explanation).
expect(volvo.explanation.map((e) => e.field)).toEqual(["name", "city"]);
expect(volvo.explanation[0].weight).toBe(2);
expect(volvo.explanation[1].similarity).toBe(1);
});
it("hands mid-band pairs to human review, never auto-merging them", async () => {
const er = new EntityResolutionService();
const res = await er.generateCandidates(request({ auto_match_threshold: 0.95, review_threshold: 0.3 }));
const eric = res.pairs.find((p) => p.record_a === "b1")!;
expect(eric.status).toBe("pending_review");
expect(res.review_queue.map((p) => p.candidate_id)).toContain(eric.candidate_id);
});
it("product hard rules override the generic score in BOTH directions (§10 hook)", async () => {
const er = new EntityResolutionService();
er.registerHardRule({
rule_id: "vehiq.vin_equality",
decide: (a, b) => {
if (!a.fields.vin || !b.fields.vin) return "abstain";
return a.fields.vin === b.fields.vin ? "force_match" : "force_non_match";
},
});
const res = await er.generateCandidates(request());
const volvo = res.pairs.find((p) => p.record_a === "a1")!;
const eric = res.pairs.find((p) => p.record_a === "b1")!;
expect(volvo.status).toBe("match");
expect(volvo.decided_by).toBe("vehiq.vin_equality");
expect(volvo.score).toBe(1);
// Same city block but different VIN → forced non-match despite name similarity.
expect(eric.status).toBe("non_match");
expect(eric.decided_by).toBe("vehiq.vin_equality");
});
it("refuses unblocked all-pairs runs and invalid thresholds", async () => {
const er = new EntityResolutionService();
await expect(er.generateCandidates(request({ blocking_fields: [] }))).rejects.toThrowError(/blocking_fields/);
await expect(
er.generateCandidates(request({ auto_match_threshold: 0.5, review_threshold: 0.6 }))
).rejects.toThrowError(/review_threshold/);
await expect(er.generateCandidates(request({ records: [RECORDS[0]] }))).rejects.toThrowError(/between 2 and 5000/);
await expect(er.generateCandidates(request({ tenant_id: "" }))).rejects.toThrowError(/tenant_id/);
});
it("records with empty blocking keys are never blocked together", async () => {
const er = new EntityResolutionService();
const res = await er.generateCandidates(
request({
records: [
{ record_id: "x1", fields: { name: "A", city: null } },
{ record_id: "x2", fields: { name: "A", city: null } },
],
})
);
expect(res.pairs).toHaveLength(0);
});
});
describe("EntityResolutionService — batch delegation (0pt-motor via N0D)", () => {
it("submits the Splink batch job with the records artifact as input (contract only, never faked)", async () => {
const { createN0dClient } = await import("@/src/clients/n0d-client");
const er = new EntityResolutionService({ n0dClient: createN0dClient() }); // test runtime → mock
const job = await er.submitBatchResolution({
tenant_id: "t_a",
project_id: "p_1",
records_artifact_ref: "st0re:artifact:art_records",
});
expect(job.job_id).toContain("mock_job_");
expect(job.job_type).toBe("0pt.er.batch_resolution");
});
it("without an N0D client the batch path fails hard (DEPENDENCY_UNAVAILABLE)", async () => {
const er = new EntityResolutionService();
await expect(
er.submitBatchResolution({ tenant_id: "t_a", project_id: "p_1", records_artifact_ref: "st0re:artifact:x" })
).rejects.toMatchObject({ code: "DEPENDENCY_UNAVAILABLE" });
});
});
+262
View File
@@ -0,0 +1,262 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { ExternalWritebackService } from "@/src/services/external-writeback-service";
import type { WritebackAdapter, WritebackAdapterContext, WritebackRequest, WritebackResult } from "@/src/adapters/writeback-adapter";
import type { ExternalWriteRequest } from "@/src/types/external-writeback";
function jsonResponse(body: unknown, opts: { status?: number } = {}) {
return {
ok: (opts.status ?? 200) < 400,
status: opts.status ?? 200,
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
/** A configurable in-memory WritebackAdapter double -- records every `write` call so tests can
* assert on call count (critical for the idempotency/concurrency tests below), and can be told
* to fail N times before succeeding, or to always fail/always succeed. */
class TestWritebackAdapter implements WritebackAdapter {
readonly adapterId = "test_adapter";
calls: Array<{ request: WritebackRequest; ctx: WritebackAdapterContext }> = [];
configured = true;
private failuresRemaining = 0;
private failureError = "test_adapter_failure";
externalIdPrefix = "ext";
isConfigured(): boolean {
return this.configured;
}
failNextCalls(n: number, error = "test_adapter_failure"): void {
this.failuresRemaining = n;
this.failureError = error;
}
async write(request: WritebackRequest, ctx: WritebackAdapterContext): Promise<WritebackResult> {
this.calls.push({ request, ctx });
if (this.failuresRemaining > 0) {
this.failuresRemaining -= 1;
return { ok: false, error: this.failureError };
}
return { ok: true, externalId: `${this.externalIdPrefix}_${this.calls.length}` };
}
}
function baseRequest(overrides: Partial<ExternalWriteRequest> = {}): ExternalWriteRequest {
return {
adapter_id: "test_adapter",
idempotency_key: "idem-1",
record_type: "test_record",
payload: { foo: "bar" },
tenant_id: "tenant1",
project_id: "proj1",
actor_id: "actor1",
correlation_id: "corr-1",
...overrides,
};
}
/** Stubs global fetch to answer CL0UD policy evaluation (always "allow" unless `denyOrApproval`
* is set) and swallow AUD0 event/lineage POSTs, recording them for assertions. */
function stubCl0udAllowAndAud0(opts: { decision?: "allow" | "deny" | "approval_required" } = {}) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- AUD0-ingest-body är fri nyttolast
const aud0Calls: { url: string; body: any }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
// REAL CL0UD wire contract (cl0ud main): POST /api/policy/evaluate with a
// `{ data: { decision, requiresApproval, ... } }` envelope; there is no
// "approval_required" decision value on the wire — it is allow +
// requiresApproval, which 0pt's client maps back onto the historical
// three-value vocabulary.
if (url.includes("/api/policy/evaluate")) {
const wanted = opts.decision ?? "allow";
return jsonResponse({
data: {
decision: wanted === "deny" ? "deny" : "allow",
requiresApproval: wanted === "approval_required",
decisionId: "pdec_test",
reason: wanted === "deny" ? "test_deny" : wanted === "approval_required" ? "test_approval_required" : undefined,
},
meta: {},
});
}
// REAL AUD0 lineage ingest is the OpenLineage endpoint (/v1/aud0/openlineage);
// /v1/aud0/lineage/events never existed on AUD0.
if (url.includes("/v1/aud0/events") || url.includes("/v1/aud0/openlineage")) {
aud0Calls.push({ url, body: init?.body ? JSON.parse(init.body as string) : null });
return jsonResponse({});
}
throw new Error(`unexpected fetch in test: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
return { aud0Calls, fetchMock };
}
describe("ExternalWritebackService — adapter resolution", () => {
afterEach(() => vi.restoreAllMocks());
it("throws when no adapter is registered for the requested adapter_id", async () => {
stubCl0udAllowAndAud0();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com" });
await expect(service.writeExternalRecord(baseRequest())).rejects.toThrow(/no adapter registered/);
});
it("throws when the registered adapter reports isConfigured() === false, without calling write()", async () => {
stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
adapter.configured = false;
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
await expect(service.writeExternalRecord(baseRequest())).rejects.toThrow(/not configured/);
expect(adapter.calls).toHaveLength(0);
});
});
describe("ExternalWritebackService — CL0UD policy gate", () => {
afterEach(() => vi.restoreAllMocks());
it("denies the write and marks the record failed when CL0UD denies", async () => {
stubCl0udAllowAndAud0({ decision: "deny" });
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
await expect(service.writeExternalRecord(baseRequest())).rejects.toThrow(/Policy denied/);
expect(adapter.calls).toHaveLength(0);
const record = await service.findByIdempotencyKey("test_adapter", "idem-1");
expect(record?.status).toBe("failed");
});
it("does not silently bypass a CL0UD approval_required decision even though ACT0's own approval step already ran upstream", async () => {
stubCl0udAllowAndAud0({ decision: "approval_required" });
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
await expect(service.writeExternalRecord(baseRequest())).rejects.toThrow(/Policy requires approval/);
expect(adapter.calls).toHaveLength(0);
});
});
describe("ExternalWritebackService — successful write", () => {
afterEach(() => vi.restoreAllMocks());
it("writes via the adapter, returns status 'written' with the adapter's external id, and emits AUD0 event + lineage", async () => {
const { aud0Calls } = stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({
cl0udBaseUrl: "https://cl0ud.example.com",
aud0BaseUrl: "https://aud0.example.com",
adapters: [adapter],
});
const record = await service.writeExternalRecord(baseRequest());
expect(record.status).toBe("written");
expect(record.external_id).toBe("ext_1");
expect(adapter.calls).toHaveLength(1);
expect(adapter.calls[0]?.request.recordType).toBe("test_record");
expect(adapter.calls[0]?.request.payload).toEqual({ foo: "bar" });
const writtenEvent = aud0Calls.find((c) => c.body?.event_type === "0pt.external_record_written");
expect(writtenEvent).toBeTruthy();
expect(writtenEvent!.body.capability_id).toBe("0pt.write_external_record");
expect(writtenEvent!.body.risk_level).toBe("L4");
expect(writtenEvent!.body.payload.external_id).toBe("ext_1");
// Lineage now goes to AUD0's REAL ingest contract: an OpenLineage
// RunEvent on /v1/aud0/openlineage (the legacy source/target shape is
// converted by aud0-client's legacyLineageToOpenLineage).
const lineageEvent = aud0Calls.find((c) => c.url.includes("/openlineage"));
expect(lineageEvent).toBeTruthy();
expect(lineageEvent!.body.eventType).toBe("COMPLETE");
expect(lineageEvent!.body.inputs[0].name).toContain("idem-1");
expect(lineageEvent!.body.outputs[0].name).toContain("ext_1");
expect(lineageEvent!.body.run.facets.siaxLegacyLineage.lineage_type).toBe("produced");
});
});
describe("ExternalWritebackService — idempotency (sequential re-calls)", () => {
afterEach(() => vi.restoreAllMocks());
it("a second sequential call with the same idempotency_key after a successful write is an idempotent no-op — the adapter is never called again", async () => {
stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
const first = await service.writeExternalRecord(baseRequest());
const second = await service.writeExternalRecord(baseRequest());
expect(adapter.calls).toHaveLength(1);
expect(second.write_id).toBe(first.write_id);
expect(second.status).toBe("written");
expect(second.external_id).toBe(first.external_id);
});
it("a failed write CAN be retried with the same idempotency_key — this is a deliberate 'claim survives failure for retry' behavior, not a bug", async () => {
stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
adapter.failNextCalls(1, "transient_error");
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
await expect(service.writeExternalRecord(baseRequest())).rejects.toThrow(/transient_error/);
const failed = await service.findByIdempotencyKey("test_adapter", "idem-1");
expect(failed?.status).toBe("failed");
const retried = await service.writeExternalRecord(baseRequest());
expect(retried.status).toBe("written");
expect(adapter.calls).toHaveLength(2); // one failed attempt, one successful retry
});
it("different idempotency_key values against the same adapter never collide", async () => {
stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
const a = await service.writeExternalRecord(baseRequest({ idempotency_key: "idem-a" }));
const b = await service.writeExternalRecord(baseRequest({ idempotency_key: "idem-b" }));
expect(adapter.calls).toHaveLength(2);
expect(a.write_id).not.toBe(b.write_id);
expect(a.external_id).not.toBe(b.external_id);
});
});
describe("ExternalWritebackService — idempotency under concurrency (the regression-critical case)", () => {
afterEach(() => vi.restoreAllMocks());
it("two concurrent writeExternalRecord calls with the SAME idempotency_key result in exactly ONE adapter.write call — the claim is synchronous and race-free within one process", async () => {
stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
const [resultA, resultB] = await Promise.all([
service.writeExternalRecord(baseRequest()),
service.writeExternalRecord(baseRequest()),
]);
// The critical assertion: no matter how the two promises interleave afterwards, the
// external system is only ever actually written to once for this idempotency_key. This is
// the exact property v0-datahub's invoice-bridge.ts's own atomic Postgres UPDATE claim
// protected in production (two concurrent triggers can't both create a Bill) -- see
// external-writeback-service.ts's own module doc comment for how this port achieves the
// same guarantee via a synchronous, pre-first-await, in-memory claim.
expect(adapter.calls).toHaveLength(1);
// One call wins the claim and completes the real write; the other observes the claim
// in-flight and returns 'skipped_duplicate' without ever touching the adapter.
expect([resultA.status, resultB.status].sort()).toEqual(["skipped_duplicate", "written"]);
});
it("three concurrent calls with the same idempotency_key still only ever produce one adapter.write call", async () => {
stubCl0udAllowAndAud0();
const adapter = new TestWritebackAdapter();
const service = new ExternalWritebackService({ cl0udBaseUrl: "https://cl0ud.example.com", adapters: [adapter] });
const results = await Promise.all([
service.writeExternalRecord(baseRequest()),
service.writeExternalRecord(baseRequest()),
service.writeExternalRecord(baseRequest()),
]);
expect(adapter.calls).toHaveLength(1);
const writtenCount = results.filter((r) => r.status === "written").length;
const skippedCount = results.filter((r) => r.status === "skipped_duplicate").length;
expect(writtenCount).toBe(1);
expect(skippedCount).toBe(2);
});
});
+271
View File
@@ -0,0 +1,271 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { acquireFabricAccessToken, type FabricOneLakeCredentials } from "@/src/adapters/fabric-onelake-adapter";
import type { DnsLookupFn } from "@/src/lib/security/ssrf-guard";
const CREDS: FabricOneLakeCredentials = { tenantId: "tenant-a", clientId: "client-a", clientSecret: "secret-a" };
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}
/**
* Deterministic stand-in for real DNS: every test in this file that opens a
* pool now goes through the SSRF guard added to `getPool()`, so a fixed,
* injected resolver keeps these tests hermetic (no live network dependency)
* instead of relying on the test fixtures' fake hostnames actually
* resolving. Returns a public, non-blocked address for any hostname unless
* overridden — use `blockedDnsLookup` below to simulate a hostname that
* resolves to a private/internal address.
*/
function publicDnsLookup(_hostname: string): ReturnType<DnsLookupFn> {
return Promise.resolve([{ address: "20.91.151.2", family: 4 }]);
}
function blockedDnsLookup(address: string, family = 4): DnsLookupFn {
return () => Promise.resolve([{ address, family }]);
}
describe("acquireFabricAccessToken — OAuth client-credentials flow", () => {
it("posts client_credentials grant to the caller's tenant AAD endpoint with the default Fabric SQL scope", async () => {
let capturedUrl = "";
let capturedBody = "";
const fetchMock = vi.fn(async (url: unknown, init: unknown) => {
capturedUrl = String(url);
capturedBody = String((init as RequestInit).body);
return jsonResponse({ access_token: "tok_123", expires_in: 3600 });
});
const token = await acquireFabricAccessToken(CREDS, undefined, fetchMock as unknown as typeof fetch);
expect(capturedUrl).toBe("https://login.microsoftonline.com/tenant-a/oauth2/v2.0/token");
const params = new URLSearchParams(capturedBody);
expect(params.get("client_id")).toBe("client-a");
expect(params.get("client_secret")).toBe("secret-a");
expect(params.get("grant_type")).toBe("client_credentials");
expect(params.get("scope")).toBe("https://database.windows.net/.default");
expect(token.accessToken).toBe("tok_123");
expect(token.expiresAtEpochMs).toBeGreaterThan(Date.now());
});
it("uses a caller-supplied scope instead of the default (e.g. OneLake storage)", async () => {
let capturedBody = "";
const fetchMock = vi.fn(async (_url: unknown, init: unknown) => {
capturedBody = String((init as RequestInit).body);
return jsonResponse({ access_token: "tok_storage", expires_in: 3600 });
});
await acquireFabricAccessToken(CREDS, "https://storage.azure.com/.default", fetchMock as unknown as typeof fetch);
expect(new URLSearchParams(capturedBody).get("scope")).toBe("https://storage.azure.com/.default");
});
it("never hardcodes a tenant — different credentials hit different tenant token URLs", async () => {
const seenUrls: string[] = [];
const fetchMock = vi.fn(async (url: unknown) => {
seenUrls.push(String(url));
return jsonResponse({ access_token: "t", expires_in: 3600 });
});
await acquireFabricAccessToken({ tenantId: "tenant-x", clientId: "c", clientSecret: "s" }, undefined, fetchMock as unknown as typeof fetch);
await acquireFabricAccessToken({ tenantId: "tenant-y", clientId: "c", clientSecret: "s" }, undefined, fetchMock as unknown as typeof fetch);
expect(seenUrls).toEqual([
"https://login.microsoftonline.com/tenant-x/oauth2/v2.0/token",
"https://login.microsoftonline.com/tenant-y/oauth2/v2.0/token",
]);
});
it("throws a descriptive error when AAD rejects the credentials", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ error: "invalid_client", error_description: "bad secret" }, 401));
await expect(acquireFabricAccessToken(CREDS, undefined, fetchMock as unknown as typeof fetch)).rejects.toThrow(/invalid_client/);
});
it("rejects locally (no network call) when tenantId/clientId/clientSecret are missing", async () => {
const fetchMock = vi.fn();
await expect(
acquireFabricAccessToken({ tenantId: "", clientId: "c", clientSecret: "s" }, undefined, fetchMock as unknown as typeof fetch),
).rejects.toThrow(/required/);
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("FabricOneLakeAdapter.query — TDS execution via a mocked mssql driver", () => {
const CONFIG = {
credentials: CREDS,
sqlEndpoint: "https://my-endpoint.datawarehouse.fabric.microsoft.com/",
database: "lh_test",
};
beforeEach(() => {
vi.resetModules();
vi.doUnmock("mssql");
});
it("acquires a token, opens a pooled TDS connection with azure-active-directory-access-token auth, runs the query, and returns rows", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_query", expires_in: 3600 }));
const queryMock = vi.fn(async () => ({ recordset: [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }] }));
const inputMock = vi.fn();
const connectMock = vi.fn(async () => {});
const closeMock = vi.fn(async () => {});
let capturedConfig: Record<string, unknown> | null = null;
class FakeConnectionPool {
constructor(config: Record<string, unknown>) {
capturedConfig = config;
}
connect = connectMock;
request() {
return { input: inputMock, query: queryMock };
}
close = closeMock;
}
vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } }));
const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter");
const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch, publicDnsLookup);
const result = await adapter.query("SELECT * FROM dbo.customers WHERE id > @minId", { minId: 1 });
expect(result.rows).toEqual([{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }]);
expect(result.rowCount).toBe(2);
expect(result.durationMs).toBeGreaterThanOrEqual(0);
expect(inputMock).toHaveBeenCalledWith("minId", 1);
expect(connectMock).toHaveBeenCalledTimes(1);
expect(capturedConfig).toMatchObject({
server: "my-endpoint.datawarehouse.fabric.microsoft.com",
database: "lh_test",
authentication: { type: "azure-active-directory-access-token", options: { token: "tok_query" } },
});
await adapter.close();
expect(closeMock).toHaveBeenCalledTimes(1);
});
it("reuses the cached token across calls and only re-authenticates once", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_cached", expires_in: 3600 }));
const queryMock = vi.fn(async () => ({ recordset: [] }));
class FakeConnectionPool {
connect = vi.fn(async () => {});
request() {
return { input: vi.fn(), query: queryMock };
}
close = vi.fn(async () => {});
}
vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } }));
const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter");
const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch, publicDnsLookup);
await adapter.query("SELECT 1");
await adapter.query("SELECT 2");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(queryMock).toHaveBeenCalledTimes(2);
});
it("throws a clear, actionable error when the mssql driver is not installed/resolvable", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_x", expires_in: 3600 }));
// No vi.doMock("mssql", ...) here — this repo does not declare "mssql" as a
// dependency (see fabric-onelake-adapter.ts header), so the real dynamic
// import genuinely fails, exercising the adapter's real error path.
const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter");
const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch, publicDnsLookup);
await expect(adapter.query("SELECT 1")).rejects.toThrow(/mssql.*not installed/i);
});
});
describe("FabricOneLakeAdapter.query — SSRF guard on connection_config.sqlEndpoint", () => {
const CONFIG = {
credentials: CREDS,
sqlEndpoint: "https://my-endpoint.datawarehouse.fabric.microsoft.com/",
database: "lh_test",
};
beforeEach(() => {
vi.resetModules();
vi.doUnmock("mssql");
});
function fakePoolFactory() {
const queryMock = vi.fn(async () => ({ recordset: [{ ok: 1 }] }));
const connectMock = vi.fn(async () => {});
const closeMock = vi.fn(async () => {});
class FakeConnectionPool {
connect = connectMock;
request() {
return { input: vi.fn(), query: queryMock };
}
close = closeMock;
}
return { FakeConnectionPool, queryMock, connectMock, closeMock };
}
it("rejects a private/internal-IP sqlEndpoint before ever opening a TDS connection", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_ssrf", expires_in: 3600 }));
const { FakeConnectionPool, connectMock } = fakePoolFactory();
vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } }));
const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter");
const { SsrfBlockedHostError } = await import("@/src/lib/security/ssrf-guard");
// An internal-looking hostname whose "DNS record" (mocked here) resolves
// to an RFC1918 private address — the exact shape a caller-supplied
// sqlEndpoint could take if pointed inward.
const adapter = new FabricOneLakeAdapter(
{ ...CONFIG, sqlEndpoint: "internal-warehouse.corp.example.com" },
fetchMock as unknown as typeof fetch,
blockedDnsLookup("10.1.2.3"),
);
let caught: unknown;
try {
await adapter.query("SELECT 1");
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(SsrfBlockedHostError);
expect((caught as Error).message).toMatch(/blocked_address_range/);
// The guard must run before the outbound connection is opened at all —
// fetch (AAD token exchange) and the TDS pool's connect() should never
// have been reached.
expect(fetchMock).not.toHaveBeenCalled();
expect(connectMock).not.toHaveBeenCalled();
});
it("rejects a literal loopback-IP sqlEndpoint (e.g. an attempt to reach 127.0.0.1) the same way", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_ssrf", expires_in: 3600 }));
const { FakeConnectionPool, connectMock } = fakePoolFactory();
vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } }));
const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter");
const { SsrfBlockedHostError } = await import("@/src/lib/security/ssrf-guard");
const adapter = new FabricOneLakeAdapter(
{ ...CONFIG, sqlEndpoint: "http://127.0.0.1:1433" },
fetchMock as unknown as typeof fetch,
// Real DNS resolution of a literal IP just returns that IP — this
// fixture doesn't even need the injected mock to prove the point, but
// stays consistent with the rest of this file's determinism.
blockedDnsLookup("127.0.0.1"),
);
await expect(adapter.query("SELECT 1")).rejects.toBeInstanceOf(SsrfBlockedHostError);
expect(connectMock).not.toHaveBeenCalled();
});
it("does not false-block a normal external Fabric hostname — query still succeeds through the guard", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ access_token: "tok_ssrf_ok", expires_in: 3600 }));
const { FakeConnectionPool, queryMock, connectMock } = fakePoolFactory();
vi.doMock("mssql", () => ({ default: { ConnectionPool: FakeConnectionPool } }));
const { FabricOneLakeAdapter } = await import("@/src/adapters/fabric-onelake-adapter");
const adapter = new FabricOneLakeAdapter(CONFIG, fetchMock as unknown as typeof fetch, publicDnsLookup);
const result = await adapter.query("SELECT 1");
expect(result.rows).toEqual([{ ok: 1 }]);
expect(connectMock).toHaveBeenCalledTimes(1);
expect(queryMock).toHaveBeenCalledTimes(1);
});
});
+158
View File
@@ -0,0 +1,158 @@
import { describe, it, expect } from "vitest";
import {
assertConnectionHostIsSafe,
checkHostnameSafety,
extractConnectionHostname,
isBlockedV4,
isBlockedV6,
SsrfBlockedHostError,
type DnsLookupFn,
} from "@/src/lib/security/ssrf-guard";
function lookupReturning(address: string, family: 4 | 6 = 4): DnsLookupFn {
return () => Promise.resolve([{ address, family }]);
}
function lookupFailing(): DnsLookupFn {
return () => Promise.reject(new Error("ENOTFOUND"));
}
function lookupEmpty(): DnsLookupFn {
return () => Promise.resolve([]);
}
describe("extractConnectionHostname — parses the bare host[:port] shape sqlEndpoint takes", () => {
it("strips an http(s):// scheme", () => {
expect(extractConnectionHostname("https://ep.datawarehouse.fabric.microsoft.com")).toBe(
"ep.datawarehouse.fabric.microsoft.com",
);
expect(extractConnectionHostname("http://10.0.0.5")).toBe("10.0.0.5");
});
it("strips a trailing port", () => {
expect(extractConnectionHostname("ep.fabric.microsoft.com:1433")).toBe("ep.fabric.microsoft.com");
expect(extractConnectionHostname("http://127.0.0.1:1433")).toBe("127.0.0.1");
});
it("strips a trailing path/query/fragment defensively", () => {
expect(extractConnectionHostname("https://ep.fabric.microsoft.com/whatever?x=1#y")).toBe("ep.fabric.microsoft.com");
});
it("unwraps a bracketed IPv6 literal, with or without a port", () => {
expect(extractConnectionHostname("[::1]")).toBe("::1");
expect(extractConnectionHostname("[::1]:1433")).toBe("::1");
expect(extractConnectionHostname("[fe80::1]:1433")).toBe("fe80::1");
});
it("does not mistake a bare (unbracketed) IPv6 literal's colons for a port separator", () => {
expect(extractConnectionHostname("fe80::1")).toBe("fe80::1");
});
it("trims whitespace and a trailing slash", () => {
expect(extractConnectionHostname(" https://ep.fabric.microsoft.com/ ".trim())).toBe("ep.fabric.microsoft.com");
});
});
describe("isBlockedV4 — RFC1918 / loopback / link-local / unspecified ranges", () => {
it.each([
["10.0.0.1", true],
["10.255.255.255", true],
["172.16.0.1", true],
["172.31.255.255", true],
["172.15.255.255", false], // just outside 172.16.0.0/12
["172.32.0.0", false], // just outside 172.16.0.0/12
["192.168.0.1", true],
["127.0.0.1", true],
["169.254.169.254", true], // cloud-metadata address
["169.254.0.1", true],
["0.0.0.0", true],
["8.8.8.8", false],
["20.91.151.2", false], // a real public Azure IP (used elsewhere in these fixtures)
["1.1.1.1", false],
])("isBlockedV4(%s) === %s", (ip, expected) => {
expect(isBlockedV4(ip)).toBe(expected);
});
it("returns false for a non-IPv4 string instead of throwing", () => {
expect(isBlockedV4("not-an-ip")).toBe(false);
expect(isBlockedV4("::1")).toBe(false);
});
});
describe("isBlockedV6 — loopback / unique-local / link-local, plus IPv4-mapped bypass", () => {
it.each([
["::1", true],
["::", true],
["fc00::1", true],
["fd12:3456::1", true],
["fe80::1", true],
["2001:4860:4860::8888", false], // public (Google DNS v6)
])("isBlockedV6(%s) === %s", (ip, expected) => {
expect(isBlockedV6(ip)).toBe(expected);
});
it("unwraps an IPv4-mapped IPv6 address and re-checks it as v4 (filter-bypass form)", () => {
expect(isBlockedV6("::ffff:127.0.0.1")).toBe(true);
expect(isBlockedV6("::ffff:169.254.169.254")).toBe(true);
expect(isBlockedV6("::ffff:8.8.8.8")).toBe(false);
});
it("returns false for a non-IPv6 string instead of throwing", () => {
expect(isBlockedV6("10.0.0.1")).toBe(false);
expect(isBlockedV6("not-an-ip")).toBe(false);
});
});
describe("checkHostnameSafety — resolves via the injected lookup and fails closed", () => {
it("blocks a hostname whose resolved address is a private IP (the DNS-rebinding case a plain string allowlist would miss)", async () => {
const result = await checkHostnameSafety("looks-public.example.com", lookupReturning("10.1.2.3"));
expect(result).toEqual({ ok: false, reason: "blocked_address_range" });
});
it("blocks the cloud-metadata address specifically", async () => {
const result = await checkHostnameSafety("metadata.internal", lookupReturning("169.254.169.254"));
expect(result).toEqual({ ok: false, reason: "blocked_address_range" });
});
it("allows a hostname that resolves to a normal public IP", async () => {
const result = await checkHostnameSafety("ep.datawarehouse.fabric.microsoft.com", lookupReturning("20.91.151.2"));
expect(result).toEqual({ ok: true });
});
it("fails closed when DNS resolution errors", async () => {
const result = await checkHostnameSafety("does-not-resolve.invalid", lookupFailing());
expect(result).toEqual({ ok: false, reason: "dns_resolution_failed" });
});
it("fails closed when DNS resolution returns no addresses", async () => {
const result = await checkHostnameSafety("no-answers.invalid", lookupEmpty());
expect(result).toEqual({ ok: false, reason: "dns_resolution_failed" });
});
it("fails closed on an empty hostname", async () => {
const result = await checkHostnameSafety("", lookupReturning("20.91.151.2"));
expect(result).toEqual({ ok: false, reason: "empty_hostname" });
});
});
describe("assertConnectionHostIsSafe — the guard fabric-onelake-adapter.ts calls", () => {
it("throws SsrfBlockedHostError for a private-IP sqlEndpoint", async () => {
await expect(assertConnectionHostIsSafe("internal-db.corp.example.com", lookupReturning("192.168.1.50"))).rejects.toBeInstanceOf(
SsrfBlockedHostError,
);
});
it("throws for a literal loopback sqlEndpoint with no DNS lookup needed at all", async () => {
// Real dns.lookup() on a literal IP just returns that IP without a
// network round-trip; simulate that here via the injected lookup.
await expect(assertConnectionHostIsSafe("http://127.0.0.1:1433", lookupReturning("127.0.0.1"))).rejects.toBeInstanceOf(
SsrfBlockedHostError,
);
});
it("resolves without throwing for a normal external Fabric/OneLake hostname", async () => {
await expect(
assertConnectionHostIsSafe("https://my-tenant.datawarehouse.fabric.microsoft.com/", lookupReturning("20.91.151.2")),
).resolves.toBeUndefined();
});
});
+149
View File
@@ -0,0 +1,149 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { GraphMailboxAdapter } from "@/src/adapters/graph-mailbox-adapter";
function jsonResponse(body: unknown, opts: { status?: number; headers?: Record<string, string> } = {}) {
return {
ok: (opts.status ?? 200) < 400,
status: opts.status ?? 200,
headers: { get: (k: string) => (opts.headers ?? {})[k] ?? null },
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
describe("GraphMailboxAdapter", () => {
const config = {
tenantId: "tenant-1",
clientId: "client-1",
clientSecret: "secret-1",
mailboxAddress: "[email protected]",
folder: "inbox",
};
beforeEach(() => {
vi.restoreAllMocks();
});
it("isConfigured requires tenantId/clientId/clientSecret/mailboxAddress", () => {
expect(GraphMailboxAdapter.isConfigured(config)).toBe(true);
expect(GraphMailboxAdapter.isConfigured({ ...config, clientSecret: "" })).toBe(false);
expect(GraphMailboxAdapter.isConfigured({ ...config, mailboxAddress: "" })).toBe(false);
});
it("polls messages across pages, following @odata.nextLink up to maxPages", async () => {
const calls: string[] = [];
const fetchMock = vi.fn(async (url: string) => {
calls.push(url);
if (url.includes("login.microsoftonline.com")) {
return jsonResponse({ access_token: "tok123", expires_in: 3600 });
}
if (url.includes("/messages?")) {
return jsonResponse({
value: [
{
id: "msg-1",
internetMessageId: "<[email protected]>",
conversationId: "conv-1",
receivedDateTime: "2026-07-01T10:00:00Z",
from: { emailAddress: { name: "Vendor AB", address: "[email protected]" } },
toRecipients: [{ emailAddress: { address: "[email protected]" } }],
subject: "Document 1",
bodyPreview: "preview",
body: { content: "<p>Hello <b>World</b></p>" },
hasAttachments: true,
webLink: "https://outlook.office.com/mail/1",
},
],
"@odata.nextLink": "https://graph.microsoft.com/v1.0/next-page",
});
}
if (url.includes("next-page")) {
return jsonResponse({
value: [
{
id: "msg-2",
receivedDateTime: "2026-07-01T11:00:00Z",
from: { emailAddress: { name: "Vendor 2", address: "[email protected]" } },
toRecipients: [],
subject: "Document 2",
hasAttachments: false,
},
],
});
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const adapter = new GraphMailboxAdapter(config);
const messages = await adapter.pollMessages({ top: 50, maxPages: 2 });
expect(messages).toHaveLength(2);
expect(messages[0].id).toBe("msg-1");
expect(messages[0].senderEmail).toBe("[email protected]");
expect(messages[0].bodyText).toBe("Hello World");
expect(messages[1].id).toBe("msg-2");
expect(messages[1].hasAttachments).toBe(false);
expect(calls.some((u) => u.includes("mailFolders/inbox/messages"))).toBe(true);
});
it("lists only file attachments and flags PDFs by content-type or filename", async () => {
const pdfBase64 = Buffer.from("%PDF-1.4 fake pdf bytes").toString("base64");
const fetchMock = vi.fn(async (url: string) => {
if (url.includes("login.microsoftonline.com")) {
return jsonResponse({ access_token: "tok123", expires_in: 3600 });
}
if (url.includes("/attachments")) {
return jsonResponse({
value: [
{
"@odata.type": "#microsoft.graph.fileAttachment",
id: "att-1",
name: "invoice.pdf",
contentType: "application/pdf",
size: 123,
contentBytes: pdfBase64,
},
{
"@odata.type": "#microsoft.graph.fileAttachment",
id: "att-2",
name: "logo.png",
contentType: "image/png",
size: 50,
contentBytes: Buffer.from("not-a-pdf").toString("base64"),
},
{
// No mime type but a .pdf filename should still be detected.
"@odata.type": "#microsoft.graph.fileAttachment",
id: "att-3",
name: "scan.PDF",
contentType: "application/octet-stream",
size: 999,
contentBytes: pdfBase64,
},
{
// Non-file attachment (e.g. embedded email) must be skipped entirely.
"@odata.type": "#microsoft.graph.itemAttachment",
id: "att-4",
name: "embedded-email",
},
],
});
}
throw new Error(`unexpected fetch: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const adapter = new GraphMailboxAdapter(config);
const attachments = await adapter.listAttachments("msg-1");
expect(attachments).toHaveLength(3); // itemAttachment skipped
const pdf = attachments.find((a) => a.name === "invoice.pdf")!;
expect(pdf.isPdf).toBe(true);
expect(pdf.contentBytes.toString()).toContain("%PDF-1.4");
const png = attachments.find((a) => a.name === "logo.png")!;
expect(png.isPdf).toBe(false);
const scanByExt = attachments.find((a) => a.name === "scan.PDF")!;
expect(scanByExt.isPdf).toBe(true);
});
});
@@ -0,0 +1,120 @@
import { describe, it, expect, beforeAll } from "vitest";
import { DatasetService } from "@/src/services/dataset-service";
import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service";
import { IcebergWriteService } from "@/src/services/iceberg-write-service";
/**
* LIVE ST0RE integration -- the SEAM pattern this session's task spec asked
* for: "attempt the real call, degrade honestly with a clear status if ST0RE
* is not reachable, never fabricate success" (same convention this same
* session verified in api0's clients, and the same convention ST0RE's own
* `integration-realinfra.test.ts` uses for its DATABASE_URL/MINIO_* gate).
*
* This is NOT a mock-client test -- it constructs `IcebergWriteService` with
* a real `st0reBaseUrl` and drives the actual `HttpSt0reLakehouseClient`
* HTTP path against production ST0RE (api.st0re.siax.io, currently reachable
* from this environment -- DNS for that name resolves here even though
* Cloudflare's public A record is still pending per this session's known
* infra state; set ST0RE_URL to override).
*
* Real writes this test produces land in ST0RE's live Postgres under a
* dedicated pilot tenant (`t_0pt_realinfra_pilot` by default, overridable via
* ST0RE_TEST_TENANT_ID) -- that IS the point of task item 3 ("write ONE
* first test dataset to an Iceberg table through ST0RE's table registry").
*
* Honest degrade: a `beforeAll` reachability probe (5s timeout) decides
* whether to run for real or `ctx.skip()` with a logged reason. This test
* never asserts success without having actually made the HTTP calls, and
* never falls back to the mock client silently.
*/
const ST0RE_URL = process.env.ST0RE_URL ?? "https://api.st0re.siax.io";
const TEST_TENANT = process.env.ST0RE_TEST_TENANT_ID ?? "t_0pt_realinfra_pilot";
const TEST_PROJECT = "p_0pt_realinfra";
const TEST_ACTOR = "0pt-realinfra-test";
let reachable = false;
let unreachableReason = "";
beforeAll(async () => {
try {
const res = await fetch(`${ST0RE_URL}/v1/st0re/lakehouse/namespaces`, {
headers: { "X-Tenant-Id": TEST_TENANT, "X-Actor-Id": TEST_ACTOR },
signal: AbortSignal.timeout(5000),
});
reachable = res.ok;
if (!reachable) unreachableReason = `ST0RE responded HTTP ${res.status}`;
} catch (err) {
reachable = false;
unreachableReason = err instanceof Error ? err.message : String(err);
}
}, 10000);
describe("IcebergWriteService against a LIVE ST0RE deployment", () => {
it(
"mapDatasetToIcebergTable + requestIcebergWrite register a real namespace/table/snapshot in ST0RE",
async (ctx) => {
if (!reachable) {
console.warn(
`[realinfra] ST0RE (${ST0RE_URL}) not reachable this run (${unreachableReason}) -- skipping honestly, not fabricating success.`
);
ctx.skip();
return;
}
const datasetService = new DatasetService();
const mappingService = new DatasetIcebergMappingService({ datasetService });
const service = new IcebergWriteService({ datasetService, mappingService, st0reBaseUrl: ST0RE_URL });
const stamp = Date.now();
const datasetId = `ds_realinfra_pilot_${stamp}`;
await datasetService.registerDataset({
dataset_id: datasetId,
tenant_id: TEST_TENANT,
project_id: TEST_PROJECT,
name: "0pt real-ST0RE pilot dataset",
dataset_type: "enriched",
});
const mapped = await service.mapDatasetToIcebergTable({
tenant_id: TEST_TENANT,
project_id: TEST_PROJECT,
dataset_id: datasetId,
dataset_iceberg_mapping_id: `dim_realinfra_${stamp}`,
namespace: "0pt_pilot",
table_name: `dim_company_se_pilot_${stamp}`,
storage_uri: `s3://siax-tenants/prod/tenants/${TEST_TENANT}/projects/${TEST_PROJECT}/lakehouse/0pt_pilot/dim_company_se_pilot_${stamp}`,
catalog_ref: `0pt_pilot.dim_company_se_pilot_${stamp}`,
actor_id: TEST_ACTOR,
correlation_id: `corr_realinfra_${stamp}`,
});
// Real ST0RE issues Postgres UUIDs -- never the mock client's
// "mock_table_<timestamp>" shape. This is the assertion that proves
// this test actually hit the live HTTP path, not the mock fallback.
expect(mapped.iceberg_table_id).not.toContain("mock_table_");
expect(mapped.iceberg_table_id).toMatch(/^[0-9a-f-]{36}$/i);
expect(mapped.namespace_id).not.toContain("mock_ns_");
expect(mapped.namespace_id).toMatch(/^[0-9a-f-]{36}$/i);
expect(mapped.mapping.dataset_id).toBe(datasetId);
// eslint-disable-next-line no-console
console.log(`[realinfra] LIVE ST0RE table registered: tableId=${mapped.iceberg_table_id} namespaceId=${mapped.namespace_id}`);
const write = await service.requestIcebergWrite({
dataset_iceberg_mapping_id: mapped.mapping.dataset_iceberg_mapping_id,
actor_id: TEST_ACTOR,
correlation_id: `corr_realinfra_write_${stamp}`,
schema_version: "1",
manifest_uri: `s3://siax-tenants/prod/tenants/${TEST_TENANT}/projects/${TEST_PROJECT}/lakehouse/0pt_pilot/dim_company_se_pilot_${stamp}/metadata/manifest-1.avro`,
record_count: 1,
size_bytes: 128,
});
expect(write.snapshot_id).not.toContain("mock_snapshot_");
expect(write.snapshot_id).toMatch(/^[0-9a-f-]{36}$/i);
expect(write.iceberg_table_id).toBe(mapped.iceberg_table_id);
// eslint-disable-next-line no-console
console.log(`[realinfra] LIVE ST0RE snapshot registered: snapshotId=${write.snapshot_id}`);
},
20000
);
});
+173
View File
@@ -0,0 +1,173 @@
import { describe, it, expect } from "vitest";
import { DatasetService } from "@/src/services/dataset-service";
import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service";
import { IcebergWriteService } from "@/src/services/iceberg-write-service";
/**
* "Write first test dataset to Iceberg through ST0RE's table registry" proof
* (task item 2). This exercises the REAL request/response shapes and control
* flow of IcebergWriteService -> St0reLakehouseClient against that client's
* deterministic MOCK implementation, the same convention this repo already
* uses for every other cross-product boundary (see
* tests/p0/cross-product-boundary.test.ts, quality-check-service.ts's own
* CL0UD/N0D/ST0RE/AUD0 usage). No ST0RE_URL was available to this pass, so
* this is NOT verified against a live, running ST0RE lakehouse API --
* src/clients/st0re-lakehouse-client.ts's module doc comment states that
* caveat explicitly and it applies here too. What IS real: the table gets
* registered, a DatasetIcebergMapping row is created referencing ST0RE's
* (mock) tableId, a snapshot gets registered against that table, and all
* four AUD0 events fire in the right order with the right payload shape.
*/
describe("IcebergWriteService", () => {
it("mapDatasetToIcebergTable registers a table in ST0RE and records the mapping", async () => {
const datasetService = new DatasetService();
const mappingService = new DatasetIcebergMappingService({ datasetService });
const service = new IcebergWriteService({ datasetService, mappingService });
await datasetService.registerDataset({
dataset_id: "ds_first_iceberg_write",
tenant_id: "t1",
project_id: "p1",
name: "First Iceberg Pilot Dataset",
dataset_type: "enriched",
});
const result = await service.mapDatasetToIcebergTable({
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_first_iceberg_write",
dataset_iceberg_mapping_id: "dim_first_write",
namespace: "0pt_pilot",
table_name: "dim_company_se_pilot",
storage_uri: "s3://siax-p0/lakehouse/0pt_pilot/dim_company_se_pilot",
catalog_ref: "0pt_pilot.dim_company_se_pilot",
actor_id: "user_123",
correlation_id: "corr_first_write",
});
expect(result.iceberg_table_id).toContain("mock_table_");
expect(result.policy_decision_id).toBeDefined();
expect(result.mapping.dataset_id).toBe("ds_first_iceberg_write");
expect(result.mapping.iceberg_table_id).toBe(result.iceberg_table_id);
expect(result.mapping.mapping_status).toBe("active");
const lookedUp = await mappingService.getMappingForDataset("ds_first_iceberg_write");
expect(lookedUp?.dataset_iceberg_mapping_id).toBe("dim_first_write");
});
it("requestIcebergWrite registers a snapshot through ST0RE for an existing mapping", async () => {
const datasetService = new DatasetService();
const mappingService = new DatasetIcebergMappingService({ datasetService });
const service = new IcebergWriteService({ datasetService, mappingService });
await datasetService.registerDataset({
dataset_id: "ds_snapshot_write",
tenant_id: "t1",
project_id: "p1",
name: "Snapshot Write Dataset",
dataset_type: "enriched",
});
const mapped = await service.mapDatasetToIcebergTable({
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_snapshot_write",
dataset_iceberg_mapping_id: "dim_snapshot_write",
namespace: "0pt_pilot",
table_name: "dim_company_se_snapshot",
storage_uri: "s3://siax-p0/lakehouse/0pt_pilot/dim_company_se_snapshot",
catalog_ref: "0pt_pilot.dim_company_se_snapshot",
actor_id: "user_123",
correlation_id: "corr_snapshot_setup",
});
const result = await service.requestIcebergWrite({
dataset_iceberg_mapping_id: mapped.mapping.dataset_iceberg_mapping_id,
actor_id: "user_123",
correlation_id: "corr_snapshot_write",
schema_version: "1",
manifest_uri: "s3://siax-p0/lakehouse/0pt_pilot/dim_company_se_snapshot/metadata/manifest-1.avro",
record_count: 1000,
size_bytes: 204800,
});
expect(result.snapshot_id).toContain("mock_snapshot_");
expect(result.iceberg_table_id).toBe(mapped.iceberg_table_id);
expect(result.n0d_job_id).toBeUndefined(); // not a heavy write
});
it("requestIcebergWrite routes heavy writes through an N0D job request, not in-process execution", async () => {
const datasetService = new DatasetService();
const mappingService = new DatasetIcebergMappingService({ datasetService });
const service = new IcebergWriteService({ datasetService, mappingService });
await datasetService.registerDataset({
dataset_id: "ds_heavy_write",
tenant_id: "t1",
project_id: "p1",
name: "Heavy Backfill Dataset",
dataset_type: "raw",
});
const mapped = await service.mapDatasetToIcebergTable({
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_heavy_write",
dataset_iceberg_mapping_id: "dim_heavy_write",
namespace: "0pt_pilot",
table_name: "fact_financials_backfill",
storage_uri: "s3://siax-p0/lakehouse/0pt_pilot/fact_financials_backfill",
catalog_ref: "0pt_pilot.fact_financials_backfill",
actor_id: "user_123",
correlation_id: "corr_heavy_setup",
});
const result = await service.requestIcebergWrite({
dataset_iceberg_mapping_id: mapped.mapping.dataset_iceberg_mapping_id,
actor_id: "user_123",
correlation_id: "corr_heavy_write",
schema_version: "1",
manifest_uri: "s3://siax-p0/lakehouse/0pt_pilot/fact_financials_backfill/metadata/manifest-backfill.avro",
heavy: true,
});
expect(result.n0d_job_id).toBeDefined();
expect(result.n0d_job_id).toContain("mock_job_");
});
it("requestIcebergWrite rejects writes against a non-active mapping", async () => {
const datasetService = new DatasetService();
const mappingService = new DatasetIcebergMappingService({ datasetService });
const service = new IcebergWriteService({ datasetService, mappingService });
await datasetService.registerDataset({
dataset_id: "ds_deprecated_mapping",
tenant_id: "t1",
project_id: "p1",
name: "Deprecated Mapping Dataset",
dataset_type: "raw",
});
await mappingService.createMapping({
dataset_iceberg_mapping_id: "dim_deprecated",
tenant_id: "t1",
project_id: "p1",
dataset_id: "ds_deprecated_mapping",
iceberg_table_id: "st0re_table_deprecated",
mapping_status: "deprecated",
});
await expect(
service.requestIcebergWrite({
dataset_iceberg_mapping_id: "dim_deprecated",
actor_id: "user_123",
correlation_id: "corr_deprecated_write",
schema_version: "1",
manifest_uri: "s3://siax-p0/lakehouse/deprecated/manifest.avro",
})
).rejects.toThrow("is not active");
});
// The live-ST0RE case this `it.todo` used to name is now built:
// tests/p0/iceberg-write-service.realinfra.test.ts attempts a real HTTP
// call against api.st0re.siax.io (SEAM pattern: real call, honest skip if
// unreachable -- see that file's header comment and
// docs/ICEBERG_WRITE_BOUNDARY.md "Live verification" section).
});
@@ -0,0 +1,310 @@
/**
* REAL Postgres proof for P060 DoD #1 ("a restart preserves every source")
* and for the durability the rest of the plane depends on (P062 checkpoints,
* P063 schema versions, P064 quarantine, P067 lineage, P068 ledger).
*
* Same honest-degrade convention as tests/p0/source-registry-postgres.realinfra.test.ts:
* gated on an env var, SKIPS HONESTLY when unset, never fabricates success.
*
* docker run -d --name opt-ingestion-pgtest \
* -e POSTGRES_USER=opt -e POSTGRES_PASSWORD=opt_test_pw -e POSTGRES_DB=opt_test \
* -p 15434:5432 postgres:16-alpine
* INGESTION_TEST_DATABASE_URL=postgres://opt:opt_test_pw@localhost:15434/opt_test \
* pnpm vitest run tests/p0/ingestion-plane-postgres.realinfra.test.ts
*
* "RESTART" here is modelled the only way a test can model it without killing
* the runner: every assertion after a write is made through a FRESHLY
* CONSTRUCTED service/repository over a NEW connection, so nothing can be
* answered out of an in-process Map. The stronger proof — stopping and
* starting the Postgres CONTAINER itself and re-reading — was run manually
* during this pass and is recorded in STATUS.md; it is not automated here
* because a test that restarts its own database would need docker access
* from inside CI, which these runners do not grant.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import fs from "node:fs";
import path from "node:path";
import postgres from "postgres";
import { SourceRegistryService } from "@/src/services/source-registry-service";
import { SourceService } from "@/src/services/source-service";
import { PostgresSourceRepository } from "@/src/repositories/postgres-source-repository";
import { PostgresSourceRegistryRepository } from "@/src/repositories/postgres-source-registry-repository";
import { PostgresIngestionRepository } from "@/src/repositories/postgres-ingestion-repository";
import { SchemaRegistry } from "@/src/schema/schema-registry";
import { LineageStore } from "@/src/lineage/lineage-store";
import { IngestionRunner } from "@/src/ingestion/ingestion-runner";
import { JsonlFileConnector } from "@/src/connectors/jsonl-file-connector";
import { SiaxError } from "@/src/platform/errors";
import type { RecordSchemaFields } from "@/src/schema/record-schema";
import os from "node:os";
import { promises as fsp } from "node:fs";
const TEST_DATABASE_URL = process.env.INGESTION_TEST_DATABASE_URL;
const run = TEST_DATABASE_URL ? describe : describe.skip;
let adminSql: ReturnType<typeof postgres> | undefined;
let reachable = false;
const tmpDir = path.join(os.tmpdir(), `opt-realinfra-${process.pid}`);
const filePath = path.join(tmpDir, "companies.jsonl");
const SCHEMA: RecordSchemaFields = {
org_number: { type: "string", required: true },
name: { type: "string", required: true },
employees: { type: "number", required: false },
};
const ROWS = Array.from({ length: 6 }, (_, i) => ({
org_number: `55611${i}-111${i}`,
name: `Realinfra ${i} AB`,
employees: (i + 1) * 10,
}));
const TENANT = "t_realinfra";
const SOURCE = "src_realinfra_1";
beforeAll(async () => {
if (!TEST_DATABASE_URL) {
console.warn(
"[realinfra] INGESTION_TEST_DATABASE_URL not set this run -- skipping honestly, not fabricating success.",
);
return;
}
adminSql = postgres(TEST_DATABASE_URL, { prepare: false, ssl: false, max: 2 });
await Promise.race([
adminSql`SELECT 1`,
new Promise((_, reject) => setTimeout(() => reject(new Error("connect timeout")), 5000)),
]);
reachable = true;
// Only the two migrations this plane needs. sql/001_init.sql is skipped on
// purpose: it requires the `vector` extension (pgvector), which a plain
// postgres:16-alpine does not ship, and none of the tables under test
// depend on it. Same choice tests/p0/source-registry-postgres.realinfra.test.ts
// already makes.
for (const file of ["002_source_registry.sql", "007_ingestion_plane.sql"]) {
const p = path.join(process.cwd(), "sql", file);
if (!fs.existsSync(p)) continue;
await adminSql.unsafe(fs.readFileSync(p, "utf8"));
}
// Clean slate for this suite's ids only — never a blanket TRUNCATE.
await adminSql`DELETE FROM opt_lineage_edges WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_quality_quarantine WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_ingestion_ledger WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_ingestion_checkpoints WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_schemas WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_authorization WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_schedule WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_rights WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_provenance WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_freshness WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_source_health_checks WHERE tenant_id = ${TENANT}`;
await adminSql`DELETE FROM opt_sources WHERE tenant_id = ${TENANT}`;
await fsp.mkdir(tmpDir, { recursive: true });
await fsp.writeFile(filePath, ROWS.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8");
});
afterAll(async () => {
await adminSql?.end({ timeout: 5 });
await fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
});
/** A brand-new service over a brand-new connection — the "restarted process". */
function freshRegistry(): SourceRegistryService {
const sql = postgres(TEST_DATABASE_URL as string, { prepare: false, ssl: false, max: 2 });
return new SourceRegistryService({
repository: new PostgresSourceRegistryRepository(sql),
sourceService: new SourceService({ repository: new PostgresSourceRepository(sql) }),
});
}
function freshIngestion(): {
repo: PostgresIngestionRepository;
runner: IngestionRunner;
lineage: LineageStore;
} {
const sql = postgres(TEST_DATABASE_URL as string, { prepare: false, ssl: false, max: 2 });
const repo = new PostgresIngestionRepository(sql);
const lineage = new LineageStore(repo);
return { repo, runner: new IngestionRunner(repo, new SchemaRegistry(repo), lineage), lineage };
}
run("P060 real Postgres — a restart preserves every source and every registry fact", () => {
it("is reachable (otherwise the rest of this suite proves nothing)", () => {
expect(reachable).toBe(true);
});
it("registers pending, refuses activation unclassified, then activates — all surviving a fresh process", async () => {
const writer = freshRegistry();
await writer.registerSource({
source_id: SOURCE,
tenant_id: TENANT,
project_id: "p_realinfra",
source_type: "file",
name: "Realinfra file drop",
owner_id: "usr_simon",
schedule: { mode: "batch", interval_seconds: 900, enabled: true },
});
// A DIFFERENT service instance over a DIFFERENT connection.
const reader = freshRegistry();
expect((await reader.sources.getSource(SOURCE)).status).toBe("pending");
await expect(reader.activateSource(SOURCE, TENANT)).rejects.toBeInstanceOf(SiaxError);
const classifier = freshRegistry();
await classifier.setRights({
source_id: SOURCE,
tenant_id: TENANT,
license_id: "proprietary:realinfra",
allowed_purposes: ["catalog"],
pii_allowed: false,
redistribution: "internal",
verified_at: "2026-09-04",
verified_by: "usr_simon",
});
await classifier.setProvenance({
source_id: SOURCE,
tenant_id: TENANT,
method: "bulk_download",
updated_at: new Date().toISOString(),
});
await classifier.setAuthorization({
source_id: SOURCE,
tenant_id: TENANT,
basis: "contract",
granted_by: "usr_simon",
granted_at: new Date().toISOString(),
});
const activator = freshRegistry();
expect((await activator.classifySource(SOURCE, TENANT)).classified).toBe(true);
expect((await activator.activateSource(SOURCE, TENANT, "usr_simon")).status).toBe("active");
// Read back through yet another fresh process AND directly in SQL, so the
// assertion cannot be satisfied by any in-process bookkeeping.
const verifier = freshRegistry();
const descriptor = await verifier.describeSource(SOURCE, TENANT);
expect(descriptor.source.status).toBe("active");
expect(descriptor.source.owner_id).toBe("usr_simon");
expect(descriptor.authorization?.basis).toBe("contract");
expect(descriptor.schedule?.interval_seconds).toBe(900);
expect(descriptor.classification?.classified).toBe(true);
const rows = await (adminSql as ReturnType<typeof postgres>)<
{ status: string; owner_id: string | null }[]
>`SELECT status, owner_id FROM opt_sources WHERE source_id = ${SOURCE}`;
expect(rows[0]).toEqual({ status: "active", owner_id: "usr_simon" });
});
it("a raw INSERT that omits status lands PENDING — the gate is in the schema too", async () => {
const sql = adminSql as ReturnType<typeof postgres>;
await sql`
INSERT INTO opt_sources (source_id, tenant_id, project_id, source_type, name)
VALUES ('src_realinfra_raw', ${TENANT}, 'p_realinfra', 'api', 'Raw insert')
ON CONFLICT (source_id) DO NOTHING`;
const rows = await sql<{ status: string }[]>`
SELECT status FROM opt_sources WHERE source_id = 'src_realinfra_raw'`;
expect(rows[0].status).toBe("pending");
});
});
run("P062/P063/P064/P067/P068 real Postgres — the durable ingestion plane", () => {
it("runs, crashes, and resumes across fresh processes with no gap and no duplicate", async () => {
const first = freshIngestion();
const delivered: string[] = [];
let pages = 0;
const input = {
source_id: SOURCE,
tenant_id: TENANT,
project_id: "p_realinfra",
mode: "batch" as const,
connector: new JsonlFileConnector(),
config: { file_path: filePath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
page_size: 2,
output_ref: "0pt:dataset:ds_realinfra",
};
await expect(
first.runner.run({
...input,
sink: async (batch) => {
pages++;
if (pages === 2) throw new Error("simulated process death");
for (const e of batch) delivered.push(e.record_key);
},
}),
).rejects.toThrow(/simulated process death/);
expect(delivered).toHaveLength(2);
// Fresh everything — only Postgres carries the position forward.
const second = freshIngestion();
const report = await second.runner.run({
...input,
connector: new JsonlFileConnector(),
sink: async (batch) => {
for (const e of batch) delivered.push(e.record_key);
},
});
expect(report.status).toBe("succeeded");
expect(delivered).toHaveLength(ROWS.length);
expect(new Set(delivered).size).toBe(ROWS.length);
const cp = await second.repo.getCheckpoint(SOURCE, "companies");
expect(cp?.records_committed).toBe(ROWS.length);
});
it("the schema version, ledger, and lineage are all readable from a fresh process", async () => {
const fresh = freshIngestion();
expect((await new SchemaRegistry(fresh.repo).getLatest(SOURCE))?.schema_version).toBe(1);
expect(await fresh.repo.countLedger(SOURCE)).toBe(ROWS.length);
const upstream = await fresh.lineage.upstreamOf(TENANT, "0pt:dataset:ds_realinfra");
expect(upstream.length).toBeGreaterThanOrEqual(1);
expect(upstream[0].input_ref).toBe(`0pt:source:${SOURCE}`);
});
it("a repeated backfill is idempotent against the durable ledger", async () => {
const fresh = freshIngestion();
const emitted: string[] = [];
const report = await fresh.runner.backfill({
source_id: SOURCE,
tenant_id: TENANT,
project_id: "p_realinfra",
mode: "batch",
connector: new JsonlFileConnector(),
config: { file_path: filePath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
sink: async (batch) => {
for (const e of batch) emitted.push(e.record_key);
},
page_size: 100,
range: { partition_key: "companies", from: "0", to: String(ROWS.length) },
});
expect(report.envelopes_emitted).toBe(0);
expect(report.duplicates_skipped).toBe(ROWS.length);
expect(emitted).toHaveLength(0);
});
it("quarantine survives to a fresh process with the full envelope", async () => {
const fresh = freshIngestion();
await fresh.runner.backfill({
source_id: SOURCE,
tenant_id: TENANT,
project_id: "p_realinfra",
mode: "batch",
connector: new JsonlFileConnector(),
config: { file_path: filePath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
sink: async () => undefined,
page_size: 100,
quality_policy: {
source_id: SOURCE,
tenant_id: TENANT,
expectations: [
{ expectation_type: "expect_column_values_to_be_between", kwargs: { column: "employees", min_value: 0, max_value: 20 } },
],
on_violation: "quarantine",
},
range: { partition_key: "companies", from: "0", to: String(ROWS.length) },
});
const reader = freshIngestion();
const quarantined = await reader.repo.listQuarantine(SOURCE);
expect(quarantined.length).toBe(ROWS.length - 2);
expect(quarantined[0].envelope.record_key).toBeTruthy();
expect(quarantined[0].violations[0].expectation_type).toBe("expect_column_values_to_be_between");
});
});
+412
View File
@@ -0,0 +1,412 @@
/**
* The ingestion plane end to end:
*
* P062 — every connector's output becomes the same envelope, and a run that
* DIES mid-page resumes from the durable checkpoint with no gap and
* no double-delivery.
* P063 — a breaking schema change stops the run BEFORE the sink is called.
* P064 — quality failures block or quarantine according to the DECLARED
* policy, and a blocked page does not advance the checkpoint.
* P067 — a run's source -> output lineage is queryable afterwards.
* P068 — a repeated backfill is idempotent.
*
* The connectors here are the real ones (JsonlFileConnector against a real
* file on disk); the "crash" is a sink that throws, which is the closest
* faithful analogue of a process dying between the consumer write and the
* checkpoint commit.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { IngestionRunner, type IngestionRunInput } from "@/src/ingestion/ingestion-runner";
import { InMemoryIngestionRepository } from "@/src/repositories/in-memory-ingestion-repository";
import { SchemaRegistry } from "@/src/schema/schema-registry";
import { LineageStore } from "@/src/lineage/lineage-store";
import { JsonlFileConnector } from "@/src/connectors/jsonl-file-connector";
import { hashPayload } from "@/src/ingestion/envelope";
import { SiaxError } from "@/src/platform/errors";
import type { IngestionEnvelope } from "@/src/types/ingestion";
import type { RecordSchemaFields } from "@/src/schema/record-schema";
const SCHEMA: RecordSchemaFields = {
org_number: { type: "string", required: true },
name: { type: "string", required: true },
employees: { type: "number", required: false },
};
const tmpDir = path.join(os.tmpdir(), `opt-runner-${process.pid}`);
const filePath = path.join(tmpDir, "companies.jsonl");
const ROWS = Array.from({ length: 10 }, (_, i) => ({
org_number: `55600${i}-000${i}`,
name: `Bolag ${i} AB`,
employees: (i + 1) * 10,
}));
beforeAll(async () => {
await fs.mkdir(tmpDir, { recursive: true });
await fs.writeFile(filePath, ROWS.map((r) => JSON.stringify(r)).join("\n") + "\n", "utf8");
});
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
});
let repo: InMemoryIngestionRepository;
let runner: IngestionRunner;
let lineage: LineageStore;
beforeEach(() => {
repo = new InMemoryIngestionRepository();
lineage = new LineageStore(repo);
runner = new IngestionRunner(repo, new SchemaRegistry(repo), lineage);
});
function baseInput(sink: IngestionRunInput["sink"], overrides: Partial<IngestionRunInput> = {}): IngestionRunInput {
return {
source_id: "src_ing",
tenant_id: "t_test",
project_id: "p_test",
mode: "batch",
connector: new JsonlFileConnector(),
config: { file_path: filePath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
sink,
page_size: 3,
output_ref: "0pt:dataset:ds_companies",
...overrides,
};
}
describe("P062 common envelope", () => {
it("normalizes every record into one envelope shape with provenance and a monotonic sequence", async () => {
const seen: IngestionEnvelope[] = [];
const report = await runner.run(baseInput(async (batch) => void seen.push(...batch)));
expect(report.status).toBe("succeeded");
expect(seen).toHaveLength(ROWS.length);
expect(seen.map((e) => e.sequence)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
for (const envelope of seen) {
expect(envelope.source_id).toBe("src_ing");
expect(envelope.tenant_id).toBe("t_test");
expect(envelope.mode).toBe("batch");
expect(envelope.operation).toBe("upsert");
expect(envelope.partition_key).toBe("companies");
expect(envelope.schema_version).toBe(1);
expect(envelope.provenance.connector_id).toBe("jsonl_file");
expect(envelope.provenance.connector_version).toBe("jsonl-file-connector@1");
expect(envelope.provenance.run_id).toBe(report.run_id);
expect(envelope.ingested_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);
}
});
it("the durable checkpoint advances to the end of the partition", async () => {
await runner.run(baseInput(async () => undefined));
const checkpoint = await repo.getCheckpoint("src_ing", "companies");
expect(checkpoint?.cursor).toBe(String(ROWS.length));
expect(checkpoint?.sequence).toBe(ROWS.length);
expect(checkpoint?.records_committed).toBe(ROWS.length);
});
it("a run that dies inside the sink resumes with NO gap and NO double delivery", async () => {
const delivered: string[] = [];
let pages = 0;
// First run: the sink dies on the third page (records 7-9), AFTER two
// pages have been committed. This is the crash window the ordering exists
// to protect: the checkpoint for page 3 was never committed.
const crashing = baseInput(async (batch) => {
pages++;
if (pages === 3) throw new Error("process died mid-write");
for (const e of batch) delivered.push(e.record_key);
});
await expect(runner.run(crashing)).rejects.toThrow(/process died mid-write/);
expect(delivered).toHaveLength(6);
const afterCrash = await repo.getCheckpoint("src_ing", "companies");
expect(afterCrash?.cursor).toBe("6");
// Second run: a FRESH runner and a FRESH connector, exactly as a restarted
// process would be — only the durable checkpoint carries over.
const resumed = new IngestionRunner(repo, new SchemaRegistry(repo), lineage);
const report = await resumed.run(
baseInput(async (batch) => {
for (const e of batch) delivered.push(e.record_key);
}),
);
expect(report.status).toBe("succeeded");
// Every record exactly once across both runs: no gap, no duplicate.
expect(delivered).toHaveLength(ROWS.length);
expect(new Set(delivered).size).toBe(ROWS.length);
expect([...delivered].sort()).toEqual(ROWS.map((r) => r.org_number).sort());
});
it("refuses a mode the connector does not serve", async () => {
// JsonlFileConnector declares batch + cdc; it never claims "stream".
await expect(runner.run(baseInput(async () => undefined, { mode: "stream" }))).rejects.toThrow(
/does not serve mode "stream"/,
);
});
});
describe("P063 breaking schema is caught before the consumer sees anything", () => {
it("fails the run BEFORE the sink is called when the shape breaks the declared policy", async () => {
// v1 registered by a clean run.
await runner.run(baseInput(async () => undefined));
expect((await new SchemaRegistry(repo).getLatest("src_ing"))?.schema_version).toBe(1);
// The source now claims a new REQUIRED field — backward-breaking.
let sinkCalls = 0;
const breaking = baseInput(async () => void sinkCalls++, {
source_id: "src_ing",
config: {
file_path: filePath,
partition_key: "companies",
schema: { ...SCHEMA, sni_code: { type: "string", required: true } },
record_key_field: "org_number",
},
});
const err = await runner.run(breaking).catch((e: unknown) => e);
expect(err).toBeInstanceOf(SiaxError);
expect((err as SiaxError).code).toBe("CONFLICT");
expect((err as SiaxError).message).toContain("refusing to ingest");
// The whole point: no consumer write happened.
expect(sinkCalls).toBe(0);
});
it("catches a record that stopped conforming mid-stream, before emitting the page", async () => {
// A file whose DECLARED schema is unchanged but whose DATA drifted:
// `employees` arrives as a string. A distinct source_id so this run starts
// from a clean checkpoint rather than resuming past the file.
const driftPath = path.join(tmpDir, "drift.jsonl");
await fs.writeFile(
driftPath,
JSON.stringify({ org_number: "556999-9999", name: "Drift AB", employees: "many" }) + "\n",
"utf8",
);
let sinkCalls = 0;
const drifting = baseInput(async () => void sinkCalls++, {
source_id: "src_drift",
config: { file_path: driftPath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
});
await expect(runner.run(drifting)).rejects.toThrow(/does not conform to registered schema v1/);
expect(sinkCalls).toBe(0);
});
});
describe("P064 quality enforcement follows the DECLARED policy", () => {
const blockingExpectation = {
expectation_type: "expect_column_values_to_be_between",
kwargs: { column: "employees", min_value: 0, max_value: 50 },
};
it("'block' stops the run and does NOT advance the checkpoint past the bad page", async () => {
const seen: IngestionEnvelope[] = [];
const report = await runner.run(
baseInput(async (b) => void seen.push(...b), {
quality_policy: {
source_id: "src_ing",
tenant_id: "t_test",
expectations: [blockingExpectation],
on_violation: "block",
},
}),
);
expect(report.quality_policy).toBe("block");
const partition = report.partitions[0];
expect(partition.stopped_because).toBe("blocked_by_quality");
// Records 0-4 have employees <= 50; the block fires on the page containing
// employees 60, i.e. page 3 (records 6,7,8 -> 70,80,90 ... employees 60 is
// record index 5 on page 2). Whatever the exact page, nothing from the
// blocked page was emitted and the checkpoint stayed behind it.
expect(partition.envelopes_emitted).toBeLessThan(ROWS.length);
const checkpoint = await repo.getCheckpoint("src_ing", "companies");
expect(Number(checkpoint?.cursor ?? "0")).toBeLessThan(ROWS.length);
expect(seen.every((e) => Number(e.payload?.employees) <= 50)).toBe(true);
});
it("'quarantine' persists the failing records, lets the clean ones through, and advances", async () => {
const seen: IngestionEnvelope[] = [];
const report = await runner.run(
baseInput(async (b) => void seen.push(...b), {
quality_policy: {
source_id: "src_ing",
tenant_id: "t_test",
expectations: [blockingExpectation],
on_violation: "quarantine",
},
}),
);
expect(report.quality_policy).toBe("quarantine");
const partition = report.partitions[0];
expect(partition.stopped_because).toBeUndefined();
expect(partition.quarantined).toBe(5); // employees 60..100
expect(partition.envelopes_emitted).toBe(5); // employees 10..50
expect(seen.every((e) => Number(e.payload?.employees) <= 50)).toBe(true);
const quarantined = await repo.listQuarantine("src_ing");
expect(quarantined).toHaveLength(5);
expect(quarantined[0].violations[0].expectation_type).toBe("expect_column_values_to_be_between");
// The full envelope is preserved — a quarantined record is recoverable,
// not just counted.
expect(quarantined[0].envelope.payload).toBeTruthy();
const checkpoint = await repo.getCheckpoint("src_ing", "companies");
expect(checkpoint?.cursor).toBe(String(ROWS.length));
});
it("'warn' lets everything through but still reports the violations", async () => {
const seen: IngestionEnvelope[] = [];
const report = await runner.run(
baseInput(async (b) => void seen.push(...b), {
quality_policy: {
source_id: "src_ing",
tenant_id: "t_test",
expectations: [blockingExpectation],
on_violation: "warn",
},
}),
);
expect(seen).toHaveLength(ROWS.length);
expect(report.partitions[0].quality_violations).toBe(5);
expect(report.partitions[0].quarantined).toBe(0);
});
it("no declared policy is reported as 'none_declared', never as a pass", async () => {
const report = await runner.run(baseInput(async () => undefined));
expect(report.quality_policy).toBe("none_declared");
});
it("an expectation the local engine cannot execute is a violation, not a silent pass", async () => {
const report = await runner.run(
baseInput(async () => undefined, {
quality_policy: {
source_id: "src_ing",
tenant_id: "t_test",
expectations: [{ expectation_type: "expect_column_kl_divergence_to_be_less_than", kwargs: { column: "name" } }],
on_violation: "quarantine",
},
}),
);
expect(report.partitions[0].quarantined).toBe(ROWS.length);
const quarantined = await repo.listQuarantine("src_ing");
expect(quarantined[0].violations[0].detail).toContain("not executable by the local engine");
});
});
describe("P067 lineage is queryable after the run", () => {
it("answers 'which source fed this output' and 'what did this source produce'", async () => {
const report = await runner.run(baseInput(async () => undefined, { correlation_id: "corr-lineage-1" }));
expect(report.lineage_edges).toBe(1);
const upstream = await lineage.upstreamOf("t_test", "0pt:dataset:ds_companies");
expect(upstream).toHaveLength(1);
expect(upstream[0].input_name).toBe("source/src_ing");
expect(upstream[0].input_ref).toBe("0pt:source:src_ing");
expect(upstream[0].capability_id).toBe("0pt.ingestion.run.v1");
expect(upstream[0].run_id).toBe(report.run_id);
expect(upstream[0].correlation_id).toBe("corr-lineage-1");
const downstream = await lineage.downstreamOf("t_test", "source/src_ing");
expect(downstream.map((e) => e.output_name)).toEqual(["0pt:dataset:ds_companies"]);
// Tenant-scoped: another tenant sees nothing.
expect(await lineage.upstreamOf("t_other", "0pt:dataset:ds_companies")).toEqual([]);
});
it("re-emitting the same run id does not duplicate edges (deterministic edge ids)", async () => {
await runner.run(baseInput(async () => undefined, { run_id: "run_fixed" }));
// A second identical run of the same id — e.g. an idempotent retry.
const repo2Runner = new IngestionRunner(repo, new SchemaRegistry(repo), lineage);
await repo2Runner.run(baseInput(async () => undefined, { run_id: "run_fixed" }));
const edges = await lineage.upstreamOf("t_test", "0pt:dataset:ds_companies");
expect(edges).toHaveLength(1);
});
});
describe("P068 backfill is bounded and idempotent", () => {
it("a repeated identical backfill emits nothing the second time", async () => {
const first: IngestionEnvelope[] = [];
const firstReport = await runner.backfill({
...baseInput(async (b) => void first.push(...b)),
range: { partition_key: "companies", from: "0", to: "5" },
page_size: 100,
});
expect(firstReport.envelopes_emitted).toBe(5);
expect(firstReport.duplicates_skipped).toBe(0);
expect(first).toHaveLength(5);
const second: IngestionEnvelope[] = [];
const secondReport = await runner.backfill({
...baseInput(async (b) => void second.push(...b)),
range: { partition_key: "companies", from: "0", to: "5" },
page_size: 100,
});
expect(secondReport.envelopes_emitted).toBe(0);
expect(secondReport.duplicates_skipped).toBe(5);
expect(second).toHaveLength(0);
});
it("a backfill does NOT move the live checkpoint", async () => {
await runner.run(baseInput(async () => undefined));
const before = await repo.getCheckpoint("src_ing", "companies");
await runner.backfill({
...baseInput(async () => undefined),
range: { partition_key: "companies", from: "0", to: "3" },
});
const after = await repo.getCheckpoint("src_ing", "companies");
expect(after).toEqual(before);
});
it("a backfill overlapping a completed run re-delivers nothing (the ledger already has it)", async () => {
await runner.run(baseInput(async () => undefined));
const emitted: IngestionEnvelope[] = [];
const report = await runner.backfill({
...baseInput(async (b) => void emitted.push(...b)),
range: { partition_key: "companies", from: "0", to: "10" },
page_size: 100,
});
expect(report.duplicates_skipped).toBe(10);
expect(emitted).toHaveLength(0);
});
it("a record whose CONTENT changed is re-emitted — idempotency is not amnesia", async () => {
await runner.run(baseInput(async () => undefined));
const changedPath = path.join(tmpDir, "changed.jsonl");
await fs.writeFile(
changedPath,
JSON.stringify({ ...ROWS[0], name: "Bolag 0 AB (namnändrad)" }) + "\n",
"utf8",
);
const emitted: IngestionEnvelope[] = [];
const report = await runner.backfill({
...baseInput(async (b) => void emitted.push(...b), {
config: { file_path: changedPath, partition_key: "companies", schema: SCHEMA, record_key_field: "org_number" },
}),
range: { partition_key: "companies", from: "0", to: "1" },
page_size: 100,
});
expect(report.changed).toBe(1);
expect(report.envelopes_emitted).toBe(1);
expect(emitted[0].payload?.name).toBe("Bolag 0 AB (namnändrad)");
});
it("an unbounded backfill is refused by the connector contract", async () => {
await expect(
runner.backfill({
...baseInput(async () => undefined),
range: { partition_key: "companies", from: "0", to: "" },
}),
).rejects.toThrow(/unbounded backfill|requires both/);
});
});
describe("envelope hashing", () => {
it("is stable across key order and distinguishes a real content change", () => {
expect(hashPayload({ a: 1, b: 2 })).toBe(hashPayload({ b: 2, a: 1 }));
expect(hashPayload({ a: 1, b: 2 })).not.toBe(hashPayload({ a: 1, b: 3 }));
// null and absent are different data, and must hash differently.
expect(hashPayload({ a: 1, b: null })).not.toBe(hashPayload({ a: 1 }));
expect(hashPayload(null)).toBe("sha256:deleted");
});
});
+300
View File
@@ -0,0 +1,300 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { OdooBillsAdapter, matchPartnerViaFabric, type OdooBillPayload } from "@/src/adapters/odoo-bills-adapter";
import { FabricOneLakeAdapter } from "@/src/adapters/fabric-onelake-adapter";
import type { WritebackAdapterContext } from "@/src/adapters/writeback-adapter";
function jsonResponse(body: unknown, opts: { status?: number } = {}) {
return {
ok: (opts.status ?? 200) < 400,
status: opts.status ?? 200,
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
const CTX: WritebackAdapterContext = {
tenant_id: "t_protosell",
project_id: "proj_ap",
actor_id: "actor1",
correlation_id: "corr-1",
};
function basePayload(overrides: Partial<OdooBillPayload> = {}): OdooBillPayload {
return {
vendor_name: "Acme AB",
vendor_org_nr: "556123-4567",
invoice_number: "INV-2026-001",
amount_gross: 1234.5,
amount_excl_vat: 987.6,
vat: 246.9,
currency: "SEK",
invoice_date: "2026-07-01",
...overrides,
};
}
describe("OdooBillsAdapter — isConfigured", () => {
it("is not configured without a baseUrl", () => {
const adapter = new OdooBillsAdapter({ baseUrl: "", apiKey: "key" });
expect(adapter.isConfigured()).toBe(false);
});
it("is not configured with a baseUrl but no apiKey and no allowUnauthenticated flag", () => {
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com" });
expect(adapter.isConfigured()).toBe(false);
});
it("is configured with baseUrl + apiKey", () => {
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key" });
expect(adapter.isConfigured()).toBe(true);
});
it("is configured with baseUrl + explicit allowUnauthenticated, without an apiKey", () => {
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", allowUnauthenticated: true });
expect(adapter.isConfigured()).toBe(true);
});
it("write() returns ok:false when not configured, without attempting a network call", async () => {
const fetchMock = vi.fn();
const adapter = new OdooBillsAdapter({ baseUrl: "", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write({ recordType: "vendor_bill", payload: basePayload() as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
expect(result.ok).toBe(false);
expect(result.error).toBe("odoo_not_configured");
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("OdooBillsAdapter — guards ported verbatim from invoice-bridge.ts", () => {
afterEach(() => vi.restoreAllMocks());
it("refuses to post a payment reminder (is_reminder: true) — mirrors 'Påminnelse postas inte till Odoo'", async () => {
const fetchMock = vi.fn();
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write(
{ recordType: "vendor_bill", payload: basePayload({ is_reminder: true }) as unknown as Record<string, unknown>, idempotencyKey: "k1" },
CTX,
);
expect(result).toEqual({ ok: false, error: "is_reminder" });
expect(fetchMock).not.toHaveBeenCalled();
});
it("refuses to post a detected duplicate (duplicate_flag: true) — mirrors 'Dubblett postas inte till Odoo'", async () => {
const fetchMock = vi.fn();
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write(
{ recordType: "vendor_bill", payload: basePayload({ duplicate_flag: true }) as unknown as Record<string, unknown>, idempotencyKey: "k1" },
CTX,
);
expect(result).toEqual({ ok: false, error: "duplicate" });
expect(fetchMock).not.toHaveBeenCalled();
});
it("treats a payload with existing_external_id as already posted — idempotent no-op, no network call, mirrors 'Redan bokförd i Odoo... hoppar över'", async () => {
const fetchMock = vi.fn();
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write(
{ recordType: "vendor_bill", payload: basePayload({ existing_external_id: "999" }) as unknown as Record<string, unknown>, idempotencyKey: "k1" },
CTX,
);
expect(result).toEqual({ ok: true, externalId: "999" });
expect(fetchMock).not.toHaveBeenCalled();
});
it("rejects a payload missing required fields without attempting a network call", async () => {
const fetchMock = vi.fn();
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write(
{ recordType: "vendor_bill", payload: { vendor_name: "Acme AB" }, idempotencyKey: "k1" },
CTX,
);
expect(result.ok).toBe(false);
expect(result.error).toBe("invalid_payload_missing_required_fields");
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("OdooBillsAdapter — real POST shape (ported from invoice-bridge.ts's pushInvoiceToOdoo)", () => {
afterEach(() => vi.restoreAllMocks());
it("POSTs account.move with itemized lines when payload.lines is present", async () => {
let capturedUrl = "";
let capturedInit: RequestInit | undefined;
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
capturedUrl = url;
capturedInit = init;
return jsonResponse({ ok: true, odoo_id: 4242 });
});
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "sekret", fetchImpl: fetchMock as unknown as typeof fetch });
const payload = basePayload({
partner_id: 77,
lines: [{ description: "Konsulttjänst", quantity: 2, unit_price: 500 }],
});
const result = await adapter.write({ recordType: "vendor_bill", payload: payload as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
expect(result).toEqual({ ok: true, externalId: "4242" });
expect(capturedUrl).toBe("https://odoo.example.com/api/odoo/invoices/write");
expect((capturedInit?.headers as Record<string, string>).Authorization).toBe("Bearer sekret");
const body = JSON.parse(capturedInit!.body as string);
expect(body.model).toBe("account.move");
expect(body.invoice.partner_id).toBe(77);
expect(body.invoice.ref).toBe("INV-2026-001");
expect(body.invoice.invoice_line_ids).toEqual([{ name: "Konsulttjänst", quantity: 2, price_unit: 500 }]);
});
it("synthesizes a single summary line from description/vendor_name when payload.lines is absent — ported verbatim from processInboxToOdoo's line-synthesis fallback", async () => {
let capturedInit: RequestInit | undefined;
const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
capturedInit = init;
return jsonResponse({ ok: true, odoo_id: 100 });
});
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const payload = basePayload({ description: "Städtjänster juni", amount_excl_vat: 800 });
await adapter.write({ recordType: "vendor_bill", payload: payload as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
const body = JSON.parse(capturedInit!.body as string);
expect(body.invoice.invoice_line_ids).toEqual([{ name: "Städtjänster juni", quantity: 1, price_unit: 800 }]);
});
it("falls back to vendor_name, then a synthesized 'Faktura <number>' string, when description is absent", async () => {
let capturedInit: RequestInit | undefined;
const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
capturedInit = init;
return jsonResponse({ ok: true, odoo_id: 101 });
});
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const payload = basePayload({ vendor_name: "", invoice_number: "INV-777", amount_excl_vat: 50 });
await adapter.write({ recordType: "vendor_bill", payload: payload as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
const body = JSON.parse(capturedInit!.body as string);
expect(body.invoice.invoice_line_ids[0].name).toBe("Faktura INV-777");
});
it("returns ok:false with an odoo_http_<status> error on a non-2xx response", async () => {
const fetchMock = vi.fn(async () => jsonResponse({}, { status: 500 }));
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write({ recordType: "vendor_bill", payload: basePayload() as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
expect(result).toEqual({ ok: false, error: "odoo_http_500" });
});
it("returns ok:false when Odoo responds 200 but ok:false/no odoo_id", async () => {
const fetchMock = vi.fn(async () => jsonResponse({ ok: false, error: "odoo_validation_error" }));
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write({ recordType: "vendor_bill", payload: basePayload() as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
expect(result).toEqual({ ok: false, error: "odoo_validation_error" });
});
it("returns ok:false on a network error, without throwing", async () => {
const fetchMock = vi.fn(async () => {
throw new Error("ECONNREFUSED");
});
const adapter = new OdooBillsAdapter({ baseUrl: "https://odoo.example.com", apiKey: "key", fetchImpl: fetchMock as unknown as typeof fetch });
const result = await adapter.write({ recordType: "vendor_bill", payload: basePayload() as unknown as Record<string, unknown>, idempotencyKey: "k1" }, CTX);
expect(result.ok).toBe(false);
expect(result.error).toContain("odoo_network_error");
});
});
describe("matchPartnerViaFabric — ported from invoice-bridge.ts's matchInvoiceToOdooPartner", () => {
it("matches by digits-only comparison so '556123-4567' resolves the same as a plain digit string", async () => {
const queryMock = vi.fn(async () => ({
rows: [{ id: 42, name: "Acme AB", vat: "SE5561234567 01" }],
rowCount: 1,
durationMs: 1,
}));
const fabric = { query: queryMock } as unknown as FabricOneLakeAdapter;
const result = await matchPartnerViaFabric(fabric, "556123-4567");
expect(result).toEqual({ partner_id: 42, partner_name: "Acme AB" });
expect(queryMock).toHaveBeenCalledWith(expect.stringContaining("odoo_export__res_partner"), { digits: "5561234567" });
});
it("returns {} (no match) when the org-nr has no digits at all", async () => {
const queryMock = vi.fn();
const fabric = { query: queryMock } as unknown as FabricOneLakeAdapter;
const result = await matchPartnerViaFabric(fabric, "N/A");
expect(result).toEqual({});
expect(queryMock).not.toHaveBeenCalled();
});
it("degrades to {} (no match) rather than throwing when the warehouse query fails — mirrors invoice-bridge.ts's own catch-all", async () => {
const queryMock = vi.fn(async () => {
throw new Error("warehouse unreachable");
});
const fabric = { query: queryMock } as unknown as FabricOneLakeAdapter;
const result = await matchPartnerViaFabric(fabric, "556123-4567");
expect(result).toEqual({});
});
it("returns {} when no partner row matches", async () => {
const queryMock = vi.fn(async () => ({ rows: [], rowCount: 0, durationMs: 1 }));
const fabric = { query: queryMock } as unknown as FabricOneLakeAdapter;
const result = await matchPartnerViaFabric(fabric, "556123-4567");
expect(result).toEqual({});
});
});
describe("OdooBillsAdapter — partner resolution wired into write()", () => {
afterEach(() => vi.restoreAllMocks());
it("uses payload.partner_id directly when already set, without calling matchPartner", async () => {
const matchPartner = vi.fn();
const fetchMock = vi.fn(async () => jsonResponse({ ok: true, odoo_id: 1 }));
const adapter = new OdooBillsAdapter({
baseUrl: "https://odoo.example.com",
apiKey: "key",
matchPartner,
fetchImpl: fetchMock as unknown as typeof fetch,
});
await adapter.write(
{ recordType: "vendor_bill", payload: basePayload({ partner_id: 55 }) as unknown as Record<string, unknown>, idempotencyKey: "k1" },
CTX,
);
expect(matchPartner).not.toHaveBeenCalled();
});
it("calls the injected matchPartner when partner_id is absent but vendor_org_nr is present, and forwards the resolved partner_id to Odoo", async () => {
const matchPartner = vi.fn(async () => ({ partner_id: 99, partner_name: "Acme AB" }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- AUD0-ingest-body är fri nyttolast
let capturedBody: any;
const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
capturedBody = JSON.parse(init!.body as string);
return jsonResponse({ ok: true, odoo_id: 1 });
});
const adapter = new OdooBillsAdapter({
baseUrl: "https://odoo.example.com",
apiKey: "key",
matchPartner,
fetchImpl: fetchMock as unknown as typeof fetch,
});
await adapter.write(
{ recordType: "vendor_bill", payload: basePayload() as unknown as Record<string, unknown>, idempotencyKey: "k1" },
CTX,
);
expect(matchPartner).toHaveBeenCalledWith("556123-4567", CTX);
expect(capturedBody.invoice.partner_id).toBe(99);
});
it("posts without a partner_id when no match is found — 'skickar utan partner-koppling'", async () => {
const matchPartner = vi.fn(async () => ({}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- AUD0-ingest-body är fri nyttolast
let capturedBody: any;
const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
capturedBody = JSON.parse(init!.body as string);
return jsonResponse({ ok: true, odoo_id: 1 });
});
const adapter = new OdooBillsAdapter({
baseUrl: "https://odoo.example.com",
apiKey: "key",
matchPartner,
fetchImpl: fetchMock as unknown as typeof fetch,
});
await adapter.write(
{ recordType: "vendor_bill", payload: basePayload() as unknown as Record<string, unknown>, idempotencyKey: "k1" },
CTX,
);
expect(capturedBody.invoice.partner_id).toBeUndefined();
});
});
+201
View File
@@ -0,0 +1,201 @@
import { describe, it, expect, vi } from "vitest";
import { PiiGateService } from "@/src/services/pii-gate-service";
import { SourceService } from "@/src/services/source-service";
import { SourceQueryService } from "@/src/services/source-query-service";
import type { FabricOneLakeConnectionConfig } from "@/src/adapters/fabric-onelake-adapter";
/** Minimal config — never reached (the pii gate fires first). */
const EMPTY_CFG = {} as FabricOneLakeConnectionConfig;
describe("PiiGateService — GDPR guardrail (fail-closed)", () => {
const ratsit = {
source_id: "src_ratsit_1",
tenant_id: "t1",
project_id: "p1",
source_type: "web" as const,
name: "ratsit.se",
status: "active" as const,
created_at: new Date().toISOString(),
};
const company = {
source_id: "src_company_1",
tenant_id: "t1",
project_id: "p1",
source_type: "api" as const,
name: "allabolag.se",
status: "active" as const,
created_at: new Date().toISOString(),
};
it("classifies known directory domains as personal-data sources", () => {
const gate = new PiiGateService();
expect(gate.classifySourcePersonal(ratsit)).toBe(true);
expect(gate.classifySourcePersonal({ ...ratsit, name: "www.ratsit.se" })).toBe(true);
expect(gate.classifySourcePersonal(company)).toBe(false);
expect(gate.classifySourcePersonal({ ...company, touches_personal_data: true })).toBe(true);
});
it("rejects processing a personal-data source with no recorded lawful basis", async () => {
const gate = new PiiGateService();
await expect(gate.assertCanStore(ratsit, [], "t1")).rejects.toThrowError(/no PiiPolicy/);
});
it("rejects half-legal policies (missing basis_ref, zero retention, empty allowlist)", async () => {
const gate = new PiiGateService();
await expect(
gate.createPiiPolicy({ source_id: "s1", tenant_id: "t1", project_id: "p1", legal_basis: "legitimate_interest", basis_ref: " ", retention_days: 90, field_allowlist: ["address"] }),
).rejects.toThrow(/basis_ref is required/);
await expect(
gate.createPiiPolicy({ source_id: "s1", tenant_id: "t1", project_id: "p1", legal_basis: "consent", basis_ref: "consent-record-1", retention_days: -1, field_allowlist: ["address"] }),
).rejects.toThrow(/retention_days/);
await expect(
gate.createPiiPolicy({ source_id: "s1", tenant_id: "t1", project_id: "p1", legal_basis: "contract", basis_ref: "clause-9", retention_days: 90, field_allowlist: [] }),
).rejects.toThrow(/data minimisation/);
});
it("enforces the recorded decision: legitimate_interest = B2B business contact, company-linked only", async () => {
const gate = new PiiGateService();
await expect(
gate.createPiiPolicy({ source_id: "s_li_wrong", tenant_id: "t1", project_id: "p1", legal_basis: "legitimate_interest", basis_ref: "lia-2026-001", retention_days: 90, field_allowlist: ["email"], purpose: "consent_marketing" }),
).rejects.toThrowError(/only accepted with purpose=business_contact/);
await expect(
gate.createPiiPolicy({ source_id: "s_li_wrong2", tenant_id: "t1", project_id: "p1", legal_basis: "legitimate_interest", basis_ref: "lia-2026-001", retention_days: 90, field_allowlist: ["email"], entity_linked_only: false }),
).rejects.toThrowError(/entity_linked_only=true/);
await gate.createPiiPolicy({
source_id: "s_li_ok", tenant_id: "t1", project_id: "p1",
legal_basis: "legitimate_interest", basis_ref: "lia-2026-b2b-01",
retention_days: 365, field_allowlist: ["email", "phone"],
});
const p = await gate.getPiiPolicy("s_li_ok");
expect(p?.purpose).toBe("business_contact");
expect(p?.entity_linked_only).toBe(true);
// Business contact must be bound to a company — stray person-only rows are refused.
const liSource = { ...company, source_id: "s_li_ok" };
await expect(
gate.recordStored({ source: liSource, tenantId: "t1", identityKey: "k", subjectId: "s", field: "email" }),
).rejects.toThrowError(/entity linkage/);
const linked = await gate.recordStored({ source: liSource, tenantId: "t1", identityKey: "k", subjectId: "s", field: "email", entityId: "556677-8899" });
expect(linked.entity_hash).toMatch(/^[0-9a-f]{64}$/);
expect(linked.entity_hash).not.toContain("556677");
});
it("blocks out-of-allowlist fields (minimisation) and unconfirmed web sources", async () => {
const gate = new PiiGateService();
await gate.createPiiPolicy({
source_id: ratsit.source_id, tenant_id: "t1", project_id: "p1",
legal_basis: "consent", basis_ref: "consent-record-42",
retention_days: 90, field_allowlist: ["name", "address"],
});
await expect(gate.assertCanStore(ratsit, ["name", "phone"], "t1")).rejects.toThrowError(/outside the allowlist/);
await expect(gate.assertCanStore(ratsit, ["name"], "t1")).rejects.toThrowError(/robots.txt \/ rate-limit not confirmed/);
const ratsitConfirmed = { ...ratsit, source_id: "src_ratsit_confirmed" };
await gate.createPiiPolicy({
source_id: ratsitConfirmed.source_id, tenant_id: "t1", project_id: "p1",
legal_basis: "consent", basis_ref: "consent-record-42",
retention_days: 90, field_allowlist: ["name", "address"], robots_and_rate_confirmed: true,
});
await expect(gate.assertCanStore(ratsitConfirmed, ["name"], "t1")).resolves.toBeUndefined();
});
it("forbids any storage when retention_days = 0", async () => {
const gate = new PiiGateService();
await gate.createPiiPolicy({
source_id: "src_drop_1", tenant_id: "t1", project_id: "p1",
legal_basis: "legitimate_interest", basis_ref: "lia-2026-001",
retention_days: 0, field_allowlist: ["name"], robots_and_rate_confirmed: true,
});
await expect(
gate.assertCanStore({ ...company, source_id: "src_drop_1", name: "ratsit.se" }, ["name"], "t1"),
).rejects.toThrowError(/forbids retention/);
});
it("stores ruled bases and enables access/erasure without plaintext identity", async () => {
const gate = new PiiGateService();
await gate.createPiiPolicy({
source_id: ratsit.source_id, tenant_id: "t1", project_id: "p1",
legal_basis: "legal_obligation", basis_ref: "prop-§5",
retention_days: 30, field_allowlist: ["street_address"], robots_and_rate_confirmed: true,
});
const key = await gate.recordStored({
source: ratsit, tenantId: "t1",
identityKey: "20250101-1234", subjectId: "subj-77", field: "street_address", artifactRef: "st0re/dataset-a",
});
expect(key.key_hash).toMatch(/^[0-9a-f]{64}$/);
expect(key.key_hash).not.toContain("20250101");
const statement = await gate.accessStatement(key.subject_hash);
expect(statement.rows).toHaveLength(1);
expect(statement.rows[0].field).toBe("street_address");
const erased = await gate.erase({ subject_hash: key.subject_hash, reason: "deleted_by_subject" });
expect(erased).toBe(1);
expect((await gate.accessStatement(key.subject_hash)).rows).toHaveLength(0);
});
it("retention worker purges rows past their deadline", async () => {
const gate = new PiiGateService();
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-08-01T00:00:00Z"));
await gate.createPiiPolicy({
source_id: ratsit.source_id, tenant_id: "t1", project_id: "p1",
legal_basis: "legitimate_interest", basis_ref: "lia-2026-002",
retention_days: 30, field_allowlist: ["street_address"], robots_and_rate_confirmed: true,
});
await gate.recordStored({ source: ratsit, tenantId: "t1", identityKey: "k-1", subjectId: "s-1", field: "street_address", entityId: "5566778899" });
vi.setSystemTime(new Date("2026-09-15T00:00:00Z"));
const { purged } = await gate.enforceRetention(new Date("2026-09-15T00:00:00Z"));
vi.useRealTimers();
expect(purged).toBe(1);
});
it("redacts personnummer, e-mail and phone from log lines", () => {
const gate = new PiiGateService();
const out = gate.redact(
"subject=202501011234 res=" +
'evt=19720101-1234 [email protected] tel=070-123 45 67 sök=ok',
);
expect(out).not.toMatch(/\d{8}-\d{4}/);
expect(out).toContain("[PERSONNUMMER]");
expect(out).toContain("[EMAIL]");
expect(out).toContain("[TELEFON]");
});
it("SourceQueryService blocks a personal-data source by default (fail-closed)", async () => {
const sourceService = new SourceService();
await sourceService.createSource({ ...ratsit });
const service = new SourceQueryService({ sourceService });
await expect(
service.querySource({
source_id: ratsit.source_id,
query: "SELECT 1",
tenant_id: "t1", project_id: "p1",
connection_config: EMPTY_CFG,
}),
).rejects.toThrowError(/no PiiPolicy/);
});
it("SourceQueryService passes non-personal sources straight through to capability checks", async () => {
const sourceService = new SourceService();
await sourceService.createSource({
source_id: "src_safe_1", tenant_id: "t1", project_id: "p1",
source_type: "web", name: "example.org", status: "active",
});
const service = new SourceQueryService({ sourceService });
// Gate passes; the sync path then correctly rejects non-database sources.
await expect(
service.querySource({
source_id: "src_safe_1",
query: "SELECT 1",
tenant_id: "t1", project_id: "p1",
connection_config: EMPTY_CFG,
}),
).rejects.toThrowError(/source_type "web"/);
});
});
+127
View File
@@ -0,0 +1,127 @@
/**
* P010: the TS/Python split-brain bridge (BEFORE_STATE.md §2 — the
* production Python pipeline and the sophisticated TS QualityService had
* "noll bryggor mellan sig"). Covers both the pure bridge helper
* (src/quality/quality-bridge.ts) and the actual HTTP route
* (app/api/0pt/quality/bridge-run/route.ts) the Python engine calls, so a
* regression here is caught even if only the route wiring breaks.
*/
import { describe, it, expect } from "vitest";
import { NextRequest } from "next/server";
import { QualityService } from "@/src/quality/quality-service";
import { ensureBaselineRules } from "@/src/quality/quality-bridge";
import { POST as bridgeRunPOST } from "@/app/api/0pt/quality/bridge-run/route";
function bridgeRequest(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/0pt/quality/bridge-run", {
method: "POST",
body: JSON.stringify(body),
headers: { "content-type": "application/json" },
});
}
describe("ensureBaselineRules — the auto-provisioning half of the bridge", () => {
it("creates the baseline rule set once, and is idempotent on repeat calls", async () => {
const q = new QualityService();
const target = { tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_order_42" };
await ensureBaselineRules(q, target);
const firstPass = q.listRules({ tenant_id: "t_a", dataset_id: "ds_order_42" });
expect(firstPass).toHaveLength(2);
expect(firstPass.every((r) => r.supplied_by === "0pt-quality-bridge")).toBe(true);
// Calling again must NOT throw CONFLICT or create duplicates/new versions.
await ensureBaselineRules(q, target);
const secondPass = q.listRules({ tenant_id: "t_a", dataset_id: "ds_order_42" });
expect(secondPass).toHaveLength(2);
expect(secondPass.map((r) => r.version)).toEqual([1, 1]);
});
it("scopes baseline rule ids per tenant so two tenants never collide (CONFLICT)", async () => {
const q = new QualityService();
await ensureBaselineRules(q, { tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_shared_name" });
// Same dataset_id, different tenant — must not throw CONFLICT on the global rule_id map.
await expect(
ensureBaselineRules(q, { tenant_id: "t_b", project_id: "p_1", dataset_id: "ds_shared_name" })
).resolves.toBeUndefined();
expect(q.listRules({ tenant_id: "t_a", dataset_id: "ds_shared_name" })).toHaveLength(2);
expect(q.listRules({ tenant_id: "t_b", dataset_id: "ds_shared_name" })).toHaveLength(2);
});
it("never overwrites a rule a caller already customized under the same id pattern", async () => {
const q = new QualityService();
const target = { tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_x" };
await ensureBaselineRules(q, target);
const before = q.getRule("baseline_name_notnull__t_a__ds_x", "t_a");
await q.updateRule("baseline_name_notnull__t_a__ds_x", "t_a", { severity: "critical" });
await ensureBaselineRules(q, target); // must not clobber the customization
const after = q.getRule("baseline_name_notnull__t_a__ds_x", "t_a");
expect(after.severity).toBe("critical");
expect(after.version).toBe(before.version + 1);
});
});
describe("POST /api/0pt/quality/bridge-run — the actual contract the Python engine calls", () => {
it("grades delivered rows for real: a row missing `name` fails the baseline and opens an issue", async () => {
const res = await bridgeRunPOST(
bridgeRequest({
tenant_id: "t_bridge",
project_id: "p_1",
dataset_id: "ds_order_1",
rows: [
{ name: "Volvo Personvagnar AB", confidence: 0.97 },
{ name: null, confidence: 0.4 },
],
})
);
expect(res.status).toBe(201);
const body = await res.json();
expect(body.run.status).toBe("failed");
expect(body.run.score).toBeGreaterThan(0);
expect(body.run.score).toBeLessThan(100);
expect(body.issues.length).toBeGreaterThan(0);
expect(body.issues.some((i: { rule_id: string }) => i.rule_id.startsWith("baseline_name_notnull__"))).toBe(true);
});
it("a clean batch of rows succeeds with score 100 and no open issues", async () => {
const res = await bridgeRunPOST(
bridgeRequest({
tenant_id: "t_bridge_clean",
project_id: "p_1",
dataset_id: "ds_order_2",
rows: [
{ name: "Ericsson AB", confidence: 0.95 },
{ name: "Atlas Copco AB", confidence: 0.88 },
],
})
);
expect(res.status).toBe(201);
const body = await res.json();
expect(body.run.status).toBe("succeeded");
expect(body.run.score).toBe(100);
expect(body.issues).toEqual([]);
});
it("rejects a malformed body with a structured 400, never a 500 (Python must be able to tell apart its own bug from a network fault)", async () => {
const res = await bridgeRunPOST(bridgeRequest({ tenant_id: "t_x" })); // missing project_id/dataset_id/rows
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toBe("validation_error");
});
it("out-of-range confidence values (data drift from upstream) are graded, not crashed on", async () => {
const res = await bridgeRunPOST(
bridgeRequest({
tenant_id: "t_bridge_drift",
project_id: "p_1",
dataset_id: "ds_order_3",
rows: [{ name: "Weird AB", confidence: 42 }], // confidence way outside [0,1] — upstream bug simulation
})
);
expect(res.status).toBe(201);
const body = await res.json();
expect(body.run.status).toBe("failed");
expect(body.issues.some((i: { rule_id: string }) => i.rule_id.startsWith("baseline_confidence_range__"))).toBe(
true
);
});
});
+247
View File
@@ -0,0 +1,247 @@
/**
* QualityService + ExpectationEngine unit tests (Master-DoD §10 Data
* quality): versioned rule registry, runs, results, issues, score, trend,
* GE delegation (never faked), cross-tenant isolation.
*/
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { QualityService } from "@/src/quality/quality-service";
import { ExpectationEngine } from "@/src/quality/expectation-engine";
import { SiaxError } from "@/src/platform/errors";
const ROWS = [
{ org_nr: "5560360793", name: "Volvo", employees: 1000 },
{ org_nr: "5560125790", name: "Ericsson", employees: 90000 },
{ org_nr: null, name: "Broken", employees: -5 },
];
async function withRules() {
const q = new QualityService();
await q.createRule({
rule_id: "r_orgnr_notnull",
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
name: "org_nr must be present",
expectation: { expectation_type: "expect_column_values_to_not_be_null", kwargs: { column: "org_nr" } },
severity: "critical",
});
await q.createRule({
rule_id: "r_employees_range",
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
name: "employees in sane range",
expectation: {
expectation_type: "expect_column_values_to_be_between",
kwargs: { column: "employees", min_value: 0, max_value: 2_000_000 },
},
severity: "warning",
supplied_by: "vehiq",
});
return q;
}
describe("ExpectationEngine — GE core subset", () => {
const engine = new ExpectationEngine();
it("executes the supported expectation types with GE semantics", () => {
expect(
engine.execute({ expectation_type: "expect_column_values_to_not_be_null", kwargs: { column: "org_nr" } }, ROWS)
).toMatchObject({ success: false, unexpected_count: 1, evaluated_count: 3 });
expect(
engine.execute({ expectation_type: "expect_column_values_to_be_unique", kwargs: { column: "name" } }, ROWS)
).toMatchObject({ success: true });
// Nulls do not fail range checks (GE semantics); -5 does.
expect(
engine.execute(
{ expectation_type: "expect_column_values_to_be_between", kwargs: { column: "employees", min_value: 0 } },
ROWS
)
).toMatchObject({ success: false, unexpected_count: 1 });
expect(
engine.execute(
{ expectation_type: "expect_column_values_to_match_regex", kwargs: { column: "org_nr", regex: "^\\d{10}$" } },
ROWS
)
).toMatchObject({ success: true }); // null skipped per GE semantics
expect(
engine.execute(
{ expectation_type: "expect_table_row_count_to_be_between", kwargs: { min_value: 1, max_value: 2 } },
ROWS
)
).toMatchObject({ success: false });
expect(
engine.execute({ expectation_type: "expect_column_to_exist", kwargs: { column: "employees" } }, ROWS)
).toMatchObject({ success: true });
});
it("NEVER silently passes an unsupported expectation type", () => {
expect(() =>
engine.execute({ expectation_type: "expect_column_kl_divergence_to_be_less_than", kwargs: {} }, ROWS)
).toThrowError(SiaxError);
});
});
describe("QualityService — rule registry with versioning (§10)", () => {
it("createRule v1, updateRule bumps version and records the superseded version", async () => {
const q = await withRules();
const updated = await q.updateRule("r_orgnr_notnull", "t_a", { severity: "error" });
expect(updated.version).toBe(2);
const versions = q.getRuleVersions("r_orgnr_notnull", "t_a");
expect(versions.map((v) => [v.version, v.status])).toEqual([
[1, "superseded"],
[2, "active"],
]);
});
it("duplicate rule_id is CONFLICT; cross-tenant reads are NOT_FOUND (§50)", async () => {
const q = await withRules();
await expect(
q.createRule({
rule_id: "r_orgnr_notnull",
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
name: "dup",
expectation: { expectation_type: "expect_column_to_exist", kwargs: { column: "x" } },
})
).rejects.toMatchObject({ code: "CONFLICT" });
expect(() => q.getRule("r_orgnr_notnull", "t_b")).toThrowError(/not found/);
expect(q.listRules({ tenant_id: "t_b" })).toEqual([]);
});
it("products supply rules (supplied_by is preserved)", async () => {
const q = await withRules();
expect(q.getRule("r_employees_range", "t_a").supplied_by).toBe("vehiq");
});
});
describe("QualityService — runs, results, issues, score, trend", () => {
it("runs all active rules locally, opens issues for failures, computes a severity-weighted score", async () => {
const q = await withRules();
const run = await q.runQuality({
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
rows: ROWS,
correlation_id: "corr-q1",
});
expect(run.status).toBe("failed"); // both rules have failures
expect(run.results).toHaveLength(2);
expect(run.results.every((r) => r.executed_by === "0pt-local")).toBe(true);
expect(run.score).toBeGreaterThan(0);
expect(run.score).toBeLessThan(100);
const issues = q.listIssues({ tenant_id: "t_a", dataset_id: "ds_companies", status: "open" });
expect(issues).toHaveLength(2);
expect(issues.find((i) => i.rule_id === "r_orgnr_notnull")?.severity).toBe("critical");
// Resolve one issue.
const resolved = await q.resolveIssue(issues[0].issue_id, "t_a", "resolved");
expect(resolved.status).toBe("resolved");
expect(q.listIssues({ tenant_id: "t_a", status: "open" })).toHaveLength(1);
});
it("a clean dataset yields status succeeded, score 100 and no issues", async () => {
const q = await withRules();
const run = await q.runQuality({
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
rows: ROWS.slice(0, 2),
});
expect(run.status).toBe("succeeded");
expect(run.score).toBe(100);
expect(q.listIssues({ tenant_id: "t_a" })).toHaveLength(0);
});
it("trend is the chronological score series for the dataset (§10 trend)", async () => {
const q = await withRules();
await q.runQuality({ tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_companies", rows: ROWS });
await q.runQuality({ tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_companies", rows: ROWS.slice(0, 2) });
const trend = q.getTrend("t_a", "ds_companies");
expect(trend).toHaveLength(2);
expect(trend[1].score).toBe(100);
expect(trend[0].score).toBeLessThan(trend[1].score);
});
it("running with zero active rules is NOT_FOUND, not a fake success", async () => {
const q = new QualityService();
await expect(
q.runQuality({ tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_empty", rows: [] })
).rejects.toMatchObject({ code: "NOT_FOUND" });
});
});
describe("QualityService — GE delegation (§11 DQ, never faked)", () => {
it("delegates the WHOLE run when any rule's expectation is not locally executable", async () => {
const q = await withRules();
await q.createRule({
rule_id: "r_kl_divergence",
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
name: "distribution check (GE only)",
expectation: { expectation_type: "expect_column_kl_divergence_to_be_less_than", kwargs: { column: "employees" } },
});
const run = await q.runQuality({
tenant_id: "t_a",
project_id: "p_1",
dataset_id: "ds_companies",
rows: ROWS,
});
expect(run.status).toBe("delegated");
expect(run.delegated_job_id).toContain("mock_job_"); // test runtime: N0D mock
expect(run.results).toEqual([]); // NOTHING fabricated
expect(run.score).toBeUndefined();
});
it("delegates when no rows are supplied (engine cannot run on nothing)", async () => {
const q = await withRules();
const run = await q.runQuality({ tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_companies" });
expect(run.status).toBe("delegated");
});
it("recordDelegatedResults finishes a delegated run; a finished run cannot be finished again", async () => {
const q = await withRules();
const run = await q.runQuality({ tenant_id: "t_a", project_id: "p_1", dataset_id: "ds_companies" });
const finished = await q.recordDelegatedResults(run.run_id, "t_a", [
{
rule_id: "r_orgnr_notnull",
rule_version: 1,
success: true,
pass_ratio: 1,
evaluated_count: 3,
unexpected_count: 0,
unexpected_samples: [],
executed_by: "great_expectations",
},
]);
expect(finished.status).toBe("succeeded");
expect(finished.results[0].executed_by).toBe("great_expectations");
await expect(q.recordDelegatedResults(run.run_id, "t_a", [])).rejects.toMatchObject({ code: "CONFLICT" });
});
it("P-002: n0dGetJobResult is registered in the 0pt OpenAPI catalog (0pt.n0dGetJobResult)", () => {
// Verify that the n0dGetJobResult operationId is present in the 0pt internal
// OpenAPI contract (contracts/openapi.yaml) — it is the P-001 owner-seam
// retrieval endpoint for delegated quality jobs.
const catalog = readFileSync(
resolve(dirname(fileURLToPath(import.meta.url)), "../../contracts/openapi.yaml"),
"utf8"
);
expect(catalog).toContain("operationId: 0pt.n0dGetJobResult");
expect(catalog).toContain("/api/0pt/n0d/results/{jobId}");
expect(catalog).toContain("operationId: 0pt.quality.run");
expect(catalog).toContain("operationId: 0pt.quality.checks");
expect(catalog).toContain("operationId: 0pt.quality.reports");
});
});
+149
View File
@@ -0,0 +1,149 @@
/**
* P063 DoD: "a breaking schema is detected BEFORE consumer corruption."
*
* Two levels, both tested here:
* - the pure comparison (checkCompatibility) per policy direction, and
* - the registry refusing to record a version that breaks the PREVIOUS
* version's declared policy — including the bypass where a producer tries
* to widen its own policy to "none" on the breaking version.
*
* The end-to-end "no consumer write happened" proof lives in
* tests/p0/ingestion-runner.test.ts, which asserts the sink was never called.
*/
import { describe, expect, it } from "vitest";
import { checkCompatibility, conformanceErrors } from "@/src/schema/compatibility";
import { SchemaRegistry } from "@/src/schema/schema-registry";
import { InMemoryIngestionRepository } from "@/src/repositories/in-memory-ingestion-repository";
import { SiaxError } from "@/src/platform/errors";
import type { RecordSchemaFields } from "@/src/schema/record-schema";
const V1: RecordSchemaFields = {
org_number: { type: "string", required: true },
name: { type: "string", required: true },
employees: { type: "number", required: false },
};
describe("P063 compatibility rules", () => {
it("adding an OPTIONAL field is backward-compatible", () => {
const next = { ...V1, sni_code: { type: "string" as const, required: false } };
expect(checkCompatibility(V1, next, "backward").compatible).toBe(true);
});
it("adding a REQUIRED field breaks backward compatibility", () => {
const next = { ...V1, sni_code: { type: "string" as const, required: true } };
const verdict = checkCompatibility(V1, next, "backward");
expect(verdict.compatible).toBe(false);
expect(verdict.breaks[0].field).toBe("sni_code");
expect(verdict.breaks[0].detail).toContain("absent from every record written under the previous version");
});
it("adding a required field is FORWARD-safe — direction matters", () => {
const next = { ...V1, sni_code: { type: "string" as const, required: true } };
expect(checkCompatibility(V1, next, "forward").compatible).toBe(true);
expect(checkCompatibility(V1, next, "full").compatible).toBe(false);
});
it("removing a required field breaks BOTH directions", () => {
const next: RecordSchemaFields = { org_number: V1.org_number, employees: V1.employees };
expect(checkCompatibility(V1, next, "backward").compatible).toBe(false);
expect(checkCompatibility(V1, next, "forward").compatible).toBe(false);
});
it("removing an OPTIONAL field is backward-safe but not forward-safe", () => {
const next: RecordSchemaFields = { org_number: V1.org_number, name: V1.name };
expect(checkCompatibility(V1, next, "backward").compatible).toBe(true);
expect(checkCompatibility(V1, next, "forward").compatible).toBe(true);
});
it("a type change breaks every policy except an explicit 'none'", () => {
const next: RecordSchemaFields = { ...V1, employees: { type: "string", required: false } };
expect(checkCompatibility(V1, next, "backward").compatible).toBe(false);
expect(checkCompatibility(V1, next, "forward").compatible).toBe(false);
expect(checkCompatibility(V1, next, "full").compatible).toBe(false);
expect(checkCompatibility(V1, next, "none").compatible).toBe(true);
});
it("conformanceErrors catches a record that silently stopped matching its schema", () => {
expect(conformanceErrors(V1, { org_number: "556001-0001", name: "Alfa AB" })).toEqual([]);
expect(conformanceErrors(V1, { org_number: "556001-0001" })).toContain('required field "name" is missing');
expect(conformanceErrors(V1, { org_number: "556001-0001", name: "Alfa", employees: "ten" })).toContain(
'field "employees" is string, expected number',
);
expect(conformanceErrors(V1, { org_number: "1", name: "A", surprise: true })).toContain(
'unregistered field "surprise" appeared in the payload',
);
});
});
describe("P063 schema registry — versioning and refusal", () => {
function registry() {
return new SchemaRegistry(new InMemoryIngestionRepository());
}
it("the first registration is v1; an identical re-registration does not create v2", async () => {
const reg = registry();
const first = await reg.register({ source_id: "src_a", tenant_id: "t", fields: V1, compatibility: "backward" });
expect(first.schema.schema_version).toBe(1);
const again = await reg.register({ source_id: "src_a", tenant_id: "t", fields: V1, compatibility: "backward" });
expect(again.unchanged).toBe(true);
expect((await reg.list("src_a")).length).toBe(1);
});
it("a compatible change becomes v2", async () => {
const reg = registry();
await reg.register({ source_id: "src_b", tenant_id: "t", fields: V1, compatibility: "backward" });
const v2 = await reg.register({
source_id: "src_b",
tenant_id: "t",
fields: { ...V1, sni_code: { type: "string", required: false } },
compatibility: "backward",
});
expect(v2.schema.schema_version).toBe(2);
expect((await reg.getLatest("src_b"))?.schema_version).toBe(2);
});
it("a BREAKING change is refused and nothing is persisted", async () => {
const reg = registry();
await reg.register({ source_id: "src_c", tenant_id: "t", fields: V1, compatibility: "backward" });
const err = await reg
.register({
source_id: "src_c",
tenant_id: "t",
fields: { ...V1, sni_code: { type: "string", required: true } },
compatibility: "backward",
})
.catch((e: unknown) => e);
expect(err).toBeInstanceOf(SiaxError);
expect((err as SiaxError).code).toBe("CONFLICT");
expect((err as SiaxError).message).toContain("breaks the declared");
// Still only v1 on record — a refused registration writes nothing.
expect((await reg.list("src_c")).map((s) => s.schema_version)).toEqual([1]);
});
it("a producer cannot widen its OWN policy to 'none' on the breaking version", async () => {
const reg = registry();
await reg.register({ source_id: "src_d", tenant_id: "t", fields: V1, compatibility: "full" });
// The PREVIOUS version's policy governs — declaring "none" here must not help.
await expect(
reg.register({
source_id: "src_d",
tenant_id: "t",
fields: { ...V1, employees: { type: "string", required: false } },
compatibility: "none",
}),
).rejects.toThrow(/breaks the declared "full" compatibility policy/);
});
it("a source that explicitly declared 'none' opts out — recorded, never assumed", async () => {
const reg = registry();
await reg.register({ source_id: "src_e", tenant_id: "t", fields: V1, compatibility: "none" });
const v2 = await reg.register({
source_id: "src_e",
tenant_id: "t",
fields: { ...V1, employees: { type: "string", required: false } },
compatibility: "none",
});
expect(v2.schema.schema_version).toBe(2);
expect(v2.schema.compatibility).toBe("none");
});
});

Some files were not shown because too many files have changed in this diff Show More