T-116: M1.2af — data-pipeline: read-only security-master → curate-etl input exporter (provider_mapping.tsv, listing_currencies.tsv, Pass 6 delistings.tsv from PostgreSQL) with tests and local benchmark
This commit is contained in:
parent
83933c5124
commit
40a48e90ee
13 changed files with 4068 additions and 1 deletions
999
test/unit/security-master-export-curate-inputs.test.ts
Normal file
999
test/unit/security-master-export-curate-inputs.test.ts
Normal file
|
|
@ -0,0 +1,999 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { mkdtemp, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import {
|
||||
assertExportCurateInputsSafety,
|
||||
buildDelistingExportRows,
|
||||
CURATE_INPUT_FILES,
|
||||
CurateInputExportError,
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
EXPORT_CURATE_INPUTS_USAGE,
|
||||
exportCurateInputs,
|
||||
formatDelistingsTsv,
|
||||
formatExportCurateInputsSummary,
|
||||
formatListingCurrenciesTsv,
|
||||
formatPlainDecimal,
|
||||
formatProviderMappingTsv,
|
||||
parseExportCurateInputsArgs,
|
||||
runExportCurateInputs,
|
||||
type ContinuityExportSourceRow,
|
||||
type DelistingExportRow,
|
||||
type ListingCurrencyExportRow,
|
||||
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(prefix = 'curate-inputs-unit-'): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function expectExportError(
|
||||
fn: () => unknown,
|
||||
expectedCode: CurateInputExportError['code'],
|
||||
expectedTable: string,
|
||||
expectedKeySubstring: string
|
||||
): CurateInputExportError {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CurateInputExportError);
|
||||
const err = error as CurateInputExportError;
|
||||
expect(err.code).toBe(expectedCode);
|
||||
expect(err.table).toBe(expectedTable);
|
||||
expect(err.key).toContain(expectedKeySubstring);
|
||||
expect(err.message).toContain(expectedTable);
|
||||
expect(err.message).toContain(expectedKeySubstring);
|
||||
return err;
|
||||
}
|
||||
throw new Error(`Expected CurateInputExportError(${expectedCode}), but function did not throw`);
|
||||
}
|
||||
|
||||
async function expectExportErrorAsync(
|
||||
fn: () => Promise<unknown>,
|
||||
expectedCode: CurateInputExportError['code'],
|
||||
expectedTable: string,
|
||||
expectedKeySubstring: string
|
||||
): Promise<CurateInputExportError> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CurateInputExportError);
|
||||
const err = error as CurateInputExportError;
|
||||
expect(err.code).toBe(expectedCode);
|
||||
expect(err.table).toBe(expectedTable);
|
||||
expect(err.key).toContain(expectedKeySubstring);
|
||||
expect(err.message).toContain(expectedTable);
|
||||
expect(err.message).toContain(expectedKeySubstring);
|
||||
return err;
|
||||
}
|
||||
throw new Error(`Expected CurateInputExportError(${expectedCode}), but async fn did not throw`);
|
||||
}
|
||||
|
||||
interface InMemorySecurityMasterData {
|
||||
readonly listings: readonly {
|
||||
readonly listing_id: number;
|
||||
readonly currency: string | null;
|
||||
readonly listed_to: string | null;
|
||||
readonly delist_reason: string | null;
|
||||
readonly terminal_return: string | null;
|
||||
}[];
|
||||
readonly continuities: readonly {
|
||||
readonly from_listing_id: number;
|
||||
readonly to_listing_id: number;
|
||||
readonly effective_date: string;
|
||||
readonly kind: string;
|
||||
}[];
|
||||
readonly providerMappings: readonly {
|
||||
readonly source: string | null;
|
||||
readonly source_id: string | null;
|
||||
readonly valid_from: string | null;
|
||||
readonly valid_to: string | null;
|
||||
readonly listing_id: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
function createInMemoryQueryable(
|
||||
data: InMemorySecurityMasterData,
|
||||
hooks?: {
|
||||
readonly failOnQueryNumber?: number;
|
||||
readonly recordedSql?: string[];
|
||||
}
|
||||
): SecurityMasterQueryable {
|
||||
const sortedContinuities = [...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 sortedListings = [...data.listings].sort((a, b) => a.listing_id - b.listing_id);
|
||||
const sortedMappings = [...data.providerMappings].sort(
|
||||
(a, b) =>
|
||||
compareAscii(a.source ?? '', b.source ?? '') ||
|
||||
compareAscii(a.source_id ?? '', b.source_id ?? '') ||
|
||||
compareAscii(a.valid_from ?? '', b.valid_from ?? '')
|
||||
);
|
||||
|
||||
let queryCount = 0;
|
||||
|
||||
return {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
queryCount += 1;
|
||||
hooks?.recordedSql?.push(text.trim());
|
||||
if (hooks?.failOnQueryNumber === queryCount) {
|
||||
throw new Error(`Simulated DB query failure at query #${queryCount}`);
|
||||
}
|
||||
|
||||
const normalized = text.replace(/\s+/g, ' ').trim();
|
||||
if (
|
||||
normalized.startsWith('BEGIN') ||
|
||||
normalized === 'COMMIT' ||
|
||||
normalized === 'ROLLBACK'
|
||||
) {
|
||||
return { rows: [] };
|
||||
}
|
||||
|
||||
if (normalized.includes('FROM corporate_action_continuity')) {
|
||||
if (values && values.length === 1) {
|
||||
const limit = values[0] as number;
|
||||
return { rows: sortedContinuities.slice(0, limit) as unknown as Row[] };
|
||||
}
|
||||
const [lastFromId, lastEffDate, limit] = values as [number, string, number];
|
||||
const filtered = sortedContinuities.filter(
|
||||
c =>
|
||||
c.from_listing_id > lastFromId ||
|
||||
(c.from_listing_id === lastFromId && c.effective_date > lastEffDate)
|
||||
);
|
||||
return { rows: filtered.slice(0, limit) as unknown as Row[] };
|
||||
}
|
||||
|
||||
if (normalized.includes('FROM listing')) {
|
||||
if (values && values.length === 1) {
|
||||
const limit = values[0] as number;
|
||||
return { rows: sortedListings.slice(0, limit) as unknown as Row[] };
|
||||
}
|
||||
const [lastListingId, limit] = values as [number, number];
|
||||
const filtered = sortedListings.filter(l => l.listing_id > lastListingId);
|
||||
return { rows: filtered.slice(0, limit) as unknown as Row[] };
|
||||
}
|
||||
|
||||
if (normalized.includes('FROM provider_mapping')) {
|
||||
if (values && values.length === 1) {
|
||||
const limit = values[0] as number;
|
||||
return { rows: sortedMappings.slice(0, limit) as unknown as Row[] };
|
||||
}
|
||||
const [lastSource, lastSourceId, lastValidFrom, limit] = values as [
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
number,
|
||||
];
|
||||
const filtered = sortedMappings.filter(m => {
|
||||
const src = m.source ?? '';
|
||||
const sid = m.source_id ?? '';
|
||||
const vf = m.valid_from ?? '';
|
||||
const srcCmp = compareAscii(src, lastSource);
|
||||
if (srcCmp !== 0) {
|
||||
return srcCmp > 0;
|
||||
}
|
||||
const sidCmp = compareAscii(sid, lastSourceId);
|
||||
if (sidCmp !== 0) {
|
||||
return sidCmp > 0;
|
||||
}
|
||||
return compareAscii(vf, lastValidFrom) > 0;
|
||||
});
|
||||
return { rows: filtered.slice(0, limit) as unknown as Row[] };
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected SQL in in-memory queryable: ${normalized}`);
|
||||
},
|
||||
release: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical golden fixture dataset shared with `tools/curate-etl/tests/fixtures/curate-inputs/`
|
||||
* and `tools/curate-etl/src/tsv_fixture_tests.rs`.
|
||||
*/
|
||||
function buildGoldenFixtureDataset() {
|
||||
const listings: ListingCurrencyExportRow[] = [
|
||||
{ listingId: 1, currency: 'USD' }, // AAPL active US
|
||||
{ listingId: 2, currency: 'USD' }, // FB old (ticker reuse range 1)
|
||||
{ listingId: 3, currency: 'USD' }, // FB new ETF (ticker reuse range 2)
|
||||
{ listingId: 4, currency: 'USD' }, // SIVB primary listing -> OTC transfer to 6
|
||||
{ listingId: 5, currency: 'USD' }, // SIVB unrelated ticker reuse after halt
|
||||
{ listingId: 6, currency: 'USD' }, // SIVBQ OTC successor -> later cancelled (-1)
|
||||
{ listingId: 7, currency: 'USD' }, // DEL30 Shumway terminal delisting (-0.3)
|
||||
{ listingId: 8, currency: 'CAD' }, // SHOP active CA
|
||||
];
|
||||
|
||||
const delistingListings: ListingDelistingSourceRow[] = [
|
||||
{ listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: null },
|
||||
{ listingId: 2, listedTo: '2022-06-08', delistReason: null, terminalReturn: null },
|
||||
{ listingId: 3, listedTo: null, delistReason: 'active', terminalReturn: null },
|
||||
{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null },
|
||||
{ listingId: 5, listedTo: null, delistReason: 'active', terminalReturn: null },
|
||||
{
|
||||
listingId: 6,
|
||||
listedTo: '2024-11-07',
|
||||
delistReason: 'bankruptcy_cancelled',
|
||||
terminalReturn: '-1.000000',
|
||||
},
|
||||
{
|
||||
listingId: 7,
|
||||
listedTo: '2023-06-15',
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: '-0.300000',
|
||||
},
|
||||
{ listingId: 8, listedTo: null, delistReason: 'active', terminalReturn: null },
|
||||
];
|
||||
|
||||
const continuities: ContinuityExportSourceRow[] = [
|
||||
{
|
||||
fromListingId: 4,
|
||||
toListingId: 6,
|
||||
effectiveDate: '2023-03-28',
|
||||
kind: 'otc_delist_transfer',
|
||||
},
|
||||
];
|
||||
|
||||
const providerMappings: ProviderMappingExportRow[] = [
|
||||
{ source: 'eod', sourceId: 'AAPL.US', validFrom: '1980-12-12', validTo: null, listingId: 1 },
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'DEL30.US',
|
||||
validFrom: '2018-01-02',
|
||||
validTo: '2023-06-15',
|
||||
listingId: 7,
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'FB.US',
|
||||
validFrom: '2012-05-18',
|
||||
validTo: '2022-06-08',
|
||||
listingId: 2,
|
||||
},
|
||||
{ source: 'eod', sourceId: 'FB.US', validFrom: '2022-06-09', validTo: null, listingId: 3 },
|
||||
{ source: 'eod', sourceId: 'SHOP.TO', validFrom: '2015-05-21', validTo: null, listingId: 8 },
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'SIVB.US',
|
||||
validFrom: '1988-01-04',
|
||||
validTo: '2023-03-10',
|
||||
listingId: 4,
|
||||
},
|
||||
{ source: 'eod', sourceId: 'SIVB.US', validFrom: '2023-03-20', validTo: null, listingId: 5 },
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'SIVBQ.US',
|
||||
validFrom: '2023-03-28',
|
||||
validTo: '2024-11-07',
|
||||
listingId: 6,
|
||||
},
|
||||
{ source: 'qm', sourceId: 'AAPL', validFrom: '1980-12-12', validTo: null, listingId: 1 },
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'DEL30',
|
||||
validFrom: '2018-01-02',
|
||||
validTo: '2023-06-15',
|
||||
listingId: 7,
|
||||
},
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'FB',
|
||||
validFrom: '2012-05-18',
|
||||
validTo: '2022-06-08',
|
||||
listingId: 2,
|
||||
},
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2022-06-09', validTo: null, listingId: 3 },
|
||||
{ source: 'qm', sourceId: 'SHOP:CA', validFrom: '2015-05-21', validTo: null, listingId: 8 },
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'SIVB',
|
||||
validFrom: '1988-01-04',
|
||||
validTo: '2023-03-10',
|
||||
listingId: 4,
|
||||
},
|
||||
{ source: 'qm', sourceId: 'SIVB', validFrom: '2023-03-20', validTo: null, listingId: 5 },
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'SIVBQ',
|
||||
validFrom: '2023-03-28',
|
||||
validTo: '2024-11-07',
|
||||
listingId: 6,
|
||||
},
|
||||
];
|
||||
|
||||
return { listings, delistingListings, continuities, providerMappings };
|
||||
}
|
||||
|
||||
describe('formatPlainDecimal', () => {
|
||||
test('normalizes -0 to 0 and expands scientific notation without losing precision', () => {
|
||||
expect(formatPlainDecimal(-0)).toBe('0');
|
||||
expect(formatPlainDecimal(0)).toBe('0');
|
||||
expect(formatPlainDecimal(-1)).toBe('-1');
|
||||
expect(formatPlainDecimal(-0.3)).toBe('-0.3');
|
||||
expect(formatPlainDecimal(-1e-7)).toBe('-0.0000001');
|
||||
expect(formatPlainDecimal(-5.25e-8)).toBe('-0.0000000525');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatProviderMappingTsv', () => {
|
||||
test('emits exact bytes with deterministic ASCII sort under shuffled input, empty valid_to, and verbatim source_id', () => {
|
||||
const rows: ProviderMappingExportRow[] = [
|
||||
{ source: 'qm', sourceId: 'b', validFrom: '2020-01-01', validTo: null, listingId: 2 },
|
||||
{ source: 'eod', sourceId: ' AAPL.US ', validFrom: '2000-01-03', validTo: null, listingId: 1 },
|
||||
{ source: 'qm', sourceId: 'A', validFrom: '2022-06-09', validTo: null, listingId: 4 },
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'A',
|
||||
validFrom: '2012-05-18',
|
||||
validTo: '2022-06-08',
|
||||
listingId: 3,
|
||||
},
|
||||
];
|
||||
|
||||
const expected = [
|
||||
'eod\t AAPL.US \t2000-01-03\t\t1',
|
||||
'qm\tA\t2012-05-18\t2022-06-08\t3',
|
||||
'qm\tA\t2022-06-09\t\t4',
|
||||
'qm\tb\t2020-01-01\t\t2',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
expect(formatProviderMappingTsv(rows)).toBe(expected);
|
||||
expect(formatProviderMappingTsv([...rows].reverse())).toBe(expected);
|
||||
});
|
||||
|
||||
test('empty input produces empty string (0-byte file)', () => {
|
||||
expect(formatProviderMappingTsv([])).toBe('');
|
||||
});
|
||||
|
||||
test('fails closed on forbidden control chars, blanks, bad dates, bad listing_id, duplicates, and overlaps', () => {
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'eod', sourceId: 'BAD\tID', validFrom: '2020-01-01', validTo: null, listingId: 1 },
|
||||
]),
|
||||
'FORBIDDEN_CONTROL_CHAR',
|
||||
'provider_mapping',
|
||||
'eod:row#0'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'eod', sourceId: 'BAD\nID', validFrom: '2020-01-01', validTo: null, listingId: 1 },
|
||||
]),
|
||||
'FORBIDDEN_CONTROL_CHAR',
|
||||
'provider_mapping',
|
||||
'eod:row#0'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'eod', sourceId: 'BAD\rID', validFrom: '2020-01-01', validTo: null, listingId: 1 },
|
||||
]),
|
||||
'FORBIDDEN_CONTROL_CHAR',
|
||||
'provider_mapping',
|
||||
'eod:row#0'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: ' ', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 1 },
|
||||
]),
|
||||
'BLANK_FIELD',
|
||||
'provider_mapping',
|
||||
'row#0'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'eod', sourceId: ' ', validFrom: '2020-01-01', validTo: null, listingId: 1 },
|
||||
]),
|
||||
'BLANK_FIELD',
|
||||
'provider_mapping',
|
||||
'eod:row#0'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'eod', sourceId: 'AAPL', validFrom: '2023-02-29', validTo: null, listingId: 1 },
|
||||
]),
|
||||
'INVALID_DATE',
|
||||
'provider_mapping',
|
||||
'eod:AAPL:2023-02-29'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL',
|
||||
validFrom: '2023-05-01',
|
||||
validTo: '2023-04-30',
|
||||
listingId: 1,
|
||||
},
|
||||
]),
|
||||
'INVALID_DATE_RANGE',
|
||||
'provider_mapping',
|
||||
'eod:AAPL:2023-05-01'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'eod', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 0 },
|
||||
]),
|
||||
'INVALID_LISTING_ID',
|
||||
'provider_mapping',
|
||||
'eod:AAPL:2020-01-01'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL',
|
||||
validFrom: '2020-01-01',
|
||||
validTo: null,
|
||||
listingId: 2_147_483_648,
|
||||
},
|
||||
]),
|
||||
'INVALID_LISTING_ID',
|
||||
'provider_mapping',
|
||||
'eod:AAPL:2020-01-01'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2021-01-01', listingId: 1 },
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2022-01-01', listingId: 2 },
|
||||
]),
|
||||
'DUPLICATE_PROVIDER_MAPPING',
|
||||
'provider_mapping',
|
||||
'qm:FB:2020-01-01'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2021-06-01', listingId: 1 },
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2021-06-01', validTo: null, listingId: 2 },
|
||||
]),
|
||||
'OVERLAPPING_PROVIDER_MAPPING',
|
||||
'provider_mapping',
|
||||
'qm:FB:2021-06-01'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatProviderMappingTsv([
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: null, listingId: 1 },
|
||||
{ source: 'qm', sourceId: 'FB', validFrom: '2021-06-01', validTo: null, listingId: 2 },
|
||||
]),
|
||||
'OVERLAPPING_PROVIDER_MAPPING',
|
||||
'provider_mapping',
|
||||
'qm:FB:2021-06-01'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatListingCurrenciesTsv', () => {
|
||||
test('sorts by ascending listing_id and handles empty input', () => {
|
||||
expect(formatListingCurrenciesTsv([])).toBe('');
|
||||
const rows: ListingCurrencyExportRow[] = [
|
||||
{ listingId: 10, currency: 'CAD' },
|
||||
{ listingId: 2, currency: 'USD' },
|
||||
{ listingId: 5, currency: 'USD' },
|
||||
];
|
||||
const expected = '2\tUSD\n5\tUSD\n10\tCAD\n';
|
||||
expect(formatListingCurrenciesTsv(rows)).toBe(expected);
|
||||
expect(formatListingCurrenciesTsv([...rows].reverse())).toBe(expected);
|
||||
});
|
||||
|
||||
test('fails closed on blank/null currency, control chars, invalid listing_id, and duplicate listing_id', () => {
|
||||
expectExportError(
|
||||
() => formatListingCurrenciesTsv([{ listingId: 1, currency: '' }]),
|
||||
'BLANK_FIELD',
|
||||
'listing',
|
||||
'listing_id=1'
|
||||
);
|
||||
expectExportError(
|
||||
() => formatListingCurrenciesTsv([{ listingId: 1, currency: null as unknown as string }]),
|
||||
'BLANK_FIELD',
|
||||
'listing',
|
||||
'listing_id=1'
|
||||
);
|
||||
expectExportError(
|
||||
() => formatListingCurrenciesTsv([{ listingId: 1, currency: 'US\tD' }]),
|
||||
'FORBIDDEN_CONTROL_CHAR',
|
||||
'listing',
|
||||
'listing_id=1'
|
||||
);
|
||||
expectExportError(
|
||||
() => formatListingCurrenciesTsv([{ listingId: -3, currency: 'USD' }]),
|
||||
'INVALID_LISTING_ID',
|
||||
'listing',
|
||||
'row#0'
|
||||
);
|
||||
expectExportError(
|
||||
() =>
|
||||
formatListingCurrenciesTsv([
|
||||
{ listingId: 7, currency: 'USD' },
|
||||
{ listingId: 7, currency: 'CAD' },
|
||||
]),
|
||||
'DUPLICATE_LISTING_CURRENCY',
|
||||
'listing',
|
||||
'listing_id=7'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildDelistingExportRows and formatDelistingsTsv', () => {
|
||||
test('handles OTC transfer + successor terminal delisting (SIVB -> SIVBQ -> -1), -0.3 Shumway, active/null skips, and stats conservation', () => {
|
||||
const listings: ListingDelistingSourceRow[] = [
|
||||
{ listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: null },
|
||||
{ listingId: 2, listedTo: '2022-06-08', delistReason: null, terminalReturn: null },
|
||||
{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null },
|
||||
{ listingId: 6, listedTo: '2024-11-07', delistReason: 'bankruptcy_cancelled', terminalReturn: -1 },
|
||||
{ listingId: 7, listedTo: '2023-06-15', delistReason: 'unknown_involuntary', terminalReturn: -0.3 },
|
||||
{ listingId: 9, listedTo: null, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, // missingListedTo
|
||||
{ listingId: 10, listedTo: '2023-07-01', delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, // missingOutgoingQmMapping
|
||||
{ listingId: 11, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, // missingSuccessorQmMapping
|
||||
{ listingId: 12, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, // missingOutgoingQmMapping for OTC
|
||||
{ listingId: 13, listedTo: '2023-08-01', delistReason: 'merger_cash', terminalReturn: -0 }, // -0 normalized to 0
|
||||
{ listingId: 14, listedTo: '2023-08-02', delistReason: 'merger_cash', terminalReturn: -1e-7 }, // tiny decimal without sci notation
|
||||
];
|
||||
|
||||
const continuities: ContinuityExportSourceRow[] = [
|
||||
{ fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' },
|
||||
{ fromListingId: 11, toListingId: 99, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' },
|
||||
{ fromListingId: 12, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' },
|
||||
{ fromListingId: 1, toListingId: 2, effectiveDate: '2021-01-01', kind: 'venue_uplisting' },
|
||||
];
|
||||
|
||||
const mappings: ProviderMappingExportRow[] = [
|
||||
{ source: 'qm', sourceId: 'SIVB', validFrom: '1988-01-04', validTo: '2023-03-10', listingId: 4 },
|
||||
{ source: 'qm', sourceId: 'SIVBQ', validFrom: '2023-03-28', validTo: '2024-11-07', listingId: 6 },
|
||||
{ source: 'qm', sourceId: 'DEL30', validFrom: '2018-01-02', validTo: '2023-06-15', listingId: 7 },
|
||||
{ source: 'qm', sourceId: 'NOSUCC', validFrom: '2019-01-01', validTo: '2023-03-10', listingId: 11 },
|
||||
{ source: 'qm', sourceId: 'ZERO', validFrom: '2020-01-01', validTo: '2023-08-01', listingId: 13 },
|
||||
{ source: 'qm', sourceId: 'TINY', validFrom: '2020-01-01', validTo: '2023-08-02', listingId: 14 },
|
||||
{ source: 'eod', sourceId: 'NOQM.US', validFrom: '2020-01-01', validTo: '2023-07-01', listingId: 10 },
|
||||
];
|
||||
|
||||
const result = buildDelistingExportRows(listings, continuities, mappings);
|
||||
const { stats } = result;
|
||||
expect(stats.otcTransfersOut).toBe(1);
|
||||
expect(stats.terminalDelistingsOut).toBe(4);
|
||||
expect(stats.rowsOut).toBe(5);
|
||||
expect(stats.skipped).toEqual({
|
||||
active: 1,
|
||||
noOutcome: 1,
|
||||
missingListedTo: 1,
|
||||
missingOutgoingQmMapping: 2,
|
||||
missingSuccessorQmMapping: 1,
|
||||
nonOtcContinuity: 1,
|
||||
});
|
||||
expect(stats.skippedTotal).toBe(7);
|
||||
expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal);
|
||||
|
||||
const tsv = formatDelistingsTsv(result.rows);
|
||||
expect(tsv).toBe(
|
||||
[
|
||||
'DEL30\t2023-06-15\t7\t\t-0.3',
|
||||
'SIVB\t2023-03-28\t4\tSIVBQ\t',
|
||||
'SIVBQ\t2024-11-07\t6\t\t-1',
|
||||
'TINY\t2023-08-02\t14\t\t-0.0000001',
|
||||
'ZERO\t2023-08-01\t13\t\t0',
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
// Deterministic under shuffled inputs
|
||||
const shuffledResult = buildDelistingExportRows(
|
||||
[...listings].reverse(),
|
||||
[...continuities].reverse(),
|
||||
[...mappings].reverse()
|
||||
);
|
||||
expect(formatDelistingsTsv(shuffledResult.rows)).toBe(tsv);
|
||||
expect(shuffledResult.stats).toEqual(stats);
|
||||
});
|
||||
|
||||
test('empty input produces empty string (0-byte file)', () => {
|
||||
expect(formatDelistingsTsv([])).toBe('');
|
||||
});
|
||||
|
||||
test('fails closed on invalid delisting rows and DB conflicts', () => {
|
||||
const bothOutcomes: DelistingExportRow = {
|
||||
sourceId: 'SIVB',
|
||||
delistDate: '2023-03-28',
|
||||
fromListingId: 4,
|
||||
successorSourceId: 'SIVBQ',
|
||||
terminalReturn: -0.3,
|
||||
};
|
||||
expectExportError(
|
||||
() => formatDelistingsTsv([bothOutcomes]),
|
||||
'INVALID_DELISTING_OUTCOME',
|
||||
'delistings',
|
||||
'SIVB:2023-03-28'
|
||||
);
|
||||
|
||||
const neitherOutcome: DelistingExportRow = {
|
||||
sourceId: 'SIVB',
|
||||
delistDate: '2023-03-28',
|
||||
fromListingId: 4,
|
||||
successorSourceId: null,
|
||||
terminalReturn: null,
|
||||
};
|
||||
expectExportError(
|
||||
() => formatDelistingsTsv([neitherOutcome]),
|
||||
'INVALID_DELISTING_OUTCOME',
|
||||
'delistings',
|
||||
'SIVB:2023-03-28'
|
||||
);
|
||||
|
||||
expectExportError(
|
||||
() =>
|
||||
formatDelistingsTsv([
|
||||
{
|
||||
sourceId: 'SIVB',
|
||||
delistDate: '2023-03-28',
|
||||
fromListingId: null,
|
||||
successorSourceId: 'SIVBQ',
|
||||
terminalReturn: null,
|
||||
},
|
||||
]),
|
||||
'MISSING_FROM_LISTING_ID',
|
||||
'delistings',
|
||||
'SIVB:2023-03-28'
|
||||
);
|
||||
|
||||
for (const badReturn of [0.01, -1.01, Number.NaN, Number.POSITIVE_INFINITY, ' -0.3', 'abc']) {
|
||||
expectExportError(
|
||||
() =>
|
||||
formatDelistingsTsv([
|
||||
{
|
||||
sourceId: 'BADRET',
|
||||
delistDate: '2023-06-15',
|
||||
fromListingId: 7,
|
||||
successorSourceId: null,
|
||||
terminalReturn: badReturn,
|
||||
},
|
||||
]),
|
||||
'INVALID_TERMINAL_RETURN',
|
||||
'delistings',
|
||||
'BADRET:2023-06-15'
|
||||
);
|
||||
}
|
||||
|
||||
expectExportError(
|
||||
() =>
|
||||
buildDelistingExportRows(
|
||||
[{ listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: -0.3 }],
|
||||
[],
|
||||
[]
|
||||
),
|
||||
'ACTIVE_LISTING_WITH_OUTCOME',
|
||||
'listing',
|
||||
'listing_id=1'
|
||||
);
|
||||
|
||||
expectExportError(
|
||||
() =>
|
||||
buildDelistingExportRows(
|
||||
[{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: -0.3 }],
|
||||
[{ fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }],
|
||||
[]
|
||||
),
|
||||
'INVALID_DELISTING_OUTCOME',
|
||||
'listing',
|
||||
'listing_id=4'
|
||||
);
|
||||
|
||||
expectExportError(
|
||||
() =>
|
||||
buildDelistingExportRows(
|
||||
[{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }],
|
||||
[{ fromListingId: 4, toListingId: 4, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }],
|
||||
[]
|
||||
),
|
||||
'SELF_SUCCESSOR_CONTINUITY',
|
||||
'corporate_action_continuity',
|
||||
'from_listing_id=4@2023-03-28'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportCurateInputs atomic publish and streaming', () => {
|
||||
test('leaves pre-existing files byte-identical with zero leftover temp/bak files on mid-query, mid-validation, and mid-rename failures', async () => {
|
||||
const outDir = await makeTempDir('curate-inputs-atomic-');
|
||||
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
||||
const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies);
|
||||
const dlPath = join(outDir, CURATE_INPUT_FILES.delistings);
|
||||
|
||||
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
|
||||
const origLc = '1\tUSD\n';
|
||||
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
|
||||
await writeFile(pmPath, origPm, 'utf8');
|
||||
await writeFile(lcPath, origLc, 'utf8');
|
||||
await writeFile(dlPath, origDl, 'utf8');
|
||||
|
||||
const baseData: InMemorySecurityMasterData = {
|
||||
listings: [
|
||||
{ listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
|
||||
],
|
||||
continuities: [],
|
||||
providerMappings: [
|
||||
{ source: 'eod', source_id: 'NEW.US', valid_from: '2021-01-01', valid_to: null, listing_id: 1 },
|
||||
],
|
||||
};
|
||||
|
||||
const assertIntact = async () => {
|
||||
expect(await readFile(pmPath, 'utf8')).toBe(origPm);
|
||||
expect(await readFile(lcPath, 'utf8')).toBe(origLc);
|
||||
expect(await readFile(dlPath, 'utf8')).toBe(origDl);
|
||||
const entries = (await readdir(outDir)).sort();
|
||||
expect(entries).toEqual([
|
||||
CURATE_INPUT_FILES.delistings,
|
||||
CURATE_INPUT_FILES.listingCurrencies,
|
||||
CURATE_INPUT_FILES.providerMapping,
|
||||
]);
|
||||
};
|
||||
|
||||
// 1. Mid-query failure
|
||||
const failingQueryClient = createInMemoryQueryable(baseData, { failOnQueryNumber: 3 });
|
||||
await expect(exportCurateInputs(failingQueryClient, { outDir })).rejects.toThrow(
|
||||
'Simulated DB query failure'
|
||||
);
|
||||
await assertIntact();
|
||||
|
||||
// 2. Mid-validation failure (tab inside source_id)
|
||||
const badDataClient = createInMemoryQueryable({
|
||||
...baseData,
|
||||
providerMappings: [
|
||||
{ source: 'eod', source_id: 'BAD\tID', valid_from: '2021-01-01', valid_to: null, listing_id: 1 },
|
||||
],
|
||||
});
|
||||
await expectExportErrorAsync(
|
||||
() => exportCurateInputs(badDataClient, { outDir }),
|
||||
'FORBIDDEN_CONTROL_CHAR',
|
||||
'provider_mapping',
|
||||
'eod:row#0'
|
||||
);
|
||||
await assertIntact();
|
||||
|
||||
// 3. Mid-rename failure on the 2nd published file (after 3 backups + 1st publish rename)
|
||||
let renameCalls = 0;
|
||||
const goodClient = createInMemoryQueryable(baseData);
|
||||
await expect(
|
||||
exportCurateInputs(goodClient, {
|
||||
outDir,
|
||||
fs: {
|
||||
rename: async (oldPath, newPath) => {
|
||||
renameCalls += 1;
|
||||
if (renameCalls === 5) {
|
||||
throw new Error('Simulated EIO on 2nd target publish rename');
|
||||
}
|
||||
return rename(oldPath, newPath);
|
||||
},
|
||||
},
|
||||
})
|
||||
).rejects.toThrow('Simulated EIO on 2nd target publish rename');
|
||||
await assertIntact();
|
||||
});
|
||||
|
||||
test('rejects pool-like objects and invalid chunkSize', async () => {
|
||||
const outDir = await makeTempDir('curate-inputs-pool-');
|
||||
const poolLike = {
|
||||
query: async () => ({ rows: [] }),
|
||||
connect: async () => ({}),
|
||||
} as unknown as SecurityMasterQueryable;
|
||||
|
||||
await expectExportErrorAsync(
|
||||
() => exportCurateInputs(poolLike, { outDir }),
|
||||
'INVALID_CLIENT',
|
||||
'connection',
|
||||
'client'
|
||||
);
|
||||
|
||||
const validClient = createInMemoryQueryable({
|
||||
listings: [],
|
||||
continuities: [],
|
||||
providerMappings: [],
|
||||
});
|
||||
await expectExportErrorAsync(
|
||||
() => exportCurateInputs(validClient, { outDir, chunkSize: 5001 }),
|
||||
'INVALID_OPTION',
|
||||
'options',
|
||||
'chunkSize'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('golden fixtures cross-language parity', () => {
|
||||
test('TS exporter reproduces committed tools/curate-etl/tests/fixtures/curate-inputs/*.tsv byte-for-byte', async () => {
|
||||
const fixtureDir = resolve(
|
||||
import.meta.dir,
|
||||
'../../tools/curate-etl/tests/fixtures/curate-inputs'
|
||||
);
|
||||
const dataset = buildGoldenFixtureDataset();
|
||||
|
||||
const expectedPm = formatProviderMappingTsv(dataset.providerMappings);
|
||||
const expectedLc = formatListingCurrenciesTsv(dataset.listings);
|
||||
const builtDelistings = buildDelistingExportRows(
|
||||
dataset.delistingListings,
|
||||
dataset.continuities,
|
||||
dataset.providerMappings
|
||||
);
|
||||
const expectedDl = formatDelistingsTsv(builtDelistings.rows);
|
||||
|
||||
expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(
|
||||
expectedPm
|
||||
);
|
||||
expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
||||
expectedLc
|
||||
);
|
||||
expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(
|
||||
expectedDl
|
||||
);
|
||||
|
||||
// Also verify streaming exportCurateInputs produces identical bytes with chunkSize=2.
|
||||
const outDir = await makeTempDir('curate-inputs-golden-');
|
||||
const queryable = createInMemoryQueryable({
|
||||
listings: dataset.delistingListings.map((l, idx) => ({
|
||||
listing_id: l.listingId,
|
||||
currency: dataset.listings[idx]!.currency,
|
||||
listed_to: l.listedTo,
|
||||
delist_reason: l.delistReason,
|
||||
terminal_return: l.terminalReturn === null ? null : String(l.terminalReturn),
|
||||
})),
|
||||
continuities: dataset.continuities.map(c => ({
|
||||
from_listing_id: c.fromListingId,
|
||||
to_listing_id: c.toListingId,
|
||||
effective_date: c.effectiveDate,
|
||||
kind: c.kind,
|
||||
})),
|
||||
providerMappings: dataset.providerMappings.map(m => ({
|
||||
source: m.source,
|
||||
source_id: m.sourceId,
|
||||
valid_from: m.validFrom,
|
||||
valid_to: m.validTo,
|
||||
listing_id: m.listingId,
|
||||
})),
|
||||
});
|
||||
|
||||
const result = await exportCurateInputs(queryable, { outDir, chunkSize: 2 });
|
||||
expect(await readFile(result.providerMapping.path, 'utf8')).toBe(expectedPm);
|
||||
expect(await readFile(result.listingCurrencies.path, 'utf8')).toBe(expectedLc);
|
||||
expect(await readFile(result.delistings.path, 'utf8')).toBe(expectedDl);
|
||||
expect(result.delistings.stats).toEqual(builtDelistings.stats);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CLI args, safety guard, and runner', () => {
|
||||
test('parseExportCurateInputsArgs parses --out-dir, --chunk-size, and --help', () => {
|
||||
expect(parseExportCurateInputsArgs(['--help'])).toEqual({ help: true });
|
||||
expect(parseExportCurateInputsArgs(['--out-dir', '/tmp/curate'])).toEqual({
|
||||
help: false,
|
||||
outDir: '/tmp/curate',
|
||||
chunkSize: DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
});
|
||||
expect(parseExportCurateInputsArgs(['--out-dir=/tmp/curate', '--chunk-size=250'])).toEqual({
|
||||
help: false,
|
||||
outDir: '/tmp/curate',
|
||||
chunkSize: 250,
|
||||
});
|
||||
expect(() => parseExportCurateInputsArgs([])).toThrow(EXPORT_CURATE_INPUTS_USAGE);
|
||||
expect(() => parseExportCurateInputsArgs(['--out-dir', '/tmp/a', '--chunk-size', '5001'])).toThrow(
|
||||
'Invalid --chunk-size'
|
||||
);
|
||||
expect(() => parseExportCurateInputsArgs(['--unknown'])).toThrow('Unknown argument');
|
||||
});
|
||||
|
||||
test('assertExportCurateInputsSafety blocks disabled PG and dev->QA PG even when override env var is set', () => {
|
||||
const devOnQaConfig = {
|
||||
environment: 'development',
|
||||
database: {
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'trading_bot',
|
||||
},
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri: 'mongodb://localhost:27017/stock',
|
||||
database: 'stock',
|
||||
},
|
||||
},
|
||||
} as unknown as StockAppConfig;
|
||||
|
||||
expect(() =>
|
||||
assertExportCurateInputsSafety(devOnQaConfig, {
|
||||
STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true',
|
||||
})
|
||||
).toThrow();
|
||||
|
||||
const disabledPgConfig = {
|
||||
...devOnQaConfig,
|
||||
database: {
|
||||
...devOnQaConfig.database,
|
||||
postgres: { ...devOnQaConfig.database.postgres, enabled: false },
|
||||
},
|
||||
} as unknown as StockAppConfig;
|
||||
expect(() => assertExportCurateInputsSafety(disabledPgConfig, {})).toThrow(
|
||||
'PostgreSQL is disabled'
|
||||
);
|
||||
|
||||
const safeDevConfig = {
|
||||
...devOnQaConfig,
|
||||
database: {
|
||||
...devOnQaConfig.database,
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 5433,
|
||||
database: 'trading_bot_dev',
|
||||
},
|
||||
},
|
||||
} as unknown as StockAppConfig;
|
||||
expect(() => assertExportCurateInputsSafety(safeDevConfig, {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('runExportCurateInputs runs safety, exports, closes PG client, and prints summary', async () => {
|
||||
const outDir = await makeTempDir('curate-inputs-cli-');
|
||||
let safetyChecked = false;
|
||||
let closed = false;
|
||||
let stdoutText = '';
|
||||
|
||||
const queryable = createInMemoryQueryable({
|
||||
listings: [
|
||||
{ listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
|
||||
],
|
||||
continuities: [],
|
||||
providerMappings: [
|
||||
{ source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const output = await runExportCurateInputs(
|
||||
{
|
||||
assertSafety: () => {
|
||||
safetyChecked = true;
|
||||
},
|
||||
createPostgresClient: () => ({
|
||||
queryable,
|
||||
close: () => {
|
||||
closed = true;
|
||||
},
|
||||
}),
|
||||
writeStdout: text => {
|
||||
stdoutText += text;
|
||||
},
|
||||
},
|
||||
{ outDir, chunkSize: 100 }
|
||||
);
|
||||
|
||||
expect(safetyChecked).toBe(true);
|
||||
expect(closed).toBe(true);
|
||||
expect(output.summary).toBe(formatExportCurateInputsSummary(output.result));
|
||||
expect(stdoutText).toContain('provider_mapping.tsv: rows_in=1 rows_out=1');
|
||||
expect(stdoutText).toContain('listing_currencies.tsv: rows_in=1 rows_out=1');
|
||||
expect(stdoutText).toContain('delistings.tsv: rows_in=1 rows_out=0');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue