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
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:
co-authored by
Claude Sonnet 5
parent
ec487746fd
commit
07158099ee
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Proves the narrow-scan property of PostgresKeyedLookupConnector — the
|
||||
* connector that stands in for "dealer_stock_entry.vehicle_id -> unique
|
||||
* vehicle IDs -> targeted lookup -> dimension_vehicle", never a scan of the
|
||||
* 98M-row `vehicle` table. The assertions are on QUERY CALLS, not just
|
||||
* returned records: a bug that widened the WHERE clause but happened to
|
||||
* still return the right rows in a test fixture would be invisible to a
|
||||
* behavioural-only test and is exactly what this file is written to catch.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PostgresKeyedLookupConnector } from "@/src/connectors/postgres-keyed-lookup-connector";
|
||||
import type { QueryImpl, SourceRow } from "@/src/connectors/postgres-watermark-connector";
|
||||
import type { RecordSchemaFields } from "@/src/schema/record-schema";
|
||||
|
||||
const SCHEMA: RecordSchemaFields = {
|
||||
id: { type: "string", required: true },
|
||||
make: { type: "string", required: false },
|
||||
model: { type: "string", required: false },
|
||||
};
|
||||
|
||||
const VEHICLE_TABLE: SourceRow[] = [
|
||||
{ id: "v1", make: "Volvo", model: "XC60" },
|
||||
{ id: "v2", make: "Volvo", model: "V70" },
|
||||
{ id: "v3", make: "Toyota", model: "Corolla" },
|
||||
{ id: "v4", make: "Audi", model: "A4" }, // never referenced by any dealer_stock_entry in these tests
|
||||
];
|
||||
|
||||
function fixtureQuery(): { 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 [ids] = params as [Array<string | number>];
|
||||
return VEHICLE_TABLE.filter((row) => ids.includes(row.id as string));
|
||||
};
|
||||
return { query, calls };
|
||||
}
|
||||
|
||||
function config(keys: Array<string | number>, keysPerQuery?: number) {
|
||||
return {
|
||||
table: "vehiq.vehicle",
|
||||
partition_key: "dimension_vehicle",
|
||||
columns: ["id", "make", "model"],
|
||||
record_key_column: "id",
|
||||
schema: SCHEMA,
|
||||
keys,
|
||||
keys_per_query: keysPerQuery,
|
||||
};
|
||||
}
|
||||
|
||||
describe("PostgresKeyedLookupConnector — validate()", () => {
|
||||
it("refuses an empty key list rather than defaulting to a full read", () => {
|
||||
const connector = new PostgresKeyedLookupConnector(fixtureQuery().query);
|
||||
const verdict = connector.validate(config([]));
|
||||
expect(verdict.valid).toBe(false);
|
||||
expect(verdict.errors.join(" ")).toMatch(/keys must not be empty/);
|
||||
});
|
||||
|
||||
it("rejects '*' in columns", () => {
|
||||
const connector = new PostgresKeyedLookupConnector(fixtureQuery().query);
|
||||
expect(connector.validate({ ...config(["v1"]), columns: ["*"] }).valid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PostgresKeyedLookupConnector — the narrow-scan property", () => {
|
||||
it("connect() with an empty key list is refused, and NO query is ever issued", async () => {
|
||||
const { query, calls } = fixtureQuery();
|
||||
const connector = new PostgresKeyedLookupConnector(query);
|
||||
await expect(
|
||||
connector.connect(config([]), { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" }),
|
||||
).rejects.toThrow(/keys must not be empty/);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("reads exactly the vehicles referenced by the batch — v4 (never referenced) is never touched", async () => {
|
||||
const referenced = ["v1", "v2", "v3"]; // simulates dedup'd dealer_stock_entry.vehicle_id values from one batch
|
||||
const { query, calls } = fixtureQuery();
|
||||
const connector = new PostgresKeyedLookupConnector(query);
|
||||
await connector.connect(config(referenced), { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
const result = await connector.read({ partition_key: "dimension_vehicle", limit: 500 });
|
||||
|
||||
expect(result.records.map((r) => r.record_key).sort()).toEqual(["v1", "v2", "v3"]);
|
||||
expect(result.exhausted).toBe(true);
|
||||
|
||||
// The narrow-scan property, checked at the QUERY level: every id ever
|
||||
// bound into a query call is a subset of `referenced`, and the union of
|
||||
// all ids queried equals exactly `referenced` — never more, never a
|
||||
// wildcard, never "v4".
|
||||
expect(calls).toHaveLength(1);
|
||||
const allQueriedIds = calls.flatMap((c) => c.params[0] as string[]);
|
||||
expect(allQueriedIds.sort()).toEqual([...referenced].sort());
|
||||
expect(allQueriedIds).not.toContain("v4");
|
||||
for (const call of calls) {
|
||||
expect(call.sql).toMatch(/WHERE id = ANY\(\$1\)/);
|
||||
expect(call.sql).not.toMatch(/select\s+\*/i);
|
||||
}
|
||||
});
|
||||
|
||||
it("chunks a large key list across multiple bounded queries, never one unbounded IN(...)", async () => {
|
||||
const referenced = Array.from({ length: 5 }, (_, i) => `v${i + 1}`);
|
||||
const { query, calls } = fixtureQuery();
|
||||
const connector = new PostgresKeyedLookupConnector(query);
|
||||
await connector.connect(config(referenced, 2), { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
|
||||
let cursor: string | undefined;
|
||||
let pages = 0;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const page = await connector.read({ partition_key: "dimension_vehicle", cursor, limit: 500 });
|
||||
pages++;
|
||||
cursor = page.next_cursor;
|
||||
if (page.exhausted) break;
|
||||
}
|
||||
expect(pages).toBe(3); // ceil(5/2)
|
||||
for (const call of calls) {
|
||||
expect((call.params[0] as string[]).length).toBeLessThanOrEqual(2);
|
||||
}
|
||||
const allQueriedIds = calls.flatMap((c) => c.params[0] as string[]);
|
||||
expect(new Set(allQueriedIds).size).toBe(5);
|
||||
});
|
||||
|
||||
it("the empty-batch case: zero referenced vehicles means this connector is never even constructed by the caller (see vehiq-oltp-ingest-runner.test.ts) — but if it IS given zero keys, it fails validation rather than scanning", () => {
|
||||
const connector = new PostgresKeyedLookupConnector(fixtureQuery().query);
|
||||
expect(connector.validate(config([])).valid).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Connector-level proof for postgres-watermark-connector.ts. No real
|
||||
* Postgres: `queryImpl` is a fixture that runs the SAME SQL text the real
|
||||
* connector builds against an in-memory row set, so the watermark math and
|
||||
* the tie-break are proven precisely rather than just "some rows came back".
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
PostgresWatermarkConnector,
|
||||
checksumRows,
|
||||
decodeCursor,
|
||||
encodeCursor,
|
||||
type QueryImpl,
|
||||
type SourceRow,
|
||||
} from "@/src/connectors/postgres-watermark-connector";
|
||||
import type { RecordSchemaFields } from "@/src/schema/record-schema";
|
||||
|
||||
const SCHEMA: RecordSchemaFields = {
|
||||
id: { type: "string", required: true },
|
||||
vehicle_id: { type: "string", required: false },
|
||||
updated_at: { type: "string", required: true },
|
||||
};
|
||||
|
||||
const CONFIG = {
|
||||
table: "app.dealer_stock_entry",
|
||||
partition_key: "dealer_stock_entry",
|
||||
columns: ["id", "vehicle_id", "updated_at"],
|
||||
record_key_column: "id",
|
||||
watermark_column: "updated_at",
|
||||
schema: SCHEMA,
|
||||
};
|
||||
|
||||
/** A fixture query engine that actually parses/applies the connector's WHERE/ORDER BY/LIMIT against an in-memory table — not a stub that ignores its arguments. */
|
||||
function fixtureQuery(rows: 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 });
|
||||
let filtered = rows;
|
||||
if (sql.includes("WHERE")) {
|
||||
const [watermark, id] = params as [string, string, number];
|
||||
filtered = rows.filter(
|
||||
(r) => (r.updated_at as string) > watermark || ((r.updated_at as string) === watermark && (r.id as string) > id),
|
||||
);
|
||||
}
|
||||
const sorted = [...filtered].sort((a, b) => {
|
||||
const w = (a.updated_at as string).localeCompare(b.updated_at as string);
|
||||
return w !== 0 ? w : (a.id as string).localeCompare(b.id as string);
|
||||
});
|
||||
const limit = Number(params[params.length - 1]);
|
||||
return sorted.slice(0, limit);
|
||||
};
|
||||
return { query, calls };
|
||||
}
|
||||
|
||||
const ROWS: SourceRow[] = [
|
||||
{ id: "a1", vehicle_id: "v1", updated_at: "2026-09-01T00:00:00.000Z" },
|
||||
{ id: "a2", vehicle_id: "v2", updated_at: "2026-09-01T00:00:00.000Z" }, // same updated_at as a1 — the tie-break case
|
||||
{ id: "a3", vehicle_id: "v1", updated_at: "2026-09-02T00:00:00.000Z" },
|
||||
{ id: "a4", vehicle_id: "v3", updated_at: "2026-09-03T00:00:00.000Z" },
|
||||
];
|
||||
|
||||
describe("PostgresWatermarkConnector — validate()", () => {
|
||||
it("rejects a config pointed at the 98M-row vehicle table", () => {
|
||||
const connector = new PostgresWatermarkConnector(fixtureQuery([]).query);
|
||||
const verdict = connector.validate({ ...CONFIG, table: "vehiq.vehicle" });
|
||||
expect(verdict.valid).toBe(false);
|
||||
expect(verdict.errors.join(" ")).toMatch(/vehicle/i);
|
||||
});
|
||||
|
||||
it("rejects SELECT * (an empty/missing columns list, or a literal '*')", () => {
|
||||
const connector = new PostgresWatermarkConnector(fixtureQuery([]).query);
|
||||
expect(connector.validate({ ...CONFIG, columns: [] }).valid).toBe(false);
|
||||
expect(connector.validate({ ...CONFIG, columns: ["*"] }).valid).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a well-formed config", () => {
|
||||
const connector = new PostgresWatermarkConnector(fixtureQuery([]).query);
|
||||
expect(connector.validate(CONFIG).valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PostgresWatermarkConnector — watermark + limit correctness", () => {
|
||||
it("first read (no cursor) honours LIMIT and orders by (updated_at, id)", async () => {
|
||||
const { query } = fixtureQuery(ROWS);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
const result = await connector.read({ partition_key: "dealer_stock_entry", limit: 2 });
|
||||
expect(result.records.map((r) => r.record_key)).toEqual(["a1", "a2"]);
|
||||
expect(result.exhausted).toBe(false); // 2 rows returned == limit, more may exist
|
||||
});
|
||||
|
||||
it("a same-updated_at tie at the page boundary is not skipped on the next page (the whole reason for the tuple WHERE)", async () => {
|
||||
const { query } = fixtureQuery(ROWS);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
const page1 = await connector.read({ partition_key: "dealer_stock_entry", limit: 1 }); // just a1
|
||||
expect(page1.records.map((r) => r.record_key)).toEqual(["a1"]);
|
||||
const page2 = await connector.read({ partition_key: "dealer_stock_entry", cursor: page1.next_cursor, limit: 1 });
|
||||
// A naive `updated_at > $1` would skip a2 here (same updated_at as a1).
|
||||
expect(page2.records.map((r) => r.record_key)).toEqual(["a2"]);
|
||||
});
|
||||
|
||||
it("reads the full table across pages in strict watermark order, once per row", async () => {
|
||||
const { query } = fixtureQuery(ROWS);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
let cursor: string | undefined;
|
||||
const seen: string[] = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const page = await connector.read({ partition_key: "dealer_stock_entry", cursor, limit: 2 });
|
||||
seen.push(...page.records.map((r) => r.record_key));
|
||||
cursor = page.next_cursor;
|
||||
if (page.exhausted) break;
|
||||
}
|
||||
expect(seen).toEqual(["a1", "a2", "a3", "a4"]);
|
||||
});
|
||||
|
||||
it("the empty-table case: zero rows, no throw, exhausted:true", async () => {
|
||||
const { query, calls } = fixtureQuery([]);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
const result = await connector.read({ partition_key: "dealer_stock_entry", limit: 100 });
|
||||
expect(result.records).toEqual([]);
|
||||
expect(result.exhausted).toBe(true);
|
||||
expect(calls).toHaveLength(1); // the query WAS issued (a real SELECT against a real, currently-empty table) — it just returned nothing
|
||||
});
|
||||
});
|
||||
|
||||
describe("PostgresWatermarkConnector — checkpoint / resume", () => {
|
||||
it("checkpoint() reflects the in-session cursor after a read", async () => {
|
||||
const { query } = fixtureQuery(ROWS);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
await connector.read({ partition_key: "dealer_stock_entry", limit: 2 });
|
||||
const cp = await connector.checkpoint("dealer_stock_entry");
|
||||
const decoded = decodeCursor(cp.cursor);
|
||||
expect(decoded?.last_id).toBe("a2");
|
||||
expect(decoded?.last_updated_at).toBe("2026-09-01T00:00:00.000Z");
|
||||
expect(decoded?.checksum).toBe(checksumRows(ROWS.slice(0, 2)));
|
||||
});
|
||||
|
||||
it("resume() with a saved checkpoint continues exactly where the checkpoint left off", async () => {
|
||||
const { query } = fixtureQuery(ROWS);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
const cursor = encodeCursor({ last_updated_at: "2026-09-02T00:00:00.000Z", last_id: "a3" });
|
||||
const result = await connector.resume(
|
||||
{ source_id: "s", tenant_id: "t", partition_key: "dealer_stock_entry", cursor, sequence: 3, records_committed: 3, committed_at: new Date().toISOString() },
|
||||
10,
|
||||
);
|
||||
expect(result.records.map((r) => r.record_key)).toEqual(["a4"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PostgresWatermarkConnector — real Postgres driver value shapes", () => {
|
||||
it("a `timestamptz` column returned as a JS Date (not a string) is encoded as proper ISO-8601 in the cursor, not Date.toString()'s locale form", async () => {
|
||||
// Regression: caught by running this connector against a REAL Postgres
|
||||
// container (postgres.js hands back `timestamptz` as `Date`), not by any
|
||||
// fixture-only test — the fixtures elsewhere in this file all use plain
|
||||
// ISO strings, which never exercised this path. Reproduced here directly
|
||||
// instead of requiring Docker so the regression stays covered in CI.
|
||||
const rowsWithDates: SourceRow[] = [
|
||||
{ id: "a1", vehicle_id: "v1", updated_at: new Date("2026-09-01T00:00:00.000Z") },
|
||||
];
|
||||
const { query } = fixtureQuery(rowsWithDates.map((r) => ({ ...r, updated_at: (r.updated_at as Date).toISOString() })));
|
||||
// fixtureQuery's own row-compare logic needs string dates to sort; feed
|
||||
// it a Date-returning query instead so the connector genuinely sees a
|
||||
// Date object, the same as the real driver.
|
||||
const dateReturningQuery: QueryImpl = async (sql, params) => {
|
||||
const rows = await query(sql, params);
|
||||
return rows.map((r) => ({ ...r, updated_at: new Date(r.updated_at as string) }));
|
||||
};
|
||||
const connector = new PostgresWatermarkConnector(dateReturningQuery);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
const result = await connector.read({ partition_key: "dealer_stock_entry", limit: 10 });
|
||||
expect(result.records[0].occurred_at).toBe("2026-09-01T00:00:00.000Z");
|
||||
const decoded = decodeCursor(result.next_cursor);
|
||||
expect(decoded?.last_updated_at).toBe("2026-09-01T00:00:00.000Z");
|
||||
expect(decoded?.last_updated_at).not.toMatch(/GMT|\(.*\)/); // not Date.toString()'s form
|
||||
});
|
||||
});
|
||||
|
||||
describe("PostgresWatermarkConnector — never SELECT *", () => {
|
||||
it("every SQL statement the connector builds names the configured columns explicitly", async () => {
|
||||
const { query, calls } = fixtureQuery(ROWS);
|
||||
const connector = new PostgresWatermarkConnector(query);
|
||||
await connector.connect(CONFIG, { tenant_id: "t", project_id: "p", source_id: "s", run_id: "r" });
|
||||
await connector.read({ partition_key: "dealer_stock_entry", limit: 10 });
|
||||
for (const call of calls) {
|
||||
expect(call.sql).not.toMatch(/select\s+\*/i);
|
||||
expect(call.sql).toContain("id, vehicle_id, updated_at");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* 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
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user