P060-P068: durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill #31

Merged
admin merged 1 commits from feat/p060-p068-ingestion-plane into main 2026-09-04 16:11:21 +00:00
43 changed files with 5506 additions and 20 deletions
+104
View File
File diff suppressed because one or more lines are too long
+47
View File
@@ -0,0 +1,47 @@
/**
* app/api/0pt/lineage/route.ts
* =============================
* P067 DoD: "source -> output lineage is QUERYABLE". This is the query.
*
* GET /api/0pt/lineage?tenant_id=…&output_name=… -> what fed this output
* GET /api/0pt/lineage?tenant_id=…&input_name=… -> what this input produced
*
* The answer comes from 0pt's local projection of the OpenLineage events it
* emits to AUD0 (src/lineage/lineage-store.ts). AUD0 remains the system of
* record; this endpoint exists because "emitted to AUD0" was never the same
* thing as "answerable from 0pt", and before this route nothing in this repo
* could answer either question.
*/
import { NextRequest, NextResponse } from "next/server";
import { lineageStore } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const tenantId = searchParams.get("tenant_id");
const outputName = searchParams.get("output_name") ?? undefined;
const inputName = searchParams.get("input_name") ?? undefined;
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
if (!outputName && !inputName) {
return NextResponse.json(
{ error: "one of output_name or input_name is required — an unfiltered lineage dump is not a query" },
{ status: 400 },
);
}
const guard = assertTenantMatchesVerified(request, tenantId);
if (guard) return guard;
const limitRaw = searchParams.get("limit");
const limit = limitRaw ? Math.min(Math.max(Number(limitRaw), 1), 500) : undefined;
const edges = await lineageStore.query({
tenant_id: tenantId,
output_name: outputName,
input_name: inputName,
limit,
});
return NextResponse.json({ edges, count: edges.length });
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -0,0 +1,47 @@
/**
* app/api/0pt/sources/[sourceId]/activate/route.ts
* ==================================================
* P060 activation gate over HTTP. POST activates a source ONLY when it is
* classified (owner + unexpired authorization + rights + provenance);
* otherwise it returns 403 AUTHORIZATION_DENIED naming every missing fact.
* GET returns the classification without changing anything, so an operator
* can see what is missing before trying.
*/
import { NextRequest, NextResponse } from "next/server";
import { activateSourceSchema, parseBody } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const tenantId = new URL(request.url).searchParams.get("tenant_id");
if (!tenantId) {
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
}
const guard = assertTenantMatchesVerified(request, tenantId);
if (guard) return guard;
return NextResponse.json(await sourceRegistryService.classifySource(sourceId, tenantId));
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const parsed = parseBody(activateSourceSchema, await request.json());
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
const guard = assertTenantMatchesVerified(request, parsed.data.tenant_id);
if (guard) return guard;
const source = await sourceRegistryService.activateSource(
sourceId,
parsed.data.tenant_id,
parsed.data.actor_id,
);
return NextResponse.json(source);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -0,0 +1,45 @@
/**
* app/api/0pt/sources/[sourceId]/authorization/route.ts
* ======================================================
* P060 "authorization": the recorded decision that 0pt may connect to this
* source at all — separate from rights (what the DATA may be used for). PUT
* is an upsert; a service identity as `granted_by` is rejected (400), because
* a source may not authorize itself.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, setSourceAuthorizationSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const tenantId = new URL(request.url).searchParams.get("tenant_id");
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
const guard = assertTenantMatchesVerified(request, tenantId);
if (guard) return guard;
const auth = await sourceRegistryService.getAuthorization(sourceId, tenantId);
if (!auth) {
return NextResponse.json({ error: `source ${sourceId} has no authorization record` }, { status: 404 });
}
return NextResponse.json(auth);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const parsed = parseBody(setSourceAuthorizationSchema, await request.json());
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
const guard = assertTenantMatchesVerified(request, parsed.data.tenant_id);
if (guard) return guard;
return NextResponse.json(
await sourceRegistryService.setAuthorization({ ...parsed.data, source_id: sourceId }),
);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
@@ -0,0 +1,48 @@
/**
* app/api/0pt/sources/[sourceId]/schedule/route.ts
* =================================================
* P060 "schedule": ingestion mode + cadence, recorded on the source. 0pt does
* NOT run cron itself — ACT0 owns scheduling; this row is the declaration a
* scheduler reads, and saying otherwise would be a claim this repo cannot back.
*/
import { NextRequest, NextResponse } from "next/server";
import { parseBody, setSourceScheduleSchema } from "@/src/validation/0pt-schemas";
import { sourceRegistryService } from "@/src/services/source-registry";
import { siaxErrorResponse } from "@/src/http/siax-error-response";
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const tenantId = new URL(request.url).searchParams.get("tenant_id");
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
const guard = assertTenantMatchesVerified(request, tenantId);
if (guard) return guard;
const schedule = await sourceRegistryService.getSchedule(sourceId, tenantId);
if (!schedule) {
return NextResponse.json({ error: `source ${sourceId} has no schedule record` }, { status: 404 });
}
return NextResponse.json(schedule);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
try {
const { sourceId } = await params;
const parsed = parseBody(setSourceScheduleSchema, await request.json());
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
const guard = assertTenantMatchesVerified(request, parsed.data.tenant_id);
if (guard) return guard;
return NextResponse.json(
await sourceRegistryService.setSchedule({
...parsed.data,
source_id: sourceId,
updated_at: new Date().toISOString(),
}),
);
} catch (error: unknown) {
return siaxErrorResponse(error);
}
}
+189
View File
@@ -0,0 +1,189 @@
# 0pt ingestion plane (P060–P068)
> Written 2026-09-04. Every claim here is backed by a test path or a
> recorded command; anything not verified says so. Read `STATUS.md`'s
> "P060-P068 ingestion plane" section for the classification table and the
> honest-gaps list — this document is the mechanism, that one is the status.
## The shape
```
Source Registry Connector Ingestion Runner
(P060: who, what, (P061: nine (P062: one envelope,
under what rights, operations, one one durable checkpoint)
on what schedule) conformance suite)
│ │ │
│ classification gate │ discover / validate │ read ─┐
│ blocks activation │ connect / read │ │
▼ ▼ resume / backfill ▼ ▼
opt_sources records ───────────────▶ IngestionEnvelope
opt_source_rights │
opt_source_authorization ├─▶ P063 schema gate
opt_source_schedule ├─▶ P064 quality gate
opt_source_schemas ├─▶ P068 ledger (peek)
opt_ingestion_checkpoints ├─▶ SINK (caller-supplied)
├─▶ P068 ledger (commit)
├─▶ checkpoint (commit)
└─▶ P067 lineage edge
```
## P060 — the registry, and the gate
A source now carries: `source_id`, `tenant_id`, `project_id`, `source_type`,
`owner_id`, an **authorization** record, a **license/purpose rights** record,
**provenance** (how the data is obtained), a **schedule**, a versioned
**schema**, a durable **checkpoint**, and a `status`.
`status` starts at **`pending`**. It was `active` before — both repository
implementations wrote `input.status ?? "active"` — which meant an
unclassified source went live the moment it was registered. `activateSource`
is now the only path to `active`, and it refuses unless ALL of these are on
record:
- an `owner_id` (distinct from `created_by`: who is accountable, not who typed it),
- an **unexpired** authorization granted by an accountable actor
(`svc_*`/`system`/`automation` are rejected — a source may not authorize itself),
- rights with a `license_id` **and** at least one `allowed_purpose`,
- provenance with a sourcing `method`.
Schedule, schema and checkpoint describe HOW a source runs, not WHETHER it
may, so they are deliberately not part of the gate.
The default is enforced in two places on purpose: in the repositories, and as
`ALTER TABLE opt_sources ALTER COLUMN status SET DEFAULT 'pending'`, so a raw
`INSERT` from psql cannot produce an unclassified-but-active source either
(proved in the realinfra suite).
Routes: `GET/POST /api/0pt/sources/{id}/activate` (GET returns the
classification without changing anything), `GET/PUT …/authorization`,
`GET/PUT …/schedule`.
## P061 — the connector contract
Nine operations on one interface: `validate` (pure, no IO, fail-closed),
`connect` (idempotent), `discover`, `health` (reports, never throws), `read`
(honours `limit` exactly), `checkpoint`, `resume`, `backfill` (bounded — an
open-ended range is refused), `disconnect` (idempotent, safe after an error).
`src/connectors/conformance.ts` is a plain async function, not a test file,
so the same suite runs from tests, from an operator script against a real
configured source, and (later) from a pre-activation check. There is no
"skip" verdict: a connector that cannot honestly serve a check FAILS it.
Two heterogeneous connectors pass it:
| | `HttpJsonConnector` | `JsonlFileConnector` |
|---|---|---|
| transport | network, real HTTP | local filesystem |
| cursor | opaque server token, with a `cursor_field` fallback | line offset it computes itself |
| exhaustion | server-reported | exact (the file is finite) |
| health | HTTP round trip | `stat` |
| backfill bounds | server-defined (sequence/timestamp) | line numbers |
| CDC deletes | no — it does not claim `cdc` | yes, via `_op` |
The `cursor_field` fallback exists because the conformance suite caught a
real defect: an API that stops returning `next_cursor` at the end of a page
left the connector with nothing to resume from, so `resume()` silently
restarted at the beginning.
## P062 — one envelope, one durable checkpoint
`IngestionEnvelope` is the single shape everything downstream sees:
`mode` (batch/stream/cdc), `operation` (upsert/insert/update/delete),
`partition_key`, `record_key`, `schema_version`, a monotonic `sequence`,
`occurred_at`/`ingested_at`, `payload` (null only for a delete) and
`provenance` (connector id + version + run id + cursor).
**Ordering is the contract.** Per page:
```
read/resume → normalize → schema conformance → quality gate
→ ledger PEEK → SINK → ledger COMMIT → checkpoint COMMIT
```
Both commits happen after the sink resolves. The two tempting shortcuts are
both data-loss bugs, and one of them was written here first — see STATUS.md's
"A real bug this pass wrote and then caught".
The resulting guarantee is **at-least-once**, not exactly-once.
`envelope_id` is a deterministic hash of
`(source, partition, record_key, content)` so a dedup-capable sink survives a
re-delivery.
## P063 — schema evolution
`RecordSchema` is a small structural shape (field → type + required) plus a
`CompatibilityPolicy` (`backward` / `forward` / `full` / `none`).
`checkCompatibility` answers what breaks, in which direction, and why. It is
deliberately not a second JSON-Schema dialect: the question is "is version
N+1 of an UPSTREAM shape safe for consumers of version N?", which needs a
comparable structure, not a validator.
Two enforcement points, both upstream of any consumer write:
1. the runner's **discovery gate** — a shape change that breaks the previous
version's declared policy fails the whole run before the first `read()`;
2. **per-record conformance** — a source that drifted without redeclaring its
schema is caught on the offending record, before the page reaches the sink.
A producer cannot widen its own policy: the PREVIOUS version's policy governs
whether a change is allowed.
## P064 — quality with consequences
`QualityGate` composes the existing `ExpectationEngine` (the Great
Expectations core subset already in this repo) and adds the missing half: a
declared `on_violation` action.
- `block` — the page fails, and the checkpoint does **not** advance, so the
bad page stays unconsumed rather than being stepped over.
- `quarantine` — failing envelopes are persisted whole to
`opt_quality_quarantine` (recoverable, not merely counted); clean ones
continue and the checkpoint advances.
- `warn` — everything continues, violations are counted and reported.
There is no default. With no policy the run report says
`quality_policy: "none_declared"` — an undeclared policy must never read as a
passed one. An expectation the local engine cannot execute counts as a
VIOLATION, never a silent pass.
## P067 — queryable lineage
`LineageEmitter` keeps emitting OpenLineage to AUD0, and **AUD0 remains the
system of record**. `LineageStore` adds 0pt's own flattened projection — one
row per (run, input, output) with a deterministic `edge_id` — because
"emitted to AUD0" was never the same thing as "answerable from 0pt".
```
GET /api/0pt/lineage?tenant_id=…&output_name=0pt:dataset:ds_x # what fed it
GET /api/0pt/lineage?tenant_id=…&input_name=source/src_x # what it produced
```
An unfiltered dump is refused (400): that is an export, not a query.
## P068 — bounded, idempotent backfill
`opt_ingestion_ledger` holds one row per `(source_id, record_key)` with the
last accepted content hash. A backfill runs through the same envelope,
schema, quality and ledger path as a normal run, and:
- **never touches the live checkpoint** — a backfill must not rewind or
advance streaming ingestion;
- **re-emits nothing** on a repeat — every record comes back `duplicate`;
- **still re-emits a genuine content change** — idempotency is not amnesia;
- **refuses an unbounded range** at the connector contract level.
## Running the real-infrastructure proof
```bash
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
```
The suite applies `sql/002_source_registry.sql` and
`sql/007_ingestion_plane.sql` itself (both are idempotent). It skips
honestly, never fabricating success, when the env var is unset.
+38
View File
@@ -3,6 +3,44 @@ Entity resolution (docs/06): block, score, and link records across sources so th
same company from GLEIF + Brreg + CVR collapses to one record with corroborated
confidence. rapidfuzz only; deterministic; no external calls.
=======================================================================
P065 — THIS IS THE SECOND ER ENGINE. IT IS NOT THE CANONICAL ONE.
=======================================================================
0pt has TWO entity-resolution implementations, and this is the simplified
one:
* CANONICAL: src/er/entity-resolution-service.ts — the declared generic ER
capability. Deterministic blocking + an explainable per-pair score,
product-supplied HARD RULES that override the score in both directions,
a configurable review band that hands ambiguous pairs to humans instead
of auto-merging, and delegation of heavy probabilistic linkage (Splink)
to 0pt-motor via the N0D job "0pt.er.batch_resolution".
* THIS FILE: blocking on (market, first initial) + a single
rapidfuzz token_sort_ratio threshold, first-match-wins, auto-merge with
no review band, no hard-rule hook, no explanation beyond the score.
P065's definition of done is that no second simplified production engine
remains. It has NOT been met: this file is still what
`workers/pipeline.py` calls (line ~110, `deduped = resolve(records)`).
WHY IT WAS NOT REPLACED IN THE P060-P068 PASS, stated plainly rather than
quietly deferred: replacing it means turning this module into an ADAPTER
that calls the canonical capability, and that change cannot be verified
from this repo today —
* `services/api` is not deployed by this repo's Dockerfile (which builds
only the Next.js app), and api.0pt.app answers 404, so there is no
running engine to test against;
* no CI workflow runs services/api's pytest suite at all (verified:
`grep -rn "pytest" .gitea/workflows .github/workflows` finds nothing),
so a rewrite here would land with zero automated coverage.
Rewriting it blind and calling P065 done would be exactly the
"claimed complete, broken in operation" failure this programme exists to
stop. The removal plan is recorded in STATUS.md.
Until then: do NOT add capability to this file. Any new ER behaviour
belongs in the canonical TypeScript service.
Deterministic by construction: for a fixed `records` input, blocking is a pure
function of (market, name-first-letter) and matching is first-match-wins
within a block, so results do not depend on which source answered first — see
+162
View File
@@ -0,0 +1,162 @@
-- 0pt ingestion plane (P060-P068).
--
-- Adds the durable state the Source Registry and the ingestion runner need
-- and that sql/002_source_registry.sql did NOT carry:
--
-- * opt_source_authorization -- P060 "authorization": the recorded decision
-- that this tenant may use this source at all. Separate from rights
-- (license/purpose) on purpose: rights say WHAT the data may be used for,
-- authorization says WHO signed off that 0pt may connect. Both are
-- required to activate.
-- * opt_source_schedule -- P060 "schedule": ingestion mode + cadence.
-- * opt_source_schemas -- P060 "schema" + P063 schema evolution:
-- one row per (source_id, schema_version), plus the compatibility policy
-- that governs the NEXT version.
-- * opt_ingestion_checkpoints -- P060 "checkpoint" + P062: the durable
-- resume point per (source_id, partition_key). This is the table that
-- makes "restart resumes without silent gaps" true rather than aspirational.
-- * opt_ingestion_ledger -- P068: idempotency ledger. One row per
-- (source_id, record_key, payload hash); a repeated backfill that
-- re-delivers the same record is recognised, not re-emitted.
-- * opt_quality_quarantine -- P064: where envelopes go when the declared
-- enforcement policy says "quarantine" instead of "block".
-- * opt_lineage_edges -- P067: the LOCAL, QUERYABLE projection of
-- the OpenLineage events 0pt already emits to AUD0. AUD0 remains the
-- system of record; this table exists because "emitted to AUD0" is not
-- the same thing as "queryable from 0pt", and the P067 DoD asks for the
-- latter.
--
-- Every statement is IF NOT EXISTS / idempotent so it can be applied to an
-- already-migrated database, matching sql/002_source_registry.sql's contract
-- (tests/p0/*.realinfra.test.ts apply the files themselves).
--
-- Ordering: requires sql/002_source_registry.sql (opt_sources) to have run.
-- ── P060 owner + the pre-activation status ────────────────────────────────
-- `created_by` (002) records who typed the registration; `owner_id` records
-- who is ACCOUNTABLE for the source afterwards. The activation gate requires
-- the latter, so they cannot be collapsed.
ALTER TABLE opt_sources ADD COLUMN IF NOT EXISTS owner_id TEXT;
CREATE INDEX IF NOT EXISTS opt_sources_owner_idx ON opt_sources (owner_id);
-- New sources are created 'pending' (see src/repositories/*-source-repository.ts).
-- The column default in 002 is 'active'; it is changed here so a plain INSERT
-- that omits `status` -- from any client, including psql -- cannot produce an
-- unclassified-but-active source. Rows that are already 'active' are left
-- exactly as they are: this migration does not retroactively deactivate
-- anything an operator has already approved.
ALTER TABLE opt_sources ALTER COLUMN status SET DEFAULT 'pending';
-- ── P060 authorization ────────────────────────────────────────────────────
-- One row per source. `basis` is the legal/contractual ground; `granted_by`
-- is the accountable actor id (never "system"); `evidence_ref` points at the
-- AUD0 evidence or 1p/contract artifact. `expires_at` is honoured by the
-- activation gate -- an expired authorization does not classify a source.
CREATE TABLE IF NOT EXISTS opt_source_authorization (
source_id TEXT PRIMARY KEY REFERENCES opt_sources (source_id),
tenant_id TEXT NOT NULL,
basis TEXT NOT NULL, -- contract | public_register | consent | legitimate_interest | internal
granted_by TEXT NOT NULL, -- accountable actor id
granted_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ,
evidence_ref TEXT, -- aud0 evidence ref / contract artifact ref
notes TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS opt_source_authorization_tenant_idx ON opt_source_authorization (tenant_id);
-- ── P060 schedule ─────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS opt_source_schedule (
source_id TEXT PRIMARY KEY REFERENCES opt_sources (source_id),
tenant_id TEXT NOT NULL,
mode TEXT NOT NULL, -- batch | stream | cdc
interval_seconds INT, -- batch/cdc poll cadence; NULL for continuous streams
cron TEXT, -- optional cron expression (documented, not executed here)
enabled BOOLEAN NOT NULL DEFAULT false,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS opt_source_schedule_tenant_idx ON opt_source_schedule (tenant_id);
-- ── P060 schema + P063 schema evolution ───────────────────────────────────
-- `fields` is the record schema as JSON: {"<field>": {"type": "...",
-- "required": true|false}}. `compatibility` governs what the NEXT registered
-- version is allowed to change (see src/schema/compatibility.ts).
CREATE TABLE IF NOT EXISTS opt_source_schemas (
source_id TEXT NOT NULL REFERENCES opt_sources (source_id),
schema_version INT NOT NULL,
tenant_id TEXT NOT NULL,
fields JSONB NOT NULL,
compatibility TEXT NOT NULL, -- backward | forward | full | none
registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
registered_by TEXT,
PRIMARY KEY (source_id, schema_version)
);
CREATE INDEX IF NOT EXISTS opt_source_schemas_tenant_idx ON opt_source_schemas (tenant_id);
-- ── P060 checkpoint + P062 durable resume ─────────────────────────────────
-- `cursor` is opaque to 0pt -- the connector defines it (an offset, an LSN,
-- a page token). `sequence` is 0pt's own monotonic envelope counter for the
-- partition, used to detect gaps on resume.
CREATE TABLE IF NOT EXISTS opt_ingestion_checkpoints (
source_id TEXT NOT NULL REFERENCES opt_sources (source_id),
partition_key TEXT NOT NULL,
tenant_id TEXT NOT NULL,
cursor TEXT,
sequence BIGINT NOT NULL DEFAULT 0,
records_committed BIGINT NOT NULL DEFAULT 0,
committed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, partition_key)
);
CREATE INDEX IF NOT EXISTS opt_ingestion_checkpoints_tenant_idx ON opt_ingestion_checkpoints (tenant_id);
-- ── P068 backfill idempotency ledger ──────────────────────────────────────
-- A backfill/replay that re-delivers a record 0pt has already accepted must
-- be a no-op, not a duplicate. `payload_hash` distinguishes "same record,
-- same content" (skip) from "same record, new content" (an update, emitted).
CREATE TABLE IF NOT EXISTS opt_ingestion_ledger (
source_id TEXT NOT NULL REFERENCES opt_sources (source_id),
record_key TEXT NOT NULL,
tenant_id TEXT NOT NULL,
payload_hash TEXT NOT NULL,
first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
delivery_count BIGINT NOT NULL DEFAULT 1,
PRIMARY KEY (source_id, record_key)
);
CREATE INDEX IF NOT EXISTS opt_ingestion_ledger_tenant_idx ON opt_ingestion_ledger (tenant_id);
-- ── P064 quarantine ───────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS opt_quality_quarantine (
quarantine_id TEXT PRIMARY KEY,
source_id TEXT NOT NULL REFERENCES opt_sources (source_id),
tenant_id TEXT NOT NULL,
run_id TEXT NOT NULL,
record_key TEXT NOT NULL,
violations JSONB NOT NULL, -- [{expectation_type, kwargs, detail}]
envelope JSONB NOT NULL,
quarantined_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS opt_quality_quarantine_source_idx ON opt_quality_quarantine (source_id, quarantined_at DESC);
CREATE INDEX IF NOT EXISTS opt_quality_quarantine_tenant_idx ON opt_quality_quarantine (tenant_id);
-- ── P067 queryable lineage projection ─────────────────────────────────────
-- One row per (run, input, output) edge. `edge_id` is deterministic
-- (sha256 of the tuple) so a re-emitted idempotent run does not duplicate
-- edges -- the same dedup property LineageEmitter relies on in AUD0.
CREATE TABLE IF NOT EXISTS opt_lineage_edges (
edge_id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
run_id TEXT NOT NULL,
capability_id TEXT NOT NULL,
input_namespace TEXT NOT NULL,
input_name TEXT NOT NULL,
input_ref TEXT,
output_namespace TEXT NOT NULL,
output_name TEXT NOT NULL,
output_ref TEXT,
event_time TIMESTAMPTZ NOT NULL,
correlation_id TEXT
);
CREATE INDEX IF NOT EXISTS opt_lineage_edges_output_idx ON opt_lineage_edges (tenant_id, output_name);
CREATE INDEX IF NOT EXISTS opt_lineage_edges_input_idx ON opt_lineage_edges (tenant_id, input_name);
CREATE INDEX IF NOT EXISTS opt_lineage_edges_run_idx ON opt_lineage_edges (tenant_id, run_id);
+276
View File
@@ -0,0 +1,276 @@
/**
* src/connectors/conformance.ts
* ==============================
* P061 DoD: "two heterogeneous connectors pass the same conformance suite."
*
* This module IS that suite. It is a plain async function returning a report
* — not a vitest file — so it can be run three ways without duplication:
* 1. from tests (tests/p0/connector-conformance.test.ts runs it per connector),
* 2. from an operator script against a real configured source,
* 3. from a future capability route as a pre-activation check.
*
* Each check is a named assertion about the CONTRACT, not about any one
* connector's data. A connector that cannot serve a check honestly (e.g. it
* has no partitions under the given config) FAILS it — there is no "skip"
* verdict, because a skip that reads as a pass is how a conformance suite
* becomes decoration.
*/
import type {
BackfillRequest,
Connector,
ConnectorConfig,
ConnectorContext,
} from "./connector";
export interface ConformanceCheck {
name: string;
passed: boolean;
detail: string;
}
export interface ConformanceReport {
connector_id: string;
connector_version: string;
passed: boolean;
checks: ConformanceCheck[];
}
export interface ConformanceFixture {
/** A config the connector must accept. */
validConfig: ConnectorConfig;
/** A config the connector must REJECT in validate() without doing IO. */
invalidConfig: ConnectorConfig;
ctx: ConnectorContext;
/**
* A bounded backfill range that overlaps data the connector can serve.
* `from`/`to` are connector-defined (documented per connector).
*/
backfill: Omit<BackfillRequest, "partition_key" | "limit"> & { partition_key?: string };
/** Total number of records the fixture's first partition holds, so paging can be checked exactly. */
expectedRecordCount: number;
}
async function check(
checks: ConformanceCheck[],
name: string,
fn: () => Promise<string> | string,
): Promise<void> {
try {
const detail = await fn();
checks.push({ name, passed: true, detail });
} catch (err) {
checks.push({
name,
passed: false,
detail: err instanceof Error ? err.message : String(err),
});
}
}
function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
/**
* Run the full conformance suite against one connector instance.
* The connector is left disconnected on return, pass or fail.
*/
export async function runConnectorConformance(
connector: Connector,
fixture: ConformanceFixture,
): Promise<ConformanceReport> {
const checks: ConformanceCheck[] = [];
await check(checks, "identity: non-empty id and version", () => {
assert(connector.connector_id.length > 0, "connector_id is empty");
assert(connector.connector_version.length > 0, "connector_version is empty");
return `${connector.connector_id}@${connector.connector_version}`;
});
await check(checks, "validate: accepts a valid config without IO", () => {
const res = connector.validate(fixture.validConfig);
assert(res.valid, `valid config rejected: ${res.errors.join("; ")}`);
assert(res.errors.length === 0, "valid config produced errors");
return "valid config accepted";
});
await check(checks, "validate: rejects an invalid config and says why", () => {
const res = connector.validate(fixture.invalidConfig);
assert(!res.valid, "invalid config was accepted (fail-open)");
assert(res.errors.length > 0, "rejection carried no reason");
return `rejected with ${res.errors.length} reason(s)`;
});
await check(checks, "operations before connect() fail closed", async () => {
let threw = false;
try {
await connector.read({ partition_key: "anything", limit: 1 });
} catch {
threw = true;
}
assert(threw, "read() succeeded without a session");
return "read() refused without a session";
});
await check(checks, "connect: idempotent", async () => {
await connector.connect(fixture.validConfig, fixture.ctx);
await connector.connect(fixture.validConfig, fixture.ctx);
return "connect() called twice without error";
});
let partitionKey = fixture.backfill.partition_key ?? "";
await check(checks, "discover: reports at least one partition with a schema", async () => {
const discovery = await connector.discover();
assert(discovery.partitions.length > 0, "no partitions discovered");
assert(discovery.modes.length > 0, "no ingestion modes declared");
const first = discovery.partitions[0];
assert(first.partition_key.length > 0, "partition_key is empty");
assert(
Object.keys(first.schema).length > 0,
`partition "${first.partition_key}" reported an empty schema`,
);
if (!partitionKey) partitionKey = first.partition_key;
return `${discovery.partitions.length} partition(s), modes: ${discovery.modes.join(",")}`;
});
await check(checks, "health: answers with a status instead of throwing", async () => {
const health = await connector.health();
assert(
["up", "degraded", "down"].includes(health.status),
`unexpected health status "${health.status}"`,
);
return `status=${health.status}`;
});
await check(checks, "read: honours the limit and advances the cursor", async () => {
const first = await connector.read({ partition_key: partitionKey, limit: 1 });
assert(first.records.length <= 1, `limit 1 returned ${first.records.length} records`);
assert(first.records.length === 1, "limit 1 returned nothing — fixture has no data");
assert(first.next_cursor !== undefined, "no cursor returned after a non-empty read");
const second = await connector.read({
partition_key: partitionKey,
cursor: first.next_cursor,
limit: 1,
});
if (second.records.length > 0) {
assert(
second.records[0].record_key !== first.records[0].record_key,
"reading from the returned cursor re-delivered the same record (cursor is not exclusive)",
);
}
return `cursor advanced past ${first.records[0].record_key}`;
});
await check(checks, "read: paging covers every record exactly once", async () => {
const seen: string[] = [];
let cursor: string | undefined;
for (let page = 0; page < 100; page++) {
const res = await connector.read({ partition_key: partitionKey, cursor, limit: 2 });
for (const r of res.records) seen.push(r.record_key);
cursor = res.next_cursor;
if (res.exhausted || res.records.length === 0) break;
}
assert(
seen.length === fixture.expectedRecordCount,
`paged ${seen.length} records, fixture declares ${fixture.expectedRecordCount}`,
);
assert(new Set(seen).size === seen.length, "paging delivered a duplicate record_key");
return `${seen.length} records, no duplicates`;
});
await check(checks, "read: an exhausted partition reports exhausted", async () => {
const everything = await connector.read({ partition_key: partitionKey, limit: 1000 });
const past = await connector.read({
partition_key: partitionKey,
cursor: everything.next_cursor,
limit: 1000,
});
assert(past.records.length === 0, "reading past the end returned records");
assert(past.exhausted, "reading past the end did not report exhausted");
return "end of partition reported honestly";
});
await check(checks, "checkpoint: reflects the session position", async () => {
const cp = await connector.checkpoint(partitionKey);
assert(cp.partition_key === partitionKey, "checkpoint returned a different partition");
return `cursor=${cp.cursor ?? "<none>"}`;
});
await check(checks, "resume: continues from a committed checkpoint without re-delivery", async () => {
const firstPage = await connector.read({ partition_key: partitionKey, limit: 2 });
assert(firstPage.records.length > 0, "fixture partition is empty");
const committed = {
source_id: fixture.ctx.source_id,
tenant_id: fixture.ctx.tenant_id,
partition_key: partitionKey,
cursor: firstPage.next_cursor,
sequence: firstPage.records.length,
records_committed: firstPage.records.length,
committed_at: new Date().toISOString(),
};
const resumed = await connector.resume(committed, 1000);
const firstKeys = new Set(firstPage.records.map((r) => r.record_key));
for (const r of resumed.records) {
assert(
!firstKeys.has(r.record_key),
`resume re-delivered already-committed record "${r.record_key}"`,
);
}
assert(
firstPage.records.length + resumed.records.length === fixture.expectedRecordCount,
`resume covered ${firstPage.records.length + resumed.records.length} of ${fixture.expectedRecordCount} records — a gap`,
);
return `resumed ${resumed.records.length} remaining records with no gap and no overlap`;
});
await check(checks, "backfill: serves a bounded range", async () => {
const res = await connector.backfill({
partition_key: partitionKey,
from: fixture.backfill.from,
to: fixture.backfill.to,
limit: 1000,
});
assert(res.records.length > 0, "bounded backfill range returned nothing");
return `${res.records.length} record(s) in range`;
});
await check(checks, "backfill: refuses an unbounded range", async () => {
let threw = false;
try {
await connector.backfill({
partition_key: partitionKey,
from: fixture.backfill.from,
to: "",
limit: 1000,
});
} catch {
threw = true;
}
assert(threw, "an unbounded backfill was accepted");
return "unbounded backfill refused";
});
await check(checks, "disconnect: idempotent and safe", async () => {
await connector.disconnect();
await connector.disconnect();
return "disconnect() called twice without error";
});
await check(checks, "operations after disconnect() fail closed", async () => {
let threw = false;
try {
await connector.read({ partition_key: partitionKey, limit: 1 });
} catch {
threw = true;
}
assert(threw, "read() succeeded after disconnect()");
return "read() refused after disconnect()";
});
return {
connector_id: connector.connector_id,
connector_version: connector.connector_version,
passed: checks.every((c) => c.passed),
checks,
};
}
+163
View File
@@ -0,0 +1,163 @@
/**
* src/connectors/connector.ts
* ============================
* P061: THE connector contract. Nine operations, one interface, every
* connector implements all nine:
*
* validate — is this config usable? Pure, no IO, no network. Fail-closed.
* connect — open whatever session the source needs. Must be idempotent.
* discover — what partitions exist, and what shape do their records have?
* health — is the source answering right now?
* read — produce records from a cursor forward, bounded by `limit`.
* checkpoint — the cursor meaning "everything before this is produced".
* resume — continue from a previously committed checkpoint.
* backfill — re-read a bounded historical range. Bounded, never "all".
* disconnect — release the session. Must be idempotent and safe after an error.
*
* WHY AN INTERFACE AND NOT A BASE CLASS: connectors are heterogeneous by
* nature (an HTTP API paginates by opaque token, a file store seeks by byte
* offset, a change feed advances an LSN). The contract fixes the SHAPE of
* the interaction and the meaning of the cursor; it does not pretend the
* mechanics are the same. `src/connectors/conformance.ts` is what proves two
* unrelated implementations really do honour the same shape.
*
* WHAT THIS REPLACES, HONESTLY: services/api/sources/connectors.py has
* per-source `async def fetch_x()` functions and nothing else — no lifecycle,
* no cursor, no resume, no health, no disconnect. Those functions remain the
* Python engine's fetch layer; they are NOT retrofitted here (that engine is
* not deployed — api.0pt.app answers 404 — and rewriting it blind would be
* the exact "build it again" failure this programme forbids). This contract
* is the seam a Python connector is wrapped into when that engine is revived.
*/
import type { IngestionCheckpoint, IngestionMode } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
/** Config is connector-specific; the contract only requires it be serializable. */
export type ConnectorConfig = Record<string, unknown>;
export interface ConnectorContext {
tenant_id: string;
project_id: string;
source_id: string;
/** Correlates every operation of one ingestion run. */
run_id: string;
}
/** Result of `validate` — never throws, always answers. */
export interface ValidationResult {
valid: boolean;
/** One entry per problem. Empty iff valid. */
errors: string[];
}
/** One readable partition (a table, a topic, a file, a page family). */
export interface PartitionDescriptor {
partition_key: string;
/** Human label; may equal partition_key. */
name: string;
/** Record shape as the connector currently sees it — fed straight into the schema registry (P063). */
schema: RecordSchemaFields;
}
export interface DiscoveryResult {
partitions: PartitionDescriptor[];
/** Modes this connector can actually serve for this config. */
modes: IngestionMode[];
}
export interface ConnectorHealth {
status: "up" | "degraded" | "down";
latency_ms?: number;
/** Short operator-facing text — never a raw upstream body. */
detail?: string;
}
export interface ReadRequest {
partition_key: string;
/** Start AFTER this cursor. Undefined = from the beginning of the partition. */
cursor?: string;
/** Hard upper bound on records returned. Connectors MUST honour it. */
limit: number;
}
/** A record as the connector sees it, before the runner wraps it in an envelope. */
export interface ConnectorRecord {
/** Stable business key within the partition. */
record_key: string;
/** Null only for a delete in a change feed. */
payload: Record<string, unknown> | null;
operation?: "upsert" | "insert" | "update" | "delete";
occurred_at?: string;
/** Cursor value AT this record — the runner records it per envelope. */
cursor?: string;
}
export interface ReadResult {
records: ConnectorRecord[];
/**
* Cursor meaning "everything up to and including `records` has been
* produced". The runner commits this only after the records are accepted.
*/
next_cursor?: string;
/** False when the connector knows more records are immediately available. */
exhausted: boolean;
}
/** A bounded historical range. Unbounded backfills are rejected by the contract. */
export interface BackfillRequest {
partition_key: string;
/** Inclusive lower bound (cursor or ISO timestamp — connector-defined, documented per connector). */
from: string;
/** Exclusive upper bound. Required: a backfill with no end is a full reload, not a backfill. */
to: string;
limit: number;
}
export interface Connector {
readonly connector_id: string;
readonly connector_version: string;
/** Pure config check. MUST NOT perform IO. MUST NOT throw. */
validate(config: ConnectorConfig): ValidationResult;
/** Open a session. Idempotent: calling it twice is a no-op, not an error. */
connect(config: ConnectorConfig, ctx: ConnectorContext): Promise<void>;
/** Requires a live session. */
discover(): Promise<DiscoveryResult>;
/** Requires a live session. Never throws for an unhealthy source — reports it. */
health(): Promise<ConnectorHealth>;
/** Requires a live session. Honours `limit` exactly. */
read(req: ReadRequest): Promise<ReadResult>;
/**
* The connector's own view of where it stands for a partition. The DURABLE
* checkpoint is owned by the runner (CheckpointStore); this is the
* in-session position, used to cross-check a resume.
*/
checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }>;
/**
* Continue from a previously committed checkpoint. Equivalent to
* `read({cursor: checkpoint.cursor})` for cursor-based connectors, but
* explicit so a connector that must re-establish server-side state (a
* replication slot, a scroll context) has a place to do it.
*/
resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult>;
/** Bounded historical re-read. MUST reject an unbounded range. */
backfill(req: BackfillRequest): Promise<ReadResult>;
/** Idempotent; safe to call without a session and after an error. */
disconnect(): Promise<void>;
}
/** Thrown by connectors when an operation needs a session that was never opened. */
export class ConnectorNotConnectedError extends Error {
constructor(connectorId: string, operation: string) {
super(`connector ${connectorId}: ${operation} requires connect() first`);
this.name = "ConnectorNotConnectedError";
}
}
+274
View File
@@ -0,0 +1,274 @@
/**
* src/connectors/http-json-connector.ts
* ======================================
* P061 conformance connector #1: a real HTTP JSON API source.
*
* Heterogeneity (the point of having two): this connector talks to a REMOTE
* service over the network, pages by an OPAQUE token the server hands back,
* cannot know how many records exist until the server says it is done, and
* has a genuine health check (an HTTP round trip). Its sibling
* (jsonl-file-connector.ts) does none of those things.
*
* COMPLIANCE (CLAUDE.md §1): this connector is a plain, self-identifying
* JSON client. It sends a fixed User-Agent, honours the caller's timeout, and
* treats 401/403/429/451 as a STOP signal for that source — the same posture
* services/api/sources/connectors.py's BLOCKED_STATUSES already takes. There
* is no retry-harder path, no proxy rotation, no header spoofing, and adding
* any would be a compliance violation, not a feature.
*
* `fetchImpl` is injectable so tests drive a real request/response cycle
* without a network. That is a seam for TESTS, not a mock fallback: with no
* override it uses global fetch and talks to the configured URL for real.
*/
import {
ConnectorNotConnectedError,
type BackfillRequest,
type Connector,
type ConnectorConfig,
type ConnectorContext,
type ConnectorHealth,
type ConnectorRecord,
type DiscoveryResult,
type ReadRequest,
type ReadResult,
type ValidationResult,
} from "./connector";
import type { IngestionCheckpoint } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
export const HTTP_JSON_CONNECTOR_VERSION = "http-json-connector@1";
/** Statuses that mean "stop asking this way" — never "retry harder". */
const BLOCKED_STATUSES = new Set([401, 403, 429, 451]);
export interface HttpJsonConnectorConfig extends ConnectorConfig {
/** Absolute https:// (or http:// for a local fixture) base URL. */
base_url: string;
/** Path serving records, e.g. "/v1/companies". */
records_path: string;
/** Partition key this endpoint serves. */
partition_key: string;
/** Declared record shape for the partition — the connector does not infer schemas from data. */
schema: RecordSchemaFields;
/** JSON field holding the business key of each record. */
record_key_field: string;
/**
* JSON field holding each record's own cursor value (an id, a sequence, an
* `updated_at`). Optional, but REQUIRED IN PRACTICE for any API that stops
* returning `next_cursor` once a page is exhausted: without it the
* connector has nothing to resume from after reading to the end, and
* resume() would silently restart at the beginning. The conformance suite
* catches exactly that ("read: an exhausted partition reports exhausted"),
* which is how this field came to exist.
*/
cursor_field?: string;
/** Request timeout (ms). Default 15000. */
timeout_ms?: number;
}
type FetchImpl = (url: string, init: RequestInit) => Promise<Response>;
/** Wire shape this connector expects from the upstream endpoint. */
interface UpstreamPage {
records?: Array<Record<string, unknown>>;
next_cursor?: string | null;
}
function isConfig(config: ConnectorConfig): config is HttpJsonConnectorConfig {
return typeof config.base_url === "string" && typeof config.records_path === "string";
}
export class HttpJsonConnector implements Connector {
readonly connector_id = "http_json";
readonly connector_version = HTTP_JSON_CONNECTOR_VERSION;
private config?: HttpJsonConnectorConfig;
private ctx?: ConnectorContext;
private lastCursor = new Map<string, string | undefined>();
constructor(private readonly fetchImpl: FetchImpl = (url, init) => fetch(url, init)) {}
validate(config: ConnectorConfig): ValidationResult {
const errors: string[] = [];
if (typeof config.base_url !== "string" || config.base_url.length === 0) {
errors.push("base_url is required");
} else if (!/^https?:\/\//.test(config.base_url)) {
errors.push("base_url must be an absolute http(s) URL");
}
if (typeof config.records_path !== "string" || !config.records_path.startsWith("/")) {
errors.push("records_path is required and must start with /");
}
if (typeof config.partition_key !== "string" || config.partition_key.length === 0) {
errors.push("partition_key is required");
}
if (typeof config.record_key_field !== "string" || config.record_key_field.length === 0) {
errors.push("record_key_field is required");
}
const schema = config.schema;
if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
errors.push("schema is required and must declare at least one field");
}
return { valid: errors.length === 0, errors };
}
async connect(config: ConnectorConfig, ctx: ConnectorContext): Promise<void> {
const verdict = this.validate(config);
if (!verdict.valid) {
throw new Error(`http_json connector config invalid: ${verdict.errors.join("; ")}`);
}
if (!isConfig(config)) throw new Error("http_json connector config invalid");
this.config = config;
this.ctx = ctx;
}
async discover(): Promise<DiscoveryResult> {
const config = this.requireSession("discover");
return {
partitions: [
{
partition_key: config.partition_key,
name: `${config.base_url}${config.records_path}`,
schema: config.schema,
},
],
// A polled JSON endpoint serves batch and (by repeated polling) stream.
// It is NOT a change feed: it carries no delete events, so "cdc" is not
// declared. Declaring it would be a lie the runner would act on.
modes: ["batch", "stream"],
};
}
async health(): Promise<ConnectorHealth> {
const config = this.requireSession("health");
const started = Date.now();
try {
const res = await this.request(this.url(config.records_path, { limit: "1" }), config);
const latency = Date.now() - started;
if (BLOCKED_STATUSES.has(res.status)) {
return { status: "down", latency_ms: latency, detail: `source signalled a block (HTTP ${res.status})` };
}
if (!res.ok) return { status: "degraded", latency_ms: latency, detail: `HTTP ${res.status}` };
return { status: "up", latency_ms: latency };
} catch (err) {
return {
status: "down",
latency_ms: Date.now() - started,
detail: err instanceof Error ? err.message : "unreachable",
};
}
}
async read(req: ReadRequest): Promise<ReadResult> {
const config = this.requireSession("read");
const query: Record<string, string> = { limit: String(req.limit) };
if (req.cursor !== undefined) query.cursor = req.cursor;
const res = await this.request(this.url(config.records_path, query), config);
if (BLOCKED_STATUSES.has(res.status)) {
throw new Error(`source signalled a block (HTTP ${res.status}) — stop, do not retry harder`);
}
if (!res.ok) throw new Error(`upstream returned HTTP ${res.status}`);
const page = (await res.json()) as UpstreamPage;
const rawRecords = page.records ?? [];
// The contract says limit is a HARD bound; a server that over-delivers is
// truncated here rather than silently widening the caller's page.
const records = rawRecords.slice(0, req.limit).map((row) => this.toRecord(row, config));
const serverCursor = page.next_cursor ?? undefined;
// When the server stops issuing a cursor at the end of a page, fall back
// to the last record's own cursor value so a later resume() starts AFTER
// the data already produced instead of at the beginning.
const trailing = records.length > 0 ? records[records.length - 1].cursor : undefined;
const nextCursor = serverCursor ?? trailing ?? req.cursor;
if (records.length > 0) this.lastCursor.set(req.partition_key, nextCursor);
return {
records,
next_cursor: nextCursor,
// The SERVER's cursor is what says "there is more"; a fallback cursor
// only preserves position, it never claims more data exists.
exhausted: serverCursor === undefined || records.length === 0,
};
}
async checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }> {
this.requireSession("checkpoint");
return { partition_key: partitionKey, cursor: this.lastCursor.get(partitionKey) };
}
async resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult> {
this.requireSession("resume");
return this.read({
partition_key: checkpoint.partition_key,
cursor: checkpoint.cursor,
limit,
});
}
async backfill(req: BackfillRequest): Promise<ReadResult> {
const config = this.requireSession("backfill");
if (!req.from || !req.to) {
throw new Error("backfill requires both `from` and `to` — an unbounded backfill is a full reload, not a backfill");
}
const res = await this.request(
this.url(config.records_path, { from: req.from, to: req.to, limit: String(req.limit) }),
config,
);
if (BLOCKED_STATUSES.has(res.status)) {
throw new Error(`source signalled a block (HTTP ${res.status}) — stop, do not retry harder`);
}
if (!res.ok) throw new Error(`upstream returned HTTP ${res.status}`);
const page = (await res.json()) as UpstreamPage;
const records = (page.records ?? []).slice(0, req.limit).map((row) => this.toRecord(row, config));
return { records, next_cursor: page.next_cursor ?? undefined, exhausted: true };
}
async disconnect(): Promise<void> {
this.config = undefined;
this.ctx = undefined;
this.lastCursor.clear();
}
// --- internals -----------------------------------------------------------
private toRecord(row: Record<string, unknown>, config: HttpJsonConnectorConfig): ConnectorRecord {
const key = row[config.record_key_field];
if (typeof key !== "string" && typeof key !== "number") {
throw new Error(`record is missing string/number key field "${config.record_key_field}"`);
}
let cursor: string | undefined;
if (config.cursor_field) {
const raw = row[config.cursor_field];
if (typeof raw === "string" || typeof raw === "number") cursor = String(raw);
}
return { record_key: String(key), payload: row, operation: "upsert", cursor };
}
private requireSession(op: string): HttpJsonConnectorConfig {
if (!this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
return this.config;
}
private url(path: string, query: Record<string, string>): string {
const config = this.config;
if (!config) throw new ConnectorNotConnectedError(this.connector_id, "url");
const url = new URL(path, config.base_url);
for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
return url.toString();
}
private async request(url: string, config: HttpJsonConnectorConfig): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), config.timeout_ms ?? 15_000);
try {
return await this.fetchImpl(url, {
method: "GET",
signal: controller.signal,
headers: {
Accept: "application/json",
"User-Agent": "0pt-connector/1 (+https://0pt.app; SIAX Technology AB)",
...(this.ctx ? { "X-Correlation-Id": this.ctx.run_id } : {}),
},
});
} finally {
clearTimeout(timer);
}
}
}
+224
View File
@@ -0,0 +1,224 @@
/**
* src/connectors/jsonl-file-connector.ts
* ========================================
* P061 conformance connector #2: a JSONL file drop on local disk.
*
* Heterogeneity vs http-json-connector.ts — these two share nothing but the
* contract:
* - no network, no server, no opaque token; the cursor is a LINE OFFSET the
* connector computes itself,
* - it knows the full record count up front (the file is finite and local),
* so `exhausted` is exact rather than server-reported,
* - health is a filesystem stat, not an HTTP round trip,
* - it serves `cdc`-shaped records: a JSONL line may carry an `_op` field
* ("insert"/"update"/"delete"), so this connector emits real delete
* envelopes with a null payload. The HTTP connector cannot,
* - backfill bounds are line numbers, not timestamps.
*
* That last point is why the conformance suite takes `from`/`to` from a
* fixture: the contract fixes that a backfill is BOUNDED, not what the
* bounds mean. Each connector documents its own bound vocabulary.
*/
import { promises as fs } from "fs";
import path from "path";
import {
ConnectorNotConnectedError,
type BackfillRequest,
type Connector,
type ConnectorConfig,
type ConnectorContext,
type ConnectorHealth,
type ConnectorRecord,
type DiscoveryResult,
type ReadRequest,
type ReadResult,
type ValidationResult,
} from "./connector";
import type { IngestionCheckpoint } from "../types/ingestion";
import type { RecordSchemaFields } from "../schema/record-schema";
export const JSONL_FILE_CONNECTOR_VERSION = "jsonl-file-connector@1";
export interface JsonlFileConnectorConfig extends ConnectorConfig {
/** Absolute path to the .jsonl file. */
file_path: string;
partition_key: string;
schema: RecordSchemaFields;
record_key_field: string;
}
function isConfig(config: ConnectorConfig): config is JsonlFileConnectorConfig {
return typeof config.file_path === "string" && typeof config.partition_key === "string";
}
/** Cursor vocabulary: the decimal count of lines already produced. */
function parseCursor(cursor: string | undefined): number {
if (cursor === undefined) return 0;
const n = Number.parseInt(cursor, 10);
if (!Number.isInteger(n) || n < 0) throw new Error(`invalid cursor "${cursor}" — expected a line offset`);
return n;
}
export class JsonlFileConnector implements Connector {
readonly connector_id = "jsonl_file";
readonly connector_version = JSONL_FILE_CONNECTOR_VERSION;
private config?: JsonlFileConnectorConfig;
private lastCursor = new Map<string, string | undefined>();
validate(config: ConnectorConfig): ValidationResult {
const errors: string[] = [];
if (typeof config.file_path !== "string" || config.file_path.length === 0) {
errors.push("file_path is required");
} else if (!path.isAbsolute(config.file_path)) {
errors.push("file_path must be absolute");
} else if (!config.file_path.endsWith(".jsonl")) {
errors.push("file_path must name a .jsonl file");
}
if (typeof config.partition_key !== "string" || config.partition_key.length === 0) {
errors.push("partition_key is required");
}
if (typeof config.record_key_field !== "string" || config.record_key_field.length === 0) {
errors.push("record_key_field is required");
}
const schema = config.schema;
if (typeof schema !== "object" || schema === null || Object.keys(schema).length === 0) {
errors.push("schema is required and must declare at least one field");
}
return { valid: errors.length === 0, errors };
}
async connect(config: ConnectorConfig, _ctx: ConnectorContext): Promise<void> {
const verdict = this.validate(config);
if (!verdict.valid) {
throw new Error(`jsonl_file connector config invalid: ${verdict.errors.join("; ")}`);
}
if (!isConfig(config)) throw new Error("jsonl_file connector config invalid");
// Fail at connect time, not at first read: a file drop that is not there
// is a connection failure, and the runner must see it as one.
await fs.access(config.file_path);
this.config = config;
}
async discover(): Promise<DiscoveryResult> {
const config = this.requireSession("discover");
return {
partitions: [
{ partition_key: config.partition_key, name: path.basename(config.file_path), schema: config.schema },
],
// A file drop is a batch source; because a line may carry `_op`, it can
// also carry a change log, so cdc is honestly available here.
modes: ["batch", "cdc"],
};
}
async health(): Promise<ConnectorHealth> {
const config = this.requireSession("health");
const started = Date.now();
try {
const stat = await fs.stat(config.file_path);
if (stat.size === 0) {
return { status: "degraded", latency_ms: Date.now() - started, detail: "file is empty" };
}
return { status: "up", latency_ms: Date.now() - started };
} catch (err) {
return {
status: "down",
latency_ms: Date.now() - started,
detail: err instanceof Error ? err.message : "stat failed",
};
}
}
async read(req: ReadRequest): Promise<ReadResult> {
const lines = await this.lines();
const start = parseCursor(req.cursor);
const slice = lines.slice(start, start + req.limit);
const records = slice.map((line, i) => this.toRecord(line, start + i));
const nextOffset = start + slice.length;
const cursor = String(nextOffset);
this.lastCursor.set(req.partition_key, cursor);
return {
records,
next_cursor: cursor,
exhausted: nextOffset >= lines.length,
};
}
async checkpoint(partitionKey: string): Promise<{ partition_key: string; cursor?: string }> {
this.requireSession("checkpoint");
return { partition_key: partitionKey, cursor: this.lastCursor.get(partitionKey) };
}
async resume(checkpoint: IngestionCheckpoint, limit: number): Promise<ReadResult> {
this.requireSession("resume");
return this.read({ partition_key: checkpoint.partition_key, cursor: checkpoint.cursor, limit });
}
/** Bounds are LINE NUMBERS: `from` inclusive, `to` exclusive. */
async backfill(req: BackfillRequest): Promise<ReadResult> {
this.requireSession("backfill");
if (!req.from || !req.to) {
throw new Error("backfill requires both `from` and `to` — an unbounded backfill is a full reload, not a backfill");
}
const from = parseCursor(req.from);
const to = parseCursor(req.to);
if (to <= from) throw new Error(`backfill range is empty or inverted (from=${from}, to=${to})`);
const lines = await this.lines();
const slice = lines.slice(from, Math.min(to, from + req.limit));
return {
records: slice.map((line, i) => this.toRecord(line, from + i)),
next_cursor: String(from + slice.length),
exhausted: true,
};
}
async disconnect(): Promise<void> {
this.config = undefined;
this.lastCursor.clear();
}
// --- internals -----------------------------------------------------------
private requireSession(op: string): JsonlFileConnectorConfig {
if (!this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
return this.config;
}
private async lines(): Promise<string[]> {
const config = this.requireSession("read");
const raw = await fs.readFile(config.file_path, "utf8");
return raw.split("\n").filter((l) => l.trim().length > 0);
}
private toRecord(line: string, lineNumber: number): ConnectorRecord {
const config = this.requireSession("read");
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(line) as Record<string, unknown>;
} catch {
throw new Error(`line ${lineNumber + 1} is not valid JSON`);
}
const key = parsed[config.record_key_field];
if (typeof key !== "string" && typeof key !== "number") {
throw new Error(`line ${lineNumber + 1} is missing key field "${config.record_key_field}"`);
}
const op = parsed._op;
const operation =
op === "insert" || op === "update" || op === "delete" ? op : ("upsert" as const);
const occurredAt = typeof parsed._occurred_at === "string" ? parsed._occurred_at : undefined;
// `_op`/`_occurred_at` are envelope metadata, not payload fields — leaving
// them in the payload would make every record fail schema conformance for
// an "unregistered field".
const payload: Record<string, unknown> = { ...parsed };
delete payload._op;
delete payload._occurred_at;
return {
record_key: String(key),
payload: operation === "delete" ? null : payload,
operation,
occurred_at: occurredAt,
cursor: String(lineNumber + 1),
};
}
}
+10
View File
@@ -23,6 +23,16 @@
* GENERIC means GENERIC: no person-matching logic, no Ratsit/PII pipelines —
* records are opaque field maps supplied by the calling product under its
* own legal basis; this module implements comparison mechanics only.
*
* P065 STATUS — THIS IS THE CANONICAL ENGINE, AND IT IS NOT YET THE ONLY ONE.
* `services/api/workers/resolve.py` is a second, simplified ER engine (fuzzy
* threshold, auto-merge, no hard rules, no review band) that
* `services/api/workers/pipeline.py` still calls. P065's DoD ("no second
* simplified duplicated production engine remains") is therefore NOT met.
* See that file's header for why it was not rewritten blind in the
* P060-P068 pass and STATUS.md for the removal plan. The ingestion plane
* added in that pass (src/ingestion/*) deliberately does no ER of its own —
* it stops at the sink, so it adds no THIRD engine.
*/
import crypto from "crypto";
import { SiaxError } from "../platform/errors";
+87
View File
@@ -0,0 +1,87 @@
/**
* src/ingestion/envelope.ts
* ==========================
* P062: the one place a ConnectorRecord becomes an IngestionEnvelope. Every
* connector, every mode, one function — that is what "normalize all ingestion
* to a common envelope" means operationally.
*
* `hashPayload` is the stable content hash the idempotency ledger (P068) and
* the deterministic `envelope_id` are both built on. Key order must not
* change the hash — two connectors reading the same record can serialize the
* same object with different key order — so keys are sorted recursively.
* Undefined values are dropped (JSON has no undefined); null is kept, because
* "field explicitly null" is different data from "field absent".
*/
import crypto from "crypto";
import type { ConnectorRecord } from "../connectors/connector";
import type { EnvelopeOperation, IngestionEnvelope, IngestionMode } from "../types/ingestion";
/** Recursively key-sorted JSON — stable across key insertion order. */
export function stableStringify(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
if (typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
/** Content hash of an envelope payload. A delete (null payload) hashes as "deleted". */
export function hashPayload(payload: Record<string, unknown> | null): string {
if (payload === null) return "sha256:deleted";
return `sha256:${crypto.createHash("sha256").update(stableStringify(payload)).digest("hex")}`;
}
export interface BuildEnvelopeInput {
record: ConnectorRecord;
source_id: string;
tenant_id: string;
project_id: string;
mode: IngestionMode;
partition_key: string;
schema_version: number;
sequence: number;
connector_id: string;
connector_version: string;
run_id: string;
/** Cursor covering this record, when the connector reports one. */
cursor?: string;
now?: string;
}
export function buildEnvelope(input: BuildEnvelopeInput): IngestionEnvelope {
const operation: EnvelopeOperation = input.record.operation ?? "upsert";
const payload = operation === "delete" ? null : input.record.payload;
const contentHash = hashPayload(payload);
return {
// Deterministic: the same record with the same content re-read after a
// crash produces the same envelope_id, so a downstream sink that dedups
// by id sees a retry, not a new record.
envelope_id: `env_${crypto
.createHash("sha256")
.update(`${input.source_id}|${input.partition_key}|${input.record.record_key}|${contentHash}`)
.digest("hex")
.slice(0, 32)}`,
source_id: input.source_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
mode: input.mode,
operation,
partition_key: input.partition_key,
record_key: input.record.record_key,
schema_version: input.schema_version,
sequence: input.sequence,
occurred_at: input.record.occurred_at,
ingested_at: input.now ?? new Date().toISOString(),
payload,
provenance: {
connector_id: input.connector_id,
connector_version: input.connector_version,
run_id: input.run_id,
cursor: input.cursor ?? input.record.cursor,
},
};
}
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
/**
* src/lineage/lineage-edge.ts
* ============================
* P067: the flattened, QUERYABLE form of an OpenLineage run event.
*
* LineageEmitter (src/lineage/lineage-emitter.ts) already emits spec-shaped
* run events to AUD0, and AUD0 remains the SYSTEM OF RECORD for them. But
* "emitted to AUD0" is not "answerable from 0pt": nothing in this repo could
* answer "which sources fed dataset ds_x?" without asking another product.
* These edges are 0pt's own projection — one row per (run, input, output)
* pair — written in the same call that emits, so the question is answerable
* locally and joins back to AUD0 by `run_id`.
*
* The projection is deliberately LOSSY (facets are not stored, only the
* canonical SIAX ref) — it is an index, not a second source of truth.
*/
export interface LineageEdge {
/** Deterministic sha256 of (run_id, input, output) — a re-emitted idempotent run does not duplicate edges. */
edge_id: string;
tenant_id: string;
run_id: string;
capability_id: string;
input_namespace: string;
input_name: string;
input_ref?: string;
output_namespace: string;
output_name: string;
output_ref?: string;
event_time: string;
correlation_id?: string;
}
/** Query one direction of the graph. Exactly one of the two selectors is required. */
export interface LineageQuery {
tenant_id: string;
/** Everything that fed this output (upstream). */
output_name?: string;
/** Everything this input produced (downstream). */
input_name?: string;
limit?: number;
}
+121
View File
@@ -0,0 +1,121 @@
/**
* src/lineage/lineage-store.ts
* =============================
* P067 DoD: "source -> output lineage is QUERYABLE."
*
* LineageEmitter already emits OpenLineage run events to AUD0 and that does
* not change — AUD0 stays the system of record. This class adds the missing
* half: it flattens the same run event into (input, output) edges, persists
* them, and answers both directions of the question.
*
* `RecordingLineageEmitter` is the composition point: it wraps the existing
* emitter so every existing caller (QualityService, DatasetVersionService,
* the ingestion runner) gets the local projection for free, without any of
* them learning about a second store. Emission to AUD0 keeps its existing
* never-throw contract; a projection write failure is likewise reported, not
* thrown, because lineage is evidence of work that already happened.
*/
import crypto from "crypto";
import type { IngestionRepository } from "../repositories/ingestion-repository";
import type { LineageEdge, LineageQuery } from "./lineage-edge";
import type { LineageEmitInput, LineageEmitResult, LineageEmitter } from "./lineage-emitter";
import type { OpenLineageRunEvent } from "./openlineage";
/** Deterministic edge id: the same run re-emitted produces the same edges. */
export function lineageEdgeId(runId: string, input: string, output: string): string {
return `led_${crypto.createHash("sha256").update(`${runId}|${input}|${output}`).digest("hex").slice(0, 32)}`;
}
function refOf(facets: Record<string, unknown> | undefined): string | undefined {
const facet = facets?.siaxResourceRef as { ref?: string } | undefined;
return typeof facet?.ref === "string" ? facet.ref : undefined;
}
/**
* Flatten one OpenLineage run event into edges. A run with N inputs and M
* outputs yields N*M edges; a run with no inputs or no outputs yields none
* (there is no edge to draw), which is why the runner always emits both.
*/
export function edgesFromRunEvent(
event: OpenLineageRunEvent,
tenantId: string,
correlationId?: string,
): LineageEdge[] {
const edges: LineageEdge[] = [];
for (const input of event.inputs ?? []) {
for (const output of event.outputs ?? []) {
edges.push({
edge_id: lineageEdgeId(event.run.runId, `${input.namespace}/${input.name}`, `${output.namespace}/${output.name}`),
tenant_id: tenantId,
run_id: event.run.runId,
capability_id: event.job.name,
input_namespace: input.namespace,
input_name: input.name,
input_ref: refOf(input.facets),
output_namespace: output.namespace,
output_name: output.name,
output_ref: refOf(output.facets),
event_time: event.eventTime,
correlation_id: correlationId,
});
}
}
return edges;
}
export class LineageStore {
constructor(private readonly repo: IngestionRepository) {}
async record(event: OpenLineageRunEvent, tenantId: string, correlationId?: string): Promise<number> {
const edges = edgesFromRunEvent(event, tenantId, correlationId);
if (edges.length > 0) await this.repo.appendLineageEdges(edges);
return edges.length;
}
/** Everything that fed `outputName`, newest first. */
async upstreamOf(tenantId: string, outputName: string, limit?: number): Promise<LineageEdge[]> {
return this.repo.queryLineage({ tenant_id: tenantId, output_name: outputName, limit });
}
/** Everything `inputName` produced, newest first. */
async downstreamOf(tenantId: string, inputName: string, limit?: number): Promise<LineageEdge[]> {
return this.repo.queryLineage({ tenant_id: tenantId, input_name: inputName, limit });
}
async query(query: LineageQuery): Promise<LineageEdge[]> {
return this.repo.queryLineage(query);
}
}
/**
* A LineageEmitter that also writes the local projection. Drop-in for the
* existing emitter: same `emit` signature, same never-throw contract.
*/
export class RecordingLineageEmitter {
constructor(
private readonly inner: LineageEmitter,
private readonly store: LineageStore,
) {}
buildRunEvent(input: LineageEmitInput): OpenLineageRunEvent {
return this.inner.buildRunEvent(input);
}
async emit(input: LineageEmitInput): Promise<LineageEmitResult & { projected: number }> {
const event = this.inner.buildRunEvent(input);
const result = await this.inner.emit(input);
let projected = 0;
try {
projected = await this.store.record(event, input.tenant_id, input.correlation_id);
} catch (err) {
return {
...result,
projected: 0,
warning: [result.warning, `lineage projection write failed: ${err instanceof Error ? err.message : String(err)}`]
.filter(Boolean)
.join("; "),
};
}
return { ...result, projected };
}
}
+129
View File
@@ -0,0 +1,129 @@
/**
* src/quality/quality-policy.ts
* ==============================
* P064: the DECLARED enforcement policy — what happens to a record that fails
* its quality rules — and the gate that applies it on the ingestion path.
*
* WHAT EXISTED BEFORE (and is reused, not rebuilt): QualityService already
* owns the rule registry, runs, results, issues and scores, and
* ExpectationEngine already executes the Great Expectations core subset. What
* neither of them had was a CONSEQUENCE: a failing rule produced an ISSUE for
* a human, and the data flowed on regardless. That is the gap this closes.
* This module deliberately does NOT re-implement rule storage or execution —
* it composes ExpectationEngine and adds the decision.
*
* Three declared actions, and nothing implicit:
* - `block` — the whole page fails; the checkpoint is NOT advanced, so
* the run stops on the bad data instead of stepping over it.
* - `quarantine` — the failing envelopes are persisted to durable quarantine
* and excluded from the output; clean envelopes continue and
* the checkpoint advances past all of them.
* - `warn` — everything continues; violations are counted and reported.
*
* There is no default. A source with no policy gets `block` from the runner
* only if a policy was supplied; with no policy at all the runner skips the
* gate and SAYS SO in the run report (`quality_policy: "none_declared"`) —
* an undeclared policy must never look like a passed one.
*/
import { ExpectationEngine } from "./expectation-engine";
import type { QualityExpectation } from "./quality-types";
import type { IngestionEnvelope } from "../types/ingestion";
export type QualityEnforcementAction = "block" | "quarantine" | "warn";
export interface QualityEnforcementPolicy {
source_id: string;
tenant_id: string;
/** Rules applied per record. Expectations are evaluated against a one-row table. */
expectations: QualityExpectation[];
on_violation: QualityEnforcementAction;
}
export interface EnvelopeViolation {
expectation_type: string;
detail: string;
}
export interface QualityGateResult {
/** Envelopes that may proceed downstream. */
accepted: IngestionEnvelope[];
/** Envelopes routed to quarantine (only under `quarantine`). */
quarantined: Array<{ envelope: IngestionEnvelope; violations: EnvelopeViolation[] }>;
/** Every violation seen, including under `warn` where nothing was withheld. */
violations: Array<{ record_key: string; violations: EnvelopeViolation[] }>;
/** True when `block` fired: the caller must NOT advance the checkpoint. */
blocked: boolean;
action: QualityEnforcementAction;
}
export class QualityGate {
constructor(private readonly engine: ExpectationEngine = new ExpectationEngine()) {}
/**
* Evaluate one page of envelopes against the policy.
*
* Delete envelopes (payload null) are passed through untouched: a CDC delete
* carries no columns to check, and failing it against a column expectation
* would quarantine the very deletions a source is asking us to honour.
*/
evaluate(envelopes: IngestionEnvelope[], policy: QualityEnforcementPolicy): QualityGateResult {
const accepted: IngestionEnvelope[] = [];
const quarantined: QualityGateResult["quarantined"] = [];
const allViolations: QualityGateResult["violations"] = [];
for (const envelope of envelopes) {
if (envelope.payload === null) {
accepted.push(envelope);
continue;
}
const violations = this.violationsFor(envelope.payload, policy.expectations);
if (violations.length === 0) {
accepted.push(envelope);
continue;
}
allViolations.push({ record_key: envelope.record_key, violations });
if (policy.on_violation === "quarantine") {
quarantined.push({ envelope, violations });
} else if (policy.on_violation === "warn") {
accepted.push(envelope);
}
// `block`: neither accepted nor quarantined — the caller stops.
}
const blocked = policy.on_violation === "block" && allViolations.length > 0;
return {
accepted: blocked ? [] : accepted,
quarantined,
violations: allViolations,
blocked,
action: policy.on_violation,
};
}
private violationsFor(
payload: Record<string, unknown>,
expectations: QualityExpectation[],
): EnvelopeViolation[] {
const violations: EnvelopeViolation[] = [];
for (const expectation of expectations) {
if (!this.engine.supports(expectation.expectation_type)) {
// An expectation this engine cannot execute is a VIOLATION of the
// policy's executability, not a silent pass. The record is treated as
// failing so an unrunnable rule can never look like a satisfied one.
violations.push({
expectation_type: expectation.expectation_type,
detail: `expectation is not executable by the local engine; delegate it to the GE backend before declaring it in an enforcement policy`,
});
continue;
}
const outcome = this.engine.execute(expectation, [payload]);
if (!outcome.success) {
violations.push({
expectation_type: expectation.expectation_type,
detail: `failed on column "${String(expectation.kwargs.column ?? "<table>")}" (${outcome.unexpected_count}/${outcome.evaluated_count} unexpected)`,
});
}
}
return violations;
}
}
@@ -0,0 +1,120 @@
/**
* src/repositories/in-memory-ingestion-repository.ts
* ====================================================
* Non-production implementation of IngestionRepository (hermetic tests, local
* dev). Semantics are kept IDENTICAL to the Postgres implementation on every
* point the runner depends on:
* - checkpoints are upserted per (source, partition),
* - ledger verdicts are new/changed/duplicate against the LAST accepted
* payload hash for the key,
* - quarantine is append-only, newest-first on read,
* - schemas are keyed by (source, version) and "latest" means highest version,
* - lineage edges are deduplicated by edge_id.
*
* Any divergence between the two implementations is a bug in one of them;
* tests/p0/ingestion-repository-parity.test.ts is what keeps them honest for
* the in-memory side, and tests/p0/ingestion-plane-postgres.realinfra.test.ts
* runs the same expectations against real Postgres.
*/
import type { LineageEdge, LineageQuery } from "../lineage/lineage-edge";
import type { RecordSchema } from "../schema/record-schema";
import type { IngestionCheckpoint, LedgerDecision, QuarantineRecord } from "../types/ingestion";
import type { IngestionRepository, LedgerEntry } from "./ingestion-repository";
function checkpointKey(sourceId: string, partitionKey: string): string {
return `${sourceId}|${partitionKey}`;
}
export class InMemoryIngestionRepository implements IngestionRepository {
private readonly checkpoints = new Map<string, IngestionCheckpoint>();
/** source_id -> record_key -> last accepted payload hash. */
private readonly ledger = new Map<string, Map<string, string>>();
private readonly quarantined = new Map<string, QuarantineRecord[]>();
private readonly schemas = new Map<string, RecordSchema[]>();
private readonly lineage = new Map<string, LineageEdge>();
async getCheckpoint(sourceId: string, partitionKey: string): Promise<IngestionCheckpoint | undefined> {
return this.checkpoints.get(checkpointKey(sourceId, partitionKey));
}
async commitCheckpoint(checkpoint: IngestionCheckpoint): Promise<void> {
this.checkpoints.set(checkpointKey(checkpoint.source_id, checkpoint.partition_key), { ...checkpoint });
}
async listCheckpoints(sourceId: string): Promise<IngestionCheckpoint[]> {
return [...this.checkpoints.values()]
.filter((c) => c.source_id === sourceId)
.sort((a, b) => a.partition_key.localeCompare(b.partition_key));
}
async peekDeliveries(sourceId: string, entries: LedgerEntry[]): Promise<LedgerDecision[]> {
const keys = this.ledger.get(sourceId);
return entries.map((entry) => {
const prior = keys?.get(entry.record_key);
return {
record_key: entry.record_key,
verdict: prior === undefined ? "new" : prior === entry.payload_hash ? "duplicate" : "changed",
} as LedgerDecision;
});
}
async commitDeliveries(sourceId: string, _tenantId: string, entries: LedgerEntry[]): Promise<void> {
let keys = this.ledger.get(sourceId);
if (!keys) {
keys = new Map<string, string>();
this.ledger.set(sourceId, keys);
}
for (const entry of entries) keys.set(entry.record_key, entry.payload_hash);
}
async countLedger(sourceId: string): Promise<number> {
return this.ledger.get(sourceId)?.size ?? 0;
}
async quarantine(record: QuarantineRecord): Promise<void> {
const list = this.quarantined.get(record.source_id) ?? [];
list.push(record);
this.quarantined.set(record.source_id, list);
}
async listQuarantine(sourceId: string, limit = 100): Promise<QuarantineRecord[]> {
const list = this.quarantined.get(sourceId) ?? [];
return [...list].reverse().slice(0, limit);
}
async putSchema(schema: RecordSchema): Promise<void> {
const list = this.schemas.get(schema.source_id) ?? [];
const existing = list.findIndex((s) => s.schema_version === schema.schema_version);
if (existing >= 0) list[existing] = { ...schema };
else list.push({ ...schema });
list.sort((a, b) => a.schema_version - b.schema_version);
this.schemas.set(schema.source_id, list);
}
async getSchema(sourceId: string, version: number): Promise<RecordSchema | undefined> {
return this.schemas.get(sourceId)?.find((s) => s.schema_version === version);
}
async getLatestSchema(sourceId: string): Promise<RecordSchema | undefined> {
const list = this.schemas.get(sourceId);
return list && list.length > 0 ? list[list.length - 1] : undefined;
}
async listSchemas(sourceId: string): Promise<RecordSchema[]> {
return [...(this.schemas.get(sourceId) ?? [])];
}
async appendLineageEdges(edges: LineageEdge[]): Promise<void> {
for (const edge of edges) this.lineage.set(edge.edge_id, { ...edge });
}
async queryLineage(query: LineageQuery): Promise<LineageEdge[]> {
const limit = query.limit ?? 200;
return [...this.lineage.values()]
.filter((e) => e.tenant_id === query.tenant_id)
.filter((e) => (query.output_name ? e.output_name === query.output_name : true))
.filter((e) => (query.input_name ? e.input_name === query.input_name : true))
.sort((a, b) => b.event_time.localeCompare(a.event_time))
.slice(0, limit);
}
}
@@ -10,7 +10,13 @@
* - 1]` for "most recent" and scanned backward for consecutive failures --
* callers now get the same data pre-ordered instead).
*/
import type { SourceHealthCheck, SourceProvenance, SourceRights } from "../types/source-registry";
import type {
SourceAuthorization,
SourceHealthCheck,
SourceProvenance,
SourceRights,
SourceSchedule,
} from "../types/source-registry";
import type { SourceRegistryRepository } from "./source-registry-repository";
export class InMemorySourceRegistryRepository implements SourceRegistryRepository {
@@ -18,6 +24,8 @@ export class InMemorySourceRegistryRepository implements SourceRegistryRepositor
private readonly provenance = new Map<string, SourceProvenance>();
private readonly healthChecks = new Map<string, SourceHealthCheck[]>();
private readonly lastSuccess = new Map<string, string>();
private readonly authorizations = new Map<string, SourceAuthorization>();
private readonly schedules = new Map<string, SourceSchedule>();
async setRights(rights: SourceRights): Promise<void> {
this.rights.set(rights.source_id, rights);
@@ -43,6 +51,22 @@ export class InMemorySourceRegistryRepository implements SourceRegistryRepositor
return this.lastSuccess.get(sourceId);
}
async setAuthorization(auth: SourceAuthorization): Promise<void> {
this.authorizations.set(auth.source_id, auth);
}
async getAuthorization(sourceId: string): Promise<SourceAuthorization | undefined> {
return this.authorizations.get(sourceId);
}
async setSchedule(schedule: SourceSchedule): Promise<void> {
this.schedules.set(schedule.source_id, schedule);
}
async getSchedule(sourceId: string): Promise<SourceSchedule | undefined> {
return this.schedules.get(sourceId);
}
async appendHealthCheck(check: SourceHealthCheck): Promise<void> {
const list = this.healthChecks.get(check.source_id) ?? [];
list.push(check);
@@ -27,6 +27,7 @@ interface SourceRecord {
created_at: string;
updated_at: string | null;
created_by: string | null;
owner_id: string | null;
}
export class InMemorySourceRepository implements SourceRepository {
@@ -50,11 +51,16 @@ export class InMemorySourceRepository implements SourceRepository {
adapter_id: input.adapter_id ?? null,
access: input.access ?? null,
description: input.description ?? null,
status: input.status ?? "active",
// P060: "pending", not "active". A source with no rights, no provenance
// and no authorization used to be live the instant it was registered;
// reaching "active" now goes through
// SourceRegistryService.activateSource's classification gate.
status: input.status ?? "pending",
correlation_id: input.correlation_id ?? null,
created_at: now,
updated_at: null,
created_by: input.created_by ?? null,
owner_id: input.owner_id ?? null,
};
this.sources.set(record.source_id, record);
return toSource(record);
@@ -66,6 +72,14 @@ export class InMemorySourceRepository implements SourceRepository {
return toSource(record);
}
async updateStatus(sourceId: string, status: SourceStatus): Promise<Source> {
const record = this.sources.get(sourceId);
if (!record) throw new Error(`Source ${sourceId} not found`);
record.status = status;
record.updated_at = new Date().toISOString();
return toSource(record);
}
async list(filter?: SourceListFilter): Promise<Source[]> {
let results = Array.from(this.sources.values());
if (filter?.tenant_id) results = results.filter((r) => r.tenant_id === filter.tenant_id);
@@ -91,5 +105,6 @@ function toSource(r: SourceRecord): Source {
created_at: r.created_at,
updated_at: r.updated_at ?? undefined,
created_by: r.created_by ?? undefined,
owner_id: r.owner_id ?? undefined,
};
}
+91
View File
@@ -0,0 +1,91 @@
/**
* src/repositories/ingestion-repository.ts
* ==========================================
* The storage seam for the P060-P068 ingestion plane: checkpoints (P060/P062),
* the idempotency ledger (P068), quarantine (P064), the schema registry
* (P060/P063) and the queryable lineage projection (P067).
*
* WHY ONE INTERFACE AND NOT FIVE. These five tables are written by ONE
* caller — IngestionRunner — inside one run, and their correctness is
* relative to each other (a checkpoint that advanced past records the ledger
* never accepted is a silent gap; a quarantined record whose checkpoint moved
* on is a silently dropped record). Splitting them into five factories would
* let a future caller wire four of them to Postgres and one to memory and
* still typecheck, which is exactly the failure this plane must not have.
* They are chosen once, together, by one `resolveStoreMode` call.
*
* Same production posture as every other 0pt store: `resolveStoreMode` fails
* hard in production with no DATABASE_URL rather than silently serving Maps
* (src/platform/dependency-mode.ts, Master-DoD §3/§10).
*/
import { resolveStoreMode } from "../platform/dependency-mode";
import type { LineageEdge, LineageQuery } from "../lineage/lineage-edge";
import type { RecordSchema } from "../schema/record-schema";
import type { IngestionCheckpoint, LedgerDecision, QuarantineRecord } from "../types/ingestion";
import { getRepositorySql, repositoryDatabaseUrl } from "./db";
import { InMemoryIngestionRepository } from "./in-memory-ingestion-repository";
import { PostgresIngestionRepository } from "./postgres-ingestion-repository";
/** One record offered to the ledger. */
export interface LedgerEntry {
record_key: string;
/** Stable hash of the payload — see hashPayload() in src/ingestion/ingestion-ledger.ts. */
payload_hash: string;
}
export interface IngestionRepository {
// --- checkpoints (P060 registry field, P062 durable resume) --------------
getCheckpoint(sourceId: string, partitionKey: string): Promise<IngestionCheckpoint | undefined>;
commitCheckpoint(checkpoint: IngestionCheckpoint): Promise<void>;
listCheckpoints(sourceId: string): Promise<IngestionCheckpoint[]>;
// --- idempotency ledger (P068) ------------------------------------------
/**
* READ-ONLY verdicts, in input order:
* "new" — this record_key has never been accepted for this source,
* "changed" — it has, but with different content (a real update),
* "duplicate" — it has, with byte-identical content (a replay).
*
* Deliberately separate from {@link commitDeliveries}. An earlier draft of
* this interface combined them into one atomic check-and-record, which was
* WRONG in the way that matters: the runner has to consult the ledger
* BEFORE the sink (to filter replays) and commit AFTER it (so a crash
* between the two re-delivers rather than loses). A combined call marked a
* record "delivered" that the sink never received, and the resumed run then
* skipped it as a duplicate — permanent, silent data loss. That is not a
* hypothetical: tests/p0/ingestion-runner.test.ts caught it, and the
* "resumes with NO gap" case is what pins the fix.
*/
peekDeliveries(sourceId: string, entries: LedgerEntry[]): Promise<LedgerDecision[]>;
/**
* Record that these records were successfully delivered. Called only after
* the sink resolved. Idempotent: re-committing the same entry bumps the
* delivery count and leaves the verdict unchanged.
*/
commitDeliveries(sourceId: string, tenantId: string, entries: LedgerEntry[]): Promise<void>;
countLedger(sourceId: string): Promise<number>;
// --- quarantine (P064) --------------------------------------------------
quarantine(record: QuarantineRecord): Promise<void>;
listQuarantine(sourceId: string, limit?: number): Promise<QuarantineRecord[]>;
// --- schema registry (P060 registry field, P063 evolution) --------------
putSchema(schema: RecordSchema): Promise<void>;
getSchema(sourceId: string, version: number): Promise<RecordSchema | undefined>;
getLatestSchema(sourceId: string): Promise<RecordSchema | undefined>;
listSchemas(sourceId: string): Promise<RecordSchema[]>;
// --- lineage projection (P067) ------------------------------------------
appendLineageEdges(edges: LineageEdge[]): Promise<void>;
queryLineage(query: LineageQuery): Promise<LineageEdge[]>;
}
export function createIngestionRepository(databaseUrl?: string): IngestionRepository {
const mode = resolveStoreMode("0pt.ingestion", databaseUrl ?? repositoryDatabaseUrl());
if (mode.mode === "postgres") {
return new PostgresIngestionRepository(getRepositorySql(mode.url));
}
return new InMemoryIngestionRepository();
}
@@ -0,0 +1,308 @@
/**
* src/repositories/postgres-ingestion-repository.ts
* ==================================================
* Real Postgres backing for IngestionRepository (sql/007_ingestion_plane.sql).
*
* THE LEDGER IS THE INTERESTING ONE (P068), and it is deliberately SPLIT:
* `peekDeliveries` reads verdicts, `commitDeliveries` records them. The
* runner peeks before the sink and commits after it, so a crash in between
* re-delivers on resume instead of losing the record. An earlier version of
* this file combined the two into one atomic check-and-record statement; that
* was measurably wrong (see the interface's doc comment) and the crash/resume
* test in tests/p0/ingestion-runner.test.ts is what proved it.
*
* KNOWN LIMIT, stated rather than papered over: the split means two runs on
* the SAME (source_id, partition) can both peek "new" and both emit. The
* delivery guarantee is therefore AT-LEAST-ONCE, which is what the
* deterministic `envelope_id` (src/ingestion/envelope.ts) exists to make
* survivable downstream. Exactly-once across concurrent runs needs a run lock
* per (source, partition); there is none yet. That is a real open gap, not a
* solved one — do not describe this plane as exactly-once.
*/
import type { LineageEdge, LineageQuery } from "../lineage/lineage-edge";
import type {
CompatibilityPolicy,
RecordSchema,
RecordSchemaFields,
} from "../schema/record-schema";
import type {
IngestionCheckpoint,
IngestionEnvelope,
LedgerDecision,
QuarantineRecord,
} from "../types/ingestion";
import type { RepositorySql } from "./db";
import type { IngestionRepository, LedgerEntry } from "./ingestion-repository";
/** postgres.js's `sql.json()` parameter type, named locally so the two JSONB columns can be passed without importing postgres' internals. */
type JsonValue = Parameters<RepositorySql["json"]>[0];
function toIso(v: string | Date): string {
return v instanceof Date ? v.toISOString() : v;
}
interface CheckpointRow {
source_id: string;
tenant_id: string;
partition_key: string;
cursor: string | null;
sequence: string | number;
records_committed: string | number;
committed_at: string | Date;
}
function toCheckpoint(r: CheckpointRow): IngestionCheckpoint {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
partition_key: r.partition_key,
cursor: r.cursor ?? undefined,
sequence: Number(r.sequence),
records_committed: Number(r.records_committed),
committed_at: toIso(r.committed_at),
};
}
export class PostgresIngestionRepository implements IngestionRepository {
constructor(private readonly sql: RepositorySql) {}
// --- checkpoints ---------------------------------------------------------
async getCheckpoint(sourceId: string, partitionKey: string): Promise<IngestionCheckpoint | undefined> {
const rows = await this.sql<CheckpointRow[]>`
SELECT source_id, tenant_id, partition_key, cursor, sequence, records_committed, committed_at
FROM opt_ingestion_checkpoints
WHERE source_id = ${sourceId} AND partition_key = ${partitionKey}
LIMIT 1`;
return rows[0] ? toCheckpoint(rows[0]) : undefined;
}
async commitCheckpoint(cp: IngestionCheckpoint): Promise<void> {
await this.sql`
INSERT INTO opt_ingestion_checkpoints
(source_id, partition_key, tenant_id, cursor, sequence, records_committed, committed_at)
VALUES
(${cp.source_id}, ${cp.partition_key}, ${cp.tenant_id}, ${cp.cursor ?? null},
${cp.sequence}, ${cp.records_committed}, ${cp.committed_at})
ON CONFLICT (source_id, partition_key) DO UPDATE
SET cursor = EXCLUDED.cursor,
sequence = EXCLUDED.sequence,
records_committed = EXCLUDED.records_committed,
committed_at = EXCLUDED.committed_at,
tenant_id = EXCLUDED.tenant_id`;
}
async listCheckpoints(sourceId: string): Promise<IngestionCheckpoint[]> {
const rows = await this.sql<CheckpointRow[]>`
SELECT source_id, tenant_id, partition_key, cursor, sequence, records_committed, committed_at
FROM opt_ingestion_checkpoints
WHERE source_id = ${sourceId}
ORDER BY partition_key ASC`;
return rows.map(toCheckpoint);
}
// --- ledger --------------------------------------------------------------
async peekDeliveries(sourceId: string, entries: LedgerEntry[]): Promise<LedgerDecision[]> {
if (entries.length === 0) return [];
const keys = entries.map((e) => e.record_key);
const rows = await this.sql<{ record_key: string; payload_hash: string }[]>`
SELECT record_key, payload_hash FROM opt_ingestion_ledger
WHERE source_id = ${sourceId} AND record_key = ANY(${this.sql.array(keys)})`;
const priorByKey = new Map(rows.map((r) => [r.record_key, r.payload_hash]));
return entries.map((entry) => {
const prior = priorByKey.get(entry.record_key);
return {
record_key: entry.record_key,
verdict: prior === undefined ? "new" : prior === entry.payload_hash ? "duplicate" : "changed",
} as LedgerDecision;
});
}
async commitDeliveries(sourceId: string, tenantId: string, entries: LedgerEntry[]): Promise<void> {
for (const entry of entries) {
await this.sql`
INSERT INTO opt_ingestion_ledger (source_id, record_key, tenant_id, payload_hash)
VALUES (${sourceId}, ${entry.record_key}, ${tenantId}, ${entry.payload_hash})
ON CONFLICT (source_id, record_key) DO UPDATE
SET last_seen_at = now(),
delivery_count = opt_ingestion_ledger.delivery_count + 1,
payload_hash = EXCLUDED.payload_hash`;
}
}
async countLedger(sourceId: string): Promise<number> {
const rows = await this.sql<{ n: string }[]>`
SELECT count(*)::text AS n FROM opt_ingestion_ledger WHERE source_id = ${sourceId}`;
return Number(rows[0]?.n ?? 0);
}
// --- quarantine ----------------------------------------------------------
async quarantine(record: QuarantineRecord): Promise<void> {
await this.sql`
INSERT INTO opt_quality_quarantine
(quarantine_id, source_id, tenant_id, run_id, record_key, violations, envelope, quarantined_at)
VALUES
(${record.quarantine_id}, ${record.source_id}, ${record.tenant_id}, ${record.run_id},
${record.record_key}, ${this.sql.json(record.violations as unknown as JsonValue)},
${this.sql.json(record.envelope as unknown as JsonValue)},
${record.quarantined_at})
ON CONFLICT (quarantine_id) DO NOTHING`;
}
async listQuarantine(sourceId: string, limit = 100): Promise<QuarantineRecord[]> {
const rows = await this.sql<
{
quarantine_id: string;
source_id: string;
tenant_id: string;
run_id: string;
record_key: string;
violations: QuarantineRecord["violations"];
envelope: IngestionEnvelope;
quarantined_at: string | Date;
}[]
>`
SELECT quarantine_id, source_id, tenant_id, run_id, record_key, violations, envelope, quarantined_at
FROM opt_quality_quarantine
WHERE source_id = ${sourceId}
ORDER BY quarantined_at DESC, quarantine_id DESC
LIMIT ${limit}`;
return rows.map((r) => ({
quarantine_id: r.quarantine_id,
source_id: r.source_id,
tenant_id: r.tenant_id,
run_id: r.run_id,
record_key: r.record_key,
violations: r.violations,
envelope: r.envelope,
quarantined_at: toIso(r.quarantined_at),
}));
}
// --- schema registry -----------------------------------------------------
async putSchema(schema: RecordSchema): Promise<void> {
await this.sql`
INSERT INTO opt_source_schemas
(source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by)
VALUES
(${schema.source_id}, ${schema.schema_version}, ${schema.tenant_id},
${this.sql.json(schema.fields as unknown as JsonValue)}, ${schema.compatibility},
${schema.registered_at}, ${schema.registered_by ?? null})
ON CONFLICT (source_id, schema_version) DO UPDATE
SET fields = EXCLUDED.fields,
compatibility = EXCLUDED.compatibility,
registered_at = EXCLUDED.registered_at,
registered_by = EXCLUDED.registered_by`;
}
async getSchema(sourceId: string, version: number): Promise<RecordSchema | undefined> {
const rows = await this.sql<SchemaRow[]>`
SELECT source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by
FROM opt_source_schemas
WHERE source_id = ${sourceId} AND schema_version = ${version}
LIMIT 1`;
return rows[0] ? toSchema(rows[0]) : undefined;
}
async getLatestSchema(sourceId: string): Promise<RecordSchema | undefined> {
const rows = await this.sql<SchemaRow[]>`
SELECT source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by
FROM opt_source_schemas
WHERE source_id = ${sourceId}
ORDER BY schema_version DESC
LIMIT 1`;
return rows[0] ? toSchema(rows[0]) : undefined;
}
async listSchemas(sourceId: string): Promise<RecordSchema[]> {
const rows = await this.sql<SchemaRow[]>`
SELECT source_id, schema_version, tenant_id, fields, compatibility, registered_at, registered_by
FROM opt_source_schemas
WHERE source_id = ${sourceId}
ORDER BY schema_version ASC`;
return rows.map(toSchema);
}
// --- lineage -------------------------------------------------------------
async appendLineageEdges(edges: LineageEdge[]): Promise<void> {
for (const e of edges) {
await this.sql`
INSERT INTO opt_lineage_edges
(edge_id, tenant_id, run_id, capability_id, input_namespace, input_name, input_ref,
output_namespace, output_name, output_ref, event_time, correlation_id)
VALUES
(${e.edge_id}, ${e.tenant_id}, ${e.run_id}, ${e.capability_id}, ${e.input_namespace},
${e.input_name}, ${e.input_ref ?? null}, ${e.output_namespace}, ${e.output_name},
${e.output_ref ?? null}, ${e.event_time}, ${e.correlation_id ?? null})
ON CONFLICT (edge_id) DO NOTHING`;
}
}
async queryLineage(query: LineageQuery): Promise<LineageEdge[]> {
const limit = query.limit ?? 200;
const rows = await this.sql<LineageRow[]>`
SELECT edge_id, tenant_id, run_id, capability_id, input_namespace, input_name, input_ref,
output_namespace, output_name, output_ref, event_time, correlation_id
FROM opt_lineage_edges
WHERE tenant_id = ${query.tenant_id}
${query.output_name ? this.sql`AND output_name = ${query.output_name}` : this.sql``}
${query.input_name ? this.sql`AND input_name = ${query.input_name}` : this.sql``}
ORDER BY event_time DESC, edge_id DESC
LIMIT ${limit}`;
return rows.map((r) => ({
edge_id: r.edge_id,
tenant_id: r.tenant_id,
run_id: r.run_id,
capability_id: r.capability_id,
input_namespace: r.input_namespace,
input_name: r.input_name,
input_ref: r.input_ref ?? undefined,
output_namespace: r.output_namespace,
output_name: r.output_name,
output_ref: r.output_ref ?? undefined,
event_time: toIso(r.event_time),
correlation_id: r.correlation_id ?? undefined,
}));
}
}
interface SchemaRow {
source_id: string;
schema_version: number;
tenant_id: string;
fields: RecordSchemaFields;
compatibility: string;
registered_at: string | Date;
registered_by: string | null;
}
function toSchema(r: SchemaRow): RecordSchema {
return {
source_id: r.source_id,
schema_version: Number(r.schema_version),
tenant_id: r.tenant_id,
fields: r.fields,
compatibility: r.compatibility as CompatibilityPolicy,
registered_at: toIso(r.registered_at),
registered_by: r.registered_by ?? undefined,
};
}
interface LineageRow {
edge_id: string;
tenant_id: string;
run_id: string;
capability_id: string;
input_namespace: string;
input_name: string;
input_ref: string | null;
output_namespace: string;
output_name: string;
output_ref: string | null;
event_time: string | Date;
correlation_id: string | null;
}
@@ -10,10 +10,13 @@
* is a single upserted "last success" row per source.
*/
import type {
AuthorizationBasis,
SourceAuthorization,
SourceHealthCheck,
SourceHealthStatus,
SourceProvenance,
SourceRights,
SourceSchedule,
} from "../types/source-registry";
import type { RepositorySql } from "./db";
import type { SourceRegistryRepository } from "./source-registry-repository";
@@ -167,6 +170,57 @@ export class PostgresSourceRegistryRepository implements SourceRegistryRepositor
return rows[0] ? toIsoString(rows[0].last_success_at) : undefined;
}
// --- P060 authorization / schedule ---------------------------------------
async setAuthorization(auth: SourceAuthorization): Promise<void> {
await this.sql`
INSERT INTO opt_source_authorization
(source_id, tenant_id, basis, granted_by, granted_at, expires_at, evidence_ref, notes)
VALUES
(${auth.source_id}, ${auth.tenant_id}, ${auth.basis}, ${auth.granted_by}, ${auth.granted_at},
${auth.expires_at ?? null}, ${auth.evidence_ref ?? null}, ${auth.notes ?? null})
ON CONFLICT (source_id) DO UPDATE
SET tenant_id = EXCLUDED.tenant_id,
basis = EXCLUDED.basis,
granted_by = EXCLUDED.granted_by,
granted_at = EXCLUDED.granted_at,
expires_at = EXCLUDED.expires_at,
evidence_ref = EXCLUDED.evidence_ref,
notes = EXCLUDED.notes,
updated_at = now()`;
}
async getAuthorization(sourceId: string): Promise<SourceAuthorization | undefined> {
const rows = await this.sql<AuthorizationRow[]>`
SELECT source_id, tenant_id, basis, granted_by, granted_at, expires_at, evidence_ref, notes
FROM opt_source_authorization WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toAuthorization(rows[0]) : undefined;
}
async setSchedule(schedule: SourceSchedule): Promise<void> {
await this.sql`
INSERT INTO opt_source_schedule
(source_id, tenant_id, mode, interval_seconds, cron, enabled, updated_at)
VALUES
(${schedule.source_id}, ${schedule.tenant_id}, ${schedule.mode},
${schedule.interval_seconds ?? null}, ${schedule.cron ?? null}, ${schedule.enabled},
${schedule.updated_at})
ON CONFLICT (source_id) DO UPDATE
SET tenant_id = EXCLUDED.tenant_id,
mode = EXCLUDED.mode,
interval_seconds = EXCLUDED.interval_seconds,
cron = EXCLUDED.cron,
enabled = EXCLUDED.enabled,
updated_at = EXCLUDED.updated_at`;
}
async getSchedule(sourceId: string): Promise<SourceSchedule | undefined> {
const rows = await this.sql<ScheduleRow[]>`
SELECT source_id, tenant_id, mode, interval_seconds, cron, enabled, updated_at
FROM opt_source_schedule WHERE source_id = ${sourceId} LIMIT 1`;
return rows[0] ? toSchedule(rows[0]) : undefined;
}
async appendHealthCheck(check: SourceHealthCheck): Promise<void> {
await this.sql`
INSERT INTO opt_source_health_checks (source_id, tenant_id, status, checked_at, latency_ms, detail)
@@ -195,3 +249,49 @@ export class PostgresSourceRegistryRepository implements SourceRegistryRepositor
return rows.map(toHealthCheck);
}
}
interface AuthorizationRow {
source_id: string;
tenant_id: string;
basis: string;
granted_by: string;
granted_at: string | Date;
expires_at: string | Date | null;
evidence_ref: string | null;
notes: string | null;
}
function toAuthorization(r: AuthorizationRow): SourceAuthorization {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
basis: r.basis as AuthorizationBasis,
granted_by: r.granted_by,
granted_at: toIsoString(r.granted_at),
expires_at: r.expires_at ? toIsoString(r.expires_at) : undefined,
evidence_ref: r.evidence_ref ?? undefined,
notes: r.notes ?? undefined,
};
}
interface ScheduleRow {
source_id: string;
tenant_id: string;
mode: string;
interval_seconds: number | string | null;
cron: string | null;
enabled: boolean;
updated_at: string | Date;
}
function toSchedule(r: ScheduleRow): SourceSchedule {
return {
source_id: r.source_id,
tenant_id: r.tenant_id,
mode: r.mode as SourceSchedule["mode"],
interval_seconds: r.interval_seconds === null ? undefined : Number(r.interval_seconds),
cron: r.cron ?? undefined,
enabled: r.enabled,
updated_at: toIsoString(r.updated_at),
};
}
+19 -5
View File
@@ -25,6 +25,7 @@ interface SourceRow {
created_at: string | Date;
updated_at: string | Date | null;
created_by: string | null;
owner_id: string | null;
}
function toIsoString(v: string | Date): string {
@@ -46,6 +47,7 @@ function toSource(r: SourceRow): Source {
created_at: toIsoString(r.created_at),
updated_at: r.updated_at ? toIsoString(r.updated_at) : undefined,
created_by: r.created_by ?? undefined,
owner_id: r.owner_id ?? undefined,
};
}
@@ -63,29 +65,41 @@ export class PostgresSourceRepository implements SourceRepository {
const rows = await this.sql<SourceRow[]>`
INSERT INTO opt_sources
(source_id, tenant_id, project_id, source_type, name, adapter_id, access, description, status, correlation_id, created_by)
(source_id, tenant_id, project_id, source_type, name, adapter_id, access, description, status, correlation_id, created_by, owner_id)
VALUES
(${input.source_id}, ${input.tenant_id}, ${input.project_id}, ${input.source_type}, ${input.name},
${input.adapter_id ?? null}, ${input.access ?? null}, ${input.description ?? null},
${input.status ?? "active"}, ${input.correlation_id ?? null}, ${input.created_by ?? null})
${input.status ?? "pending"}, ${input.correlation_id ?? null}, ${input.created_by ?? null},
${input.owner_id ?? null})
RETURNING source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by`;
status, correlation_id, created_at, updated_at, created_by, owner_id`;
return toSource(rows[0]);
}
async get(sourceId: string): Promise<Source> {
const rows = await this.sql<SourceRow[]>`
SELECT source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by
status, correlation_id, created_at, updated_at, created_by, owner_id
FROM opt_sources WHERE source_id = ${sourceId} LIMIT 1`;
if (!rows[0]) throw new Error(`Source ${sourceId} not found`);
return toSource(rows[0]);
}
async updateStatus(sourceId: string, status: SourceStatus): Promise<Source> {
const rows = await this.sql<SourceRow[]>`
UPDATE opt_sources
SET status = ${status}, updated_at = now()
WHERE source_id = ${sourceId}
RETURNING source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by, owner_id`;
if (!rows[0]) throw new Error(`Source ${sourceId} not found`);
return toSource(rows[0]);
}
async list(filter?: SourceListFilter): Promise<Source[]> {
const rows = await this.sql<SourceRow[]>`
SELECT source_id, tenant_id, project_id, source_type, name, adapter_id, access, description,
status, correlation_id, created_at, updated_at, created_by
status, correlation_id, created_at, updated_at, created_by, owner_id
FROM opt_sources
WHERE 1=1
${filter?.tenant_id ? this.sql`AND tenant_id = ${filter.tenant_id}` : this.sql``}
+15 -1
View File
@@ -16,7 +16,13 @@
* layer trusts the caller, same as the Maps did.
*/
import { resolveStoreMode } from "../platform/dependency-mode";
import type { SourceHealthCheck, SourceProvenance, SourceRights } from "../types/source-registry";
import type {
SourceAuthorization,
SourceHealthCheck,
SourceProvenance,
SourceRights,
SourceSchedule,
} from "../types/source-registry";
import { getRepositorySql, repositoryDatabaseUrl } from "./db";
import { InMemorySourceRegistryRepository } from "./in-memory-source-registry-repository";
import { PostgresSourceRegistryRepository } from "./postgres-source-registry-repository";
@@ -31,6 +37,14 @@ export interface SourceRegistryRepository {
recordSuccess(sourceId: string, tenantId: string, atIso: string): Promise<void>;
getLastSuccess(sourceId: string): Promise<string | undefined>;
/** P060 authorization — the recorded decision that 0pt may connect at all. */
setAuthorization(auth: SourceAuthorization): Promise<void>;
getAuthorization(sourceId: string): Promise<SourceAuthorization | undefined>;
/** P060 schedule — ingestion mode + cadence. */
setSchedule(schedule: SourceSchedule): Promise<void>;
getSchedule(sourceId: string): Promise<SourceSchedule | undefined>;
appendHealthCheck(check: SourceHealthCheck): Promise<void>;
/** Newest-first, bounded to the latest `limit` observations (default 100) -- health is an operational signal, not an audit log; AUD0 owns history. */
listHealthChecks(sourceId: string, limit?: number): Promise<SourceHealthCheck[]>;
+6
View File
@@ -33,6 +33,12 @@ export interface SourceRepository {
/** Throws (message contains "not found") when no such source exists -- matches the pre-migration Map behavior every caller already handles. */
get(sourceId: string): Promise<Source>;
list(filter?: SourceListFilter): Promise<Source[]>;
/**
* P060: the only way a source's lifecycle status changes. Deliberately NOT
* a general `update` -- status is the field the activation gate protects,
* and a generic patch method would be the obvious way around it.
*/
updateStatus(sourceId: string, status: SourceStatus): Promise<Source>;
}
export function createSourceRepository(databaseUrl?: string): SourceRepository {
+170
View File
@@ -0,0 +1,170 @@
/**
* src/schema/compatibility.ts
* ============================
* P063: the pure comparison. `checkCompatibility(previous, next, policy)`
* returns every way `next` breaks readers/writers of `previous` under the
* declared policy. No IO, no throwing — the caller decides what a break
* means (SchemaRegistry refuses the registration; the ingestion runner
* refuses the RUN, before a single envelope reaches a consumer).
*/
import type {
CompatibilityPolicy,
CompatibilityVerdict,
RecordSchemaFields,
SchemaBreak,
} from "./record-schema";
/**
* BACKWARD breaks: a consumer written against `next` reading data produced
* under `previous` fails when
* - `next` adds a REQUIRED field `previous` never produced, or
* - `next` changes a field's type (old data has the old type), or
* - `next` drops a field that was REQUIRED in `previous` and is therefore
* part of the contract consumers rely on.
*/
function backwardBreaks(previous: RecordSchemaFields, next: RecordSchemaFields): SchemaBreak[] {
const breaks: SchemaBreak[] = [];
for (const [field, spec] of Object.entries(next)) {
const before = previous[field];
if (!before) {
if (spec.required) {
breaks.push({
field,
breaks: "backward",
detail: `new required field "${field}" is absent from every record written under the previous version`,
});
}
continue;
}
if (before.type !== spec.type) {
breaks.push({
field,
breaks: "backward",
detail: `field "${field}" changed type ${before.type} -> ${spec.type}; existing data still carries ${before.type}`,
});
}
}
for (const [field, before] of Object.entries(previous)) {
if (!next[field] && before.required) {
breaks.push({
field,
breaks: "backward",
detail: `required field "${field}" was removed; consumers of the previous version still depend on it`,
});
}
}
return breaks;
}
/**
* FORWARD breaks: a consumer written against `previous` reading data produced
* under `next` fails when
* - `next` removes a field `previous` marked REQUIRED, or
* - `next` changes a field's type.
* Adding a required field is forward-SAFE (old readers ignore it).
*/
function forwardBreaks(previous: RecordSchemaFields, next: RecordSchemaFields): SchemaBreak[] {
const breaks: SchemaBreak[] = [];
for (const [field, before] of Object.entries(previous)) {
const after = next[field];
if (!after) {
if (before.required) {
breaks.push({
field,
breaks: "forward",
detail: `required field "${field}" was removed; readers pinned to the previous version will not find it`,
});
}
continue;
}
if (before.type !== after.type) {
breaks.push({
field,
breaks: "forward",
detail: `field "${field}" changed type ${before.type} -> ${after.type}; readers pinned to the previous version expect ${before.type}`,
});
}
}
return breaks;
}
/** Deduplicate identical (field, direction, detail) triples produced by both directions under `full`. */
function dedupe(breaks: SchemaBreak[]): SchemaBreak[] {
const seen = new Set<string>();
const out: SchemaBreak[] = [];
for (const b of breaks) {
const key = `${b.field}|${b.breaks}|${b.detail}`;
if (seen.has(key)) continue;
seen.add(key);
out.push(b);
}
return out;
}
export function checkCompatibility(
previous: RecordSchemaFields,
next: RecordSchemaFields,
policy: CompatibilityPolicy,
): CompatibilityVerdict {
if (policy === "none") {
return { compatible: true, policy, breaks: [] };
}
const breaks: SchemaBreak[] = [];
if (policy === "backward" || policy === "full") breaks.push(...backwardBreaks(previous, next));
if (policy === "forward" || policy === "full") breaks.push(...forwardBreaks(previous, next));
const deduped = dedupe(breaks);
return { compatible: deduped.length === 0, policy, breaks: deduped };
}
/**
* Does a concrete record conform to a schema? Used by the ingestion runner to
* detect that a source has SILENTLY changed shape — i.e. it is emitting data
* the registered schema does not describe — which is the case P063 exists to
* catch before consumers see it. Returns the problems; empty = conforming.
*/
export function conformanceErrors(
fields: RecordSchemaFields,
payload: Record<string, unknown>,
): string[] {
const errors: string[] = [];
for (const [field, spec] of Object.entries(fields)) {
const value = payload[field];
if (value === undefined || value === null) {
if (spec.required) errors.push(`required field "${field}" is missing`);
continue;
}
if (!matchesType(value, spec.type)) {
errors.push(`field "${field}" is ${describe(value)}, expected ${spec.type}`);
}
}
for (const field of Object.keys(payload)) {
if (!fields[field]) {
errors.push(`unregistered field "${field}" appeared in the payload`);
}
}
return errors;
}
function matchesType(value: unknown, type: string): boolean {
switch (type) {
case "string":
return typeof value === "string";
case "number":
return typeof value === "number" && Number.isFinite(value);
case "boolean":
return typeof value === "boolean";
case "timestamp":
return typeof value === "string" && !Number.isNaN(Date.parse(value));
case "array":
return Array.isArray(value);
case "object":
return typeof value === "object" && value !== null && !Array.isArray(value);
default:
return false;
}
}
function describe(value: unknown): string {
if (Array.isArray(value)) return "array";
return typeof value;
}
+65
View File
@@ -0,0 +1,65 @@
/**
* src/schema/record-schema.ts
* ============================
* P063: the schema 0pt versions per source, and the compatibility policy that
* governs what the next version may change.
*
* Deliberately a SMALL structural schema (field name -> type + required), not
* a second JSON-Schema dialect: 0pt already ships JSON Schema in
* packages/schemas/ for its own contracts, and Zod in src/validation for HTTP
* bodies. Neither of those answers the question P063 actually asks — "is
* version N+1 of an UPSTREAM source's record shape safe for the consumers
* reading version N?" — which needs a comparable, field-level structure, not
* a validator. Anything richer belongs in a real schema registry
* (Confluent/Apicurio) and would be an integration, not a rewrite of this.
*/
export type FieldType = "string" | "number" | "boolean" | "timestamp" | "object" | "array";
export interface FieldSpec {
type: FieldType;
required: boolean;
}
/** A record shape: field name -> spec. */
export type RecordSchemaFields = Record<string, FieldSpec>;
/**
* Compatibility policy, using the standard schema-registry vocabulary:
*
* - `backward` — new readers can read data written under the OLD schema.
* Safe: adding an optional field, removing an optional field, relaxing a
* required field to optional. Breaking: adding a REQUIRED field, removing
* a field an old writer still emits as required, changing a type.
* - `forward` — old readers can read data written under the NEW schema.
* Safe: adding a required field, removing an optional field. Breaking:
* removing a REQUIRED field, changing a type.
* - `full` — both of the above.
* - `none` — no check. Recorded, never silently assumed: a source must
* declare `none` explicitly, and the runner logs it as an accepted risk.
*/
export type CompatibilityPolicy = "backward" | "forward" | "full" | "none";
export interface RecordSchema {
source_id: string;
tenant_id: string;
schema_version: number;
fields: RecordSchemaFields;
compatibility: CompatibilityPolicy;
registered_at: string;
registered_by?: string;
}
/** One incompatibility between two schema versions. */
export interface SchemaBreak {
field: string;
/** Which direction the change breaks. */
breaks: "backward" | "forward";
detail: string;
}
export interface CompatibilityVerdict {
compatible: boolean;
policy: CompatibilityPolicy;
breaks: SchemaBreak[];
}
+144
View File
@@ -0,0 +1,144 @@
/**
* src/schema/schema-registry.ts
* ==============================
* P063: versioning + compatibility policy for a source's record shape.
*
* The DoD is "a breaking schema is detected BEFORE consumer corruption", so
* this registry is placed on the ingestion path in two places, both of them
* upstream of any consumer write:
*
* 1. `registerFromDiscovery` runs when the runner calls connector.discover(),
* i.e. before the first read. A shape change that breaks the declared
* policy makes the RUN fail with the field-level reasons — no envelope is
* produced at all.
* 2. `conformanceErrors` (src/schema/compatibility.ts) runs per envelope, so
* a source that changes shape mid-stream without changing its declared
* schema is caught on the offending record rather than on the next
* discovery, days later.
*
* A source whose policy is "none" opts out of (1) — explicitly, recorded in
* the registry row, never by default.
*/
import { SiaxError } from "../platform/errors";
import type { IngestionRepository } from "../repositories/ingestion-repository";
import { checkCompatibility } from "./compatibility";
import type {
CompatibilityPolicy,
CompatibilityVerdict,
RecordSchema,
RecordSchemaFields,
} from "./record-schema";
export interface RegisterSchemaInput {
source_id: string;
tenant_id: string;
fields: RecordSchemaFields;
/** Policy governing THIS and future versions. Required — there is no default. */
compatibility: CompatibilityPolicy;
registered_by?: string;
}
export interface RegisterSchemaResult {
schema: RecordSchema;
/** True when the shape was identical to the current version and no new version was created. */
unchanged: boolean;
/** Present when a comparison ran (i.e. a previous version existed). */
verdict?: CompatibilityVerdict;
}
/** Stable comparison of two field maps, order-independent. */
function sameFields(a: RecordSchemaFields, b: RecordSchemaFields): boolean {
const ka = Object.keys(a).sort();
const kb = Object.keys(b).sort();
if (ka.length !== kb.length) return false;
for (let i = 0; i < ka.length; i++) {
if (ka[i] !== kb[i]) return false;
const fa = a[ka[i]];
const fb = b[kb[i]];
if (fa.type !== fb.type || fa.required !== fb.required) return false;
}
return true;
}
export class SchemaRegistry {
constructor(private readonly repo: IngestionRepository) {}
async getLatest(sourceId: string): Promise<RecordSchema | undefined> {
return this.repo.getLatestSchema(sourceId);
}
async list(sourceId: string): Promise<RecordSchema[]> {
return this.repo.listSchemas(sourceId);
}
/**
* Register a shape. Throws `SiaxError("CONFLICT")` — naming every break —
* when the new shape violates the previous version's declared policy.
* Nothing is persisted when it throws.
*/
async register(input: RegisterSchemaInput): Promise<RegisterSchemaResult> {
if (Object.keys(input.fields).length === 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.schema_registry", "a schema must declare at least one field");
}
const previous = await this.repo.getLatestSchema(input.source_id);
if (!previous) {
const schema: RecordSchema = {
source_id: input.source_id,
tenant_id: input.tenant_id,
schema_version: 1,
fields: input.fields,
compatibility: input.compatibility,
registered_at: new Date().toISOString(),
registered_by: input.registered_by,
};
await this.repo.putSchema(schema);
return { schema, unchanged: false };
}
if (sameFields(previous.fields, input.fields) && previous.compatibility === input.compatibility) {
return { schema: previous, unchanged: true };
}
// The PREVIOUS version's policy governs whether this change is allowed —
// a producer must not be able to widen its own policy retroactively by
// declaring "none" on the breaking version.
const verdict = checkCompatibility(previous.fields, input.fields, previous.compatibility);
if (!verdict.compatible) {
throw new SiaxError(
"CONFLICT",
"0pt.schema_registry",
`schema v${previous.schema_version + 1} for source ${input.source_id} breaks the declared ` +
`"${previous.compatibility}" compatibility policy: ` +
verdict.breaks.map((b) => `[${b.breaks}] ${b.detail}`).join("; "),
);
}
const schema: RecordSchema = {
source_id: input.source_id,
tenant_id: input.tenant_id,
schema_version: previous.schema_version + 1,
fields: input.fields,
compatibility: input.compatibility,
registered_at: new Date().toISOString(),
registered_by: input.registered_by,
};
await this.repo.putSchema(schema);
return { schema, unchanged: false, verdict };
}
/**
* Non-throwing form used by the runner's pre-flight: answers whether the
* shape a connector just discovered would be accepted, without registering
* it. Used to report a break as a RUN failure with a full reason list
* rather than an exception message.
*/
async evaluate(
sourceId: string,
fields: RecordSchemaFields,
): Promise<{ previous?: RecordSchema; verdict?: CompatibilityVerdict; changed: boolean }> {
const previous = await this.repo.getLatestSchema(sourceId);
if (!previous) return { changed: true };
if (sameFields(previous.fields, fields)) return { previous, changed: false };
return { previous, verdict: checkCompatibility(previous.fields, fields, previous.compatibility), changed: true };
}
}

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