feat(data-os): P060-P068 durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill
CI (SIAX Cloud) / integration (push) Successful in 42s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / security (push) Successful in 46s
Security Scan (SIAX Cloud) / security (push) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 27s
CI (SIAX Cloud) / integration (push) Successful in 42s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / security (push) Successful in 46s
Security Scan (SIAX Cloud) / security (push) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 27s
BEFORE_STATE (verified, with evidence):
* P060 PARTIAL/BROKEN. The registry persisted rights/provenance/health/
freshness to Postgres, but carried no authorization, no schedule, no
checkpoint, no schema and no owner distinct from created_by — and the
activation DoD was inverted: postgres-source-repository.ts wrote
`${input.status ?? "active"}`, so a source with no rights, no provenance
and no authorization was ACTIVE the instant it was registered. No
activation operation existed at all.
* P061 MISSING. services/api/sources/connectors.py had per-source fetch_*()
functions only — no lifecycle, no cursor, no resume, no health, no
conformance suite.
* P062 MISSING, already documented as such in
services/api/tests/test_known_gaps.py:10-19 (no CDC pipeline anywhere;
workers/pipeline.py has no persistence at all).
* P063 MISSING. schema_version existed as a free string; no comparison,
no policy, no versioned source schema.
* P064 PARTIAL. Rules/runs/issues/scores existed, but a failing rule only
opened an issue and the data flowed on. No quarantine anywhere.
* P065 DUPLICATE (confirmed). Two ER engines: src/er/entity-resolution-
service.ts (canonical) and services/api/workers/resolve.py (simplified,
still called by pipeline.py:110).
* P067 PARTIAL. Lineage was emitted to AUD0 but nothing here could ANSWER a
lineage question — no store, no query, no route.
* P068 MISSING, documented in test_known_gaps.py:44-52 ("no delivery-store
persistence layer exists to dedupe a backfill against").
BUILT (only what was PARTIAL/BROKEN/MISSING):
* P060 sql/007_ingestion_plane.sql adds authorization/schedule/schemas/
checkpoints/ledger/quarantine/lineage tables, owner_id, and flips the
opt_sources status DEFAULT to 'pending' so even a raw psql INSERT cannot
produce an unclassified-but-active source. SourceRegistryService gains
classifySource/activateSource/deactivateSource + authorization/schedule
accessors; registration NEVER activates (asking for status:"active" goes
through the gate, not around it); a service identity cannot authorize a
source. Routes: activate (GET classification / POST activate),
authorization, schedule.
* P061 src/connectors/connector.ts — all nine operations on one interface.
src/connectors/conformance.ts — a runnable suite (15 checks, no "skip"
verdict). HttpJsonConnector (real HTTP, opaque cursor) and
JsonlFileConnector (real file, line offsets, CDC deletes) both pass it.
The suite caught a real defect while being written: an API that drops
next_cursor at the end left the connector unable to resume, which is why
HttpJsonConnectorConfig has cursor_field.
* P062 src/types/ingestion.ts + src/ingestion/{envelope,ingestion-runner}.ts.
One envelope for batch/stream/cdc; durable per-(source,partition)
checkpoints; resume proven by killing a run inside the sink.
* P063 src/schema/{record-schema,compatibility,schema-registry}.ts. Two
enforcement points, both upstream of any consumer write: a discovery gate
before the first read, and per-record conformance before the page reaches
the sink. A producer cannot widen its own policy retroactively.
* P064 src/quality/quality-policy.ts composes the EXISTING ExpectationEngine
(not a second engine) and adds the missing consequence: block /
quarantine / warn, with quarantine durable and recoverable. No policy is
reported as "none_declared", never as a pass; an unexecutable expectation
counts as a violation, never a silent pass.
* P067 src/lineage/{lineage-edge,lineage-store}.ts + GET /api/0pt/lineage.
AUD0 stays the system of record; this is 0pt's own queryable projection.
* P068 opt_ingestion_ledger + IngestionRunner.backfill: bounded, idempotent
on repeat, leaves the live checkpoint alone, still re-emits real changes.
A BUG THIS PASS WROTE AND CAUGHT: the first IngestionRepository draft
combined the idempotency check and its recording into one atomic call
BEFORE the sink. The crash/resume test then delivered 7 of 10 records — the
page in flight when the sink died was already marked delivered, so the
resumed run skipped it as a duplicate. Permanent, silent data loss. Fixed by
splitting peekDeliveries/commitDeliveries and committing both the ledger and
the checkpoint only after the sink resolves.
NOT DONE, stated rather than deferred quietly:
* P065 is NOT met. resolve.py is still a second simplified production
engine. Closing it means rewriting it as an adapter over the canonical
service, which cannot be verified from this repo today: services/api is
not built by this repo's Dockerfile, api.0pt.app answers 404, and NO CI
workflow runs its pytest suite. The duplication is now stated at both
sites in code and the removal plan is in STATUS.md. The new ingestion
plane performs no ER, so it adds no third engine.
* P066 (Iceberg) untouched — ST0RE is owned by another workflow. Contract
read only.
* Delivery is AT-LEAST-ONCE, not exactly-once (no per-partition run lock).
* No CDC *source* exists; the contract is met, a CDC connector is not built.
* 0pt does not schedule itself — the schedule row is a declaration ACT0
would read.
VERIFIED: pnpm typecheck clean; pnpm test 365 passed / 25 skipped (was
311/18); pnpm build clean with all four new routes in the route table; lint
unchanged at 12 pre-existing errors. Real Postgres 16
(tests/p0/ingestion-plane-postgres.realinfra.test.ts, 7 passed) plus a real
`docker restart` of that container with an identical read-back through the
production code path — that is P060's "a restart preserves all sources",
measured.
DEPLOYMENT REALITY (curl, 2026-09-04): 0pt.app/api/health returns 200 from
Vercel with db:not_configured; 0pt.app/api/0pt/sources returns 404;
api.0pt.app/health returns 404; cd.yml still guards on a placeholder Coolify
app id. None of the capability layer runs in production. Nothing here is
LIVE_VERIFIED and STATUS.md says so.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
c5ebceff38
commit
9267576b7c
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* HTTP-level tests for the P060/P067 routes added in this pass, in the same
|
||||
* shape as tests/api/0pt-cross-tenant-routes.test.ts: call the handler
|
||||
* directly with a hand-built NextRequest carrying `x-0pt-verified-tenant`,
|
||||
* which is exactly what middleware.ts forwards once a real Bearer token has
|
||||
* been verified.
|
||||
*
|
||||
* Two things are proved here that the service-level tests cannot:
|
||||
* - the new routes carry the SAME cross-tenant guard as the existing ones
|
||||
* (a new route with no guard would be the P014 hole reopened), and
|
||||
* - the activation gate is enforced at the HTTP boundary too — an
|
||||
* unclassified source gets 403, not a 200 with a quiet no-op.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST as sourcesPOST } from "@/app/api/0pt/sources/route";
|
||||
import { GET as classifyGET, POST as activatePOST } from "@/app/api/0pt/sources/[sourceId]/activate/route";
|
||||
import { PUT as authorizationPUT } from "@/app/api/0pt/sources/[sourceId]/authorization/route";
|
||||
import { PUT as schedulePUT } from "@/app/api/0pt/sources/[sourceId]/schedule/route";
|
||||
import { GET as lineageGET } from "@/app/api/0pt/lineage/route";
|
||||
|
||||
const VERIFIED = "x-0pt-verified-tenant";
|
||||
|
||||
function getReq(url: string, verifiedTenant = "t_a"): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), { headers: { [VERIFIED]: verifiedTenant } });
|
||||
}
|
||||
function bodyReq(url: string, method: "POST" | "PUT", body: unknown, verifiedTenant = "t_a"): NextRequest {
|
||||
return new NextRequest(new URL(url, "http://localhost"), {
|
||||
method,
|
||||
headers: { "content-type": "application/json", [VERIFIED]: verifiedTenant },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
const params = (sourceId: string) => ({ params: Promise.resolve({ sourceId }) });
|
||||
|
||||
describe("P060 routes — cross-tenant guard", () => {
|
||||
it("POST /activate rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await activatePOST(
|
||||
bodyReq("/api/0pt/sources/src_x/activate", "POST", { tenant_id: "t_victim" }),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
expect((await res.json()).error).toBe("OPT_ACCESS_DENIED");
|
||||
});
|
||||
|
||||
it("GET /activate (classification) rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await classifyGET(
|
||||
getReq("/api/0pt/sources/src_x/activate?tenant_id=t_victim"),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("PUT /authorization rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await authorizationPUT(
|
||||
bodyReq("/api/0pt/sources/src_x/authorization", "PUT", {
|
||||
tenant_id: "t_victim",
|
||||
basis: "contract",
|
||||
granted_by: "usr_attacker",
|
||||
granted_at: "2026-09-04T00:00:00.000Z",
|
||||
}),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("PUT /schedule rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await schedulePUT(
|
||||
bodyReq("/api/0pt/sources/src_x/schedule", "PUT", { tenant_id: "t_victim", mode: "batch", enabled: true }),
|
||||
params("src_x"),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /lineage rejects a foreign tenant_id (403)", async () => {
|
||||
const res = await lineageGET(getReq("/api/0pt/lineage?tenant_id=t_victim&output_name=0pt:dataset:ds_x"));
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("GET /lineage refuses an unfiltered dump (400)", async () => {
|
||||
const res = await lineageGET(getReq("/api/0pt/lineage?tenant_id=t_a"));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("P060 routes — the activation gate over HTTP", () => {
|
||||
it("an unclassified source cannot be activated through the API", async () => {
|
||||
const created = await sourcesPOST(
|
||||
bodyReq("/api/0pt/sources", "POST", {
|
||||
source_id: "src_http_gate_1",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p_a",
|
||||
source_type: "api",
|
||||
name: "Unclassified source",
|
||||
}),
|
||||
);
|
||||
expect(created.status).toBeLessThan(300);
|
||||
const body = await created.json();
|
||||
expect(body.source.status).toBe("pending");
|
||||
|
||||
const classification = await classifyGET(
|
||||
getReq("/api/0pt/sources/src_http_gate_1/activate?tenant_id=t_a"),
|
||||
params("src_http_gate_1"),
|
||||
);
|
||||
expect(classification.status).toBe(200);
|
||||
expect((await classification.json()).classified).toBe(false);
|
||||
|
||||
const activated = await activatePOST(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_1/activate", "POST", { tenant_id: "t_a" }),
|
||||
params("src_http_gate_1"),
|
||||
);
|
||||
expect(activated.status).toBe(403);
|
||||
});
|
||||
|
||||
it("a classified source activates through the API", async () => {
|
||||
await sourcesPOST(
|
||||
bodyReq("/api/0pt/sources", "POST", {
|
||||
source_id: "src_http_gate_2",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p_a",
|
||||
source_type: "api",
|
||||
name: "Classified source",
|
||||
owner_id: "usr_simon",
|
||||
rights: {
|
||||
license_id: "CC-BY-4.0",
|
||||
allowed_purposes: ["catalog"],
|
||||
pii_allowed: false,
|
||||
redistribution: "internal",
|
||||
verified_at: "2026-09-04",
|
||||
verified_by: "usr_simon",
|
||||
},
|
||||
provenance: { method: "official_api" },
|
||||
}),
|
||||
);
|
||||
const auth = await authorizationPUT(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_2/authorization", "PUT", {
|
||||
tenant_id: "t_a",
|
||||
basis: "public_register",
|
||||
granted_by: "usr_simon",
|
||||
granted_at: "2026-09-01T00:00:00.000Z",
|
||||
}),
|
||||
params("src_http_gate_2"),
|
||||
);
|
||||
expect(auth.status).toBe(200);
|
||||
|
||||
const activated = await activatePOST(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_2/activate", "POST", { tenant_id: "t_a", actor_id: "usr_simon" }),
|
||||
params("src_http_gate_2"),
|
||||
);
|
||||
expect(activated.status).toBe(200);
|
||||
expect((await activated.json()).status).toBe("active");
|
||||
});
|
||||
|
||||
it("a service identity cannot be recorded as the authorizing actor (400)", async () => {
|
||||
await sourcesPOST(
|
||||
bodyReq("/api/0pt/sources", "POST", {
|
||||
source_id: "src_http_gate_3",
|
||||
tenant_id: "t_a",
|
||||
project_id: "p_a",
|
||||
source_type: "api",
|
||||
name: "Self-authorizing source",
|
||||
}),
|
||||
);
|
||||
const res = await authorizationPUT(
|
||||
bodyReq("/api/0pt/sources/src_http_gate_3/authorization", "PUT", {
|
||||
tenant_id: "t_a",
|
||||
basis: "internal",
|
||||
granted_by: "svc_0pt",
|
||||
granted_at: "2026-09-01T00:00:00.000Z",
|
||||
}),
|
||||
params("src_http_gate_3"),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* P060 DoD #2: "an unclassified source can NOT be activated."
|
||||
*
|
||||
* Before this pass the opposite was true, and provably so:
|
||||
* src/repositories/postgres-source-repository.ts wrote
|
||||
* `${input.status ?? "active"}` and there was no activation operation at all
|
||||
* — registering a source with no rights, no provenance and no authorization
|
||||
* made it `active` on the spot. These tests pin the closed gate AND its
|
||||
* obvious bypasses (asking for status "active" at registration; a service
|
||||
* identity authorizing itself; an expired authorization).
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SourceRegistryService } from "@/src/services/source-registry-service";
|
||||
import { SourceService } from "@/src/services/source-service";
|
||||
import { InMemorySourceRepository } from "@/src/repositories/in-memory-source-repository";
|
||||
import { InMemorySourceRegistryRepository } from "@/src/repositories/in-memory-source-registry-repository";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
|
||||
function newService(): SourceRegistryService {
|
||||
return new SourceRegistryService({
|
||||
repository: new InMemorySourceRegistryRepository(),
|
||||
sourceService: new SourceService({ repository: new InMemorySourceRepository() }),
|
||||
});
|
||||
}
|
||||
|
||||
const TENANT = "t_test";
|
||||
const base = {
|
||||
source_id: "src_gate_1",
|
||||
tenant_id: TENANT,
|
||||
project_id: "p_test",
|
||||
source_type: "api" as const,
|
||||
name: "Bolagsverket öppna data",
|
||||
owner_id: "usr_simon",
|
||||
};
|
||||
|
||||
const RIGHTS = {
|
||||
license_id: "CC-BY-4.0",
|
||||
allowed_purposes: ["catalog", "enrichment"],
|
||||
pii_allowed: false,
|
||||
redistribution: "customer_deliverable" as const,
|
||||
verified_at: "2026-09-04",
|
||||
verified_by: "usr_simon",
|
||||
};
|
||||
|
||||
const PROVENANCE = { method: "official_api" as const, authority: "Bolagsverket" };
|
||||
|
||||
const AUTHORIZATION = {
|
||||
basis: "public_register" as const,
|
||||
granted_by: "usr_simon",
|
||||
granted_at: "2026-09-01T08:00:00.000Z",
|
||||
};
|
||||
|
||||
describe("P060 source registry — the activation gate", () => {
|
||||
it("a newly registered source is PENDING, never active", async () => {
|
||||
const svc = newService();
|
||||
const descriptor = await svc.registerSource(base);
|
||||
expect(descriptor.source.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("asking for status:'active' at registration does NOT bypass the gate", async () => {
|
||||
const svc = newService();
|
||||
// The most obvious bypass: just ask for it.
|
||||
await expect(svc.registerSource({ ...base, status: "active" })).rejects.toBeInstanceOf(SiaxError);
|
||||
// ...and the source is still on record, still pending — not half-created.
|
||||
const source = await svc.sources.getSource(base.source_id);
|
||||
expect(source.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("activating an unclassified source is denied and names every missing fact", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({ ...base, owner_id: undefined });
|
||||
const err = await svc.activateSource(base.source_id, TENANT).catch((e: unknown) => e);
|
||||
expect(err).toBeInstanceOf(SiaxError);
|
||||
const siax = err as SiaxError;
|
||||
expect(siax.code).toBe("AUTHORIZATION_DENIED");
|
||||
expect(siax.message).toContain("owner_id is not set");
|
||||
expect(siax.message).toContain("no authorization on record");
|
||||
expect(siax.message).toContain("no rights record");
|
||||
expect(siax.message).toContain("no provenance record");
|
||||
expect((await svc.sources.getSource(base.source_id)).status).toBe("pending");
|
||||
});
|
||||
|
||||
it("a fully classified source activates, and describe() reports the classification", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({
|
||||
...base,
|
||||
rights: RIGHTS,
|
||||
provenance: PROVENANCE,
|
||||
authorization: AUTHORIZATION,
|
||||
});
|
||||
const classification = await svc.classifySource(base.source_id, TENANT);
|
||||
expect(classification).toEqual({ source_id: base.source_id, classified: true, missing: [] });
|
||||
|
||||
const activated = await svc.activateSource(base.source_id, TENANT, "usr_simon");
|
||||
expect(activated.status).toBe("active");
|
||||
|
||||
const descriptor = await svc.describeSource(base.source_id, TENANT);
|
||||
expect(descriptor.classification?.classified).toBe(true);
|
||||
expect(descriptor.authorization?.basis).toBe("public_register");
|
||||
});
|
||||
|
||||
it("registering fully classified WITH status:'active' activates through the gate, not around it", async () => {
|
||||
const svc = newService();
|
||||
const descriptor = await svc.registerSource({
|
||||
...base,
|
||||
status: "active",
|
||||
rights: RIGHTS,
|
||||
provenance: PROVENANCE,
|
||||
authorization: AUTHORIZATION,
|
||||
});
|
||||
expect(descriptor.source.status).toBe("active");
|
||||
});
|
||||
|
||||
it("a service identity cannot authorize a source (no self-granted rubber stamp)", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource(base);
|
||||
await expect(
|
||||
svc.setAuthorization({
|
||||
source_id: base.source_id,
|
||||
tenant_id: TENANT,
|
||||
basis: "internal",
|
||||
granted_by: "svc_0pt",
|
||||
granted_at: "2026-09-01T08:00:00.000Z",
|
||||
}),
|
||||
).rejects.toThrow(/accountable actor/);
|
||||
});
|
||||
|
||||
it("an EXPIRED authorization does not classify the source", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({
|
||||
...base,
|
||||
rights: RIGHTS,
|
||||
provenance: PROVENANCE,
|
||||
authorization: { ...AUTHORIZATION, expires_at: "2026-01-01T00:00:00.000Z" },
|
||||
});
|
||||
const classification = await svc.classifySource(base.source_id, TENANT);
|
||||
expect(classification.classified).toBe(false);
|
||||
expect(classification.missing.join(" ")).toContain("expired");
|
||||
await expect(svc.activateSource(base.source_id, TENANT)).rejects.toThrow(/not classified/);
|
||||
});
|
||||
|
||||
it("rights with an empty purpose list do not classify (purpose limitation is not optional)", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({
|
||||
...base,
|
||||
rights: { ...RIGHTS, allowed_purposes: [] },
|
||||
provenance: PROVENANCE,
|
||||
authorization: AUTHORIZATION,
|
||||
});
|
||||
const classification = await svc.classifySource(base.source_id, TENANT);
|
||||
expect(classification.classified).toBe(false);
|
||||
expect(classification.missing.join(" ")).toContain("allowed_purposes is empty");
|
||||
});
|
||||
|
||||
it("deactivating is never gated — a source can always be taken out of service", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({ ...base, rights: RIGHTS, provenance: PROVENANCE, authorization: AUTHORIZATION });
|
||||
await svc.activateSource(base.source_id, TENANT);
|
||||
const paused = await svc.deactivateSource(base.source_id, TENANT, "paused");
|
||||
expect(paused.status).toBe("paused");
|
||||
});
|
||||
|
||||
it("the gate is tenant-scoped: another tenant cannot activate this source", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({ ...base, rights: RIGHTS, provenance: PROVENANCE, authorization: AUTHORIZATION });
|
||||
await expect(svc.activateSource(base.source_id, "t_attacker")).rejects.toThrow(/not found/);
|
||||
expect((await svc.sources.getSource(base.source_id)).status).toBe("pending");
|
||||
});
|
||||
|
||||
it("schedule is recorded as a registry field and validated", async () => {
|
||||
const svc = newService();
|
||||
await svc.registerSource({
|
||||
...base,
|
||||
schedule: { mode: "batch", interval_seconds: 3600, enabled: true },
|
||||
});
|
||||
const schedule = await svc.getSchedule(base.source_id, TENANT);
|
||||
expect(schedule?.mode).toBe("batch");
|
||||
expect(schedule?.interval_seconds).toBe(3600);
|
||||
await expect(
|
||||
svc.setSchedule({
|
||||
source_id: base.source_id,
|
||||
tenant_id: TENANT,
|
||||
mode: "stream",
|
||||
interval_seconds: 0,
|
||||
enabled: true,
|
||||
updated_at: new Date().toISOString(),
|
||||
}),
|
||||
).rejects.toThrow(/interval_seconds must be positive/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user