Files
0pt/src/connectors/jsonl-file-connector.ts
T
Simon AxelssonandClaude Opus 5 9267576b7c
CI (SIAX Cloud) / integration (push) Successful in 42s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / security (push) Successful in 46s
Security Scan (SIAX Cloud) / security (push) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 27s
feat(data-os): P060-P068 durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill
BEFORE_STATE (verified, with evidence):

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

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

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

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

NOT DONE, stated rather than deferred quietly:

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

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

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

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-04 17:03:14 +02:00

225 lines
8.6 KiB
TypeScript

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