386 lines
15 KiB
TypeScript
386 lines
15 KiB
TypeScript
/**
|
|
* QA edge-case coverage for T-211 (M2.2v): `listing_venues.tsv` produced by `exportCurateInputs`.
|
|
*
|
|
* Complements `security-master-export-curate-inputs.test.ts` with:
|
|
* - end-to-end streaming parity against the pure `formatListingVenuesTsv` core for a seeded
|
|
* random security master across chunk sizes (incl. exact chunk boundaries),
|
|
* - the 1:1 join invariant between `listing_currencies.tsv` and `listing_venues.tsv`
|
|
* (curate-fundamentals must never see a listing with a currency but no statutory-lag class),
|
|
* - a TS port of `tools/curate-etl/src/run_curate_fundamentals.rs::load_listing_venues_tsv`
|
|
* (+ `read_tsv_lines` / `parse_strict_positive_i32`) applied to the exported bytes,
|
|
* - fail-closed rollback for null / blank / padded / lowercase MICs read from PostgreSQL,
|
|
* - i32 max listing_id, empty listing table, and the `current/` top-level symlink layout.
|
|
*/
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { mkdtemp, readdir, readFile, readlink, realpath, rm, writeFile } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import {
|
|
CURATE_INPUT_CURRENT_LINK,
|
|
CURATE_INPUT_FILES,
|
|
CURATE_INPUT_GENERATIONS_DIR,
|
|
CurateInputExportError,
|
|
exportCurateInputs,
|
|
formatListingVenuesTsv,
|
|
ISO_EXCHANGE_SEEDS,
|
|
LISTING_VENUE_BY_MIC,
|
|
pinCurateInputSnapshot,
|
|
type ListingStatutoryLagVenue,
|
|
type SecurityMasterQueryable,
|
|
type SecurityMasterQueryResult,
|
|
} from '../../apps/stock/data-pipeline/src/security-master';
|
|
|
|
const tempDirs: string[] = [];
|
|
afterEach(async () => {
|
|
for (const dir of tempDirs.splice(0).reverse()) {
|
|
await rm(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
async function makeTempDir(prefix: string): Promise<string> {
|
|
const dir = await mkdtemp(join(tmpdir(), prefix));
|
|
tempDirs.push(dir);
|
|
return dir;
|
|
}
|
|
|
|
interface ListingRow {
|
|
readonly listing_id: number;
|
|
readonly mic: string | null;
|
|
readonly currency: string | null;
|
|
readonly listed_to: string | null;
|
|
readonly delist_reason: string | null;
|
|
readonly terminal_return: string | null;
|
|
}
|
|
|
|
/**
|
|
* Minimal in-memory stand-in for the read-only PostgreSQL snapshot: empty provider_mapping and
|
|
* continuity tables, keyset-paginated listing table. Records every SQL statement.
|
|
*/
|
|
function createListingOnlyQueryable(
|
|
listings: readonly ListingRow[],
|
|
recordedSql: string[] = []
|
|
): SecurityMasterQueryable {
|
|
const sorted = [...listings].sort((a, b) => a.listing_id - b.listing_id);
|
|
return {
|
|
async query<Row = Record<string, unknown>>(
|
|
text: string,
|
|
values?: readonly unknown[]
|
|
): Promise<SecurityMasterQueryResult<Row>> {
|
|
const normalized = text.replace(/\s+/g, ' ').trim();
|
|
recordedSql.push(normalized);
|
|
if (
|
|
normalized.startsWith('BEGIN') ||
|
|
normalized === 'COMMIT' ||
|
|
normalized === 'ROLLBACK' ||
|
|
normalized.startsWith('DECLARE ') ||
|
|
/^CLOSE \S+$/i.test(normalized) ||
|
|
/^FETCH FORWARD \d+ FROM \S+$/i.test(normalized)
|
|
) {
|
|
return { rows: [] };
|
|
}
|
|
if (normalized.includes('FROM corporate_action_continuity')) {
|
|
return { rows: [] };
|
|
}
|
|
if (normalized.includes('FROM provider_mapping')) {
|
|
return { rows: [] };
|
|
}
|
|
if (normalized.includes('FROM listing')) {
|
|
if (values && values.length === 1) {
|
|
return { rows: sorted.slice(0, values[0] as number) as unknown as Row[] };
|
|
}
|
|
const [lastId, limit] = values as [number, number];
|
|
return {
|
|
rows: sorted.filter(l => l.listing_id > lastId).slice(0, limit) as unknown as Row[],
|
|
};
|
|
}
|
|
throw new Error(`Unexpected SQL in listing-only queryable: ${normalized}`);
|
|
},
|
|
release: () => {},
|
|
};
|
|
}
|
|
|
|
function activeListing(listingId: number, mic: string | null, currency = 'USD'): ListingRow {
|
|
return {
|
|
listing_id: listingId,
|
|
mic,
|
|
currency,
|
|
listed_to: null,
|
|
delist_reason: 'active',
|
|
terminal_return: null,
|
|
};
|
|
}
|
|
|
|
/** mulberry32 — deterministic seeded PRNG. */
|
|
function mulberry32(seed: number): () => number {
|
|
let a = seed >>> 0;
|
|
return () => {
|
|
a = (a + 0x6d2b79f5) >>> 0;
|
|
let t = a;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
};
|
|
}
|
|
|
|
/** TS port of Rust `parse_strict_positive_i32` (run_curate_bars.rs). */
|
|
function parseStrictPositiveI32(raw: string): number | null {
|
|
if (raw.length === 0 || !/^[0-9]+$/.test(raw)) {
|
|
return null;
|
|
}
|
|
const val = Number(raw);
|
|
if (!Number.isSafeInteger(val) || val > 2_147_483_647 || val <= 0) {
|
|
return null;
|
|
}
|
|
return val;
|
|
}
|
|
|
|
/**
|
|
* TS port of Rust `load_listing_venues_tsv` + `read_tsv_lines`: strict headerless 2-column TSV,
|
|
* at most one trailing blank line, strictly positive i32 listing_id, `us_tsx|tsxv_cse`, no dups.
|
|
* Additionally asserts the stricter exporter contract (LF only, ascending listing_id).
|
|
*/
|
|
function loadListingVenuesTsvStrict(text: string): Map<number, ListingStatutoryLagVenue> {
|
|
const venues = new Map<number, ListingStatutoryLagVenue>();
|
|
if (text.length === 0) {
|
|
return venues;
|
|
}
|
|
if (text.includes('\r')) {
|
|
throw new Error('exporter must emit LF-only line endings');
|
|
}
|
|
if (!text.endsWith('\n')) {
|
|
throw new Error('exporter must terminate the last line with LF');
|
|
}
|
|
const lines = text.slice(0, -1).split('\n');
|
|
let prev = 0;
|
|
for (const [i, line] of lines.entries()) {
|
|
if (line.length === 0) {
|
|
throw new Error(`line ${i + 1}: interior blank line`);
|
|
}
|
|
const cols = line.split('\t');
|
|
if (cols.length !== 2) {
|
|
throw new Error(`line ${i + 1}: expected 2 tab-separated columns, got ${cols.length}`);
|
|
}
|
|
const id = parseStrictPositiveI32(cols[0]!);
|
|
if (id === null) {
|
|
throw new Error(`line ${i + 1}: invalid listing_id '${cols[0]}'`);
|
|
}
|
|
const venue = cols[1];
|
|
if (venue !== 'us_tsx' && venue !== 'tsxv_cse') {
|
|
throw new Error(`line ${i + 1}: unknown venue '${venue}'`);
|
|
}
|
|
if (venues.has(id)) {
|
|
throw new Error(`line ${i + 1}: duplicate listing_id ${id}`);
|
|
}
|
|
if (id <= prev) {
|
|
throw new Error(`line ${i + 1}: listing_id ${id} not strictly ascending after ${prev}`);
|
|
}
|
|
prev = id;
|
|
venues.set(id, venue);
|
|
}
|
|
return venues;
|
|
}
|
|
|
|
function buildRandomListings(seed: number, count: number): ListingRow[] {
|
|
const rand = mulberry32(seed);
|
|
const mics = ISO_EXCHANGE_SEEDS.map(e => e.mic);
|
|
const usedIds = new Set<number>();
|
|
const rows: ListingRow[] = [];
|
|
while (rows.length < count) {
|
|
// Sparse ids (gaps) up to i32 max to exercise keyset pagination on non-contiguous keys.
|
|
const id = 1 + Math.floor(rand() * 2_147_483_646);
|
|
if (usedIds.has(id)) {
|
|
continue;
|
|
}
|
|
usedIds.add(id);
|
|
const mic = mics[Math.floor(rand() * mics.length)]!;
|
|
rows.push(activeListing(id, mic, rand() < 0.5 ? 'CAD' : 'USD'));
|
|
}
|
|
// Shuffle insertion order so only the DB ORDER BY can produce sorted output.
|
|
for (let i = rows.length - 1; i > 0; i--) {
|
|
const j = Math.floor(rand() * (i + 1));
|
|
[rows[i], rows[j]] = [rows[j]!, rows[i]!];
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
describe('listing_venues.tsv QA: streaming parity and Rust loader compliance', () => {
|
|
for (const seed of [7, 2026, 31337]) {
|
|
test(`seed ${seed}: streamed listing_venues.tsv is byte-identical to the pure formatter across chunk sizes and joins 1:1 with listing_currencies.tsv`, async () => {
|
|
// Arrange
|
|
const listings = buildRandomListings(seed, 257);
|
|
const expected = formatListingVenuesTsv(
|
|
listings.map(l => ({ listingId: l.listing_id, venue: LISTING_VENUE_BY_MIC[l.mic!]! }))
|
|
);
|
|
|
|
// Act / Assert
|
|
for (const chunkSize of [1, 16, 256, 257, 258, 5000]) {
|
|
const outDir = await makeTempDir(`curate-venues-parity-${seed}-${chunkSize}-`);
|
|
const res = await exportCurateInputs(createListingOnlyQueryable(listings), {
|
|
outDir,
|
|
chunkSize,
|
|
});
|
|
|
|
const venuesText = await readFile(res.listingVenues.path, 'utf8');
|
|
const currenciesText = await readFile(res.listingCurrencies.path, 'utf8');
|
|
expect(venuesText).toBe(expected);
|
|
expect(res.listingVenues.rowsIn).toBe(257);
|
|
expect(res.listingVenues.rowsOut).toBe(257);
|
|
expect(res.listingVenues.bytesWritten).toBe(Buffer.byteLength(expected, 'utf8'));
|
|
expect(res.totalBytesWritten).toBe(
|
|
res.providerMapping.bytesWritten +
|
|
res.listingCurrencies.bytesWritten +
|
|
res.listingVenues.bytesWritten +
|
|
res.delistings.bytesWritten
|
|
);
|
|
|
|
const venues = loadListingVenuesTsvStrict(venuesText);
|
|
const currencyIds = currenciesText
|
|
.slice(0, -1)
|
|
.split('\n')
|
|
.map(line => Number(line.split('\t')[0]));
|
|
expect([...venues.keys()]).toEqual(currencyIds);
|
|
|
|
const micById = new Map(listings.map(l => [l.listing_id, l.mic!]));
|
|
for (const [id, venue] of venues) {
|
|
const mic = micById.get(id)!;
|
|
expect(venue).toBe(mic === 'XTSX' || mic === 'XCNQ' ? 'tsxv_cse' : 'us_tsx');
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
test('empty listing table publishes a 0-byte listing_venues.tsv that the Rust loader accepts as an empty map', async () => {
|
|
// Arrange
|
|
const outDir = await makeTempDir('curate-venues-empty-');
|
|
|
|
// Act
|
|
const res = await exportCurateInputs(createListingOnlyQueryable([]), { outDir });
|
|
|
|
// Assert
|
|
const text = await readFile(res.listingVenues.path, 'utf8');
|
|
expect(text).toBe('');
|
|
expect(res.listingVenues).toMatchObject({ rowsIn: 0, rowsOut: 0, bytesWritten: 0 });
|
|
expect(loadListingVenuesTsvStrict(text).size).toBe(0);
|
|
});
|
|
|
|
test('i32-max listing_id is exported verbatim and parses under the Rust strict positive i32 rule', async () => {
|
|
// Arrange
|
|
const outDir = await makeTempDir('curate-venues-i32max-');
|
|
const listings = [activeListing(2_147_483_647, 'XCNQ', 'CAD'), activeListing(1, 'XTSE', 'CAD')];
|
|
|
|
// Act
|
|
const res = await exportCurateInputs(createListingOnlyQueryable(listings), {
|
|
outDir,
|
|
chunkSize: 1,
|
|
});
|
|
|
|
// Assert
|
|
const text = await readFile(res.listingVenues.path, 'utf8');
|
|
expect(text).toBe('1\tus_tsx\n2147483647\ttsxv_cse\n');
|
|
expect([...loadListingVenuesTsvStrict(text)]).toEqual([
|
|
[1, 'us_tsx'],
|
|
[2147483647, 'tsxv_cse'],
|
|
]);
|
|
});
|
|
|
|
test('top-level listing_venues.tsv resolves through current/ to the same generation pinned by pinCurateInputSnapshot, and only read-only SQL is issued', async () => {
|
|
// Arrange
|
|
const outDir = await makeTempDir('curate-venues-layout-');
|
|
const sql: string[] = [];
|
|
const listings = [activeListing(10, 'XTSX', 'CAD'), activeListing(20, 'XNYS')];
|
|
|
|
// Act
|
|
const res = await exportCurateInputs(createListingOnlyQueryable(listings, sql), { outDir });
|
|
const pinned = await pinCurateInputSnapshot(outDir);
|
|
|
|
// Assert
|
|
const topLevel = join(outDir, CURATE_INPUT_FILES.listingVenues);
|
|
expect(await readlink(topLevel)).toBe(
|
|
join(CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES.listingVenues)
|
|
);
|
|
expect(await realpath(topLevel)).toBe(await realpath(res.listingVenues.path));
|
|
expect(pinned.listingVenues).toBe(res.listingVenues.path);
|
|
expect(pinned.generationDir).toBe(
|
|
await realpath(join(outDir, CURATE_INPUT_GENERATIONS_DIR, res.generationId))
|
|
);
|
|
expect(await readFile(topLevel, 'utf8')).toBe('10\ttsxv_cse\n20\tus_tsx\n');
|
|
|
|
expect(sql[0]).toMatch(/^BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY/i);
|
|
for (const stmt of sql) {
|
|
expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT)\b/i);
|
|
}
|
|
expect(sql.filter(s => s.includes('FROM listing')).every(s => /\bmic\b/.test(s))).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('listing_venues.tsv QA: fail-closed MIC values from PostgreSQL', () => {
|
|
const badMics: ReadonlyArray<{ readonly mic: string | null; readonly code: string }> = [
|
|
{ mic: null, code: 'BLANK_FIELD' },
|
|
{ mic: '', code: 'BLANK_FIELD' },
|
|
{ mic: ' ', code: 'BLANK_FIELD' },
|
|
{ mic: ' XTSX', code: 'UNKNOWN_LISTING_MIC' },
|
|
{ mic: 'xtsx', code: 'UNKNOWN_LISTING_MIC' },
|
|
{ mic: 'XLON', code: 'UNKNOWN_LISTING_MIC' },
|
|
{ mic: 'hasOwnProperty', code: 'UNKNOWN_LISTING_MIC' },
|
|
{ mic: 'XT\tSX', code: 'FORBIDDEN_CONTROL_CHAR' },
|
|
];
|
|
|
|
for (const { mic, code } of badMics) {
|
|
test(`mic=${JSON.stringify(mic)} on a later page aborts with ${code} and leaves the previous 4-file generation byte-identical`, async () => {
|
|
// Arrange: publish a good generation first.
|
|
const outDir = await makeTempDir('curate-venues-badmic-');
|
|
const good = [activeListing(1, 'XTSE', 'CAD'), activeListing(2, 'XNAS')];
|
|
const first = await exportCurateInputs(createListingOnlyQueryable(good), { outDir });
|
|
const before = {
|
|
venues: await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8'),
|
|
currencies: await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8'),
|
|
generations: (await readdir(join(outDir, CURATE_INPUT_GENERATIONS_DIR))).sort(),
|
|
entries: (await readdir(outDir)).sort(),
|
|
};
|
|
|
|
// Act: the bad row sits on the 3rd chunk (chunkSize=1) after good rows were already staged.
|
|
const bad = [...good, activeListing(3, mic)];
|
|
let caught: unknown;
|
|
try {
|
|
await exportCurateInputs(createListingOnlyQueryable(bad), { outDir, chunkSize: 1 });
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
// Assert
|
|
expect(caught).toBeInstanceOf(CurateInputExportError);
|
|
expect((caught as CurateInputExportError).code).toBe(code as CurateInputExportError['code']);
|
|
expect((caught as CurateInputExportError).key).toContain('listing_id=3');
|
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(
|
|
before.venues
|
|
);
|
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
|
before.currencies
|
|
);
|
|
expect((await readdir(join(outDir, CURATE_INPUT_GENERATIONS_DIR))).sort()).toEqual(
|
|
before.generations
|
|
);
|
|
expect((await readdir(outDir)).sort()).toEqual(before.entries);
|
|
expect((await pinCurateInputSnapshot(outDir)).generationId).toBe(first.generationId);
|
|
});
|
|
}
|
|
|
|
test('a pre-existing regular listing_venues.tsv (pre-generation layout) survives a failed export untouched', async () => {
|
|
// Arrange
|
|
const outDir = await makeTempDir('curate-venues-legacy-file-');
|
|
const legacy = '5\tus_tsx\n';
|
|
await writeFile(join(outDir, CURATE_INPUT_FILES.listingVenues), legacy, 'utf8');
|
|
|
|
// Act
|
|
await expect(
|
|
exportCurateInputs(createListingOnlyQueryable([activeListing(1, 'XLON')]), { outDir })
|
|
).rejects.toMatchObject({ code: 'UNKNOWN_LISTING_MIC' });
|
|
|
|
// Assert
|
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(legacy);
|
|
const leftovers = (await readdir(outDir)).filter(
|
|
e => e.endsWith('.tmp') || e.endsWith('.bak') || e === '.publish.lock'
|
|
);
|
|
expect(leftovers).toEqual([]);
|
|
});
|
|
});
|