Files
0pt/tests/p0/source-activation-gate.test.ts
T
Simon AxelssonandClaude Opus 5 9267576b7c
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
feat(data-os): P060-P068 durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill
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>
2026-09-04 17:03:14 +02:00

191 lines
7.5 KiB
TypeScript

/**
* 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/);
});
});