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 <[email protected]>
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
@@ -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 {