feat(data-os): P060-P068 durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill
CI (SIAX Cloud) / integration (push) Successful in 42s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / security (push) Successful in 46s
Security Scan (SIAX Cloud) / security (push) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 27s

BEFORE_STATE (verified, with evidence):

* P060 PARTIAL/BROKEN. The registry persisted rights/provenance/health/
  freshness to Postgres, but carried no authorization, no schedule, no
  checkpoint, no schema and no owner distinct from created_by — and the
  activation DoD was inverted: postgres-source-repository.ts wrote
  `${input.status ?? "active"}`, so a source with no rights, no provenance
  and no authorization was ACTIVE the instant it was registered. No
  activation operation existed at all.
* P061 MISSING. services/api/sources/connectors.py had per-source fetch_*()
  functions only — no lifecycle, no cursor, no resume, no health, no
  conformance suite.
* P062 MISSING, already documented as such in
  services/api/tests/test_known_gaps.py:10-19 (no CDC pipeline anywhere;
  workers/pipeline.py has no persistence at all).
* P063 MISSING. schema_version existed as a free string; no comparison,
  no policy, no versioned source schema.
* P064 PARTIAL. Rules/runs/issues/scores existed, but a failing rule only
  opened an issue and the data flowed on. No quarantine anywhere.
* P065 DUPLICATE (confirmed). Two ER engines: src/er/entity-resolution-
  service.ts (canonical) and services/api/workers/resolve.py (simplified,
  still called by pipeline.py:110).
* P067 PARTIAL. Lineage was emitted to AUD0 but nothing here could ANSWER a
  lineage question — no store, no query, no route.
* P068 MISSING, documented in test_known_gaps.py:44-52 ("no delivery-store
  persistence layer exists to dedupe a backfill against").

BUILT (only what was PARTIAL/BROKEN/MISSING):

* P060 sql/007_ingestion_plane.sql adds authorization/schedule/schemas/
  checkpoints/ledger/quarantine/lineage tables, owner_id, and flips the
  opt_sources status DEFAULT to 'pending' so even a raw psql INSERT cannot
  produce an unclassified-but-active source. SourceRegistryService gains
  classifySource/activateSource/deactivateSource + authorization/schedule
  accessors; registration NEVER activates (asking for status:"active" goes
  through the gate, not around it); a service identity cannot authorize a
  source. Routes: activate (GET classification / POST activate),
  authorization, schedule.
* P061 src/connectors/connector.ts — all nine operations on one interface.
  src/connectors/conformance.ts — a runnable suite (15 checks, no "skip"
  verdict). HttpJsonConnector (real HTTP, opaque cursor) and
  JsonlFileConnector (real file, line offsets, CDC deletes) both pass it.
  The suite caught a real defect while being written: an API that drops
  next_cursor at the end left the connector unable to resume, which is why
  HttpJsonConnectorConfig has cursor_field.
* P062 src/types/ingestion.ts + src/ingestion/{envelope,ingestion-runner}.ts.
  One envelope for batch/stream/cdc; durable per-(source,partition)
  checkpoints; resume proven by killing a run inside the sink.
* P063 src/schema/{record-schema,compatibility,schema-registry}.ts. Two
  enforcement points, both upstream of any consumer write: a discovery gate
  before the first read, and per-record conformance before the page reaches
  the sink. A producer cannot widen its own policy retroactively.
* P064 src/quality/quality-policy.ts composes the EXISTING ExpectationEngine
  (not a second engine) and adds the missing consequence: block /
  quarantine / warn, with quarantine durable and recoverable. No policy is
  reported as "none_declared", never as a pass; an unexecutable expectation
  counts as a violation, never a silent pass.
* P067 src/lineage/{lineage-edge,lineage-store}.ts + GET /api/0pt/lineage.
  AUD0 stays the system of record; this is 0pt's own queryable projection.
* P068 opt_ingestion_ledger + IngestionRunner.backfill: bounded, idempotent
  on repeat, leaves the live checkpoint alone, still re-emits real changes.

A BUG THIS PASS WROTE AND CAUGHT: the first IngestionRepository draft
combined the idempotency check and its recording into one atomic call
BEFORE the sink. The crash/resume test then delivered 7 of 10 records — the
page in flight when the sink died was already marked delivered, so the
resumed run skipped it as a duplicate. Permanent, silent data loss. Fixed by
splitting peekDeliveries/commitDeliveries and committing both the ledger and
the checkpoint only after the sink resolves.

NOT DONE, stated rather than deferred quietly:

* P065 is NOT met. resolve.py is still a second simplified production
  engine. Closing it means rewriting it as an adapter over the canonical
  service, which cannot be verified from this repo today: services/api is
  not built by this repo's Dockerfile, api.0pt.app answers 404, and NO CI
  workflow runs its pytest suite. The duplication is now stated at both
  sites in code and the removal plan is in STATUS.md. The new ingestion
  plane performs no ER, so it adds no third engine.
* P066 (Iceberg) untouched — ST0RE is owned by another workflow. Contract
  read only.
* Delivery is AT-LEAST-ONCE, not exactly-once (no per-partition run lock).
* No CDC *source* exists; the contract is met, a CDC connector is not built.
* 0pt does not schedule itself — the schedule row is a declaration ACT0
  would read.

VERIFIED: pnpm typecheck clean; pnpm test 365 passed / 25 skipped (was
311/18); pnpm build clean with all four new routes in the route table; lint
unchanged at 12 pre-existing errors. Real Postgres 16
(tests/p0/ingestion-plane-postgres.realinfra.test.ts, 7 passed) plus a real
`docker restart` of that container with an identical read-back through the
production code path — that is P060's "a restart preserves all sources",
measured.

DEPLOYMENT REALITY (curl, 2026-09-04): 0pt.app/api/health returns 200 from
Vercel with db:not_configured; 0pt.app/api/0pt/sources returns 404;
api.0pt.app/health returns 404; cd.yml still guards on a placeholder Coolify
app id. None of the capability layer runs in production. Nothing here is
LIVE_VERIFIED and STATUS.md says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Simon Axelsson
2026-09-04 17:03:14 +02:00
co-authored by Claude Opus 5
parent c5ebceff38
commit 9267576b7c
43 changed files with 5506 additions and 20 deletions
+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 };
}
}