stock-bot/test/unit/security-master-export-curate-inputs-parity.test.ts
2026-11-29 05:51:54 -05:00

740 lines
25 KiB
TypeScript

/**
* QA differential tests for the curate-etl TSV exporter (T-116).
*
* - The streaming PostgreSQL exporter (`exportCurateInputs`) and the pure core
* (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `buildDelistingExportRows` +
* `formatDelistingsTsv`) must produce byte-identical TSVs and identical skip stats on the same
* seeded random security master, for every chunk size (including exact chunk-boundary sizes).
* - Every emitted `delistings.tsv` row must resolve under the exact Rust `curate-corporate-actions`
* lookup rules (`cursor.resolve(delist_date) == from_listing_id` for terminal rows,
* `resolve_for_listing_on_or_before` + successor `resolve(effective_date)` for OTC rows) against the
* emitted `provider_mapping.tsv`, so the exporter never feeds Rust a row it would drop.
*/
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, test } from 'bun:test';
import {
buildDelistingExportRows,
CURATE_INPUT_FILES,
exportCurateInputs,
formatDelistingsTsv,
formatListingCurrenciesTsv,
formatProviderMappingTsv,
type ContinuityExportSourceRow,
type ListingDelistingSourceRow,
type ProviderMappingExportRow,
type SecurityMasterQueryable,
type SecurityMasterQueryResult,
} from '../../apps/stock/data-pipeline/src/security-master';
import { compareAscii } from '../../apps/stock/data-pipeline/src/security-master/exchange-pass1';
const tempDirs: string[] = [];
afterEach(async () => {
for (const dir of tempDirs.splice(0).reverse()) {
await rm(dir, { recursive: true, force: true });
}
});
async function makeTempDir(): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), 'curate-inputs-parity-'));
tempDirs.push(dir);
return dir;
}
/** mulberry32: small deterministic PRNG so every run sees the same dataset. */
function createRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const DAY_MS = 86_400_000;
const EPOCH_2010 = Date.UTC(2010, 0, 1);
function dayToYmd(day: number): string {
return new Date(EPOCH_2010 + day * DAY_MS).toISOString().slice(0, 10);
}
function ymdToDay(ymd: string): number {
return Math.round((Date.parse(`${ymd}T00:00:00Z`) - EPOCH_2010) / DAY_MS);
}
interface DbListing {
listing_id: number;
currency: string;
listed_to: string | null;
delist_reason: string | null;
terminal_return: string | null;
}
interface DbContinuity {
from_listing_id: number;
to_listing_id: number;
effective_date: string;
kind: string;
}
interface DbMapping {
source: string;
source_id: string;
valid_from: string;
valid_to: string | null;
listing_id: number;
}
interface Dataset {
listings: DbListing[];
continuities: DbContinuity[];
mappings: DbMapping[];
}
/**
* Builds a seeded random security master that satisfies the DB invariants the exporter relies on
* (unique PKs, non-overlapping `(source, source_id)` ranges, at most one OTC continuity per
* `from_listing_id`), with ticker reuse, OTC chains, terminal returns as PG `numeric::text`,
* missing mappings, mappings that end before `listed_to`, and successors starting late.
*/
function buildRandomDataset(seed: number, listingCount: number): Dataset {
const rng = createRng(seed);
const pick = <T>(items: readonly T[]): T => items[Math.floor(rng() * items.length)] as T;
const listings: DbListing[] = [];
const continuities: DbContinuity[] = [];
const mappings: DbMapping[] = [];
// Per (source, source_id): last occupied end day (null = open-ended) to keep ranges disjoint.
const tickerEnds = new Map<string, number | null>();
const tickerPool = Array.from(
{ length: Math.max(4, Math.floor(listingCount / 3)) },
(_, i) => `T${String(i).padStart(3, '0')}${pick(['', '.A', '-B', 'Q'])}`
);
const addMapping = (
source: string,
listingId: number,
fromDay: number,
toDay: number | null
): boolean => {
for (let attempt = 0; attempt < 6; attempt++) {
const sourceId = pick(tickerPool);
const key = `${source}\u0000${sourceId}`;
if (tickerEnds.has(key)) {
const end = tickerEnds.get(key);
if (end === null || end === undefined || end >= fromDay) {
continue;
}
}
tickerEnds.set(key, toDay);
mappings.push({
source,
source_id: sourceId,
valid_from: dayToYmd(fromDay),
valid_to: toDay === null ? null : dayToYmd(toDay),
listing_id: listingId,
});
return true;
}
return false;
};
// Allocate listing ids with gaps so keyset pagination over non-contiguous ids is exercised.
const ids: number[] = [];
let nextId = 1;
for (let i = 0; i < listingCount; i++) {
nextId += 1 + Math.floor(rng() * 3);
ids.push(nextId);
}
// Listings are generated in chronological "start" order so reuse can find free tickers.
const otcSuccessorIds = new Set<number>();
for (let i = 0; i < ids.length; i++) {
const listingId = ids[i] as number;
if (otcSuccessorIds.has(listingId)) {
continue;
}
const startDay = Math.floor(rng() * 3000);
const roll = rng();
const currency = pick(['USD', 'USD', 'CAD']);
if (roll < 0.35) {
listings.push({
listing_id: listingId,
currency,
listed_to: null,
delist_reason: 'active',
terminal_return: null,
});
addMapping('qm', listingId, startDay, null);
addMapping('eod', listingId, startDay, null);
continue;
}
const endDay = startDay + 30 + Math.floor(rng() * 400);
if (roll < 0.55 && i + 1 < ids.length) {
// OTC transfer to the next id (successor), possibly ending in a terminal cancellation.
const successorId = ids[i + 1] as number;
otcSuccessorIds.add(successorId);
const gap = Math.floor(rng() * 20);
const effectiveDay = endDay + gap;
listings.push({
listing_id: listingId,
currency,
listed_to: dayToYmd(endDay),
delist_reason: 'moved_to_otc',
terminal_return: null,
});
continuities.push({
from_listing_id: listingId,
to_listing_id: successorId,
effective_date: dayToYmd(effectiveDay),
kind: 'otc_delist_transfer',
});
if (rng() < 0.9) {
addMapping('qm', listingId, startDay, endDay);
}
addMapping('eod', listingId, startDay, endDay);
const successorEnd = effectiveDay + 50 + Math.floor(rng() * 200);
const successorCancelled = rng() < 0.6;
listings.push({
listing_id: successorId,
currency,
listed_to: successorCancelled ? dayToYmd(successorEnd) : null,
delist_reason: successorCancelled ? 'bankruptcy_cancelled' : 'active',
terminal_return: successorCancelled ? '-1.000000' : null,
});
const successorRoll = rng();
if (successorRoll < 0.8) {
addMapping('qm', successorId, effectiveDay, successorCancelled ? successorEnd : null);
} else if (successorRoll < 0.9) {
// Successor mapping starts after effective_date -> missingSuccessorQmMapping.
addMapping('qm', successorId, effectiveDay + 3, successorCancelled ? successorEnd : null);
}
continue;
}
if (roll < 0.85) {
const terminalReturn = pick([
'-0.300000',
'-1.000000',
'0.000000',
'-0.000001',
'-0.550000',
'-0.123456',
]);
const missingDate = rng() < 0.08;
listings.push({
listing_id: listingId,
currency,
listed_to: missingDate ? null : dayToYmd(endDay),
delist_reason: pick(['unknown_involuntary', 'bankruptcy_cancelled', 'merger_cash']),
terminal_return: terminalReturn,
});
const mappingRoll = rng();
if (mappingRoll < 0.8) {
addMapping('qm', listingId, startDay, endDay);
} else if (mappingRoll < 0.9) {
// qm mapping ends before listed_to -> not valid on delist_date.
addMapping('qm', listingId, startDay, endDay - 5);
}
addMapping('eod', listingId, startDay, endDay);
continue;
}
listings.push({
listing_id: listingId,
currency,
listed_to: dayToYmd(endDay),
delist_reason: rng() < 0.5 ? null : 'unknown',
terminal_return: null,
});
addMapping('qm', listingId, startDay, endDay);
}
// Non-OTC continuities must be ignored by the DB query (`WHERE kind = 'otc_delist_transfer'`).
continuities.push({
from_listing_id: ids[0] as number,
to_listing_id: ids[1] as number,
effective_date: '2015-01-02',
kind: 'ticker_change',
});
return { listings, continuities, mappings };
}
function shuffle<T>(items: readonly T[], rng: () => number): T[] {
const out = [...items];
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[out[i], out[j]] = [out[j] as T, out[i] as T];
}
return out;
}
/** In-memory PostgreSQL stand-in honouring the exporter's SQL contract (keyset + NO SCROLL cursor). */
function createQueryable(data: Dataset, recordedSql: string[]): SecurityMasterQueryable {
const otc = data.continuities
.filter(c => c.kind === 'otc_delist_transfer')
.sort(
(a, b) =>
a.from_listing_id - b.from_listing_id || compareAscii(a.effective_date, b.effective_date)
);
const listings = [...data.listings].sort((a, b) => a.listing_id - b.listing_id);
const mappings = [...data.mappings].sort(
(a, b) =>
compareAscii(a.source, b.source) ||
compareAscii(a.source_id, b.source_id) ||
compareAscii(a.valid_from, b.valid_from)
);
let cursorOffset = -1;
return {
async query<Row = Record<string, unknown>>(
text: string,
values?: readonly unknown[]
): Promise<SecurityMasterQueryResult<Row>> {
const sql = text.replace(/\s+/g, ' ').trim();
recordedSql.push(sql);
const rows = (r: unknown[]) => ({ rows: r as Row[] });
if (sql.startsWith('BEGIN') || sql === 'COMMIT' || sql === 'ROLLBACK') {
return rows([]);
}
if (sql.startsWith('DECLARE ')) {
cursorOffset = 0;
return rows([]);
}
const fetch = /^FETCH FORWARD (\d+) FROM \S+$/.exec(sql);
if (fetch) {
if (cursorOffset < 0) {
throw new Error('FETCH without DECLARE');
}
const slice = mappings.slice(cursorOffset, cursorOffset + Number(fetch[1]));
cursorOffset += slice.length;
return rows(slice);
}
if (sql.startsWith('CLOSE ')) {
cursorOffset = -1;
return rows([]);
}
if (sql.includes('FROM corporate_action_continuity')) {
if (values?.length === 1) {
return rows(otc.slice(0, values[0] as number));
}
const [lastFrom, lastEff, limit] = values as [number, string, number];
return rows(
otc
.filter(
c =>
c.from_listing_id > lastFrom ||
(c.from_listing_id === lastFrom && c.effective_date > lastEff)
)
.slice(0, limit)
);
}
if (sql.includes('FROM listing')) {
if (values?.length === 1) {
return rows(listings.slice(0, values[0] as number));
}
const [lastId, limit] = values as [number, number];
return rows(listings.filter(l => l.listing_id > lastId).slice(0, limit));
}
throw new Error(`Unexpected SQL: ${sql}`);
},
release: () => {},
};
}
function toPure(data: Dataset): {
providerMappings: ProviderMappingExportRow[];
delistingListings: ListingDelistingSourceRow[];
continuities: ContinuityExportSourceRow[];
} {
return {
providerMappings: data.mappings.map(m => ({
source: m.source,
sourceId: m.source_id,
validFrom: m.valid_from,
validTo: m.valid_to,
listingId: m.listing_id,
})),
delistingListings: data.listings.map(l => ({
listingId: l.listing_id,
listedTo: l.listed_to,
delistReason: l.delist_reason,
terminalReturn: l.terminal_return,
})),
continuities: data.continuities
.filter(c => c.kind === 'otc_delist_transfer')
.map(c => ({
fromListingId: c.from_listing_id,
toListingId: c.to_listing_id,
effectiveDate: c.effective_date,
kind: c.kind,
})),
};
}
interface RustRange {
validFrom: number;
validTo: number | null;
listingId: number;
}
/** Parses emitted `provider_mapping.tsv` into Rust `ProviderMappingTable` shape (sorted by valid_from). */
function parseMappingTable(tsv: string): Map<string, RustRange[]> {
const table = new Map<string, RustRange[]>();
for (const line of tsv.split('\n')) {
if (line.length === 0) {
continue;
}
const [source, sourceId, from, to, listingId] = line.split('\t') as [
string,
string,
string,
string,
string,
];
const key = `${source}\u0000${sourceId}`;
const list = table.get(key) ?? [];
list.push({
validFrom: ymdToDay(from),
validTo: to === '' ? null : ymdToDay(to),
listingId: Number(listingId),
});
table.set(key, list);
}
for (const list of table.values()) {
list.sort((a, b) => a.validFrom - b.validFrom);
}
return table;
}
/** Mirror of `ProviderMappingTable::resolve` (provider_mapping.rs). */
function rustResolve(ranges: readonly RustRange[], day: number): number | null {
let idx = 0;
while (idx < ranges.length && (ranges[idx] as RustRange).validFrom <= day) {
idx += 1;
}
if (idx === 0) {
return null;
}
const candidate = ranges[idx - 1] as RustRange;
return candidate.validTo === null || candidate.validTo >= day ? candidate.listingId : null;
}
/** Mirror of `resolve_for_listing_on_or_before` (curate_corporate_actions.rs). */
function rustResolveForListingOnOrBefore(
ranges: readonly RustRange[],
day: number,
expected: number
): number | null {
for (let i = ranges.length - 1; i >= 0; i--) {
const r = ranges[i] as RustRange;
if (r.validFrom <= day && r.listingId === expected) {
return r.listingId;
}
}
return null;
}
async function runExport(data: Dataset, chunkSize: number) {
const outDir = await makeTempDir();
const recordedSql: string[] = [];
const result = await exportCurateInputs(createQueryable(data, recordedSql), {
outDir,
chunkSize,
});
const read = (file: string) => readFile(join(outDir, file), 'utf8');
return {
result,
recordedSql,
providerMapping: await read(CURATE_INPUT_FILES.providerMapping),
listingCurrencies: await read(CURATE_INPUT_FILES.listingCurrencies),
delistings: await read(CURATE_INPUT_FILES.delistings),
};
}
describe('exportCurateInputs streaming vs pure core parity (seeded random security master)', () => {
for (const seed of [11, 4242, 90210]) {
test(`seed ${seed}: streamed TSV bytes and skip stats equal the pure formatters for every chunk size`, async () => {
// Arrange
const data = buildRandomDataset(seed, 160);
const pure = toPure(data);
const rng = createRng(seed ^ 0x5eed);
const expectedProviderMapping = formatProviderMappingTsv(shuffle(pure.providerMappings, rng));
const expectedListingCurrencies = formatListingCurrenciesTsv(
shuffle(
data.listings.map(l => ({ listingId: l.listing_id, currency: l.currency })),
rng
)
);
const built = buildDelistingExportRows(
shuffle(pure.delistingListings, rng),
shuffle(pure.continuities, rng),
shuffle(pure.providerMappings, rng)
);
const expectedDelistings = formatDelistingsTsv(shuffle(built.rows, rng));
const mappingRows = data.mappings.length;
const listingRows = data.listings.length;
// Sanity: the generator really exercises every branch, otherwise parity proves little.
expect(built.stats.otcTransfersOut).toBeGreaterThan(0);
expect(built.stats.terminalDelistingsOut).toBeGreaterThan(0);
expect(built.stats.skipped.active).toBeGreaterThan(0);
expect(built.stats.skipped.noOutcome).toBeGreaterThan(0);
expect(built.stats.skipped.missingOutgoingQmMapping).toBeGreaterThan(0);
// Act + Assert: chunk sizes include 1, a prime, exact divisors of the row counts, and max.
for (const chunkSize of [1, 7, listingRows, mappingRows, 5000]) {
const out = await runExport(data, Math.min(chunkSize, 5000));
expect(out.providerMapping).toBe(expectedProviderMapping);
expect(out.listingCurrencies).toBe(expectedListingCurrencies);
expect(out.delistings).toBe(expectedDelistings);
const s = out.result.delistings.stats;
expect(s.rowsOut).toBe(built.stats.rowsOut);
expect(s.otcTransfersOut).toBe(built.stats.otcTransfersOut);
expect(s.terminalDelistingsOut).toBe(built.stats.terminalDelistingsOut);
expect({ ...s.skipped, nonOtcContinuity: 0 }).toEqual({
...built.stats.skipped,
nonOtcContinuity: 0,
});
expect(s.skipped.nonOtcContinuity).toBe(0);
const skipSum = Object.values(s.skipped).reduce((acc, n) => acc + n, 0);
expect(s.skippedTotal).toBe(skipSum);
expect(s.rowsIn).toBe(s.rowsOut + s.skippedTotal);
// Every non-OTC-transferred listing is accounted for exactly once, plus OTC sources.
expect(s.rowsIn).toBe(listingRows);
expect(out.result.providerMapping.rowsIn).toBe(mappingRows);
expect(out.result.providerMapping.rowsOut).toBe(mappingRows);
expect(out.result.listingCurrencies.rowsOut).toBe(listingRows);
expect(out.result.totalBytesWritten).toBe(
Buffer.byteLength(out.providerMapping) +
Buffer.byteLength(out.listingCurrencies) +
Buffer.byteLength(out.delistings)
);
// Read-only contract: SELECT/cursor statements only, all inside one READ ONLY transaction.
expect(out.recordedSql[0]).toBe(
'BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'
);
expect(out.recordedSql.at(-1)).toBe('COMMIT');
for (const sql of out.recordedSql) {
expect(sql).not.toMatch(
/\b(INSERT|UPDATE|DELETE|TRUNCATE|CREATE|ALTER|DROP|GRANT|COPY)\b/i
);
}
const fetches = out.recordedSql.filter(sql => sql.startsWith('FETCH FORWARD'));
expect(fetches.length).toBeGreaterThanOrEqual(
Math.ceil(mappingRows / Math.min(chunkSize, 5000))
);
for (const fetch of fetches) {
const n = Number(/FETCH FORWARD (\d+)/.exec(fetch)?.[1]);
expect(n).toBeLessThanOrEqual(5000);
}
}
});
}
test('every emitted delisting resolves under the Rust curate-corporate-actions lookup rules (0 drops)', async () => {
for (const seed of [11, 4242, 90210, 7]) {
// Arrange
const data = buildRandomDataset(seed, 200);
// Act
const out = await runExport(data, 13);
const table = parseMappingTable(out.providerMapping);
// Assert
const lines = out.delistings.split('\n').filter(line => line.length > 0);
expect(lines.length).toBe(out.result.delistings.rowsOut);
for (const line of lines) {
const fields = line.split('\t');
expect(fields.length).toBe(5);
const [sourceId, delistDate, fromListingId, successorSourceId, terminalReturn] = fields as [
string,
string,
string,
string,
string,
];
const day = ymdToDay(delistDate);
const expectedId = Number(fromListingId);
expect(Number.isInteger(expectedId) && expectedId > 0).toBe(true);
const ranges = table.get(`qm\u0000${sourceId}`) ?? [];
if (successorSourceId === '') {
// Terminal: cursor.resolve(ex_date).filter(id == from_listing_id); terminal_return parses in [-1, 0].
expect(rustResolve(ranges, day)).toBe(expectedId);
const parsed = Number(terminalReturn);
expect(terminalReturn).toMatch(/^-?\d+(\.\d+)?$/);
expect(parsed >= -1 && parsed <= 0).toBe(true);
const listing = data.listings.find(l => l.listing_id === expectedId);
expect(listing?.listed_to).toBe(delistDate);
expect(parsed).toBe(Number(listing?.terminal_return));
} else {
expect(terminalReturn).toBe('');
expect(rustResolveForListingOnOrBefore(ranges, day, expectedId)).toBe(expectedId);
const successorId = rustResolve(table.get(`qm\u0000${successorSourceId}`) ?? [], day);
const continuity = data.continuities.find(
c => c.kind === 'otc_delist_transfer' && c.from_listing_id === expectedId
);
expect(continuity?.effective_date).toBe(delistDate);
expect(successorId).toBe(continuity?.to_listing_id ?? -1);
expect(successorId).not.toBe(expectedId);
}
}
}
});
test('terminal returns from PostgreSQL numeric::text are normalized to plain decimals Rust parses identically', async () => {
// Arrange
const data: Dataset = {
listings: [
{
listing_id: 1,
currency: 'USD',
listed_to: '2023-01-03',
delist_reason: 'x',
terminal_return: '0.000000',
},
{
listing_id: 2,
currency: 'USD',
listed_to: '2023-01-03',
delist_reason: 'x',
terminal_return: '-0.000000',
},
{
listing_id: 3,
currency: 'USD',
listed_to: '2023-01-03',
delist_reason: 'x',
terminal_return: '-0.000001',
},
{
listing_id: 4,
currency: 'USD',
listed_to: '2023-01-03',
delist_reason: 'x',
terminal_return: '-1.000000',
},
{
listing_id: 5,
currency: 'USD',
listed_to: '2023-01-03',
delist_reason: 'x',
terminal_return: '-0.300000',
},
],
continuities: [],
mappings: [1, 2, 3, 4, 5].map(id => ({
source: 'qm',
source_id: `L${id}`,
valid_from: '2020-01-01',
valid_to: '2023-01-03',
listing_id: id,
})),
};
// Act
const out = await runExport(data, 2);
// Assert
expect(out.delistings).toBe(
[
'L1\t2023-01-03\t1\t\t0',
'L2\t2023-01-03\t2\t\t0',
'L3\t2023-01-03\t3\t\t-0.000001',
'L4\t2023-01-03\t4\t\t-1',
'L5\t2023-01-03\t5\t\t-0.3',
'',
].join('\n')
);
});
test('exact chunk-boundary row counts neither drop nor duplicate the last page', async () => {
// Arrange: 4 listings, 4 mappings, 2 OTC continuities with chunkSize 2 (two full pages each).
const data: Dataset = {
listings: [
{
listing_id: 10,
currency: 'USD',
listed_to: '2023-03-10',
delist_reason: 'moved_to_otc',
terminal_return: null,
},
{
listing_id: 11,
currency: 'USD',
listed_to: null,
delist_reason: 'active',
terminal_return: null,
},
{
listing_id: 20,
currency: 'CAD',
listed_to: '2023-03-10',
delist_reason: 'moved_to_otc',
terminal_return: null,
},
{
listing_id: 21,
currency: 'CAD',
listed_to: null,
delist_reason: 'active',
terminal_return: null,
},
],
continuities: [
{
from_listing_id: 10,
to_listing_id: 11,
effective_date: '2023-03-28',
kind: 'otc_delist_transfer',
},
{
from_listing_id: 20,
to_listing_id: 21,
effective_date: '2023-03-28',
kind: 'otc_delist_transfer',
},
],
mappings: [
{
source: 'qm',
source_id: 'A',
valid_from: '2000-01-03',
valid_to: '2023-03-10',
listing_id: 10,
},
{ source: 'qm', source_id: 'AQ', valid_from: '2023-03-28', valid_to: null, listing_id: 11 },
{
source: 'qm',
source_id: 'B',
valid_from: '2000-01-03',
valid_to: '2023-03-10',
listing_id: 20,
},
{ source: 'qm', source_id: 'BQ', valid_from: '2023-03-28', valid_to: null, listing_id: 21 },
],
};
// Act
const out = await runExport(data, 2);
// Assert
expect(out.listingCurrencies).toBe('10\tUSD\n11\tUSD\n20\tCAD\n21\tCAD\n');
expect(out.providerMapping).toBe(
'qm\tA\t2000-01-03\t2023-03-10\t10\nqm\tAQ\t2023-03-28\t\t11\nqm\tB\t2000-01-03\t2023-03-10\t20\nqm\tBQ\t2023-03-28\t\t21\n'
);
expect(out.delistings).toBe('A\t2023-03-28\t10\tAQ\t\nB\t2023-03-28\t20\tBQ\t\n');
expect(out.result.delistings.stats.rowsIn).toBe(4);
expect(out.result.delistings.stats.skipped.active).toBe(2);
});
});