feat(ingestion): VehIQ OLTP -> ClickHouse watermark extractor (P070)
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]>
This commit is contained in:
Claude Code
2026-09-25 19:11:15 +02:00
co-authored by Claude Sonnet 5
parent ec487746fd
commit 07158099ee
13 changed files with 1995 additions and 11 deletions
+117
View File
@@ -0,0 +1,117 @@
/**
* src/ingestion/projection-sink.ts
* ===================================
* Adapts the P062 runner's generic `IngestionSink` (envelopes in) onto
* `SiaxAnalyticsEngine.ingestProjection` (BI-P009 capability 7, writes
* `opt_dataset_projection` in ClickHouse — see `src/analytics/engine/
* clickhouse-engine.ts`).
*
* WHY `ingestProjection` / `opt_dataset_projection` AND NOT `opt_analytics_
* event`. `opt_analytics_event` (BI-P010 schema.ts) is documented as a
* "high-volume per-tenant EVENT stream" with a 30-day TTL — the right shape
* for discrete occurrences (a page view, a search, a status transition).
* `dealer_stock_entry`/`listing`/`deal` rows and vehicle-dimension rows are
* ENTITY SNAPSHOTS — current state of a stock entry, a listing, a deal, a
* vehicle — which is exactly what `opt_dataset_projection` (ReplacingMerge
* Tree serving tier, `entity_key`+`version`) already exists to hold, and
* `ingestProjection` is the one write port `SiaxAnalyticsEngine` exposes for
* it. Landing entity rows into the raw event stream would be forcing an
* entity shape through an event shape — this sink does not do that.
*
* THE FIREWALL IS RESPECTED BY CONSTRUCTION: this file imports only the
* `SiaxAnalyticsEngine`/`AnalyticsIdentity`/`ProjectionRow` TYPES from
* `../analytics/engine/siax-analytics-engine` — no ClickHouse client, no
* `CLICKHOUSE_*` env read, no connection string. Which concrete engine
* (ClickHouse today, anything else later) answers `ingestProjection` is the
* caller's concern (see `scripts/vehiq-oltp-ingest/run.ts`), not this file's.
*
* ORDERING STAYS THE RUNNER'S: this function is called AS the runner's
* `sink`, so its own crash/partial-failure behaviour is exactly what
* `ingestion-runner.ts`'s header already documents — a thrown error here
* leaves the page's checkpoint uncommitted, and the next run re-reads it.
*/
import type { IngestionEnvelope } from "../types/ingestion";
import type {
AnalyticsIdentity,
ProjectionRow,
SiaxAnalyticsEngine,
} from "../analytics/engine/siax-analytics-engine";
import { SiaxError } from "../platform/errors";
export interface ProjectionSinkOptions {
engine: SiaxAnalyticsEngine;
identity: AnalyticsIdentity;
/** Maps a partition_key (e.g. "dealer_stock_entry") to a logical dataset id (e.g. "vehiq.dealer_stock_entry"). */
datasetIdFor: (partitionKey: string) => string;
}
/**
* Splits an envelope's payload into ClickHouse-projection-friendly
* attributes (strings) and measures (numbers). `null`/`undefined` fields are
* dropped rather than coerced to `"null"`/`NaN`, which would fabricate a
* value nothing upstream actually asserted.
*/
export function toProjectionRow(envelope: IngestionEnvelope): ProjectionRow {
if (envelope.operation === "delete" || envelope.payload === null) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.ingestion.projection-sink",
`envelope ${envelope.envelope_id} is a delete (payload: null) — opt_dataset_projection has no tombstone ` +
`representation via ingestProjection today; a CDC-capable source reaching this sink is a real gap, not ` +
`silently handled here (this connector programme currently emits "upsert" only, so this path is untested ` +
`by design, not unreachable by contract)`,
);
}
const attributes: Record<string, string> = {};
const measures: Record<string, number> = {};
for (const [field, value] of Object.entries(envelope.payload)) {
if (value === null || value === undefined) continue;
if (typeof value === "number" && Number.isFinite(value)) {
measures[field] = value;
} else if (value instanceof Date) {
attributes[field] = value.toISOString();
} else if (typeof value === "object") {
attributes[field] = JSON.stringify(value);
} else {
attributes[field] = String(value);
}
}
return {
entity_key: envelope.record_key,
as_of: envelope.occurred_at ?? envelope.ingested_at,
version: envelope.sequence,
attributes,
measures,
};
}
export function projectionSink(
opts: ProjectionSinkOptions,
): (envelopes: IngestionEnvelope[]) => Promise<void> {
return async (envelopes: IngestionEnvelope[]): Promise<void> => {
if (envelopes.length === 0) return;
const byPartition = new Map<string, IngestionEnvelope[]>();
for (const envelope of envelopes) {
const list = byPartition.get(envelope.partition_key) ?? [];
list.push(envelope);
byPartition.set(envelope.partition_key, list);
}
for (const [partitionKey, group] of byPartition) {
const rows = group.map(toProjectionRow);
const dataset_id = opts.datasetIdFor(partitionKey);
const result = await opts.engine.ingestProjection(opts.identity, { dataset_id, rows });
if (result.ingested !== rows.length) {
// Partial ingest is a hard failure, on purpose: the runner only
// commits the checkpoint AFTER this sink resolves. Resolving
// "successfully" on a partial write would silently drop the
// un-ingested rows on the next run's resume.
throw new SiaxError(
"RETRYABLE_FAILURE",
"0pt.ingestion.projection-sink",
`ingestProjection for dataset "${dataset_id}" reported ${result.ingested}/${rows.length} rows ingested — ` +
`treating as a failed page so the checkpoint does not advance past unlanded rows`,
);
}
}
};
}
+343
View File
@@ -0,0 +1,343 @@
/**
* src/ingestion/vehiq-oltp-ingest-runner.ts
* ============================================
* BI-3/BI-4 — the controlled, incremental VehIQ OLTP -> 0pt ClickHouse path,
* as Simon specified it (`admin/vehiq` 2026-09-25 pass, "Data path for
* inventory.days_in_stock"):
*
* OLTP operational tables -> read-only analytical extraction ->
* watermark/updated_at -> 0pt ingestion -> ClickHouse
*
* WHY THIS LIVES IN `admin/0pt`, NOT `admin/vehiq`. ADR-0035 (admin/vehiq,
* decisions 1/2/10, CI-enforced by `tools/validate_engine_firewall.py`):
* VehIQ's own codebase must NEVER hold a ClickHouse credential or import a
* ClickHouse client, and product code must never hammer the live OLTP
* primary with analytical queries directly. `admin/vehiq`'s own hub
* (`docs/CURRENT_STATE.md`, "Connection details for a future API0
* connector") says this explicitly: "VehIQ's own codebase must never see
* any of this. This is 0pt's data plane; only a future `admin/api0`
* connector should hold these details." This repo is 0pt's data plane —
* the correct home per that same guidance (a sibling of `admin/api0`, not
* `admin/api0` itself, since the read/write mechanics belong next to the
* P060-P068 ingestion plane and the BI-P009/P010 ClickHouse engine that
* already live here).
*
* TWO ENTRY POINTS, DELIBERATELY SEPARATE:
*
* `previewVehiqOltpSource` — connect, discover, ONE bounded read. Never
* calls checkpoint()/commits anything, never runs the P062 runner. Safe
* to point at production at any time, table empty or not: nothing it does
* can advance a checkpoint or land a row. This is what proves "zero
* batches, zero writes" without deploying a live scheduled service.
*
* `runVehiqOltpIngestion` — the real, scheduled path: the P062
* `IngestionRunner` across all three OLTP sources, then the narrow
* `dimension_vehicle` lookup keyed on exactly the `vehicle_id`s the OLTP
* batch referenced. This is what `.gitea/workflows/vehiq-oltp-ingest.yml`
* runs — see that file and docs/P070_VEHIQ_OLTP_EXTRACTOR.md for the
* activation gate this stays behind until Simon flips it.
*
* CHECKPOINT FIELD MAPPING (Simon's own list: source, table, last_updated_at,
* last_id, batch_count, checksum, ingested_at) onto the canonical P062
* `IngestionCheckpoint` (source_id, tenant_id, partition_key, cursor,
* sequence, records_committed, committed_at) — deliberately reusing the
* existing durable checkpoint mechanism rather than building a second one:
*
* source -> checkpoint.source_id
* table -> checkpoint.partition_key
* last_updated_at-> decoded from checkpoint.cursor (WatermarkCursor)
* last_id -> decoded from checkpoint.cursor (WatermarkCursor)
* checksum -> decoded from checkpoint.cursor (WatermarkCursor)
* batch_count -> checkpoint.records_committed (cumulative) / a
* per-run page count is also in each PartitionRunReport
* ingested_at -> checkpoint.committed_at
*/
import type { IngestionRepository } from "../repositories/ingestion-repository";
import type { SchemaRegistry } from "../schema/schema-registry";
import type { LineageStore } from "../lineage/lineage-store";
import type { RecordSchemaFields } from "../schema/record-schema";
import { IngestionRunner, type IngestionRunReport, type IngestionSink } from "./ingestion-runner";
import {
PostgresWatermarkConnector,
decodeCursor,
type QueryImpl,
} from "../connectors/postgres-watermark-connector";
import { PostgresKeyedLookupConnector } from "../connectors/postgres-keyed-lookup-connector";
import type { IngestionEnvelope } from "../types/ingestion";
export interface VehiqOltpSourceDef {
/** e.g. "dealer_stock_entry" — also the logical dataset name suffix. */
partition_key: "dealer_stock_entry" | "deal";
/** Fully-qualified source table, e.g. "app.dealer_stock_entry". */
table: string;
columns: string[];
record_key_column: string;
watermark_column: string;
schema: RecordSchemaFields;
}
/**
* TWO sources, not three — READ THIS BEFORE ASSUMING `app.listing` IS
* COVERED. The task's own wording (and `admin/vehiq`'s `docs/CURRENT_STATE.
* md`, "the columns already exist") assumed all three OLTP tables carry a
* generic `updated_at`. Verified LIVE against production (`server10`,
* `vehiq-db`, read-only `information_schema.columns`, 2026-09-25) that
* this is only true for none of the three as a literal `updated_at` column
* — and NOT true at all for `app.listing`:
*
* app.dealer_stock_entry — id, tenant_id, vehicle_id, lot_location,
* floorplan_status, listed_at, sold_at. No `updated_at`, no `status`
* (it's `floorplan_status`). `listed_at` (NOT NULL) is the best
* available watermark — see the caveat below.
* app.deal — id, tenant_id, party_id, vehicle_id, sale_price_minor,
* currency, status, created_at. No `updated_at`. `created_at`
* (NOT NULL DEFAULT now()) is the best available watermark.
* app.listing — id, tenant_id, vehicle_id, asking_price_minor, currency,
* channels, status. NO timestamp column of any kind exists today.
* `admin/vehiq` migration 0084 (`published_at`/`unpublished_at`) is
* written but NOT YET APPLIED to production (verified: those columns
* are absent live) — until it lands, there is no honest way to build a
* watermark connector for `app.listing` without inventing a column that
* does not exist. Not built here — see docs/P070's "Deferred: app.
* listing extraction" section for exactly what unblocks it.
*
* HONEST CAVEAT ON THE TWO SOURCES THAT ARE HERE: `listed_at`/`created_at`
* are set ONCE, at insert. Neither table has a column that bumps when an
* EXISTING row changes (`sold_at`/`floorplan_status` on dealer_stock_entry;
* `status` on deal). This connector will therefore reliably see every NEW
* row, but will NOT see an in-place UPDATE to an existing row as "changed" —
* it has already passed the watermark and will not be re-read. This is the
* same gap a real `updated_at` column (plus a trigger, e.g. `0084`-style)
* would close, and is exactly why building a permanent extractor deserves
* that schema decision rather than silently working around its absence.
* `docs/P070_VEHIQ_OLTP_EXTRACTOR.md` documents this as the #1 thing to
* settle before leaning on this extractor for anything beyond "count of new
* rows since X".
*/
export const VEHIQ_OLTP_SOURCES: VehiqOltpSourceDef[] = [
{
partition_key: "dealer_stock_entry",
table: "app.dealer_stock_entry",
columns: ["id", "tenant_id", "vehicle_id", "lot_location", "floorplan_status", "listed_at", "sold_at"],
record_key_column: "id",
watermark_column: "listed_at",
schema: {
id: { type: "string", required: true },
tenant_id: { type: "string", required: true },
vehicle_id: { type: "string", required: true },
lot_location: { type: "string", required: true },
floorplan_status: { type: "string", required: true },
listed_at: { type: "timestamp", required: true },
sold_at: { type: "timestamp", required: false },
},
},
{
partition_key: "deal",
table: "app.deal",
columns: ["id", "tenant_id", "party_id", "vehicle_id", "sale_price_minor", "currency", "status", "created_at"],
record_key_column: "id",
watermark_column: "created_at",
schema: {
id: { type: "string", required: true },
tenant_id: { type: "string", required: true },
party_id: { type: "string", required: true },
vehicle_id: { type: "string", required: true },
sale_price_minor: { type: "number", required: true },
currency: { type: "string", required: true },
status: { type: "string", required: true },
created_at: { type: "timestamp", required: true },
},
},
];
/**
* `vehiq.vehicle`'s primary key column is `vehicle_id`, NOT `id` — verified
* live (information_schema.columns, read-only, no data scanned) 2026-09-25.
* Column list otherwise matches what BI-P010/VEHIQ_ANALYTICS_BASELINE.md
* already documented (make/model/model_year/fuel_type all present and
* correctly named).
*/
export const VEHIQ_VEHICLE_DIMENSION_TABLE = "vehiq.vehicle";
export const VEHIQ_VEHICLE_DIMENSION_RECORD_KEY_COLUMN = "vehicle_id";
export const VEHIQ_VEHICLE_DIMENSION_COLUMNS = ["vehicle_id", "make", "model", "model_year", "fuel_type"];
export const VEHIQ_VEHICLE_DIMENSION_SCHEMA: RecordSchemaFields = {
vehicle_id: { type: "string", required: true },
make: { type: "string", required: false },
model: { type: "string", required: false },
model_year: { type: "number", required: false },
fuel_type: { type: "string", required: false },
};
// --- preview: read-only, never commits, safe against production at any time ---
export interface PreviewResult {
partition_key: string;
table: string;
/** Records this ONE bounded read would produce right now. */
would_read: number;
exhausted: boolean;
checkpoint_before: string | undefined;
next_cursor: string | undefined;
}
/**
* ONE bounded connect -> discover -> read(existing checkpoint, limit), then
* disconnect. Never calls IngestionRunner, never calls connector.checkpoint()
* against the repo, never writes anything anywhere. This is intentionally
* the ONLY function in this file that is safe to point at a real production
* source before the extractor is "activated" (see docs/P070).
*/
export async function previewVehiqOltpSource(
source: VehiqOltpSourceDef,
query: QueryImpl,
repo: Pick<IngestionRepository, "getCheckpoint">,
opts: { sourceId: string; tenantId: string; projectId: string; limit?: number } = {
sourceId: "vehiq_oltp",
tenantId: "t_vehiq",
projectId: "vehiq",
},
): Promise<PreviewResult> {
const connector = new PostgresWatermarkConnector(query);
const config = {
table: source.table,
partition_key: source.partition_key,
columns: source.columns,
record_key_column: source.record_key_column,
watermark_column: source.watermark_column,
schema: source.schema,
};
await connector.connect(config, {
tenant_id: opts.tenantId,
project_id: opts.projectId,
source_id: opts.sourceId,
run_id: `preview_${Date.now()}`,
});
try {
const existing = await repo.getCheckpoint(opts.sourceId, source.partition_key);
const result = await connector.read({
partition_key: source.partition_key,
cursor: existing?.cursor,
limit: opts.limit ?? 100,
});
return {
partition_key: source.partition_key,
table: source.table,
would_read: result.records.length,
exhausted: result.exhausted,
checkpoint_before: existing?.cursor,
next_cursor: result.next_cursor,
};
} finally {
await connector.disconnect();
}
}
// --- real run: the P062 highway, scheduled/activated path ---------------------
export interface VehiqOltpIngestDeps {
repo: IngestionRepository;
schemas: SchemaRegistry;
lineage?: LineageStore;
/** Read-only query against VehIQ's `vehiq-db` (server10) — see makePostgresQueryImpl in the calling script for the real implementation. */
sourceQuery: QueryImpl;
/** Where OLTP-entity envelopes land (see src/ingestion/projection-sink.ts). */
oltpSink: IngestionSink;
/** Where the narrow vehicle-dimension envelopes land. Same sink shape; kept separate so the two datasets can be routed differently if ever needed. */
dimensionSink: IngestionSink;
tenantId: string;
projectId: string;
sourceIdPrefix?: string;
pageSize?: number;
maxPages?: number;
}
export interface VehiqOltpIngestSummary {
oltp: IngestionRunReport[];
dimension?: IngestionRunReport;
referenced_vehicle_ids: number;
}
/**
* Runs the three watermark sources through the P062 runner, then derives the
* narrow vehicle-dimension key set from exactly what THIS run's
* `dealer_stock_entry` batch referenced (never a fresh scan, never the full
* 98M-row table) and runs that through the runner too, if there is anything
* to look up. When there is nothing new (today's actual production state:
* all three OLTP tables are empty), this function runs, reports 0 records
* read for every source, calls the dimension sink zero times, and returns
* cleanly — the empty-table case is a normal, successful, no-op run, not a
* special case that needs its own error handling.
*/
export async function runVehiqOltpIngestion(deps: VehiqOltpIngestDeps): Promise<VehiqOltpIngestSummary> {
const runner = new IngestionRunner(deps.repo, deps.schemas, deps.lineage);
const sourceIdPrefix = deps.sourceIdPrefix ?? "vehiq_oltp";
const oltpReports: IngestionRunReport[] = [];
const referencedVehicleIds = new Set<string>();
for (const source of VEHIQ_OLTP_SOURCES) {
const seen: IngestionEnvelope[] = [];
const wrappedSink: IngestionSink = async (envelopes) => {
seen.push(...envelopes);
await deps.oltpSink(envelopes);
};
const connector = new PostgresWatermarkConnector(deps.sourceQuery);
const report = await runner.run({
source_id: `${sourceIdPrefix}_${source.partition_key}`,
tenant_id: deps.tenantId,
project_id: deps.projectId,
mode: "batch",
connector,
config: {
table: source.table,
partition_key: source.partition_key,
columns: source.columns,
record_key_column: source.record_key_column,
watermark_column: source.watermark_column,
schema: source.schema,
},
sink: wrappedSink,
page_size: deps.pageSize ?? 200,
max_pages: deps.maxPages ?? 1000,
output_ref: `0pt:dataset:vehiq.${source.partition_key}`,
});
oltpReports.push(report);
if (source.partition_key === "dealer_stock_entry") {
for (const envelope of seen) {
const vehicleId = envelope.payload?.["vehicle_id"];
if (typeof vehicleId === "string" && vehicleId.length > 0) referencedVehicleIds.add(vehicleId);
else if (typeof vehicleId === "number") referencedVehicleIds.add(String(vehicleId));
}
}
}
let dimensionReport: IngestionRunReport | undefined;
if (referencedVehicleIds.size > 0) {
const keys = [...referencedVehicleIds];
const dimensionConnector = new PostgresKeyedLookupConnector(deps.sourceQuery);
dimensionReport = await runner.run({
source_id: `${sourceIdPrefix}_dimension_vehicle`,
tenant_id: deps.tenantId,
project_id: deps.projectId,
mode: "batch",
connector: dimensionConnector,
config: {
table: VEHIQ_VEHICLE_DIMENSION_TABLE,
partition_key: "dimension_vehicle",
columns: VEHIQ_VEHICLE_DIMENSION_COLUMNS,
record_key_column: VEHIQ_VEHICLE_DIMENSION_RECORD_KEY_COLUMN,
schema: VEHIQ_VEHICLE_DIMENSION_SCHEMA,
keys,
},
sink: deps.dimensionSink,
page_size: deps.pageSize ?? 200,
max_pages: deps.maxPages ?? 1000,
output_ref: "0pt:dataset:vehiq.dimension_vehicle",
});
}
return { oltp: oltpReports, dimension: dimensionReport, referenced_vehicle_ids: referencedVehicleIds.size };
}
/** Re-exported so callers (the CLI script, tests) don't need a second import from the connector module. */
export { decodeCursor };