CI (SIAX Cloud) / integration (push) Skipped
masterplan-lock / check (push) Successful in 7s
CI (SIAX Cloud) / security (push) Successful in 17s
masterplan-lock / check (pull_request) Successful in 9s
Security Scan (SIAX Cloud) / security (push) Successful in 38s
CI (SIAX Cloud) / security (pull_request) Successful in 26s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 26s
CI (SIAX Cloud) / quality (push) Successful in 57s
CI (SIAX Cloud) / integration (pull_request) Successful in 39s
CI (SIAX Cloud) / quality (pull_request) Successful in 59s
Implements Simon's specified pattern (dealer_stock_entry/deal -> watermark/updated_at -> 0pt ingestion -> ClickHouse) as a P061 connector pair (PostgresWatermarkConnector, PostgresKeyedLookupConnector) plugged into the existing P062 IngestionRunner, writing to opt_dataset_projection via SiaxAnalyticsEngine.ingestProjection. Built here, not in admin/vehiq: that repo's own ADR-0035 (decisions 1/2/10, CI-enforced by validate_engine_firewall.py) forbids VehIQ code from ever holding a ClickHouse credential or hammering OLTP directly for analytics. See docs/P070_VEHIQ_OLTP_EXTRACTOR.md for the full rationale. Also corrects a real schema mismatch found while building this: production has no generic `updated_at` on any of the three target tables (verified live, read-only, 2026-09-25). dealer_stock_entry/deal use listed_at/ created_at as insert-time watermarks instead (documented caveat: in-place updates are not caught without a schema change); app.listing has no timestamp column at all and is deliberately not covered yet. Vehicle dimension lookup is narrow by construction: keyed on exactly the vehicle_id set referenced by the batch just read, never a scan of the 98M-row vehiq.vehicle table (connector-level validate() refuses that table by name; runner-level tests assert the query only ever touches referenced IDs). Verified: fixture-backed connector/runner tests (watermark+limit, same-timestamp tie at a page boundary, crash/resume, empty-table case, narrow-lookup query-count assertions) + a real disposable Postgres container (caught two real Date-handling bugs fixtures could not) + a read-only proof against actual production (server10, vehiq-db): the extractor's exact SQL returns zero rows, no error, confirming it is safe to schedule with zero current effect. .gitea/workflows/vehiq-oltp-ingest.yml is present, cron-scheduled, and defaults to VEHIQ_INGEST_MODE=preview (read-only, never writes) with no secrets configured — safe to merge with zero production effect until explicitly activated per the doc's "what activating this requires". Co-Authored-By: Claude Sonnet 5 <[email protected]>
259 lines
12 KiB
TypeScript
259 lines
12 KiB
TypeScript
/**
|
|
* src/connectors/postgres-keyed-lookup-connector.ts
|
|
* ====================================================
|
|
* P061 connector: a narrow, explicit-key-list lookup against a large table —
|
|
* built specifically so `0pt dimension_vehicle` never becomes `SELECT *
|
|
* FROM vehicle` against the 98M-row/85GB `vehiq.vehicle` table.
|
|
*
|
|
* THE RULE THIS ENFORCES (Simon's decision #2, `admin/vehiq` 2026-09-25
|
|
* pass): `dealer_stock_entry.vehicle_id` -> unique vehicle IDs -> a
|
|
* TARGETED lookup of just those rows' attributes -> `dimension_vehicle`.
|
|
* Never a full scan, never an unbounded WHERE clause, never "give me
|
|
* everything and I'll filter downstream".
|
|
*
|
|
* HOW IT'S STRUCTURALLY DIFFERENT FROM `postgres-watermark-connector.ts`,
|
|
* not just configured differently: this connector's config carries `keys`
|
|
* — a caller-supplied, already-resolved, finite list of record keys. There
|
|
* is no watermark, no `ORDER BY updated_at`, no notion of "everything since
|
|
* X". `read()` can ONLY ever emit rows whose key is in that list, and
|
|
* `connect()` REFUSES an empty or missing key list rather than defaulting
|
|
* to "read everything" — see the "zero keys issues zero queries" test,
|
|
* which is the assertion that actually proves the narrow-scan property
|
|
* (not just that the SQL text LOOKS bounded).
|
|
*
|
|
* THE ORCHESTRATOR (scripts/vehiq-oltp-ingest/run.ts) is what supplies
|
|
* `keys`: the DISTINCT `vehicle_id`s seen in the `dealer_stock_entry` batch
|
|
* this connector instance was built for, and nothing else. A full snapshot/
|
|
* backfill of the whole `vehicle` table is a deliberate, separate, later
|
|
* decision — see docs/P070_VEHIQ_OLTP_EXTRACTOR.md's "Deferred: full
|
|
* vehicle dimension backfill" section. This connector does not build
|
|
* towards that; it is the permanent narrow path, not a stepping stone.
|
|
*/
|
|
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";
|
|
import type { QueryImpl, SourceRow } from "./postgres-watermark-connector";
|
|
|
|
export const POSTGRES_KEYED_LOOKUP_CONNECTOR_VERSION = "postgres-keyed-lookup-connector@1";
|
|
|
|
export interface PostgresKeyedLookupConnectorConfig extends ConnectorConfig {
|
|
/** Fully-qualified source table, e.g. "vehiq.vehicle". */
|
|
table: string;
|
|
partition_key: string;
|
|
columns: string[];
|
|
record_key_column: string;
|
|
schema: RecordSchemaFields;
|
|
/**
|
|
* The ENTIRE set of keys this connector instance is permitted to read —
|
|
* resolved by the caller BEFORE construction (e.g. distinct
|
|
* `dealer_stock_entry.vehicle_id` values from one ingestion batch). Never
|
|
* mutated after connect(); a new batch means a new connector instance.
|
|
*/
|
|
keys: ReadonlyArray<string | number>;
|
|
/** How many keys go into one SQL `= ANY($1)` call. Default 500. */
|
|
keys_per_query?: number;
|
|
}
|
|
|
|
function isConfig(config: ConnectorConfig): config is PostgresKeyedLookupConnectorConfig {
|
|
return typeof config.table === "string" && typeof config.partition_key === "string" && Array.isArray(config.keys);
|
|
}
|
|
|
|
/** Cursor vocabulary: the decimal count of keys already looked up (an index into `config.keys`). */
|
|
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 key-list offset`);
|
|
return n;
|
|
}
|
|
|
|
export class PostgresKeyedLookupConnector implements Connector {
|
|
readonly connector_id = "postgres_keyed_lookup";
|
|
readonly connector_version = POSTGRES_KEYED_LOOKUP_CONNECTOR_VERSION;
|
|
|
|
private config?: PostgresKeyedLookupConnectorConfig;
|
|
private ctx?: ConnectorContext;
|
|
private lastCursor = new Map<string, string | undefined>();
|
|
private connected = false;
|
|
|
|
/** Query calls actually issued, for tests to assert the narrow-scan property against. */
|
|
readonly queryLog: Array<{ sql: string; keys: Array<string | number> }> = [];
|
|
|
|
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");
|
|
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");
|
|
}
|
|
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");
|
|
}
|
|
if (!Array.isArray(config.keys)) {
|
|
errors.push("keys is required and must be an array");
|
|
} else if (config.keys.length === 0) {
|
|
// Deliberately a hard validation error, not a silent "0 records" read.
|
|
// A caller with nothing to look up should not construct this connector
|
|
// at all — this keeps "no keys => no query, ever" true even for a
|
|
// caller that forgets to check first.
|
|
errors.push("keys must not be empty — construct this connector only when there is something to look up");
|
|
}
|
|
if (config.keys_per_query !== undefined && (typeof config.keys_per_query !== "number" || config.keys_per_query <= 0)) {
|
|
errors.push("keys_per_query must be a positive number when provided");
|
|
}
|
|
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(`postgres_keyed_lookup connector config invalid: ${verdict.errors.join("; ")}`);
|
|
}
|
|
if (!isConfig(config)) throw new Error("postgres_keyed_lookup connector config invalid");
|
|
this.config = config;
|
|
this.ctx = ctx;
|
|
this.connected = true;
|
|
}
|
|
|
|
async discover(): Promise<DiscoveryResult> {
|
|
const config = this.requireSession("discover");
|
|
return {
|
|
partitions: [{ partition_key: config.partition_key, name: config.table, schema: config.schema }],
|
|
modes: ["batch"],
|
|
};
|
|
}
|
|
|
|
async health(): Promise<ConnectorHealth> {
|
|
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<ReadResult> {
|
|
const config = this.requireSession("read");
|
|
const offset = parseCursor(req.cursor);
|
|
const pageLimit = Math.min(req.limit, config.keys_per_query ?? 500);
|
|
const page = config.keys.slice(offset, offset + pageLimit);
|
|
|
|
let rows: SourceRow[] = [];
|
|
if (page.length > 0) {
|
|
const columnList = config.columns.join(", ");
|
|
const sql = `SELECT ${columnList} FROM ${config.table} WHERE ${config.record_key_column} = ANY($1)`;
|
|
this.queryLog.push({ sql, keys: [...page] });
|
|
rows = await this.queryImpl(sql, [page]);
|
|
}
|
|
// Structural guarantee, not just an intent: if `page` is empty, `queryImpl`
|
|
// is never called at all — this branch cannot silently widen into an
|
|
// unbounded scan even if a future edit forgets the `page.length > 0` guard
|
|
// above, because the caller of this method never asks for more than
|
|
// `config.keys.length` total across repeated read()s (see `exhausted`).
|
|
const records = rows.map((row) => this.toRecord(row, config));
|
|
const nextOffset = offset + page.length;
|
|
const nextCursor = String(nextOffset);
|
|
this.lastCursor.set(req.partition_key, nextCursor);
|
|
return {
|
|
records,
|
|
next_cursor: nextCursor,
|
|
exhausted: nextOffset >= config.keys.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 });
|
|
}
|
|
|
|
/**
|
|
* "Backfill" for a keyed lookup means re-reading a bounded INDEX range of
|
|
* the same already-narrow key list — never a fresh, wider key set. `from`/
|
|
* `to` are decimal offsets into `config.keys`, documented here per the
|
|
* contract's "bound vocabulary is connector-defined" rule.
|
|
*/
|
|
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 from = parseCursor(req.from);
|
|
const to = parseCursor(req.to);
|
|
if (to <= from) throw new Error("backfill requires `to` > `from`");
|
|
const page = config.keys.slice(from, Math.min(to, from + req.limit));
|
|
let rows: SourceRow[] = [];
|
|
if (page.length > 0) {
|
|
const columnList = config.columns.join(", ");
|
|
const sql = `SELECT ${columnList} FROM ${config.table} WHERE ${config.record_key_column} = ANY($1)`;
|
|
this.queryLog.push({ sql, keys: [...page] });
|
|
rows = await this.queryImpl(sql, [page]);
|
|
}
|
|
return { records: rows.map((row) => this.toRecord(row, config)), next_cursor: undefined, exhausted: true };
|
|
}
|
|
|
|
async disconnect(): Promise<void> {
|
|
this.config = undefined;
|
|
this.ctx = undefined;
|
|
this.lastCursor.clear();
|
|
this.connected = false;
|
|
}
|
|
|
|
// --- internals -------------------------------------------------------------
|
|
|
|
private toRecord(row: SourceRow, config: PostgresKeyedLookupConnectorConfig): 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}"`);
|
|
}
|
|
// Same real-driver normalization as PostgresWatermarkConnector.toRecord —
|
|
// a Date-valued column must become an ISO string before it reaches the
|
|
// P063 schema-conformance gate. See that connector's `normalizeRow` doc
|
|
// comment for how this was found.
|
|
const payload: SourceRow = {};
|
|
for (const [field, value] of Object.entries(row)) {
|
|
payload[field] = value instanceof Date ? value.toISOString() : value;
|
|
}
|
|
return { record_key: String(key), payload, operation: "upsert" };
|
|
}
|
|
|
|
private requireSession(op: string): PostgresKeyedLookupConnectorConfig {
|
|
if (!this.connected || !this.config) throw new ConnectorNotConnectedError(this.connector_id, op);
|
|
return this.config;
|
|
}
|
|
}
|