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]>
218 lines
10 KiB
TypeScript
218 lines
10 KiB
TypeScript
/**
|
|
* End-to-end proof for src/ingestion/vehiq-oltp-ingest-runner.ts — the
|
|
* actual pipeline the scheduled workflow runs, wired through the REAL P062
|
|
* IngestionRunner (InMemoryIngestionRepository backing it, no real
|
|
* Postgres/ClickHouse). Four things the task requires are asserted here
|
|
* specifically, not just "it doesn't throw":
|
|
*
|
|
* 1. a batch respects the watermark/limit (proven at the connector layer
|
|
* already; here proven again at the FULL pipeline layer, envelope by
|
|
* envelope);
|
|
* 2. a run resumes correctly from a checkpoint after an interruption (a
|
|
* sink that throws on its 2nd call, mid-run — same technique
|
|
* tests/p0/ingestion-runner.test.ts itself uses to prove this for the
|
|
* generic runner);
|
|
* 3. the empty-table case (today's actual production state for all three
|
|
* OLTP tables) completes with zero batches / zero sink calls / no
|
|
* throw;
|
|
* 4. the vehicle-dimension lookup only ever touches vehicle rows actually
|
|
* referenced by dealer_stock_entry in the batch that ran — asserted by
|
|
* capturing every query the dimension connector issues.
|
|
*/
|
|
import { describe, expect, it } from "vitest";
|
|
import { InMemoryIngestionRepository } from "@/src/repositories/in-memory-ingestion-repository";
|
|
import { SchemaRegistry } from "@/src/schema/schema-registry";
|
|
import {
|
|
runVehiqOltpIngestion,
|
|
previewVehiqOltpSource,
|
|
VEHIQ_OLTP_SOURCES,
|
|
type VehiqOltpIngestDeps,
|
|
} from "@/src/ingestion/vehiq-oltp-ingest-runner";
|
|
import type { QueryImpl, SourceRow } from "@/src/connectors/postgres-watermark-connector";
|
|
import type { IngestionEnvelope } from "@/src/types/ingestion";
|
|
|
|
/**
|
|
* A fake source Postgres. One table per fixture entry, keyed by the
|
|
* connector's own `table` name. Generic across whichever watermark/
|
|
* record-key column names the real connector puts in the SQL text — parsed
|
|
* out of the statement itself (`ORDER BY <watermark>, <key>`) rather than
|
|
* hardcoded, since `dealer_stock_entry` (watermark `listed_at`, key `id`)
|
|
* and `deal` (watermark `created_at`, key `id`) use different column names.
|
|
*/
|
|
function fixtureVehiqDb(tables: Record<string, SourceRow[]>): { query: QueryImpl; calls: Array<{ sql: string; params: unknown[] }> } {
|
|
const calls: Array<{ sql: string; params: unknown[] }> = [];
|
|
const query: QueryImpl = async (sql, params) => {
|
|
calls.push({ sql, params });
|
|
const tableName = Object.keys(tables).find((t) => sql.includes(`FROM ${t}`));
|
|
const rows = tableName ? tables[tableName] : [];
|
|
const orderBy = /ORDER BY (\w+), (\w+)/.exec(sql);
|
|
if (sql.includes("= ANY($1)")) {
|
|
const keyColMatch = /WHERE (\w+) = ANY/.exec(sql);
|
|
const keyCol = keyColMatch ? keyColMatch[1] : "id";
|
|
const [ids] = params as [Array<string | number>];
|
|
return rows.filter((r) => ids.includes(r[keyCol] as string));
|
|
}
|
|
if (!orderBy) return rows.slice(0, Number(params[params.length - 1]));
|
|
const [, watermarkCol, keyCol] = orderBy;
|
|
let filtered = rows;
|
|
if (sql.includes("WHERE")) {
|
|
const [watermark, id] = params as [string, string, number];
|
|
filtered = rows.filter(
|
|
(r) => (r[watermarkCol] as string) > watermark || ((r[watermarkCol] as string) === watermark && (r[keyCol] as string) > id),
|
|
);
|
|
}
|
|
const sorted = [...filtered].sort((a, b) => {
|
|
const w = (a[watermarkCol] as string).localeCompare(b[watermarkCol] as string);
|
|
return w !== 0 ? w : (a[keyCol] as string).localeCompare(b[keyCol] as string);
|
|
});
|
|
const limit = Number(params[params.length - 1]);
|
|
return sorted.slice(0, limit);
|
|
};
|
|
return { query, calls };
|
|
}
|
|
|
|
function baseDeps(query: QueryImpl, sink: (e: IngestionEnvelope[]) => Promise<void>): VehiqOltpIngestDeps {
|
|
const repo = new InMemoryIngestionRepository();
|
|
return {
|
|
repo,
|
|
schemas: new SchemaRegistry(repo),
|
|
sourceQuery: query,
|
|
oltpSink: sink,
|
|
dimensionSink: sink,
|
|
tenantId: "t_vehiq",
|
|
projectId: "vehiq",
|
|
pageSize: 2,
|
|
};
|
|
}
|
|
|
|
describe("runVehiqOltpIngestion — empty-table case (today's actual production state)", () => {
|
|
it("completes with zero batches, zero sink calls, no error, for all three OLTP tables", async () => {
|
|
const { query } = fixtureVehiqDb({ "app.dealer_stock_entry": [], "app.listing": [], "app.deal": [] });
|
|
const seen: IngestionEnvelope[] = [];
|
|
const summary = await runVehiqOltpIngestion(baseDeps(query, async (e) => void seen.push(...e)));
|
|
|
|
expect(seen).toHaveLength(0);
|
|
expect(summary.referenced_vehicle_ids).toBe(0);
|
|
expect(summary.dimension).toBeUndefined(); // no referenced vehicles => the keyed-lookup connector is never even constructed
|
|
for (const report of summary.oltp) {
|
|
expect(report.status).toBe("succeeded");
|
|
expect(report.partitions.every((p) => p.records_read === 0)).toBe(true);
|
|
expect(report.partitions.every((p) => p.envelopes_emitted === 0)).toBe(true);
|
|
}
|
|
});
|
|
|
|
it("previewVehiqOltpSource against empty tables never commits a checkpoint and reports would_read: 0", async () => {
|
|
const { query } = fixtureVehiqDb({ "app.dealer_stock_entry": [] });
|
|
const repo = new InMemoryIngestionRepository();
|
|
const source = VEHIQ_OLTP_SOURCES.find((s) => s.partition_key === "dealer_stock_entry")!;
|
|
const preview = await previewVehiqOltpSource(source, query, repo, {
|
|
sourceId: "vehiq_oltp",
|
|
tenantId: "t_vehiq",
|
|
projectId: "vehiq",
|
|
});
|
|
expect(preview.would_read).toBe(0);
|
|
expect(preview.exhausted).toBe(true);
|
|
// Never committed — getCheckpoint after the preview still reports nothing.
|
|
expect(await repo.getCheckpoint("vehiq_oltp", "dealer_stock_entry")).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// Column shape verified live against production (server10, vehiq-db,
|
|
// information_schema.columns, read-only, 2026-09-25) — see the doc comment
|
|
// on VEHIQ_OLTP_SOURCES for why there is no `updated_at` here.
|
|
const DEALER_STOCK_ROWS: SourceRow[] = [
|
|
{ id: "d1", tenant_id: "t_vehiq", vehicle_id: "v1", lot_location: "Lot A", floorplan_status: "owned", listed_at: "2026-09-01T00:00:00.000Z", sold_at: null },
|
|
{ id: "d2", tenant_id: "t_vehiq", vehicle_id: "v2", lot_location: "Lot A", floorplan_status: "financed", listed_at: "2026-09-02T00:00:00.000Z", sold_at: null },
|
|
{ id: "d3", tenant_id: "t_vehiq", vehicle_id: "v1", lot_location: "Lot B", floorplan_status: "owned", listed_at: "2026-09-03T00:00:00.000Z", sold_at: "2026-09-04T00:00:00.000Z" },
|
|
];
|
|
const VEHICLE_ROWS: SourceRow[] = [
|
|
{ vehicle_id: "v1", make: "Volvo", model: "XC60", model_year: 2022, fuel_type: "electric" },
|
|
{ vehicle_id: "v2", make: "Toyota", model: "Corolla", model_year: 2021, fuel_type: "petrol" },
|
|
{ vehicle_id: "v9", make: "Never", model: "Referenced", model_year: 2020, fuel_type: "diesel" }, // must never be queried
|
|
];
|
|
|
|
describe("runVehiqOltpIngestion — watermark/limit correctness with real data", () => {
|
|
it("emits envelopes for every row, in watermark order, and derives exactly the referenced vehicle ids", async () => {
|
|
const { query } = fixtureVehiqDb({
|
|
"app.dealer_stock_entry": DEALER_STOCK_ROWS,
|
|
"app.listing": [],
|
|
"app.deal": [],
|
|
"vehiq.vehicle": VEHICLE_ROWS,
|
|
});
|
|
const seen: IngestionEnvelope[] = [];
|
|
const dimensionSeen: IngestionEnvelope[] = [];
|
|
const deps = baseDeps(query, async (e) => void seen.push(...e));
|
|
deps.dimensionSink = async (e) => void dimensionSeen.push(...e);
|
|
|
|
const summary = await runVehiqOltpIngestion(deps);
|
|
|
|
const dealerEnvelopes = seen.filter((e) => e.partition_key === "dealer_stock_entry");
|
|
expect(dealerEnvelopes.map((e) => e.record_key)).toEqual(["d1", "d2", "d3"]);
|
|
expect(summary.referenced_vehicle_ids).toBe(2); // v1, v2 — deduped from d1/d2/d3
|
|
expect(summary.dimension?.status).toBe("succeeded");
|
|
expect(dimensionSeen.map((e) => e.record_key).sort()).toEqual(["v1", "v2"]);
|
|
expect(dimensionSeen.map((e) => e.record_key)).not.toContain("v9");
|
|
});
|
|
});
|
|
|
|
describe("runVehiqOltpIngestion — resume from checkpoint after an interruption", () => {
|
|
it("a sink that dies mid-run leaves the checkpoint unmoved for the failed page; the NEXT run resumes with no gap and no duplicate landing", async () => {
|
|
const { query } = fixtureVehiqDb({
|
|
"app.dealer_stock_entry": DEALER_STOCK_ROWS,
|
|
"app.listing": [],
|
|
"app.deal": [],
|
|
"vehiq.vehicle": VEHICLE_ROWS,
|
|
});
|
|
const repo = new InMemoryIngestionRepository();
|
|
const schemas = new SchemaRegistry(repo);
|
|
const landed: IngestionEnvelope[] = [];
|
|
let call = 0;
|
|
|
|
// First run: the sink accepts page 1 (2 rows, page_size=2) then throws on
|
|
// page 2 — simulating the process dying after the first page's checkpoint
|
|
// committed but before the second page's did.
|
|
const crashingSink = async (batch: IngestionEnvelope[]): Promise<void> => {
|
|
call++;
|
|
if (call === 2) throw new Error("simulated crash mid-run");
|
|
landed.push(...batch);
|
|
};
|
|
// Matches the generic runner's own documented behaviour (tests/p0/
|
|
// ingestion-runner.test.ts "a run that dies inside the sink..."): a
|
|
// throwing sink REJECTS the run, it does not resolve with status:"failed".
|
|
// dealer_stock_entry is the FIRST source this pipeline processes, so its
|
|
// page-2 crash is what aborts runVehiqOltpIngestion() itself here.
|
|
await expect(
|
|
runVehiqOltpIngestion({
|
|
repo,
|
|
schemas,
|
|
sourceQuery: query,
|
|
oltpSink: crashingSink,
|
|
dimensionSink: async () => undefined,
|
|
tenantId: "t_vehiq",
|
|
projectId: "vehiq",
|
|
pageSize: 2,
|
|
}),
|
|
).rejects.toThrow(/simulated crash mid-run/);
|
|
expect(landed.map((e) => e.record_key)).toEqual(["d1", "d2"]); // page 1 landed before the crash
|
|
// The durable checkpoint reflects page 1 only — page 2's checkpoint never committed.
|
|
const afterCrash = await repo.getCheckpoint("vehiq_oltp_dealer_stock_entry", "dealer_stock_entry");
|
|
expect(afterCrash?.records_committed).toBe(2);
|
|
|
|
// Second run, same repo (durable checkpoint survives the "restart"): must
|
|
// NOT re-deliver d1/d2, and MUST deliver d3.
|
|
const run2 = await runVehiqOltpIngestion({
|
|
repo,
|
|
schemas,
|
|
sourceQuery: query,
|
|
oltpSink: async (batch) => void landed.push(...batch),
|
|
dimensionSink: async () => undefined,
|
|
tenantId: "t_vehiq",
|
|
projectId: "vehiq",
|
|
pageSize: 2,
|
|
});
|
|
const dealerReport2 = run2.oltp.find((r) => r.partitions[0]?.partition_key === "dealer_stock_entry");
|
|
expect(dealerReport2?.status).toBe("succeeded");
|
|
expect(landed.map((e) => e.record_key)).toEqual(["d1", "d2", "d3"]); // exactly once each, no gap, no dupe
|
|
});
|
|
});
|