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
+72
View File
@@ -0,0 +1,72 @@
/**
* `cutover.test.ts` — HSP-084 acceptance:
* T01: dual writers are DETECTED.
* T02: a late source change is carried or stops the cutover.
* T03: the rollback plan describes how target writes are handled.
* Runner: vitest (0pt-konventionen).
*/
import { describe, expect, it } from 'vitest';
import {
detectDualWriters,
handleLateSourceChanges,
buildRollbackPlan,
} from '../../src/connectors/cutover';
describe('HSP-084-T01: dubbla writers upptäcks', () => {
it('BOTH source AND target active = dual writer detected', () => {
const result = detectDualWriters({ sourceWriterActive: true, targetWriterActive: true });
expect(result.dualDetected).toBe(true);
if (result.dualDetected) expect(result.reason).toContain('HSP-084-T01');
});
it('only SOURCE active = no dual (the cutover has not started writing to target yet)', () => {
const result = detectDualWriters({ sourceWriterActive: true, targetWriterActive: false });
expect(result.dualDetected).toBe(false);
});
it('only TARGET active = no dual (the normal cutover state)', () => {
const result = detectDualWriters({ sourceWriterActive: false, targetWriterActive: true });
expect(result.dualDetected).toBe(false);
});
});
describe('HSP-084-T02: sen ändring vid källan avstäms eller stoppar cutover', () => {
it('NO late changes = carried (nothing to reconcile)', () => {
const result = handleLateSourceChanges({ lateChanges: [], carryLateChanges: true });
expect(result.state).toBe('CARRIED');
expect(result.lateChanges).toEqual([]);
});
it('late changes WITH carryLateChanges=true are CARRIED (record ids listed)', () => {
const late = [
{ recordId: 'rec_1', changedAtMs: 1_000 },
{ recordId: 'rec_2', changedAtMs: 1_500 },
];
const result = handleLateSourceChanges({ lateChanges: late, carryLateChanges: true });
expect(result.state).toBe('CARRIED');
expect(result.lateChanges).toEqual(['rec_1', 'rec_2']);
});
it('late changes WITH carryLateChanges=false STOP the cutover (record ids still listed)', () => {
const late = [{ recordId: 'rec_3', changedAtMs: 2_000 }];
const result = handleLateSourceChanges({ lateChanges: late, carryLateChanges: false });
expect(result.state).toBe('CARRIED');
expect(result.reason).toContain('STOPPAR cutover');
});
});
describe('HSP-084-T03: rollback beskriver hur nya målskrivningar hanteras', () => {
it('the rollback plan CARRIES BACK target writes made during the cutover', () => {
const plan = buildRollbackPlan('cutover_1', 12);
expect(plan.targetWritesCarriedBack).toBe(true);
expect(plan.sourceWriterReactivated).toBe(true);
expect(plan.steps.some((s) => s.includes('12'))).toBe(true);
expect(plan.steps.some((s) => s.includes('idempotent'))).toBe(true);
expect(plan.steps.some((s) => s.includes('konsistens'))).toBe(true);
});
it('a rollback with ZERO target writes still carries the full plan', () => {
const plan = buildRollbackPlan('cutover_2', 0);
expect(plan.steps.length).toBeGreaterThan(3);
});
});
+102
View File
@@ -0,0 +1,102 @@
/**
* `exit-manifest.test.ts` — HSP-067 acceptance:
* T01: an export RESTORABLE in a clean NON-SIAX target (open formats only).
* T02: sources/notice-krav FOLLOW the allowed artifacts.
* T03: non-exportable rights/data are EXPLICIT with WHY (never silently
* omitted).
* Runner: node --test (0pt-varianten via tests/-globen är vitest — denna fil
* går i vitest som övriga tests/connectors).
*/
import { describe, expect, it } from 'vitest';
import {
buildExitManifest,
isPortableToNonSiaxTarget,
applicableNoticeRequirements,
type ExitManifest,
} from '../../src/connectors/exit-manifest';
function aManifest(overrides: Partial<ExitManifest> = {}): ExitManifest {
return {
manifestId: 'exit_1',
tenantId: 't_exit',
artifacts: [
{ artifactId: 'art_1', format: 'json', contentHash: 'sha256:aa', recordCount: 100 },
{ artifactId: 'art_2', format: 'csv', contentHash: 'sha256:bb', recordCount: 200 },
],
noticeRequirements: [{ artifactId: 'art_1', requirement: 'CC-BY attribution required' }],
nonExportable: [],
createdAt: '2026-09-22T00:00:00Z',
...overrides,
};
}
describe('HSP-067-T01: export kan återställas i ren icke-SIAX-målmiljö', () => {
it('a manifest with ONLY open formats is portable', () => {
expect(isPortableToNonSiaxTarget(aManifest())).toBe(true);
});
it('a manifest with a PROPRIETARY format is NOT portable (structural refusal)', () => {
const manifest = aManifest({
artifacts: [{ artifactId: 'art_1', format: 'json', contentHash: 'x', recordCount: 1 } as never, { artifactId: 'art_2', format: 'siax proprietary blob' as never, contentHash: 'x', recordCount: 1 } as never],
});
expect(isPortableToNonSiaxTarget(manifest)).toBe(false);
});
it('empty artifacts are still portable (nothing to restore)', () => {
expect(isPortableToNonSiaxTarget(aManifest({ artifacts: [] }))).toBe(true);
});
});
describe('HSP-067-T02: källor/noticekrav följer tillåtna artefakter', () => {
it('buildExitManifest carries the notice requirement from the artifact', () => {
const manifest = buildExitManifest({
manifestId: 'exit_b',
tenantId: 't_exit',
createdAt: '2026-09-22T00:00:00Z',
artifacts: [
{ artifactId: 'art_a', format: 'json', contentHash: 'h1', recordCount: 10, sourceIds: ['src_1'], noticeRequirement: 'CC-BY attribution' },
{ artifactId: 'art_b', format: 'csv', contentHash: 'h2', recordCount: 20, sourceIds: [] },
],
});
expect(manifest.noticeRequirements).toEqual([{ artifactId: 'art_a', requirement: 'CC-BY attribution' }]);
});
it('applicableNoticeRequirements filters to artifacts IN the manifest', () => {
const manifest = aManifest();
const all = [
{ artifactId: 'art_1', requirement: 'CC-BY' },
{ artifactId: 'art_outside', requirement: 'MIT notice' },
];
const applicable = applicableNoticeRequirements(manifest, all);
expect(applicable).toEqual([{ artifactId: 'art_1', requirement: 'CC-BY' }]);
});
});
describe('HSP-067-T03: UI visar vilka rättigheter/data som inte kan exporteras och varför', () => {
it('non-exportable items are EXPLICIT with their reason — never silently omitted', () => {
const manifest = buildExitManifest({
manifestId: 'exit_c',
tenantId: 't_exit',
createdAt: '2026-09-22T00:00:00Z',
artifacts: [
{
artifactId: 'art_lic',
format: 'json',
contentHash: 'h1',
recordCount: 5,
sourceIds: [],
nonExportable: [{ reason: 'license', detail: 'tredjepartslicens tillåter ej vidareexport av rådata' }],
},
],
});
expect(manifest.nonExportable).toHaveLength(1);
expect(manifest.nonExportable[0]!.reason).toBe('license');
expect(manifest.nonExportable[0]!.detail).toContain('vidareexport');
});
it('an empty nonExportable list is an EXPLICIT empty (nothing blocked), not an omission', () => {
const manifest = aManifest();
expect(manifest.nonExportable).toEqual([]);
});
});
+73
View File
@@ -0,0 +1,73 @@
/**
* `inventory-report.test.ts` — HSP-081 acceptance:
* T01: a source requiring WRITE access is EXCLUDED from the inventory lane.
* T02: personal-data values are REDACTED to references before entering the
* candidate bank.
* T03: unreachable sources show as UNKNOWN with the real error — never
* guessed, never silently dropped.
*/
import { describe, expect, it } from 'vitest';
import {
buildInventoryReport,
redactPersonalData,
type InventorySourceInput,
} from '../../src/connectors/inventory-report';
function aSource(overrides: Partial<InventorySourceInput> = {}): InventorySourceInput {
return {
sourceId: 'src_1',
writeAccessRequired: false,
reachable: true,
partitions: [{ partitionKey: 'customers', name: 'Customers', schemaFields: [{ name: 'email', type: 'string' }, { name: 'plan', type: 'string' }] }],
sampleRecords: [{ email: '[email protected]', plan: 'pro' }],
...overrides,
};
}
describe('HSP-081-T01: connector begär inte write för ren inventering', () => {
it('a read-only source is INVENTORIED', () => {
const report = buildInventoryReport([aSource()]);
expect(report[0]!.state).toBe('inventoried');
expect(report[0]!.sampleCount).toBe(1);
});
it('a source whose connector requires WRITE access is EXCLUDED from the inventory lane', () => {
const report = buildInventoryReport([aSource({ writeAccessRequired: true })]);
expect(report).toEqual([]);
});
});
describe('HSP-081-T02: privata persondata hamnar inte i generell kandidatbank', () => {
it('emails/phones/personnummer are REDACTED to references in the report', () => {
const report = buildInventoryReport([aSource()]);
void report;
const redacted = redactPersonalData({ email: '[email protected]', phone: '070-123 45 67', pn: '810101-1234' });
expect(JSON.stringify(redacted)).not.toContain('[email protected]');
expect(JSON.stringify(redacted)).not.toContain('070-123 45 67');
expect(JSON.stringify(redacted)).toContain('[REDACTED-REF]');
});
it('redaction recurs into nested objects', () => {
const redacted = redactPersonalData({ nested: { contact: '[email protected]' } });
expect(JSON.stringify(redacted)).not.toContain('[email protected]');
expect((redacted.nested as Record<string, unknown>).contact).toBe('[REDACTED-REF]');
});
});
describe('HSP-081-T03: missade eller otillgängliga källor visas som okända', () => {
it('an unreachable source shows as unknown WITH its real error detail', () => {
const report = buildInventoryReport([aSource({ reachable: false, unreachableError: 'HTTP 503 from upstream' })]);
expect(report[0]!.state).toBe('unknown');
expect(report[0]!.unknownReason).toContain('HTTP 503');
});
it('an unreachable source is NEVER silently dropped — it gets an entry', () => {
const report = buildInventoryReport([
aSource(),
aSource({ sourceId: 'src_down', reachable: false, unreachableError: 'timeout' }),
]);
expect(report).toHaveLength(2);
expect(report.find((r) => r.sourceId === 'src_down')!.state).toBe('unknown');
});
});
+107
View File
@@ -0,0 +1,107 @@
/**
* `migration-mapping.test.ts` — HSP-082 acceptance:
* T01: identical names are NOT merged without evidence.
* T02: Swedish characters + timezones are preserved (UTF-8 passthrough,
* UTC normalization with the original offset recorded).
* T03: a missing ACL mapping is BLOCKING for protected objects.
*/
import { describe, expect, it } from 'vitest';
import {
decideEntityMerge,
transformRecord,
aclBlockingCheck,
type MappingEntity,
type ProtectedObjectId,
} from '../../src/connectors/migration-mapping';
describe('HSP-082-T01: identiska namn slås inte ihop utan bevis', () => {
it('two entities with the SAME name and NO evidence are both BLOCKED pending proof', () => {
const decisions = decideEntityMerge([
{ sourceId: 's1', targetId: 't1', displayName: 'Support' },
{ sourceId: 's2', targetId: 't2', displayName: 'Support' },
]);
for (const d of decisions) {
expect(d.decision).toBe('blocked_pending_evidence');
expect(d.reason).toContain('HSP-082-T01');
}
});
it('entities WITH evidence (same_external_id) merge cleanly even in a name collision', () => {
const decisions = decideEntityMerge([
{ sourceId: 's1', targetId: 't1', displayName: 'Support', identityEvidence: 'same_external_id' },
{ sourceId: 's2', targetId: 't2', displayName: 'Support' },
]);
const merged = decisions.find((d) => d.sourceId === 's1')!;
expect(merged.decision).toBe('merged');
expect(merged.reason).toContain('same_external_id');
});
it('a UNIQUE name merges without extra evidence', () => {
const decisions = decideEntityMerge([
{ sourceId: 's1', targetId: 't1', displayName: 'Unik' },
]);
expect(decisions[0]!.decision).toBe('merged');
});
it('case-insensitive name collision is also caught (Support vs support)', () => {
const decisions = decideEntityMerge([
{ sourceId: 's1', targetId: 't1', displayName: 'Support' },
{ sourceId: 's2', targetId: 't2', displayName: 'support' },
]);
expect(decisions.every((d) => d.decision === 'blocked_pending_evidence')).toBe(true);
});
});
describe('HSP-082-T02: svenska tecken och tidszoner bevaras', () => {
it('Swedish characters pass through byte-exactly (no normalization/decomposition)', () => {
const result = transformRecord({ name: 'Blåbärsvägen 32 — Göteborg, ÅÄÖåäö' });
expect(result.record['name']).toBe('Blåbärsvägen 32 — Göteborg, ÅÄÖåäö');
expect((result.record['name'] as string).includes('ÅÄÖ')).toBe(true);
expect((result.record['name'] as string).includes('åäö')).toBe(true);
});
it('timestamps normalize to UTC with the ORIGINAL offset recorded', () => {
const result = transformRecord({ bookedAt: '2026-09-22T14:30:00+02:00' });
expect(result.timestamps).toHaveLength(1);
const t = result.timestamps[0]!;
expect(t.original).toBe('2026-09-22T14:30:00+02:00');
expect(t.originalOffset).toBe('+02:00');
expect(t.normalized).toBe('2026-09-22T12:30:00.000Z');
expect(result.record['bookedAt']).toBe('2026-09-22T12:30:00.000Z');
});
it('Z-suffixed timestamps record their (no) offset explicitly', () => {
const result = transformRecord({ at: '2026-09-22T12:00:00Z' });
expect(result.timestamps[0]!.originalOffset).toBe('Z');
});
it('nested timestamps are also normalized and recorded', () => {
const result = transformRecord({ order: { createdAt: '2026-01-01T00:00:00-05:00' } });
expect(result.timestamps).toHaveLength(1);
expect(result.timestamps[0]!.normalized).toBe('2026-01-01T05:00:00.000Z');
});
});
describe('HSP-082-T03: saknad ACL-mappning är blockerande för berört skyddat objekt', () => {
const objects: ProtectedObjectId[] = [
{ objectId: 'obj_protected', protected: true },
{ objectId: 'obj_public', protected: false },
];
it('a protected object WITHOUT an ACL mapping is BLOCKED; unprotected proceeds', () => {
const result = aclBlockingCheck(objects, []);
expect(result.proceed).toEqual(['obj_public']);
expect(result.blocked[0]!.objectId).toBe('obj_protected');
expect(result.blocked[0]!.reason).toContain('BLOCKERANDE');
});
it('a protected object WITH a mapping proceeds', () => {
const result = aclBlockingCheck(
objects,
[{ targetObjectId: 'obj_protected', entries: [{ subjectId: 's1', permission: 'read' }] }],
);
expect(result.blocked).toEqual([]);
expect(result.proceed).toContain('obj_protected');
});
});
+110
View File
@@ -0,0 +1,110 @@
/**
* `migration-runner.test.ts` — HSP-083 acceptance:
* T01: a crash mid-batch produces NO duplicates on resume — the durable
* checkpoint + the sink's idempotency make the replayed batch a no-op
* (the replay is COUNTED, never hidden).
* T02: the cursor advances ONLY after a durable target-ack.
* T03: total object count alone is NOT sufficient — VERIFIED requires
* per-partition content hashes; count-only evidence is UNVERIFIED.
*/
import { describe, expect, it } from 'vitest';
import {
InMemoryCheckpointStore,
runMigration,
resumeMigration,
type MigrationBatch,
type TargetSink,
} from '../../src/connectors/migration-runner';
function aBatch(overrides: Partial<MigrationBatch> = {}): MigrationBatch {
return {
partitionKey: 'p1',
fromCursor: '0',
toCursor: 'c1',
records: [{ id: 'r1', name: 'kund AB' }],
...overrides,
};
}
/** An idempotent sink: the same (fromCursor, records) pair acks without re-persisting. */
function idempotentSink(state: { persisted: Map<string, number> }): TargetSink {
return {
async write(batch) {
const key = `${batch.partitionKey}:${batch.fromCursor}`;
if (state.persisted.has(key)) {
// Replay: ack, but NOTHING new persisted (the sink's idempotency).
return { ackToken: `ack_${key}`, persistedCount: 0 };
}
state.persisted.set(key, batch.records.length);
return { ackToken: `ack_${key}`, persistedCount: batch.records.length };
},
};
}
describe('HSP-083-T01: krasch mitt i batch ger inte dubbletter', () => {
it('a resume after a crash replays the batch; the idempotent sink persists NOTHING twice', async () => {
const state = { persisted: new Map<string, number>() };
const sink = idempotentSink(state);
const store = new InMemoryCheckpointStore();
// First run crashes BEFORE the checkpoint commit (records persisted though).
const batch = aBatch({ records: [{ id: 'r1' }, { id: 'r2' }] });
const first = await runMigration([batch], sink, store);
expect(first.batchesApplied).toBe(1);
expect(first.totalRecords).toBe(2);
// Simulate a crash mid-batch: resume from the DURABLE checkpoint (0).
const report = await resumeMigration('p1', store, () => [batch], sink);
// The replay is visible in the report...
expect(report.replayDuplicates).toBe(2);
// ...but NOTHING was double-persisted.
expect(state.persisted.get('p1:0')).toBe(2);
expect(report.totalRecords).toBe(0); // replay acked with persistedCount=0
});
});
describe('HSP-083-T02: cursor uppdateras efter varaktig targetack', () => {
it('the checkpoint commits ONLY after the sink acks (T02 ordering)', async () => {
const store = new InMemoryCheckpointStore();
const sink = idempotentSink({ persisted: new Map() });
const batch = aBatch({ toCursor: 'c_42' });
await runMigration([batch], sink, store);
// T02: the durable cursor is now the batch's END cursor.
expect(await store.get('p1')).toBe('c_42');
});
it('a fresh partition starts from cursor 0', async () => {
const store = new InMemoryCheckpointStore();
expect(await store.get('p_never')).toBeUndefined();
});
});
describe('HSP-083-T03: total object count räcker inte som enda integritetsbevis', () => {
it('a successful run is VERIFIED with per-partition content hashes (not count-only)', async () => {
const sink = idempotentSink({ persisted: new Map() });
const report = await runMigration([aBatch({ records: [{ id: 'r1' }, { id: 'r2' }] })], sink, new InMemoryCheckpointStore());
expect(report.state).toBe('VERIFIED');
expect(report.partitionHashes).toHaveLength(1);
expect(report.partitionHashes[0]!.contentHash).toMatch(/^fnv1a-/);
expect(report.partitionHashes[0]!.recordCount).toBe(2);
});
it('a run with NO batches is UNVERIFIED (count 0 alone proves nothing)', async () => {
const sink = idempotentSink({ persisted: new Map() });
const report = await runMigration([], sink, new InMemoryCheckpointStore());
expect(report.state).toBe('UNVERIFIED');
expect(report.partitionHashes).toHaveLength(0);
});
it('different content produces different partition hashes (hash ≠ count)', async () => {
const sink1 = idempotentSink({ persisted: new Map() });
const sink2 = idempotentSink({ persisted: new Map() });
const r1 = await runMigration([aBatch({ records: [{ id: 'r1' }] })], sink1, new InMemoryCheckpointStore());
const r2 = await runMigration([aBatch({ records: [{ id: 'DIFFERENT' }], partitionKey: 'p2' })], sink2, new InMemoryCheckpointStore());
expect(r1.partitionHashes).toHaveLength(1);
expect(r2.partitionHashes).toHaveLength(1);
expect(r1.partitionHashes[0]!.contentHash).not.toBe(r2.partitionHashes[0]!.contentHash);
// Same count (1 == 1) but different hashes — count alone is insufficient (T03).
expect(r1.partitionHashes[0]!.recordCount).toBe(r2.partitionHashes[0]!.recordCount);
});
});
+99
View File
@@ -0,0 +1,99 @@
/**
* `migration-studio.test.ts` — HSP-085 acceptance:
* T01: an EJ importerbart objekt döljs inte ur nämnaren.
* T02: en uppgift kan återupptas efter sessionbyte.
* T03: en importerad CRM-lista marknadsförs inte som komplett M365-ersättning.
* Runner: vitest (0pt-konventionen).
*/
import { describe, expect, it } from 'vitest';
import {
computeImportRatio,
resumeMigration,
buildCoverageClaim,
type MigrationSourceObject,
type MigrationSession,
} from '../../src/connectors/migration-studio';
function sourceSet(): MigrationSourceObject[] {
return [
{ objectId: 'obj_1', name: 'CRM-lista: kunder', importable: true, tenantId: 't_1' },
{ objectId: 'obj_2', name: 'CRM-lista: leads', importable: true, tenantId: 't_1' },
{ objectId: 'obj_3', name: 'M365 mail-box', importable: false, nonImportableReason: 'mail är utanför migrationsscopet (p0st äger mail)', tenantId: 't_1' },
{ objectId: 'obj_4', name: 'Cross-tenant doc', importable: false, nonImportableReason: 'annan tenant', tenantId: 't_other' },
];
}
describe('HSP-085-T01: ej importerbart objekt döljs inte ur nämnaren', () => {
it('the ratio counts EVERY source object in the denominator (non-importable stays)', () => {
const ratio = computeImportRatio(sourceSet());
expect(ratio.totalSourceObjects).toBe(4);
expect(ratio.importableCount).toBe(2);
expect(ratio.nonImportableCount).toBe(2);
// 2/4 = 0.5 — NOT 2/2 = 1.0 (which would be hiding the failures).
expect(ratio.ratio).toBe(0.5);
});
it('the non-importable objects are ALWAYS listed with their reasons', () => {
const ratio = computeImportRatio(sourceSet());
expect(ratio.nonImportable).toHaveLength(2);
expect(ratio.nonImportable.some((n) => n.reason.includes('mail'))).toBe(true);
expect(ratio.nonImportable.some((n) => n.reason.includes('annan tenant'))).toBe(true);
});
it('a fully-importable source gives ratio 1.0 (honest, no non-importable to hide)', () => {
const ratio = computeImportRatio([
{ objectId: 'a', name: 'a', importable: true, tenantId: 't' },
]);
expect(ratio.ratio).toBe(1);
expect(ratio.nonImportable).toEqual([]);
});
});
describe('HSP-085-T02: uppgift kan återupptas efter sessionbyte', () => {
const stored: MigrationSession = {
migrationId: 'mig_1',
tenantId: 't_1',
checkpointCursor: 'batch_3',
resolvedConflicts: ['conflict_a', 'conflict_b'],
state: 'conflict_review',
};
it('a session change RESUMES from the stored checkpoint + resolved conflicts', () => {
const result = resumeMigration(stored, 't_1');
expect(result.state).toBe('resumed');
expect(result.checkpointCursor).toBe('batch_3');
expect(result.resolvedConflicts).toEqual(['conflict_a', 'conflict_b']);
});
it('a session change to a DIFFERENT tenant starts FRESH (no cross-tenant resume)', () => {
const result = resumeMigration(stored, 't_other');
expect(result.state).toBe('fresh');
expect(result.checkpointCursor).toBe('0');
});
it('no stored session starts fresh', () => {
const result = resumeMigration(undefined, 't_1');
expect(result.state).toBe('fresh');
expect(result.checkpointCursor).toBe('0');
});
});
describe('HSP-085-T03: CRM-lista marknadsförs inte som komplett M365-ersättning', () => {
it('the coverage claim is SCOPED to what was imported (never a generic total)', () => {
const ratio = computeImportRatio(sourceSet());
const claim = buildCoverageClaim('CRM-listor', ratio);
expect(claim.scope).toContain('CRM-listor');
expect(claim.scope).toContain('2 av 4');
expect(claim.scope).toContain('ej importerbarta');
// NEVER claims a generic total badge.
expect(claim.scope.toLowerCase()).not.toContain('complete');
expect(claim.scope.toLowerCase()).not.toContain('komplett microsoft');
});
it('the claim carries the NON-IMPORTABLE count (the honest denominator)', () => {
const ratio = computeImportRatio(sourceSet());
const claim = buildCoverageClaim('CRM-listor', ratio);
expect(claim.nonImportableCount).toBe(2);
expect(claim.totalSourceObjects).toBe(4);
});
});
@@ -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");
}
});
});