fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
+87
View File
@@ -0,0 +1,87 @@
/**
* src/ingestion/envelope.ts
* ==========================
* P062: the one place a ConnectorRecord becomes an IngestionEnvelope. Every
* connector, every mode, one function — that is what "normalize all ingestion
* to a common envelope" means operationally.
*
* `hashPayload` is the stable content hash the idempotency ledger (P068) and
* the deterministic `envelope_id` are both built on. Key order must not
* change the hash — two connectors reading the same record can serialize the
* same object with different key order — so keys are sorted recursively.
* Undefined values are dropped (JSON has no undefined); null is kept, because
* "field explicitly null" is different data from "field absent".
*/
import crypto from "crypto";
import type { ConnectorRecord } from "../connectors/connector";
import type { EnvelopeOperation, IngestionEnvelope, IngestionMode } from "../types/ingestion";
/** Recursively key-sorted JSON — stable across key insertion order. */
export function stableStringify(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
if (typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}
/** Content hash of an envelope payload. A delete (null payload) hashes as "deleted". */
export function hashPayload(payload: Record<string, unknown> | null): string {
if (payload === null) return "sha256:deleted";
return `sha256:${crypto.createHash("sha256").update(stableStringify(payload)).digest("hex")}`;
}
export interface BuildEnvelopeInput {
record: ConnectorRecord;
source_id: string;
tenant_id: string;
project_id: string;
mode: IngestionMode;
partition_key: string;
schema_version: number;
sequence: number;
connector_id: string;
connector_version: string;
run_id: string;
/** Cursor covering this record, when the connector reports one. */
cursor?: string;
now?: string;
}
export function buildEnvelope(input: BuildEnvelopeInput): IngestionEnvelope {
const operation: EnvelopeOperation = input.record.operation ?? "upsert";
const payload = operation === "delete" ? null : input.record.payload;
const contentHash = hashPayload(payload);
return {
// Deterministic: the same record with the same content re-read after a
// crash produces the same envelope_id, so a downstream sink that dedups
// by id sees a retry, not a new record.
envelope_id: `env_${crypto
.createHash("sha256")
.update(`${input.source_id}|${input.partition_key}|${input.record.record_key}|${contentHash}`)
.digest("hex")
.slice(0, 32)}`,
source_id: input.source_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
mode: input.mode,
operation,
partition_key: input.partition_key,
record_key: input.record.record_key,
schema_version: input.schema_version,
sequence: input.sequence,
occurred_at: input.record.occurred_at,
ingested_at: input.now ?? new Date().toISOString(),
payload,
provenance: {
connector_id: input.connector_id,
connector_version: input.connector_version,
run_id: input.run_id,
cursor: input.cursor ?? input.record.cursor,
},
};
}
+557
View File
@@ -0,0 +1,557 @@
/**
* src/ingestion/ingestion-runner.ts
* ==================================
* The single ingestion highway (P062, P063 gate, P064 gate, P067 emission,
* P068 ledger). One loop, one envelope shape, one durable checkpoint.
*
* ORDERING IS THE WHOLE CONTRACT. Per page:
*
* read/resume -> normalize to envelopes -> schema conformance -> quality gate
* -> ledger PEEK (filter replays) -> SINK -> ledger COMMIT -> checkpoint COMMIT
*
* Both commits happen AFTER the sink resolves. That is what makes "a restart
* resumes without silent gaps" true: a process that dies anywhere before the
* commits leaves the page unconsumed, the next run re-reads it, and nothing is
* lost. The two tempting shortcuts are both data-loss bugs, and one of them
* was actually written here first:
* - committing the CHECKPOINT before the sink skips the page entirely;
* - committing the LEDGER before the sink marks records delivered that the
* sink never received, so the resumed run drops them as duplicates. This
* one shipped in the first draft of this file and was caught by
* tests/p0/ingestion-runner.test.ts's crash/resume case (7 of 10 records
* delivered). The peek/commit split in IngestionRepository exists because
* of it.
*
* The resulting delivery guarantee is AT-LEAST-ONCE, not exactly-once: two
* concurrent runs on the same partition can both peek "new". `envelope_id` is
* deterministic so a dedup-capable sink survives that. A per-(source,
* partition) run lock does not exist yet — see STATUS.md.
*
* A BLOCKED quality page also stops WITHOUT committing: a blocked page must
* stay unconsumed, not be skipped over.
*
* WHAT THIS RUNNER DOES NOT DO, stated plainly:
* - it does not schedule itself (ACT0 owns scheduling; the source's
* `schedule` row is a declaration, not a cron daemon in this repo),
* - it does not write to a lakehouse — the `sink` is supplied by the
* caller, because the Iceberg write boundary is ST0RE's contract
* (src/services/iceberg-write-service.ts) and is owned by another repo
* in this programme (P066),
* - it does not do entity resolution. The canonical ER engine is
* src/er/entity-resolution-service.ts and runs downstream of the sink.
*/
import crypto from "crypto";
import { SiaxError } from "../platform/errors";
import { conformanceErrors } from "../schema/compatibility";
import type { SchemaRegistry } from "../schema/schema-registry";
import { QualityGate, type QualityEnforcementPolicy } from "../quality/quality-policy";
import type { IngestionRepository } from "../repositories/ingestion-repository";
import type { LineageStore } from "../lineage/lineage-store";
import type {
BackfillRequest,
Connector,
ConnectorConfig,
ReadResult,
} from "../connectors/connector";
import type {
IngestionCheckpoint,
IngestionEnvelope,
IngestionMode,
QuarantineRecord,
} from "../types/ingestion";
import { buildEnvelope, hashPayload } from "./envelope";
/** Where accepted envelopes go. Supplied by the caller — see the module note. */
export type IngestionSink = (envelopes: IngestionEnvelope[]) => Promise<void>;
export interface IngestionRunInput {
source_id: string;
tenant_id: string;
project_id: string;
mode: IngestionMode;
connector: Connector;
config: ConnectorConfig;
sink: IngestionSink;
/** Deterministic run id. Defaults to a random one. */
run_id?: string;
/** Records per connector read. Default 100. */
page_size?: number;
/** Safety stop. Default 1000 pages. */
max_pages?: number;
/** Only this partition; default is every partition discover() reports. */
partition_key?: string;
/** P064. Omitted = no gate runs, and the report says so explicitly. */
quality_policy?: QualityEnforcementPolicy;
/** Canonical ref of what the sink produces, for lineage (e.g. "0pt:dataset:ds_x"). */
output_ref?: string;
correlation_id?: string;
}
export interface PartitionRunReport {
partition_key: string;
schema_version: number;
pages_read: number;
records_read: number;
envelopes_emitted: number;
duplicates_skipped: number;
changed: number;
quarantined: number;
quality_violations: number;
checkpoint: IngestionCheckpoint;
/** Set when the partition stopped early. */
stopped_because?: "blocked_by_quality" | "max_pages" | "sink_failed";
}
export interface IngestionRunReport {
run_id: string;
source_id: string;
tenant_id: string;
mode: IngestionMode;
status: "succeeded" | "failed";
/** Honest marker: "none_declared" when the caller supplied no policy at all. */
quality_policy: "block" | "quarantine" | "warn" | "none_declared";
partitions: PartitionRunReport[];
lineage_edges: number;
/** Present when status is "failed". */
failure?: { code: string; detail: string };
}
export class IngestionRunner {
private readonly gate: QualityGate;
constructor(
private readonly repo: IngestionRepository,
private readonly schemas: SchemaRegistry,
private readonly lineage?: LineageStore,
gate?: QualityGate,
) {
this.gate = gate ?? new QualityGate();
}
async run(input: IngestionRunInput): Promise<IngestionRunReport> {
const runId = input.run_id ?? `run_${crypto.randomUUID()}`;
const pageSize = input.page_size ?? 100;
const maxPages = input.max_pages ?? 1000;
const report: IngestionRunReport = {
run_id: runId,
source_id: input.source_id,
tenant_id: input.tenant_id,
mode: input.mode,
status: "succeeded",
quality_policy: input.quality_policy?.on_violation ?? "none_declared",
partitions: [],
lineage_edges: 0,
};
const verdict = input.connector.validate(input.config);
if (!verdict.valid) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.ingestion",
`connector config rejected: ${verdict.errors.join("; ")}`,
);
}
await input.connector.connect(input.config, {
tenant_id: input.tenant_id,
project_id: input.project_id,
source_id: input.source_id,
run_id: runId,
});
try {
const discovery = await input.connector.discover();
if (!discovery.modes.includes(input.mode)) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.ingestion",
`connector ${input.connector.connector_id} does not serve mode "${input.mode}" for this config (serves: ${discovery.modes.join(", ")})`,
);
}
const partitions = input.partition_key
? discovery.partitions.filter((p) => p.partition_key === input.partition_key)
: discovery.partitions;
if (partitions.length === 0) {
throw new SiaxError(
"NOT_FOUND",
"0pt.ingestion",
`partition "${input.partition_key}" was not discovered on source ${input.source_id}`,
);
}
// ---- P063: schema gate, BEFORE any record is read ------------------
// Every partition's shape is checked and registered first. A break
// fails the whole run here, so no envelope — and therefore no consumer
// write — can happen under a broken schema.
const schemaVersions = new Map<string, number>();
for (const partition of partitions) {
const evaluated = await this.schemas.evaluate(input.source_id, partition.schema);
if (evaluated.verdict && !evaluated.verdict.compatible) {
throw new SiaxError(
"CONFLICT",
"0pt.ingestion",
`source ${input.source_id} partition "${partition.partition_key}" changed shape in a way that breaks its declared ` +
`"${evaluated.verdict.policy}" compatibility policy — refusing to ingest: ` +
evaluated.verdict.breaks.map((b) => `[${b.breaks}] ${b.detail}`).join("; "),
);
}
const registered = await this.schemas.register({
source_id: input.source_id,
tenant_id: input.tenant_id,
fields: partition.schema,
compatibility: evaluated.previous?.compatibility ?? "backward",
registered_by: `run:${runId}`,
});
schemaVersions.set(partition.partition_key, registered.schema.schema_version);
}
for (const partition of partitions) {
report.partitions.push(
await this.runPartition(input, {
runId,
pageSize,
maxPages,
partitionKey: partition.partition_key,
schemaVersion: schemaVersions.get(partition.partition_key) ?? 1,
}),
);
}
// ---- P067: one lineage event per run, source -> output -------------
if (this.lineage) {
report.lineage_edges = await this.lineage.record(
{
eventType: "COMPLETE",
eventTime: new Date().toISOString(),
producer: "https://git.siax.io/sax3l/0pt",
run: { runId },
job: { namespace: "0pt", name: "0pt.ingestion.run.v1" },
inputs: [
{
namespace: "0pt",
name: `source/${input.source_id}`,
facets: { siaxResourceRef: { ref: `0pt:source:${input.source_id}` } },
},
],
outputs: [
{
namespace: "0pt",
name: input.output_ref ?? `ingestion/${input.source_id}`,
...(input.output_ref ? { facets: { siaxResourceRef: { ref: input.output_ref } } } : {}),
},
],
},
input.tenant_id,
input.correlation_id,
);
}
return report;
} finally {
await input.connector.disconnect();
}
}
/**
* P068: a bounded historical re-read. Runs through the SAME envelope,
* quality and ledger path as `run`, and deliberately does NOT touch the
* streaming checkpoint — a backfill must not rewind or advance live
* ingestion. Repeating an identical backfill emits nothing: every record
* comes back "duplicate" from the ledger.
*/
async backfill(
input: IngestionRunInput & { range: Omit<BackfillRequest, "limit"> },
): Promise<PartitionRunReport> {
const runId = input.run_id ?? `bkf_${crypto.randomUUID()}`;
const pageSize = input.page_size ?? 100;
const verdict = input.connector.validate(input.config);
if (!verdict.valid) {
throw new SiaxError("INVALID_REQUEST", "0pt.ingestion", `connector config rejected: ${verdict.errors.join("; ")}`);
}
await input.connector.connect(input.config, {
tenant_id: input.tenant_id,
project_id: input.project_id,
source_id: input.source_id,
run_id: runId,
});
try {
const latest = await this.schemas.getLatest(input.source_id);
const schemaVersion = latest?.schema_version ?? 1;
const result = await input.connector.backfill({ ...input.range, limit: pageSize });
const existing =
(await this.repo.getCheckpoint(input.source_id, input.range.partition_key)) ??
this.emptyCheckpoint(input, input.range.partition_key);
const outcome = await this.consumePage(input, {
runId,
result,
partitionKey: input.range.partition_key,
schemaVersion,
startSequence: existing.sequence,
schemaFields: latest?.fields,
});
return {
partition_key: input.range.partition_key,
schema_version: schemaVersion,
pages_read: 1,
records_read: result.records.length,
envelopes_emitted: outcome.emitted,
duplicates_skipped: outcome.duplicates,
changed: outcome.changed,
quarantined: outcome.quarantined,
quality_violations: outcome.violations,
// Unchanged on purpose — a backfill leaves the live checkpoint alone.
checkpoint: existing,
stopped_because: outcome.blocked ? "blocked_by_quality" : undefined,
};
} finally {
await input.connector.disconnect();
}
}
// -------------------------------------------------------------------------
private emptyCheckpoint(
input: { source_id: string; tenant_id: string },
partitionKey: string,
): IngestionCheckpoint {
return {
source_id: input.source_id,
tenant_id: input.tenant_id,
partition_key: partitionKey,
cursor: undefined,
sequence: 0,
records_committed: 0,
committed_at: new Date(0).toISOString(),
};
}
private async runPartition(
input: IngestionRunInput,
opts: {
runId: string;
pageSize: number;
maxPages: number;
partitionKey: string;
schemaVersion: number;
},
): Promise<PartitionRunReport> {
const schema = await this.schemas.getLatest(input.source_id);
let checkpoint =
(await this.repo.getCheckpoint(input.source_id, opts.partitionKey)) ??
this.emptyCheckpoint(input, opts.partitionKey);
const stats = {
pages: 0,
records: 0,
emitted: 0,
duplicates: 0,
changed: 0,
quarantined: 0,
violations: 0,
};
let stoppedBecause: PartitionRunReport["stopped_because"];
for (let page = 0; page < opts.maxPages; page++) {
// First page of a partition that has a durable checkpoint goes through
// resume(), so a connector that must re-establish server-side state has
// its chance; later pages are ordinary reads from the running cursor.
const result: ReadResult =
page === 0 && checkpoint.cursor !== undefined
? await input.connector.resume(checkpoint, opts.pageSize)
: await input.connector.read({
partition_key: opts.partitionKey,
cursor: checkpoint.cursor,
limit: opts.pageSize,
});
stats.pages++;
stats.records += result.records.length;
if (result.records.length === 0) break;
const outcome = await this.consumePage(input, {
runId: opts.runId,
result,
partitionKey: opts.partitionKey,
schemaVersion: opts.schemaVersion,
startSequence: checkpoint.sequence,
schemaFields: schema?.fields,
});
stats.emitted += outcome.emitted;
stats.duplicates += outcome.duplicates;
stats.changed += outcome.changed;
stats.quarantined += outcome.quarantined;
stats.violations += outcome.violations;
if (outcome.blocked) {
// The checkpoint is NOT advanced: the offending page stays unconsumed
// so the next run sees it again rather than stepping over it.
stoppedBecause = "blocked_by_quality";
break;
}
checkpoint = {
source_id: input.source_id,
tenant_id: input.tenant_id,
partition_key: opts.partitionKey,
cursor: result.next_cursor,
sequence: checkpoint.sequence + result.records.length,
records_committed: checkpoint.records_committed + outcome.emitted,
committed_at: new Date().toISOString(),
};
await this.repo.commitCheckpoint(checkpoint);
if (result.exhausted) break;
if (page === opts.maxPages - 1) stoppedBecause = "max_pages";
}
return {
partition_key: opts.partitionKey,
schema_version: opts.schemaVersion,
pages_read: stats.pages,
records_read: stats.records,
envelopes_emitted: stats.emitted,
duplicates_skipped: stats.duplicates,
changed: stats.changed,
quarantined: stats.quarantined,
quality_violations: stats.violations,
checkpoint,
stopped_because: stoppedBecause,
};
}
/**
* Normalize -> schema conformance -> quality gate -> ledger -> sink.
* Throws if the sink throws; the caller must NOT have committed a
* checkpoint by then.
*/
private async consumePage(
input: IngestionRunInput,
opts: {
runId: string;
result: ReadResult;
partitionKey: string;
schemaVersion: number;
startSequence: number;
schemaFields?: Record<string, { type: string; required: boolean }>;
},
): Promise<{
emitted: number;
duplicates: number;
changed: number;
quarantined: number;
violations: number;
blocked: boolean;
}> {
const envelopes: IngestionEnvelope[] = opts.result.records.map((record, i) =>
buildEnvelope({
record,
source_id: input.source_id,
tenant_id: input.tenant_id,
project_id: input.project_id,
mode: input.mode,
partition_key: opts.partitionKey,
schema_version: opts.schemaVersion,
sequence: opts.startSequence + i + 1,
connector_id: input.connector.connector_id,
connector_version: input.connector.connector_version,
run_id: opts.runId,
cursor: opts.result.next_cursor,
}),
);
// ---- P063 per-record conformance ------------------------------------
// A source that silently changed shape without a new discovery is caught
// here, on the record, before the sink sees anything from this page.
if (opts.schemaFields) {
for (const envelope of envelopes) {
if (envelope.payload === null) continue;
const errors = conformanceErrors(
opts.schemaFields as never,
envelope.payload,
);
if (errors.length > 0) {
throw new SiaxError(
"CONFLICT",
"0pt.ingestion",
`record "${envelope.record_key}" does not conform to registered schema v${opts.schemaVersion} ` +
`for source ${input.source_id}: ${errors.join("; ")}`,
);
}
}
}
// ---- P064 quality gate ----------------------------------------------
let accepted = envelopes;
let quarantinedCount = 0;
let violationCount = 0;
let blocked = false;
if (input.quality_policy) {
const gated = this.gate.evaluate(envelopes, input.quality_policy);
accepted = gated.accepted;
blocked = gated.blocked;
violationCount = gated.violations.length;
for (const item of gated.quarantined) {
const record: QuarantineRecord = {
quarantine_id: `qtn_${crypto
.createHash("sha256")
.update(`${opts.runId}|${item.envelope.envelope_id}`)
.digest("hex")
.slice(0, 32)}`,
source_id: input.source_id,
tenant_id: input.tenant_id,
run_id: opts.runId,
record_key: item.envelope.record_key,
violations: item.violations,
envelope: item.envelope,
quarantined_at: new Date().toISOString(),
};
await this.repo.quarantine(record);
quarantinedCount++;
}
if (blocked) {
return {
emitted: 0,
duplicates: 0,
changed: 0,
quarantined: quarantinedCount,
violations: violationCount,
blocked: true,
};
}
}
// ---- P068 idempotency ledger, PEEK ONLY ------------------------------
// Read the verdicts, filter replays, and commit NOTHING yet: a record is
// only "delivered" once the sink has actually taken it. Committing here
// would mark records delivered that a crashing sink never received, and
// the resumed run would then skip them as duplicates — silent data loss.
const entries = accepted.map((e) => ({
record_key: e.record_key,
payload_hash: hashPayload(e.payload),
}));
const decisions = await this.repo.peekDeliveries(input.source_id, entries);
const verdictByKey = new Map(decisions.map((d) => [d.record_key, d.verdict]));
const toEmit = accepted.filter((e) => verdictByKey.get(e.record_key) !== "duplicate");
const duplicates = accepted.length - toEmit.length;
const changed = decisions.filter((d) => d.verdict === "changed").length;
// ---- sink (the consumer write) --------------------------------------
if (toEmit.length > 0) await input.sink(toEmit);
// ---- P068 ledger COMMIT, after the sink resolved ---------------------
const emitted = new Set(toEmit.map((e) => e.record_key));
const committed = entries.filter((e) => emitted.has(e.record_key));
if (committed.length > 0) {
await this.repo.commitDeliveries(input.source_id, input.tenant_id, committed);
}
return {
emitted: toEmit.length,
duplicates,
changed,
quarantined: quarantinedCount,
violations: violationCount,
blocked: false,
};
}
}
+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 };