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