/** * src/connectors/postgres-watermark-connector.ts * ================================================= * P061 connector: a read-only, watermark-polled Postgres OLTP table. * * WHY THIS EXISTS. BI-3/BI-4 need a controlled, incremental path from a * product's live OLTP Postgres into 0pt — without `wal_level=logical`, * without a Postgres restart, without a permanent replica, and without ever * scanning a whole table. `docs/60-data/bi/...` (read from `admin/vehiq`, * 2026-09-25 pass) names the exact shape this connector implements: * * WHERE updated_at > :last_watermark ORDER BY updated_at, id * LIMIT :batch_size * * with a checkpoint of `(source, table, last_updated_at, last_id, * batch_count, checksum, ingested_at)`. This connector produces exactly * that query and that checkpoint — see the field-mapping table in * `docs/P070_VEHIQ_OLTP_EXTRACTOR.md`. * * TIE-BREAK, NOT A DEVIATION. A bare `updated_at > $1` drops rows that share * the exact same `updated_at` as the LAST row of a page: if row 100 and row * 101 both have `updated_at = T`, and row 100 is the last row of a page, a * naive `> T` on the next page skips row 101 forever. The query below adds * the documented `ORDER BY updated_at, id` tie-break to the WHERE clause * too: `updated_at > $1 OR (updated_at = $1 AND id > $2)`. Same watermark * semantics Simon specified, correct at page boundaries — exactly the class * of bug `tests/connectors/postgres-watermark-connector.test.ts`'s * "same-timestamp tie at a page boundary" case exists to catch. * * GUARD RAIL, NOT DECORATION. `validate()` refuses any config whose `table` * is (or ends in) the 98M-row `vehicle` table. That table gets its own * narrow, keyed connector (`postgres-keyed-lookup-connector.ts`) — this one * must never be pointed at it, even by a future caller's typo. The refusal * is asserted in tests, not just documented. * * READ-ONLY, STRUCTURALLY. There is no INSERT/UPDATE/DELETE anywhere in this * file. `columns` is an explicit allow-list the caller declares — never * `SELECT *` — so a schema drift on the source table cannot silently widen * what this connector reads or hands downstream. * * INJECTABLE QUERY IMPL — same seam as `http-json-connector.ts`'s * `fetchImpl`: tests drive real SQL text/params through a fixture function, * no real Postgres required for the connector-level tests. The default * implementation (`makePostgresQueryImpl`) is a thin wrapper over `postgres` * (postgres.js, already a repo dependency), used only by the orchestration * script and the opt-in realinfra test. */ import { createHash } from "node:crypto"; 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 POSTGRES_WATERMARK_CONNECTOR_VERSION = "postgres-watermark-connector@1"; /** One row back from the source, column name -> raw value. */ export type SourceRow = Record; /** * Injectable query seam. `params` are positional (`$1`, `$2`, ...). Tests * supply a fixture; `makePostgresQueryImpl` supplies the real thing. */ export type QueryImpl = (sql: string, params: unknown[]) => Promise; export interface PostgresWatermarkConnectorConfig extends ConnectorConfig { /** Fully-qualified source table, e.g. "app.dealer_stock_entry". */ table: string; /** Logical partition name exposed to the runner — a dataset name, never a physical detail leak beyond `table` itself. */ partition_key: string; /** Explicit column allow-list. Never "*". Must include `record_key_column` and `watermark_column`. */ columns: string[]; record_key_column: string; watermark_column: string; /** Declared record shape, fed to the schema registry (P063). */ schema: RecordSchemaFields; } /** The 98M-row table this connector must never be pointed at. See file header. */ const FORBIDDEN_TABLE_PATTERN = /(^|\.)vehicle$/i; function isConfig(config: ConnectorConfig): config is PostgresWatermarkConnectorConfig { return typeof config.table === "string" && typeof config.partition_key === "string"; } /** Cursor vocabulary: JSON `{last_updated_at, last_id, checksum}` — see docs/P070 for the checkpoint field mapping. */ export interface WatermarkCursor { last_updated_at: string; last_id: string; /** sha256 of the page just produced, hex-encoded. Absent only for the "never read" case. */ checksum?: string; } export function encodeCursor(cursor: WatermarkCursor): string { return JSON.stringify(cursor); } export function decodeCursor(raw: string | undefined): WatermarkCursor | undefined { if (raw === undefined) return undefined; const parsed = JSON.parse(raw) as unknown; if ( typeof parsed !== "object" || parsed === null || typeof (parsed as WatermarkCursor).last_updated_at !== "string" || typeof (parsed as WatermarkCursor).last_id !== "string" ) { throw new Error(`invalid watermark cursor "${raw}"`); } return parsed as WatermarkCursor; } /** * Postgres drivers (postgres.js included) hand back `timestamptz` columns as * native JS `Date` objects, not strings. `String(date)` produces the * locale/timezone-dependent `Date.toString()` form ("Thu Sep 03 2026 * 02:00:00 GMT+0200 (...)") — useless as a stored watermark, and NOT what a * fixture-based test (which hands back plain ISO strings) would ever catch. * Found by running this connector against a real Postgres container, not by * the fixture-only unit tests — which is why this helper exists instead of * an inline `String(...)` at each call site. */ function watermarkValueToIso(value: unknown): string { return value instanceof Date ? value.toISOString() : String(value); } /** * The P063 schema-conformance gate (src/schema/compatibility.ts) checks a * payload's field VALUES against the declared schema — and even its * `"timestamp"` type requires an already-ISO-string value, never a raw * `Date`. A real Postgres driver hands back `timestamptz`/`date` columns as * `Date` objects, so a payload built straight from `queryImpl`'s rows fails * conformance the moment it reaches a real database — caught by running * this connector against a real Postgres container (see docs/P070's * verification log), not by the fixture-only unit tests, which all use * plain strings. Every row is normalized through this function before it * becomes a `ConnectorRecord` payload, so the envelope's payload is always * JSON-safe and schema-checkable, independent of which driver produced it. */ function normalizeRow(row: SourceRow): SourceRow { const normalized: SourceRow = {}; for (const [field, value] of Object.entries(row)) { normalized[field] = value instanceof Date ? value.toISOString() : value; } return normalized; } /** sha256 over a stable JSON encoding of the rows, hex-encoded. Deterministic regardless of object key insertion order upstream. */ export function checksumRows(rows: SourceRow[]): string { const stable = rows.map((row) => Object.fromEntries(Object.keys(row).sort().map((k) => [k, row[k]])), ); return createHash("sha256").update(JSON.stringify(stable)).digest("hex"); } export class PostgresWatermarkConnector implements Connector { readonly connector_id = "postgres_watermark"; readonly connector_version = POSTGRES_WATERMARK_CONNECTOR_VERSION; private config?: PostgresWatermarkConnectorConfig; private ctx?: ConnectorContext; private lastCursor = new Map(); private connected = false; constructor(private readonly queryImpl: QueryImpl) {} validate(config: ConnectorConfig): ValidationResult { const errors: string[] = []; if (typeof config.table !== "string" || config.table.length === 0) { errors.push("table is required"); } else if (FORBIDDEN_TABLE_PATTERN.test(config.table)) { errors.push( `table "${config.table}" looks like the 98M-row vehicle catalog table — this connector is for watermark-polled ` + `OLTP tables only; use PostgresKeyedLookupConnector for narrow, keyed vehicle attribute lookups instead`, ); } if (typeof config.partition_key !== "string" || config.partition_key.length === 0) { errors.push("partition_key is required"); } const columns = config.columns; if (!Array.isArray(columns) || columns.length === 0) { errors.push("columns is required and must be a non-empty explicit column list"); } else if (columns.some((c) => c === "*" || typeof c !== "string" || c.length === 0)) { errors.push('columns must not contain "*" or an empty entry — SELECT * is not permitted'); } if (typeof config.record_key_column !== "string" || config.record_key_column.length === 0) { errors.push("record_key_column is required"); } else if (Array.isArray(columns) && !columns.includes(config.record_key_column)) { errors.push("record_key_column must be included in columns"); } if (typeof config.watermark_column !== "string" || config.watermark_column.length === 0) { errors.push("watermark_column is required"); } else if (Array.isArray(columns) && !columns.includes(config.watermark_column)) { errors.push("watermark_column must be included in columns"); } 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 { const verdict = this.validate(config); if (!verdict.valid) { throw new Error(`postgres_watermark connector config invalid: ${verdict.errors.join("; ")}`); } if (!isConfig(config)) throw new Error("postgres_watermark connector config invalid"); this.config = config; this.ctx = ctx; this.connected = true; } async discover(): Promise { const config = this.requireSession("discover"); return { partitions: [{ partition_key: config.partition_key, name: config.table, schema: config.schema }], // A polled table is batch/stream, never cdc: this connector never emits deletes. modes: ["batch", "stream"], }; } async health(): Promise { const config = this.requireSession("health"); const started = Date.now(); try { await this.queryImpl(`SELECT 1 FROM ${config.table} LIMIT 0`, []); return { status: "up", latency_ms: Date.now() - started }; } catch (err) { return { status: "down", latency_ms: Date.now() - started, detail: err instanceof Error ? err.message : "unreachable", }; } } async read(req: ReadRequest): Promise { const config = this.requireSession("read"); const cursor = decodeCursor(req.cursor); const columnList = config.columns.join(", "); let rows: SourceRow[]; if (cursor === undefined) { rows = await this.queryImpl( `SELECT ${columnList} FROM ${config.table} ORDER BY ${config.watermark_column}, ${config.record_key_column} LIMIT $1`, [req.limit], ); } else { rows = await this.queryImpl( `SELECT ${columnList} FROM ${config.table} ` + `WHERE ${config.watermark_column} > $1 OR (${config.watermark_column} = $1 AND ${config.record_key_column} > $2) ` + `ORDER BY ${config.watermark_column}, ${config.record_key_column} LIMIT $3`, [cursor.last_updated_at, cursor.last_id, req.limit], ); } // Hard bound — a queryImpl that over-delivers (a fixture bug, or a // future real driver quirk) is truncated here rather than silently // widening the caller's page. rows = rows.slice(0, req.limit); const records: ConnectorRecord[] = rows.map((row) => this.toRecord(row, config)); let nextCursor = req.cursor; if (rows.length > 0) { const last = rows[rows.length - 1]; const nextWatermark: WatermarkCursor = { last_updated_at: watermarkValueToIso(last[config.watermark_column]), last_id: String(last[config.record_key_column]), checksum: checksumRows(rows), }; nextCursor = encodeCursor(nextWatermark); this.lastCursor.set(req.partition_key, nextCursor); } return { records, next_cursor: nextCursor, // Fewer rows than the limit means we caught up to "now" — there may be // MORE later (this is a live table), but nothing more RIGHT NOW. exhausted: rows.length < req.limit, }; } 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 { this.requireSession("resume"); return this.read({ partition_key: checkpoint.partition_key, cursor: checkpoint.cursor, limit }); } async backfill(req: BackfillRequest): Promise { 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 columnList = config.columns.join(", "); const rows = ( await this.queryImpl( `SELECT ${columnList} FROM ${config.table} ` + `WHERE ${config.watermark_column} >= $1 AND ${config.watermark_column} < $2 ` + `ORDER BY ${config.watermark_column}, ${config.record_key_column} LIMIT $3`, [req.from, req.to, req.limit], ) ).slice(0, req.limit); return { records: rows.map((row) => this.toRecord(row, config)), next_cursor: undefined, exhausted: true, }; } async disconnect(): Promise { this.config = undefined; this.ctx = undefined; this.lastCursor.clear(); this.connected = false; } // --- internals ------------------------------------------------------------- private toRecord(row: SourceRow, config: PostgresWatermarkConnectorConfig): ConnectorRecord { const key = row[config.record_key_column]; if (typeof key !== "string" && typeof key !== "number") { throw new Error(`record is missing string/number key column "${config.record_key_column}"`); } const watermark = watermarkValueToIso(row[config.watermark_column]); return { record_key: String(key), payload: normalizeRow(row), operation: "upsert", occurred_at: watermark, cursor: encodeCursor({ last_updated_at: watermark, last_id: String(key) }), }; } private requireSession(op: string): PostgresWatermarkConnectorConfig { if (!this.connected || !this.config) throw new ConnectorNotConnectedError(this.connector_id, op); return this.config; } }