diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index a714a1f5..aba96819 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -230,3 +230,37 @@ bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts - Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`. - Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta). - After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta). + +## Read-Only Curate-ETL TSV Exporter (`export-curate-inputs.ts`) +`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts` and its CLI `run-export-curate-inputs.ts` read the PostgreSQL security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` transaction (keyset-paginated in chunks `<= 5,000`) and atomically publish the three headerless `\t`-separated TSV inputs consumed by `tools/curate-etl`: + +```bash +NODE_ENV=development \ +POSTGRES_HOST=localhost \ +POSTGRES_PORT=5433 \ +POSTGRES_DATABASE=trading_bot_dev \ + bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \ + --out-dir ./tmp/curate-inputs \ + [--chunk-size 5000] +``` + +- **Output files (`--out-dir`, atomic publish via temp files + rollback on error):** + - `provider_mapping.tsv` — `source \t source_id \t valid_from \t valid_to(or empty) \t listing_id`, sorted in `COLLATE "C"` ASCII order, preserving non-blank values verbatim and failing closed on `\t`/`\n`/`\r`, duplicates, or overlapping inclusive ranges. + - `listing_currencies.tsv` — `listing_id \t currency`, sorted by ascending `listing_id`. + - `delistings.tsv` — Pass 6 delistings (`source_id \t delist_date \t from_listing_id \t successor_source_id(or empty) \t terminal_return(or empty)`), resolved against `qm` mappings (`valid_from <= effective_date` for outgoing OTC transfers, valid on `effective_date` for OTC successors, valid on `listed_to` for terminal delistings) and indexed by `from_listing_id` so OTC successors (e.g. `SIVBQ`) still emit their own terminal delisting. +- **Skip-reason accounting (`rowsIn === rowsOut + skippedTotal`):** + - `active`: active listings (no delisting row emitted; fails closed if an `active` listing has a continuity or `terminal_return`). + - `noOutcome`: non-active listings with neither an outgoing `otc_delist_transfer` nor a `terminal_return`. + - `missingListedTo`: terminal-return listings with `listed_to IS NULL`. + - `missingOutgoingQmMapping`: delisting/OTC candidates without a qualifying outgoing `qm` mapping. + - `missingSuccessorQmMapping`: OTC transfers whose successor listing has no `qm` mapping valid on `effective_date`. + - `nonOtcContinuity`: non-`otc_delist_transfer` continuities skipped in the pure `buildDelistingExportRows` builder. +- **Local synthetic benchmark (zero PostgreSQL):** Run the fixed-seed 500,000-mapping / 100,000-listing streaming benchmark with: + +```bash +bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts +``` + +- **Recorded baseline (`2026-11-29`, local sandbox, in-memory keyset-paginated queryable, `chunkSize = 5000`):** + - Workload: `500,000` `provider_mapping` rows, `100,000` `listing` rows, `2,000` OTC continuities, terminal delistings, and skipped rows (`606,680` exported rows, `17,203,861` bytes written across all three TSVs). + - Observed throughput: `1,525,062 rows/s` (`397.8 ms` elapsed, `262.88 MiB` peak RSS). diff --git a/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts b/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts new file mode 100644 index 00000000..6b945000 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts @@ -0,0 +1,278 @@ +/** + * Reproducible headless benchmark for `exportCurateInputs`. + * Streams 500,000 `provider_mapping` rows + 100,000 `listing` rows + 2,000 OTC continuities + + * terminal delistings + skipped rows through an in-memory keyset-paginated + * `SecurityMasterQueryable` into a temporary directory (cleaned up in `finally`), with zero + * database or network dependencies. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts + */ + +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + DEFAULT_EXPORT_CHUNK_SIZE, + exportCurateInputs, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, +} from '../src/security-master/export-curate-inputs'; + +const LISTING_COUNT = 100_000; +const PROVIDER_MAPPING_COUNT = 500_000; +const OTC_CONTINUITY_COUNT = 2_000; + +interface BenchContinuityRow { + from_listing_id: number; + to_listing_id: number; + effective_date: string; + kind: string; +} + +interface BenchListingRow { + listing_id: number; + currency: string; + listed_to: string | null; + delist_reason: string | null; + terminal_return: string | null; +} + +interface BenchMappingRow { + source: string; + source_id: string; + valid_from: string; + valid_to: string | null; + listing_id: number; +} + +/** + * Generates deterministic sorted synthetic rows (matching PostgreSQL ORDER BY): + * - 100,000 listings: + * - 1..2000: OTC outgoing listings (moved_to_otc -> successor listing_id + 2000) + * - 2001..4000: OTC successor listings (half bankruptcy_cancelled -1.0, half active) + * - 4001..8000: terminal delistings (-0.3; every 20th has listed_to = null -> missingListedTo) + * - 8001..10000: delisted with null outcome (noOutcome) + * - 10001..100000: active US/CA listings + * - 500,000 provider_mapping rows in strict ASCII COLLATE "C" order across 5 sources: + * ceo (100k), eod (100k), ib (100k), qm (100k), te (100k). + * For a small deterministic subset of listings, omit the `qm` mapping (assign to listing 10001) + * so missingOutgoingQmMapping and missingSuccessorQmMapping are exercised too. + */ +function buildSyntheticTables(): { + continuities: BenchContinuityRow[]; + listings: BenchListingRow[]; + mappings: BenchMappingRow[]; +} { + const continuities = new Array(OTC_CONTINUITY_COUNT); + for (let i = 0; i < OTC_CONTINUITY_COUNT; i++) { + const fromId = i + 1; + continuities[i] = { + from_listing_id: fromId, + to_listing_id: fromId + OTC_CONTINUITY_COUNT, + effective_date: '2023-03-28', + kind: 'otc_delist_transfer', + }; + } + + const listings = new Array(LISTING_COUNT); + for (let i = 0; i < LISTING_COUNT; i++) { + const id = i + 1; + const currency = id % 5 === 0 ? 'CAD' : 'USD'; + if (id <= OTC_CONTINUITY_COUNT) { + listings[i] = { + listing_id: id, + currency, + listed_to: '2023-03-10', + delist_reason: 'moved_to_otc', + terminal_return: null, + }; + } else if (id <= OTC_CONTINUITY_COUNT * 2) { + if (id % 2 === 0) { + listings[i] = { + listing_id: id, + currency, + listed_to: '2024-11-07', + delist_reason: 'bankruptcy_cancelled', + terminal_return: '-1.000000', + }; + } else { + listings[i] = { + listing_id: id, + currency, + listed_to: null, + delist_reason: 'active', + terminal_return: null, + }; + } + } else if (id <= 8_000) { + const missingDate = id % 20 === 0; + listings[i] = { + listing_id: id, + currency, + listed_to: missingDate ? null : '2023-06-15', + delist_reason: 'unknown_involuntary', + terminal_return: '-0.300000', + }; + } else if (id <= 10_000) { + listings[i] = { + listing_id: id, + currency, + listed_to: '2022-12-30', + delist_reason: null, + terminal_return: null, + }; + } else { + listings[i] = { + listing_id: id, + currency, + listed_to: null, + delist_reason: 'active', + terminal_return: null, + }; + } + } + + // 5 sources in strict ASCII order: ceo, eod, ib, qm, te (100,000 rows each = 500,000 total). + const sources = ['ceo', 'eod', 'ib', 'qm', 'te'] as const; + const mappings = new Array(PROVIDER_MAPPING_COUNT); + let idx = 0; + for (const source of sources) { + for (let i = 0; i < LISTING_COUNT; i++) { + const naturalListingId = i + 1; + const padded = String(naturalListingId).padStart(6, '0'); + let listingId = naturalListingId; + let validFrom = '2015-01-02'; + let validTo: string | null = null; + + if (naturalListingId <= OTC_CONTINUITY_COUNT) { + validTo = '2023-03-10'; + // Drop QM mapping for every 40th outgoing OTC listing (redirect to active listing 10001). + if (source === 'qm' && naturalListingId % 40 === 0) { + listingId = 10_001; + } + } else if (naturalListingId <= OTC_CONTINUITY_COUNT * 2) { + validFrom = '2023-03-28'; + validTo = naturalListingId % 2 === 0 ? '2024-11-07' : null; + // Drop QM mapping for every 50th successor OTC listing. + if (source === 'qm' && naturalListingId % 50 === 0) { + listingId = 10_002; + } + } else if (naturalListingId <= 8_000) { + validTo = '2023-06-15'; + } + + mappings[idx++] = { + source, + source_id: `SYM${padded}`, + valid_from: validFrom, + valid_to: validTo, + listing_id: listingId, + }; + } + } + + return { continuities, listings, mappings }; +} + +function createFastPaginatedQueryable(tables: { + continuities: BenchContinuityRow[]; + listings: BenchListingRow[]; + mappings: BenchMappingRow[]; +}): SecurityMasterQueryable { + let contOffset = 0; + let listingOffset = 0; + let mappingOffset = 0; + + return { + async query>( + text: string, + values?: readonly unknown[] + ): Promise> { + const normalized = text.replace(/\s+/g, ' ').trim(); + if (normalized.startsWith('BEGIN')) { + contOffset = 0; + listingOffset = 0; + mappingOffset = 0; + return { rows: [] }; + } + if (normalized === 'COMMIT' || normalized === 'ROLLBACK') { + return { rows: [] }; + } + + const limit = values ? (values[values.length - 1] as number) : DEFAULT_EXPORT_CHUNK_SIZE; + + if (normalized.includes('FROM corporate_action_continuity')) { + const slice = tables.continuities.slice(contOffset, contOffset + limit); + contOffset += slice.length; + return { rows: slice as unknown as Row[] }; + } + if (normalized.includes('FROM listing')) { + const slice = tables.listings.slice(listingOffset, listingOffset + limit); + listingOffset += slice.length; + return { rows: slice as unknown as Row[] }; + } + if (normalized.includes('FROM provider_mapping')) { + const slice = tables.mappings.slice(mappingOffset, mappingOffset + limit); + mappingOffset += slice.length; + return { rows: slice as unknown as Row[] }; + } + + throw new Error(`Unexpected SQL in benchmark queryable: ${normalized}`); + }, + release: () => {}, + }; +} + +async function main(): Promise { + const tables = buildSyntheticTables(); + const queryable = createFastPaginatedQueryable(tables); + const outDir = await mkdtemp(join(tmpdir(), 'curate-inputs-bench-')); + + try { + const startNs = Bun.nanoseconds(); + const result = await exportCurateInputs(queryable, { + outDir, + chunkSize: DEFAULT_EXPORT_CHUNK_SIZE, + }); + const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; + + const d = result.delistings.stats; + const skipSum = + d.skipped.active + + d.skipped.noOutcome + + d.skipped.missingListedTo + + d.skipped.missingOutgoingQmMapping + + d.skipped.missingSuccessorQmMapping + + d.skipped.nonOtcContinuity; + if (d.skippedTotal !== skipSum || d.rowsIn !== d.rowsOut + d.skippedTotal) { + throw new Error( + `Delisting stats reconciliation failed: rowsIn=${d.rowsIn} rowsOut=${d.rowsOut} skippedTotal=${d.skippedTotal} skipSum=${skipSum}` + ); + } + + const totalRowsExported = + result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut; + const rowsPerSec = totalRowsExported / (elapsedMs / 1000); + // process.resourceUsage().maxRSS is reported in KiB on Linux. + const peakRssMiB = process.resourceUsage().maxRSS / 1024; + + process.stdout.write('exportCurateInputs benchmark complete\n'); + process.stdout.write( + ` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n` + ); + process.stdout.write( + ` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n` + ); + process.stdout.write( + ` total_rows_out=${totalRowsExported} bytes_written=${result.totalBytesWritten} elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(rowsPerSec)} rows/s peak_rss=${peakRssMiB.toFixed(2)} MiB\n` + ); + } finally { + await rm(outDir, { recursive: true, force: true }); + } +} + +main().catch(error => { + process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); + process.exit(1); +}); diff --git a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts new file mode 100644 index 00000000..8a4dff5e --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts @@ -0,0 +1,1775 @@ +import { randomUUID } from 'node:crypto'; +import { access, mkdir, open, rename, unlink, type FileHandle } from 'node:fs/promises'; +import { join } from 'node:path'; +import { compareAscii } from './exchange-pass1'; +import type { SecurityMasterQueryable } from './persist'; + +export const CURATE_INPUT_FILES = Object.freeze({ + providerMapping: 'provider_mapping.tsv', + listingCurrencies: 'listing_currencies.tsv', + delistings: 'delistings.tsv', +} as const); + +export const DEFAULT_EXPORT_CHUNK_SIZE = 5000; +export const MAX_EXPORT_CHUNK_SIZE = 5000; +export const DEFAULT_DELISTING_MAPPING_SOURCE = 'qm'; + +const MAX_PG_INT4 = 2_147_483_647; +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const STRICT_DECIMAL_PATTERN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +export type CurateInputExportErrorCode = + | 'INVALID_OPTION' + | 'INVALID_CLIENT' + | 'FORBIDDEN_CONTROL_CHAR' + | 'BLANK_FIELD' + | 'INVALID_LISTING_ID' + | 'INVALID_DATE' + | 'INVALID_DATE_RANGE' + | 'DUPLICATE_PROVIDER_MAPPING' + | 'OVERLAPPING_PROVIDER_MAPPING' + | 'UNSORTED_PROVIDER_MAPPING_STREAM' + | 'DUPLICATE_LISTING_CURRENCY' + | 'UNSORTED_LISTING_STREAM' + | 'INVALID_TERMINAL_RETURN' + | 'INVALID_DELISTING_OUTCOME' + | 'MISSING_FROM_LISTING_ID' + | 'ACTIVE_LISTING_WITH_OUTCOME' + | 'SELF_SUCCESSOR_CONTINUITY' + | 'DUPLICATE_OTC_CONTINUITY' + | 'OUT_OF_ORDER_CONTINUITY_STREAM'; + +export interface CurateInputExportErrorOptions { + readonly code: CurateInputExportErrorCode; + readonly table: string; + readonly key: string; + readonly field?: string; + readonly detail: string; +} + +export class CurateInputExportError extends Error { + readonly code: CurateInputExportErrorCode; + readonly table: string; + readonly key: string; + readonly field?: string; + + constructor(options: CurateInputExportErrorOptions) { + const fieldPart = options.field !== undefined ? ` field=${options.field}` : ''; + super(`[${options.code}] ${options.table} (${options.key})${fieldPart}: ${options.detail}`); + this.name = 'CurateInputExportError'; + this.code = options.code; + this.table = options.table; + this.key = options.key; + if (options.field !== undefined) { + this.field = options.field; + } + } +} + +export interface ProviderMappingExportRow { + readonly source: string; + readonly sourceId: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly listingId: number; +} + +export interface ListingCurrencyExportRow { + readonly listingId: number; + readonly currency: string; +} + +export interface DelistingExportRow { + readonly sourceId: string; + readonly delistDate: string; + readonly fromListingId: number | null; + readonly successorSourceId: string | null; + readonly terminalReturn: number | string | null; +} + +export interface ListingDelistingSourceRow { + readonly listingId: number; + readonly listedTo: string | null; + readonly delistReason: string | null; + readonly terminalReturn: number | string | null; +} + +export interface ContinuityExportSourceRow { + readonly fromListingId: number; + readonly toListingId: number; + readonly effectiveDate: string; + readonly kind: string; +} + +export interface BuildDelistingExportRowsOptions { + readonly mappingSource?: string; +} + +export interface DelistingExportSkippedByReason { + readonly active: number; + readonly noOutcome: number; + readonly missingListedTo: number; + readonly missingOutgoingQmMapping: number; + readonly missingSuccessorQmMapping: number; + readonly nonOtcContinuity: number; +} + +export interface DelistingExportStats { + readonly rowsIn: number; + readonly rowsOut: number; + readonly otcTransfersOut: number; + readonly terminalDelistingsOut: number; + readonly skippedTotal: number; + readonly skipped: DelistingExportSkippedByReason; +} + +export interface BuildDelistingExportRowsResult { + readonly rows: readonly DelistingExportRow[]; + readonly stats: DelistingExportStats; +} + +export interface ExportCurateInputsFsHooks { + readonly mkdir?: typeof mkdir; + readonly open?: typeof open; + readonly rename?: typeof rename; + readonly unlink?: typeof unlink; + readonly access?: typeof access; +} + +export interface ExportCurateInputsOptions { + readonly outDir: string; + readonly chunkSize?: number; + readonly delistingMappingSource?: string; + readonly fs?: ExportCurateInputsFsHooks; +} + +export interface ExportCurateInputsFileStats { + readonly path: string; + readonly rowsIn: number; + readonly rowsOut: number; + readonly bytesWritten: number; +} + +export interface ExportCurateInputsResult { + readonly outDir: string; + readonly chunkSize: number; + readonly delistingMappingSource: string; + readonly providerMapping: ExportCurateInputsFileStats; + readonly listingCurrencies: ExportCurateInputsFileStats; + readonly delistings: ExportCurateInputsFileStats & { + readonly stats: DelistingExportStats; + }; + readonly totalBytesWritten: number; +} + +interface QmListingMappingRange { + readonly sourceId: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly listingId: number; +} + +interface ValidatedDelistingRow { + readonly sourceId: string; + readonly delistDate: string; + readonly fromListingId: number | null; + readonly successorSourceId: string | null; + readonly formattedTerminalReturn: string; +} + +interface DbContinuityRow { + from_listing_id: number; + to_listing_id: number; + effective_date: string; + kind: string; +} + +interface DbListingRow { + listing_id: number; + currency: string | null; + listed_to: string | null; + delist_reason: string | null; + terminal_return: string | null; +} + +interface DbProviderMappingRow { + source: string | null; + source_id: string | null; + valid_from: string | null; + valid_to: string | null; + listing_id: number; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +export function isValidStrictYmd(value: string): boolean { + if (!EXACT_YMD_PATTERN.test(value)) { + return false; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + if (year < 1 || year > 9999 || month < 1 || month > 12) { + return false; + } + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + return day >= 1 && day <= maxDay; +} + +function assertNoTsvControlChars( + value: string, + table: string, + key: string, + field: string +): void { + if (value.includes('\t') || value.includes('\n') || value.includes('\r')) { + throw new CurateInputExportError({ + code: 'FORBIDDEN_CONTROL_CHAR', + table, + key, + field, + detail: `${field} must not contain tab, newline, or carriage return characters`, + }); + } +} + +function assertNonBlankVerbatim( + value: unknown, + table: string, + key: string, + field: string +): string { + if (typeof value !== 'string') { + throw new CurateInputExportError({ + code: 'BLANK_FIELD', + table, + key, + field, + detail: `${field} must be a non-blank string`, + }); + } + assertNoTsvControlChars(value, table, key, field); + if (value.trim().length === 0) { + throw new CurateInputExportError({ + code: 'BLANK_FIELD', + table, + key, + field, + detail: `${field} must not be empty or whitespace-only`, + }); + } + return value; +} + +function assertStrictYmd(value: unknown, table: string, key: string, field: string): string { + if (typeof value !== 'string') { + throw new CurateInputExportError({ + code: 'INVALID_DATE', + table, + key, + field, + detail: `${field} must be a strict Gregorian YYYY-MM-DD string`, + }); + } + assertNoTsvControlChars(value, table, key, field); + if (!isValidStrictYmd(value)) { + throw new CurateInputExportError({ + code: 'INVALID_DATE', + table, + key, + field, + detail: `invalid ${field} "${value}" (expected strict Gregorian YYYY-MM-DD)`, + }); + } + return value; +} + +function assertPositiveI32(value: unknown, table: string, key: string, field: string): number { + if ( + typeof value !== 'number' || + !Number.isInteger(value) || + value < 1 || + value > MAX_PG_INT4 + ) { + throw new CurateInputExportError({ + code: 'INVALID_LISTING_ID', + table, + key, + field, + detail: `invalid ${field} "${String(value)}" (expected integer in 1..=${MAX_PG_INT4})`, + }); + } + return value; +} + +/** + * Formats a finite JS number as a plain base-10 decimal string without scientific notation. + * Normalizes `-0` to `"0"`. + */ +export function formatPlainDecimal(value: number): string { + if (value === 0) { + return '0'; + } + const raw = String(value); + const expIdx = raw.search(/[eE]/); + if (expIdx === -1) { + return raw; + } + + const sign = raw.startsWith('-') ? '-' : ''; + const unsigned = sign.length > 0 ? raw.slice(1, expIdx) : raw.slice(0, expIdx); + const exponent = Number(raw.slice(expIdx + 1)); + const dotIdx = unsigned.indexOf('.'); + const digits = dotIdx === -1 ? unsigned : unsigned.slice(0, dotIdx) + unsigned.slice(dotIdx + 1); + const integerLen = dotIdx === -1 ? unsigned.length : dotIdx; + const decimalPos = integerLen + exponent; + + if (decimalPos <= 0) { + return `${sign}0.${'0'.repeat(-decimalPos)}${digits}`; + } + if (decimalPos >= digits.length) { + return `${sign}${digits}${'0'.repeat(decimalPos - digits.length)}`; + } + return `${sign}${digits.slice(0, decimalPos)}.${digits.slice(decimalPos)}`; +} + +function normalizeAndFormatTerminalReturn( + value: number | string, + table: string, + key: string, + field: string +): string { + let num: number; + if (typeof value === 'string') { + assertNoTsvControlChars(value, table, key, field); + if (value.length === 0 || value.trim() !== value || !STRICT_DECIMAL_PATTERN.test(value)) { + throw new CurateInputExportError({ + code: 'INVALID_TERMINAL_RETURN', + table, + key, + field, + detail: `invalid ${field} "${value}" (expected finite decimal in [-1, 0])`, + }); + } + num = Number(value); + } else if (typeof value === 'number') { + num = value; + } else { + throw new CurateInputExportError({ + code: 'INVALID_TERMINAL_RETURN', + table, + key, + field, + detail: `invalid ${field} "${String(value)}" (expected finite decimal in [-1, 0])`, + }); + } + + if (!Number.isFinite(num) || num < -1 || num > 0) { + throw new CurateInputExportError({ + code: 'INVALID_TERMINAL_RETURN', + table, + key, + field, + detail: `invalid ${field} "${String(value)}" (must be finite and in [-1, 0])`, + }); + } + + const normalized = num === 0 ? 0 : num; + return formatPlainDecimal(normalized); +} + +function compareNullableAscii(a: string | null, b: string | null): number { + if (a === b) { + return 0; + } + if (a === null) { + return 1; + } + if (b === null) { + return -1; + } + return compareAscii(a, b); +} + +function joinLinesInChunks(lines: readonly string[], chunkSize = DEFAULT_EXPORT_CHUNK_SIZE): string { + if (lines.length === 0) { + return ''; + } + if (lines.length <= chunkSize) { + return `${lines.join('\n')}\n`; + } + const chunks: string[] = []; + for (let offset = 0; offset < lines.length; offset += chunkSize) { + chunks.push(lines.slice(offset, offset + chunkSize).join('\n')); + } + return `${chunks.join('\n')}\n`; +} + +function validateProviderMappingRow( + row: ProviderMappingExportRow, + index: number +): ProviderMappingExportRow { + const fallbackKey = `row#${index}`; + const source = assertNonBlankVerbatim(row.source, 'provider_mapping', fallbackKey, 'source'); + const sourceId = assertNonBlankVerbatim( + row.sourceId, + 'provider_mapping', + `${source}:${fallbackKey}`, + 'source_id' + ); + const key = `${source}:${sourceId}:${String(row.validFrom)}`; + const validFrom = assertStrictYmd(row.validFrom, 'provider_mapping', key, 'valid_from'); + let validTo: string | null = null; + if (row.validTo !== null && row.validTo !== undefined) { + validTo = assertStrictYmd(row.validTo, 'provider_mapping', key, 'valid_to'); + if (validTo < validFrom) { + throw new CurateInputExportError({ + code: 'INVALID_DATE_RANGE', + table: 'provider_mapping', + key: `${source}:${sourceId}:${validFrom}`, + field: 'valid_to', + detail: `valid_to "${validTo}" precedes valid_from "${validFrom}"`, + }); + } + } + const listingId = assertPositiveI32( + row.listingId, + 'provider_mapping', + `${source}:${sourceId}:${validFrom}`, + 'listing_id' + ); + return { source, sourceId, validFrom, validTo, listingId }; +} + +/** + * Validates, deterministically ASCII-sorts, overlap-checks, and formats `provider_mapping.tsv`. + * Headerless 5-column TSV: `source\tsource_id\tvalid_from\tvalid_to\tlisting_id`. + */ +export function formatProviderMappingTsv(rows: readonly ProviderMappingExportRow[]): string { + if (rows.length === 0) { + return ''; + } + + const validated: ProviderMappingExportRow[] = []; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row === undefined) { + continue; + } + validated.push(validateProviderMappingRow(row, i)); + } + + validated.sort( + (a, b) => + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.validFrom, b.validFrom) || + compareNullableAscii(a.validTo, b.validTo) || + a.listingId - b.listingId + ); + + const lines: string[] = []; + let prev: ProviderMappingExportRow | undefined; + for (const curr of validated) { + if (prev !== undefined && prev.source === curr.source && prev.sourceId === curr.sourceId) { + if (prev.validFrom === curr.validFrom) { + throw new CurateInputExportError({ + code: 'DUPLICATE_PROVIDER_MAPPING', + table: 'provider_mapping', + key: `${curr.source}:${curr.sourceId}:${curr.validFrom}`, + detail: 'duplicate (source, source_id, valid_from) primary key', + }); + } + if (prev.validTo === null || prev.validTo >= curr.validFrom) { + throw new CurateInputExportError({ + code: 'OVERLAPPING_PROVIDER_MAPPING', + table: 'provider_mapping', + key: `${curr.source}:${curr.sourceId}:${curr.validFrom}`, + detail: `inclusive range [${prev.validFrom}, ${prev.validTo ?? '+inf'}] overlaps [${curr.validFrom}, ${curr.validTo ?? '+inf'}]`, + }); + } + } + lines.push( + `${curr.source}\t${curr.sourceId}\t${curr.validFrom}\t${curr.validTo ?? ''}\t${curr.listingId}` + ); + prev = curr; + } + + return joinLinesInChunks(lines); +} + +/** + * Validates, sorts by ascending `listing_id`, rejects duplicate `listing_id`s, and formats + * `listing_currencies.tsv`. Headerless 2-column TSV: `listing_id\tcurrency`. + */ +export function formatListingCurrenciesTsv(rows: readonly ListingCurrencyExportRow[]): string { + if (rows.length === 0) { + return ''; + } + + const validated: ListingCurrencyExportRow[] = []; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row === undefined) { + continue; + } + const listingId = assertPositiveI32(row.listingId, 'listing', `row#${i}`, 'listing_id'); + const currency = assertNonBlankVerbatim( + row.currency, + 'listing', + `listing_id=${listingId}`, + 'currency' + ); + validated.push({ listingId, currency }); + } + + validated.sort((a, b) => a.listingId - b.listingId); + + const lines: string[] = []; + let prevListingId: number | undefined; + for (const curr of validated) { + if (prevListingId === curr.listingId) { + throw new CurateInputExportError({ + code: 'DUPLICATE_LISTING_CURRENCY', + table: 'listing', + key: `listing_id=${curr.listingId}`, + field: 'listing_id', + detail: `duplicate listing_id ${curr.listingId} in listing_currencies`, + }); + } + lines.push(`${curr.listingId}\t${curr.currency}`); + prevListingId = curr.listingId; + } + + return joinLinesInChunks(lines); +} + +function validateDelistingExportRow(row: DelistingExportRow, index: number): ValidatedDelistingRow { + const fallbackKey = `row#${index}`; + const sourceId = assertNonBlankVerbatim(row.sourceId, 'delistings', fallbackKey, 'source_id'); + const rowKey = `${sourceId}:${String(row.delistDate)}`; + const delistDate = assertStrictYmd(row.delistDate, 'delistings', rowKey, 'delist_date'); + const fromListingId = + row.fromListingId === null || row.fromListingId === undefined + ? null + : assertPositiveI32(row.fromListingId, 'delistings', rowKey, 'from_listing_id'); + const successorSourceId = + row.successorSourceId === null || row.successorSourceId === undefined + ? null + : assertNonBlankVerbatim( + row.successorSourceId, + 'delistings', + rowKey, + 'successor_source_id' + ); + const formattedTerminalReturn = + row.terminalReturn === null || row.terminalReturn === undefined + ? '' + : normalizeAndFormatTerminalReturn(row.terminalReturn, 'delistings', rowKey, 'terminal_return'); + + const hasSuccessor = successorSourceId !== null; + const hasTerminalReturn = formattedTerminalReturn.length > 0; + if (hasSuccessor && hasTerminalReturn) { + throw new CurateInputExportError({ + code: 'INVALID_DELISTING_OUTCOME', + table: 'delistings', + key: rowKey, + detail: 'delisting row must set exactly one of successor_source_id or terminal_return (got both)', + }); + } + if (!hasSuccessor && !hasTerminalReturn) { + throw new CurateInputExportError({ + code: 'INVALID_DELISTING_OUTCOME', + table: 'delistings', + key: rowKey, + detail: + 'delisting row must set exactly one of successor_source_id or terminal_return (got neither)', + }); + } + if (hasSuccessor && fromListingId === null) { + throw new CurateInputExportError({ + code: 'MISSING_FROM_LISTING_ID', + table: 'delistings', + key: rowKey, + field: 'from_listing_id', + detail: 'OTC delisting transfer row with successor_source_id requires from_listing_id', + }); + } + + return { + sourceId, + delistDate, + fromListingId, + successorSourceId, + formattedTerminalReturn, + }; +} + +function compareValidatedDelistingRows(a: ValidatedDelistingRow, b: ValidatedDelistingRow): number { + return ( + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.delistDate, b.delistDate) || + (a.fromListingId ?? 0) - (b.fromListingId ?? 0) || + compareAscii(a.successorSourceId ?? '', b.successorSourceId ?? '') || + compareAscii(a.formattedTerminalReturn, b.formattedTerminalReturn) + ); +} + +/** + * Validates, deterministically sorts, and formats Pass 6 `delistings.tsv`. + * Headerless 5-column TSV: + * `source_id\tdelist_date\tfrom_listing_id\tsuccessor_source_id\tterminal_return`. + */ +export function formatDelistingsTsv(rows: readonly DelistingExportRow[]): string { + if (rows.length === 0) { + return ''; + } + + const validated: ValidatedDelistingRow[] = []; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row === undefined) { + continue; + } + validated.push(validateDelistingExportRow(row, i)); + } + + validated.sort(compareValidatedDelistingRows); + + const lines: string[] = []; + for (const row of validated) { + lines.push( + `${row.sourceId}\t${row.delistDate}\t${row.fromListingId === null ? '' : String(row.fromListingId)}\t${row.successorSourceId ?? ''}\t${row.formattedTerminalReturn}` + ); + } + + return joinLinesInChunks(lines); +} + +/** + * Deterministic tie-breaker when multiple `qm` mappings qualify for the same `listing_id`: + * 1. `validFrom DESC` (most recently started mapping) + * 2. `validTo DESC NULLS FIRST` (open-ended active mapping beats closed, then latest end date) + * 3. `sourceId ASC` (ASCII) + */ +function compareQualifyingQmMappings(a: QmListingMappingRange, b: QmListingMappingRange): number { + const fromCmp = compareAscii(b.validFrom, a.validFrom); + if (fromCmp !== 0) { + return fromCmp; + } + if (a.validTo !== b.validTo) { + if (a.validTo === null) { + return -1; + } + if (b.validTo === null) { + return 1; + } + const toCmp = compareAscii(b.validTo, a.validTo); + if (toCmp !== 0) { + return toCmp; + } + } + return compareAscii(a.sourceId, b.sourceId); +} + +function selectQmMappingOnOrBefore( + ranges: readonly QmListingMappingRange[] | undefined, + date: string +): QmListingMappingRange | null { + if (!ranges || ranges.length === 0) { + return null; + } + let best: QmListingMappingRange | null = null; + for (const candidate of ranges) { + if (candidate.validFrom <= date) { + if (best === null || compareQualifyingQmMappings(candidate, best) < 0) { + best = candidate; + } + } + } + return best; +} + +function selectQmMappingOnDate( + ranges: readonly QmListingMappingRange[] | undefined, + date: string +): QmListingMappingRange | null { + if (!ranges || ranges.length === 0) { + return null; + } + let best: QmListingMappingRange | null = null; + for (const candidate of ranges) { + if (candidate.validFrom <= date && (candidate.validTo === null || candidate.validTo >= date)) { + if (best === null || compareQualifyingQmMappings(candidate, best) < 0) { + best = candidate; + } + } + } + return best; +} + +/** + * Pure Pass 6 delistings builder turning `listing`, `corporate_action_continuity`, and + * `provider_mapping` rows into `DelistingExportRow[]` plus exact skip-reason stats + * (`rowsIn === rowsOut + skippedTotal`). + * + * Indexes `otc_delist_transfer` continuities strictly by `fromListingId` so OTC successor listings + * (e.g. `SIVBQ`) still emit their own subsequent terminal delisting (e.g. bankruptcy `-1`). + */ +export function buildDelistingExportRows( + listings: readonly ListingDelistingSourceRow[], + continuities: readonly ContinuityExportSourceRow[], + providerMappings: readonly ProviderMappingExportRow[], + options: BuildDelistingExportRowsOptions = {} +): BuildDelistingExportRowsResult { + const mappingSource = assertNonBlankVerbatim( + options.mappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, + 'options', + 'mappingSource', + 'mappingSource' + ); + + let nonOtcContinuity = 0; + const otcByFromListingId = new Map(); + for (let i = 0; i < continuities.length; i++) { + const raw = continuities[i]; + if (raw === undefined) { + continue; + } + if (raw.kind !== 'otc_delist_transfer') { + nonOtcContinuity += 1; + continue; + } + const fromListingId = assertPositiveI32( + raw.fromListingId, + 'corporate_action_continuity', + `row#${i}`, + 'from_listing_id' + ); + const toListingId = assertPositiveI32( + raw.toListingId, + 'corporate_action_continuity', + `from_listing_id=${fromListingId}`, + 'to_listing_id' + ); + const effectiveDate = assertStrictYmd( + raw.effectiveDate, + 'corporate_action_continuity', + `from_listing_id=${fromListingId}`, + 'effective_date' + ); + if (fromListingId === toListingId) { + throw new CurateInputExportError({ + code: 'SELF_SUCCESSOR_CONTINUITY', + table: 'corporate_action_continuity', + key: `from_listing_id=${fromListingId}@${effectiveDate}`, + field: 'to_listing_id', + detail: `otc_delist_transfer continuity cannot link listing ${fromListingId} to itself`, + }); + } + if (otcByFromListingId.has(fromListingId)) { + throw new CurateInputExportError({ + code: 'DUPLICATE_OTC_CONTINUITY', + table: 'corporate_action_continuity', + key: `from_listing_id=${fromListingId}`, + detail: `multiple otc_delist_transfer continuities found for from_listing_id=${fromListingId}`, + }); + } + otcByFromListingId.set(fromListingId, { + fromListingId, + toListingId, + effectiveDate, + kind: raw.kind, + }); + } + + const qmMappingsByListingId = new Map(); + for (let i = 0; i < providerMappings.length; i++) { + const rawMapping = providerMappings[i]; + if (rawMapping === undefined) { + continue; + } + const validated = validateProviderMappingRow(rawMapping, i); + if (validated.source !== mappingSource) { + continue; + } + let list = qmMappingsByListingId.get(validated.listingId); + if (list === undefined) { + list = []; + qmMappingsByListingId.set(validated.listingId, list); + } + list.push({ + sourceId: validated.sourceId, + validFrom: validated.validFrom, + validTo: validated.validTo, + listingId: validated.listingId, + }); + } + + let active = 0; + let noOutcome = 0; + let missingListedTo = 0; + let missingOutgoingQmMapping = 0; + let missingSuccessorQmMapping = 0; + let otcTransfersOut = 0; + let terminalDelistingsOut = 0; + + const seenListingIds = new Set(); + const rows: DelistingExportRow[] = []; + + for (let i = 0; i < listings.length; i++) { + const listing = listings[i]; + if (listing === undefined) { + continue; + } + const listingId = assertPositiveI32(listing.listingId, 'listing', `row#${i}`, 'listing_id'); + const listingKey = `listing_id=${listingId}`; + if (seenListingIds.has(listingId)) { + throw new CurateInputExportError({ + code: 'DUPLICATE_LISTING_CURRENCY', + table: 'listing', + key: listingKey, + field: 'listing_id', + detail: `duplicate listing_id ${listingId} in listings input`, + }); + } + seenListingIds.add(listingId); + + const otc = otcByFromListingId.get(listingId); + const hasTerminalReturn = + listing.terminalReturn !== null && listing.terminalReturn !== undefined; + + if (listing.delistReason === 'active') { + if (otc !== undefined || hasTerminalReturn) { + throw new CurateInputExportError({ + code: 'ACTIVE_LISTING_WITH_OUTCOME', + table: 'listing', + key: listingKey, + field: 'delist_reason', + detail: 'listing marked active cannot have an OTC continuity or terminal_return', + }); + } + active += 1; + continue; + } + + if (otc !== undefined && hasTerminalReturn) { + throw new CurateInputExportError({ + code: 'INVALID_DELISTING_OUTCOME', + table: 'listing', + key: listingKey, + detail: 'listing cannot have both an outgoing otc_delist_transfer and a terminal_return', + }); + } + + if (otc !== undefined) { + const outgoing = selectQmMappingOnOrBefore( + qmMappingsByListingId.get(listingId), + otc.effectiveDate + ); + if (outgoing === null) { + missingOutgoingQmMapping += 1; + continue; + } + const successor = selectQmMappingOnDate( + qmMappingsByListingId.get(otc.toListingId), + otc.effectiveDate + ); + if (successor === null) { + missingSuccessorQmMapping += 1; + continue; + } + rows.push({ + sourceId: outgoing.sourceId, + delistDate: otc.effectiveDate, + fromListingId: listingId, + successorSourceId: successor.sourceId, + terminalReturn: null, + }); + otcTransfersOut += 1; + continue; + } + + if (hasTerminalReturn) { + const formattedReturn = normalizeAndFormatTerminalReturn( + listing.terminalReturn as number | string, + 'listing', + listingKey, + 'terminal_return' + ); + if (listing.listedTo === null || listing.listedTo === undefined) { + missingListedTo += 1; + continue; + } + const listedTo = assertStrictYmd(listing.listedTo, 'listing', listingKey, 'listed_to'); + const outgoing = selectQmMappingOnDate(qmMappingsByListingId.get(listingId), listedTo); + if (outgoing === null) { + missingOutgoingQmMapping += 1; + continue; + } + rows.push({ + sourceId: outgoing.sourceId, + delistDate: listedTo, + fromListingId: listingId, + successorSourceId: null, + terminalReturn: formattedReturn, + }); + terminalDelistingsOut += 1; + continue; + } + + noOutcome += 1; + } + + // Handle any OTC continuity whose fromListingId was absent from `listings` (pure caller input). + const orphanOtcIds = Array.from(otcByFromListingId.keys()) + .filter(id => !seenListingIds.has(id)) + .sort((a, b) => a - b); + for (const fromListingId of orphanOtcIds) { + const otc = otcByFromListingId.get(fromListingId); + if (otc === undefined) { + continue; + } + const outgoing = selectQmMappingOnOrBefore( + qmMappingsByListingId.get(fromListingId), + otc.effectiveDate + ); + if (outgoing === null) { + missingOutgoingQmMapping += 1; + continue; + } + const successor = selectQmMappingOnDate( + qmMappingsByListingId.get(otc.toListingId), + otc.effectiveDate + ); + if (successor === null) { + missingSuccessorQmMapping += 1; + continue; + } + rows.push({ + sourceId: outgoing.sourceId, + delistDate: otc.effectiveDate, + fromListingId, + successorSourceId: successor.sourceId, + terminalReturn: null, + }); + otcTransfersOut += 1; + } + + rows.sort((a, b) => + compareValidatedDelistingRows( + { + sourceId: a.sourceId, + delistDate: a.delistDate, + fromListingId: a.fromListingId, + successorSourceId: a.successorSourceId, + formattedTerminalReturn: a.terminalReturn === null ? '' : String(a.terminalReturn), + }, + { + sourceId: b.sourceId, + delistDate: b.delistDate, + fromListingId: b.fromListingId, + successorSourceId: b.successorSourceId, + formattedTerminalReturn: b.terminalReturn === null ? '' : String(b.terminalReturn), + } + ) + ); + + const rowsOut = otcTransfersOut + terminalDelistingsOut; + const skippedTotal = + active + + noOutcome + + missingListedTo + + missingOutgoingQmMapping + + missingSuccessorQmMapping + + nonOtcContinuity; + const rowsIn = rowsOut + skippedTotal; + + return { + rows, + stats: { + rowsIn, + rowsOut, + otcTransfersOut, + terminalDelistingsOut, + skippedTotal, + skipped: { + active, + noOutcome, + missingListedTo, + missingOutgoingQmMapping, + missingSuccessorQmMapping, + nonOtcContinuity, + }, + }, + }; +} + +function assertDedicatedQueryable(client: SecurityMasterQueryable): void { + if (client === null || client === undefined || typeof client !== 'object') { + throw new CurateInputExportError({ + code: 'INVALID_CLIENT', + table: 'connection', + key: 'client', + detail: 'exportCurateInputs requires a dedicated SecurityMasterQueryable client', + }); + } + if (typeof client.query !== 'function') { + throw new CurateInputExportError({ + code: 'INVALID_CLIENT', + table: 'connection', + key: 'client', + detail: 'exportCurateInputs client must expose a query() method', + }); + } + const maybePool = client as unknown as { connect?: unknown; release?: unknown }; + if (typeof maybePool.connect === 'function' && typeof maybePool.release !== 'function') { + throw new CurateInputExportError({ + code: 'INVALID_CLIENT', + table: 'connection', + key: 'client', + detail: + 'exportCurateInputs requires a dedicated single-session client (e.g. pg.PoolClient), not a Pool', + }); + } +} + +function validateChunkSize(chunkSize: number | undefined): number { + const resolved = chunkSize ?? DEFAULT_EXPORT_CHUNK_SIZE; + if ( + typeof resolved !== 'number' || + !Number.isSafeInteger(resolved) || + resolved < 1 || + resolved > MAX_EXPORT_CHUNK_SIZE + ) { + throw new CurateInputExportError({ + code: 'INVALID_OPTION', + table: 'options', + key: 'chunkSize', + field: 'chunkSize', + detail: `chunkSize must be an integer in 1..=${MAX_EXPORT_CHUNK_SIZE} (got ${String(resolved)})`, + }); + } + return resolved; +} + +async function fileExists( + accessFn: typeof access, + filePath: string +): Promise { + try { + await accessFn(filePath); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') { + return false; + } + throw error; + } +} + +async function safeUnlink(unlinkFn: typeof unlink, filePath: string): Promise { + try { + await unlinkFn(filePath); + } catch (error) { + if ((error as NodeJS.ErrnoException | undefined)?.code !== 'ENOENT') { + throw error; + } + } +} + +async function writeAll(handle: FileHandle, buf: Buffer): Promise { + let offset = 0; + while (offset < buf.byteLength) { + const { bytesWritten } = await handle.write(buf, offset, buf.byteLength - offset); + if (bytesWritten <= 0) { + throw new Error('Short write (0 bytes written) while streaming TSV chunk'); + } + offset += bytesWritten; + } +} + +/** + * Reads security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` + * transaction using keyset pagination (`chunkSize <= 5000`), streams formatted chunks to per-run + * temp files, and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and + * Pass 6 `delistings.tsv` into `options.outDir`. + */ +export async function exportCurateInputs( + queryable: SecurityMasterQueryable, + options: ExportCurateInputsOptions +): Promise { + assertDedicatedQueryable(queryable); + + if ( + options === null || + options === undefined || + typeof options !== 'object' || + typeof options.outDir !== 'string' || + options.outDir.trim().length === 0 + ) { + throw new CurateInputExportError({ + code: 'INVALID_OPTION', + table: 'options', + key: 'outDir', + field: 'outDir', + detail: 'outDir must be a non-empty string', + }); + } + + const outDir = options.outDir.trim(); + const chunkSize = validateChunkSize(options.chunkSize); + const delistingMappingSource = assertNonBlankVerbatim( + options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, + 'options', + 'delistingMappingSource', + 'delistingMappingSource' + ); + + const fsMkdir = options.fs?.mkdir ?? mkdir; + const fsOpen = options.fs?.open ?? open; + const fsRename = options.fs?.rename ?? rename; + const fsUnlink = options.fs?.unlink ?? unlink; + const fsAccess = options.fs?.access ?? access; + + await fsMkdir(outDir, { recursive: true }); + + const runTag = `${process.pid}-${Date.now()}-${randomUUID().slice(0, 8)}`; + const targets = { + providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping), + listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies), + delistings: join(outDir, CURATE_INPUT_FILES.delistings), + }; + const temps = { + providerMapping: `${targets.providerMapping}.${runTag}.tmp`, + listingCurrencies: `${targets.listingCurrencies}.${runTag}.tmp`, + delistings: `${targets.delistings}.${runTag}.tmp`, + }; + const backups = { + providerMapping: `${targets.providerMapping}.${runTag}.bak`, + listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`, + delistings: `${targets.delistings}.${runTag}.bak`, + }; + + let providerMappingHandle: FileHandle | null = null; + let listingCurrenciesHandle: FileHandle | null = null; + let delistingsHandle: FileHandle | null = null; + + let providerMappingRowsIn = 0; + let providerMappingRowsOut = 0; + let providerMappingBytes = 0; + + let listingCurrenciesRowsIn = 0; + let listingCurrenciesRowsOut = 0; + let listingCurrenciesBytes = 0; + + let delistingsBytes = 0; + let delistingsStats: DelistingExportStats; + + const publishOrder: Array<'providerMapping' | 'listingCurrencies' | 'delistings'> = [ + 'providerMapping', + 'listingCurrencies', + 'delistings', + ]; + + const backedUp = new Set<'providerMapping' | 'listingCurrencies' | 'delistings'>(); + const published = new Set<'providerMapping' | 'listingCurrencies' | 'delistings'>(); + + try { + providerMappingHandle = await fsOpen(temps.providerMapping, 'wx'); + listingCurrenciesHandle = await fsOpen(temps.listingCurrencies, 'wx'); + delistingsHandle = await fsOpen(temps.delistings, 'wx'); + + const otcByFromListingId = new Map(); + const relevantDelistingListingIds = new Set(); + const otcCandidates: Array<{ listingId: number; otc: ContinuityExportSourceRow }> = []; + const terminalCandidates: Array<{ + listingId: number; + listedTo: string; + formattedTerminalReturn: string; + }> = []; + const qmMappingsByListingId = new Map(); + + let skippedActive = 0; + let skippedNoOutcome = 0; + let skippedMissingListedTo = 0; + + await queryable.query('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + try { + // 1. Keyset-paginated read of corporate_action_continuity (kind = 'otc_delist_transfer'). + let lastContFromId: number | null = null; + let lastContEffDate: string | null = null; + for (;;) { + const res = + lastContFromId === null + ? await queryable.query( + `SELECT + from_listing_id, + to_listing_id, + to_char(effective_date, 'YYYY-MM-DD') AS effective_date, + kind + FROM corporate_action_continuity + WHERE kind = 'otc_delist_transfer' + ORDER BY from_listing_id ASC, effective_date ASC + LIMIT $1`, + [chunkSize] + ) + : await queryable.query( + `SELECT + from_listing_id, + to_listing_id, + to_char(effective_date, 'YYYY-MM-DD') AS effective_date, + kind + FROM corporate_action_continuity + WHERE kind = 'otc_delist_transfer' + AND ( + from_listing_id > $1 + OR (from_listing_id = $1 AND effective_date > $2::date) + ) + ORDER BY from_listing_id ASC, effective_date ASC + LIMIT $3`, + [lastContFromId, lastContEffDate, chunkSize] + ); + + if (res.rows.length === 0) { + break; + } + + for (const row of res.rows) { + const fromListingId = assertPositiveI32( + row.from_listing_id, + 'corporate_action_continuity', + `from_listing_id=${String(row.from_listing_id)}`, + 'from_listing_id' + ); + const toListingId = assertPositiveI32( + row.to_listing_id, + 'corporate_action_continuity', + `from_listing_id=${fromListingId}`, + 'to_listing_id' + ); + const effectiveDate = assertStrictYmd( + row.effective_date, + 'corporate_action_continuity', + `from_listing_id=${fromListingId}`, + 'effective_date' + ); + + if (lastContFromId !== null && lastContEffDate !== null) { + if ( + fromListingId < lastContFromId || + (fromListingId === lastContFromId && effectiveDate <= lastContEffDate) + ) { + throw new CurateInputExportError({ + code: 'OUT_OF_ORDER_CONTINUITY_STREAM', + table: 'corporate_action_continuity', + key: `from_listing_id=${fromListingId}@${effectiveDate}`, + detail: 'corporate_action_continuity stream was not strictly ordered by (from_listing_id, effective_date)', + }); + } + } + + if (fromListingId === toListingId) { + throw new CurateInputExportError({ + code: 'SELF_SUCCESSOR_CONTINUITY', + table: 'corporate_action_continuity', + key: `from_listing_id=${fromListingId}@${effectiveDate}`, + field: 'to_listing_id', + detail: `otc_delist_transfer continuity cannot link listing ${fromListingId} to itself`, + }); + } + + if (otcByFromListingId.has(fromListingId)) { + throw new CurateInputExportError({ + code: 'DUPLICATE_OTC_CONTINUITY', + table: 'corporate_action_continuity', + key: `from_listing_id=${fromListingId}`, + detail: `multiple otc_delist_transfer continuities found for from_listing_id=${fromListingId}`, + }); + } + + otcByFromListingId.set(fromListingId, { + fromListingId, + toListingId, + effectiveDate, + kind: row.kind, + }); + relevantDelistingListingIds.add(fromListingId); + relevantDelistingListingIds.add(toListingId); + + lastContFromId = fromListingId; + lastContEffDate = effectiveDate; + } + + if (res.rows.length < chunkSize) { + break; + } + } + + // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv directly. + let lastListingId: number | null = null; + for (;;) { + const res = + lastListingId === null + ? await queryable.query( + `SELECT + listing_id, + btrim(currency) AS currency, + to_char(listed_to, 'YYYY-MM-DD') AS listed_to, + delist_reason, + terminal_return::text AS terminal_return + FROM listing + ORDER BY listing_id ASC + LIMIT $1`, + [chunkSize] + ) + : await queryable.query( + `SELECT + listing_id, + btrim(currency) AS currency, + to_char(listed_to, 'YYYY-MM-DD') AS listed_to, + delist_reason, + terminal_return::text AS terminal_return + FROM listing + WHERE listing_id > $1 + ORDER BY listing_id ASC + LIMIT $2`, + [lastListingId, chunkSize] + ); + + if (res.rows.length === 0) { + break; + } + + const chunkLines: string[] = []; + for (const row of res.rows) { + const listingId = assertPositiveI32( + row.listing_id, + 'listing', + `listing_id=${String(row.listing_id)}`, + 'listing_id' + ); + const listingKey = `listing_id=${listingId}`; + + if (lastListingId !== null) { + if (listingId === lastListingId) { + throw new CurateInputExportError({ + code: 'DUPLICATE_LISTING_CURRENCY', + table: 'listing', + key: listingKey, + field: 'listing_id', + detail: `duplicate listing_id ${listingId} in listing stream`, + }); + } + if (listingId < lastListingId) { + throw new CurateInputExportError({ + code: 'UNSORTED_LISTING_STREAM', + table: 'listing', + key: listingKey, + field: 'listing_id', + detail: `listing stream out of ascending listing_id order (${listingId} after ${lastListingId})`, + }); + } + } + + const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency'); + chunkLines.push(`${listingId}\t${currency}`); + listingCurrenciesRowsIn += 1; + listingCurrenciesRowsOut += 1; + + const otc = otcByFromListingId.get(listingId); + const hasTerminalReturn = + row.terminal_return !== null && row.terminal_return !== undefined; + + if (row.delist_reason === 'active') { + if (otc !== undefined || hasTerminalReturn) { + throw new CurateInputExportError({ + code: 'ACTIVE_LISTING_WITH_OUTCOME', + table: 'listing', + key: listingKey, + field: 'delist_reason', + detail: 'listing marked active cannot have an OTC continuity or terminal_return', + }); + } + skippedActive += 1; + } else if (otc !== undefined && hasTerminalReturn) { + throw new CurateInputExportError({ + code: 'INVALID_DELISTING_OUTCOME', + table: 'listing', + key: listingKey, + detail: + 'listing cannot have both an outgoing otc_delist_transfer and a terminal_return', + }); + } else if (otc !== undefined) { + otcCandidates.push({ listingId, otc }); + } else if (hasTerminalReturn) { + const formattedTerminalReturn = normalizeAndFormatTerminalReturn( + row.terminal_return as string, + 'listing', + listingKey, + 'terminal_return' + ); + if (row.listed_to === null || row.listed_to === undefined) { + skippedMissingListedTo += 1; + } else { + const listedTo = assertStrictYmd(row.listed_to, 'listing', listingKey, 'listed_to'); + relevantDelistingListingIds.add(listingId); + terminalCandidates.push({ + listingId, + listedTo, + formattedTerminalReturn, + }); + } + } else { + skippedNoOutcome += 1; + } + + lastListingId = listingId; + } + + const chunkText = `${chunkLines.join('\n')}\n`; + const buf = Buffer.from(chunkText, 'utf8'); + await writeAll(listingCurrenciesHandle, buf); + listingCurrenciesBytes += buf.byteLength; + + if (res.rows.length < chunkSize) { + break; + } + } + + // 3. Keyset-paginated read of provider_mapping -> stream provider_mapping.tsv directly. + let lastSource: string | null = null; + let lastSourceId: string | null = null; + let lastValidFrom: string | null = null; + let lastValidTo: string | null = null; + + for (;;) { + const res = + lastSource === null + ? await queryable.query( + `SELECT + source, + source_id, + to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, + listing_id + FROM provider_mapping + ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC + LIMIT $1`, + [chunkSize] + ) + : await queryable.query( + `SELECT + source, + source_id, + to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, + listing_id + FROM provider_mapping + WHERE ( + source COLLATE "C" > $1 COLLATE "C" + OR (source COLLATE "C" = $1 COLLATE "C" AND source_id COLLATE "C" > $2 COLLATE "C") + OR (source COLLATE "C" = $1 COLLATE "C" AND source_id COLLATE "C" = $2 COLLATE "C" AND valid_from > $3::date) + ) + ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC + LIMIT $4`, + [lastSource, lastSourceId, lastValidFrom, chunkSize] + ); + + if (res.rows.length === 0) { + break; + } + + const chunkLines: string[] = []; + for (const row of res.rows) { + const fallbackKey = `row#${providerMappingRowsIn}`; + const source = assertNonBlankVerbatim(row.source, 'provider_mapping', fallbackKey, 'source'); + const sourceId = assertNonBlankVerbatim( + row.source_id, + 'provider_mapping', + `${source}:${fallbackKey}`, + 'source_id' + ); + const key = `${source}:${sourceId}:${String(row.valid_from)}`; + const validFrom = assertStrictYmd(row.valid_from, 'provider_mapping', key, 'valid_from'); + let validTo: string | null = null; + if (row.valid_to !== null && row.valid_to !== undefined) { + validTo = assertStrictYmd(row.valid_to, 'provider_mapping', key, 'valid_to'); + if (validTo < validFrom) { + throw new CurateInputExportError({ + code: 'INVALID_DATE_RANGE', + table: 'provider_mapping', + key: `${source}:${sourceId}:${validFrom}`, + field: 'valid_to', + detail: `valid_to "${validTo}" precedes valid_from "${validFrom}"`, + }); + } + } + const listingId = assertPositiveI32( + row.listing_id, + 'provider_mapping', + `${source}:${sourceId}:${validFrom}`, + 'listing_id' + ); + + if (lastSource !== null && lastSourceId !== null && lastValidFrom !== null) { + const pairCmp = + compareAscii(source, lastSource) || compareAscii(sourceId, lastSourceId); + if (pairCmp < 0) { + throw new CurateInputExportError({ + code: 'UNSORTED_PROVIDER_MAPPING_STREAM', + table: 'provider_mapping', + key: `${source}:${sourceId}:${validFrom}`, + detail: `provider_mapping stream out of COLLATE "C" order ("${source}:${sourceId}" after "${lastSource}:${lastSourceId}")`, + }); + } + if (pairCmp === 0) { + const fromCmp = compareAscii(validFrom, lastValidFrom); + if (fromCmp < 0) { + throw new CurateInputExportError({ + code: 'UNSORTED_PROVIDER_MAPPING_STREAM', + table: 'provider_mapping', + key: `${source}:${sourceId}:${validFrom}`, + detail: `provider_mapping stream out of valid_from order ("${validFrom}" after "${lastValidFrom}")`, + }); + } + if (fromCmp === 0) { + throw new CurateInputExportError({ + code: 'DUPLICATE_PROVIDER_MAPPING', + table: 'provider_mapping', + key: `${source}:${sourceId}:${validFrom}`, + detail: 'duplicate (source, source_id, valid_from) primary key', + }); + } + if (lastValidTo === null || lastValidTo >= validFrom) { + throw new CurateInputExportError({ + code: 'OVERLAPPING_PROVIDER_MAPPING', + table: 'provider_mapping', + key: `${source}:${sourceId}:${validFrom}`, + detail: `inclusive range [${lastValidFrom}, ${lastValidTo ?? '+inf'}] overlaps [${validFrom}, ${validTo ?? '+inf'}]`, + }); + } + } + } + + if (source === delistingMappingSource && relevantDelistingListingIds.has(listingId)) { + let list = qmMappingsByListingId.get(listingId); + if (list === undefined) { + list = []; + qmMappingsByListingId.set(listingId, list); + } + list.push({ sourceId, validFrom, validTo, listingId }); + } + + chunkLines.push( + `${source}\t${sourceId}\t${validFrom}\t${validTo ?? ''}\t${listingId}` + ); + providerMappingRowsIn += 1; + providerMappingRowsOut += 1; + + lastSource = source; + lastSourceId = sourceId; + lastValidFrom = validFrom; + lastValidTo = validTo; + } + + const chunkText = `${chunkLines.join('\n')}\n`; + const buf = Buffer.from(chunkText, 'utf8'); + await writeAll(providerMappingHandle, buf); + providerMappingBytes += buf.byteLength; + + if (res.rows.length < chunkSize) { + break; + } + } + + await queryable.query('COMMIT'); + } catch (error) { + try { + await queryable.query('ROLLBACK'); + } catch { + // Preserve original error if ROLLBACK fails on a broken session. + } + throw error; + } + + // 4. Assemble and chunk-write delistings.tsv. + let skippedMissingOutgoingQmMapping = 0; + let skippedMissingSuccessorQmMapping = 0; + let otcTransfersOut = 0; + let terminalDelistingsOut = 0; + const delistingRows: ValidatedDelistingRow[] = []; + + for (const { listingId, otc } of otcCandidates) { + const outgoing = selectQmMappingOnOrBefore( + qmMappingsByListingId.get(listingId), + otc.effectiveDate + ); + if (outgoing === null) { + skippedMissingOutgoingQmMapping += 1; + continue; + } + const successor = selectQmMappingOnDate( + qmMappingsByListingId.get(otc.toListingId), + otc.effectiveDate + ); + if (successor === null) { + skippedMissingSuccessorQmMapping += 1; + continue; + } + delistingRows.push({ + sourceId: outgoing.sourceId, + delistDate: otc.effectiveDate, + fromListingId: listingId, + successorSourceId: successor.sourceId, + formattedTerminalReturn: '', + }); + otcTransfersOut += 1; + } + + for (const { listingId, listedTo, formattedTerminalReturn } of terminalCandidates) { + const outgoing = selectQmMappingOnDate(qmMappingsByListingId.get(listingId), listedTo); + if (outgoing === null) { + skippedMissingOutgoingQmMapping += 1; + continue; + } + delistingRows.push({ + sourceId: outgoing.sourceId, + delistDate: listedTo, + fromListingId: listingId, + successorSourceId: null, + formattedTerminalReturn, + }); + terminalDelistingsOut += 1; + } + + delistingRows.sort(compareValidatedDelistingRows); + + for (let offset = 0; offset < delistingRows.length; offset += chunkSize) { + const slice = delistingRows.slice(offset, offset + chunkSize); + const chunkLines: string[] = []; + for (const row of slice) { + chunkLines.push( + `${row.sourceId}\t${row.delistDate}\t${row.fromListingId === null ? '' : String(row.fromListingId)}\t${row.successorSourceId ?? ''}\t${row.formattedTerminalReturn}` + ); + } + const buf = Buffer.from(`${chunkLines.join('\n')}\n`, 'utf8'); + await writeAll(delistingsHandle, buf); + delistingsBytes += buf.byteLength; + } + + const delistingsRowsOut = otcTransfersOut + terminalDelistingsOut; + const delistingsSkippedTotal = + skippedActive + + skippedNoOutcome + + skippedMissingListedTo + + skippedMissingOutgoingQmMapping + + skippedMissingSuccessorQmMapping; + delistingsStats = { + rowsIn: delistingsRowsOut + delistingsSkippedTotal, + rowsOut: delistingsRowsOut, + otcTransfersOut, + terminalDelistingsOut, + skippedTotal: delistingsSkippedTotal, + skipped: { + active: skippedActive, + noOutcome: skippedNoOutcome, + missingListedTo: skippedMissingListedTo, + missingOutgoingQmMapping: skippedMissingOutgoingQmMapping, + missingSuccessorQmMapping: skippedMissingSuccessorQmMapping, + nonOtcContinuity: 0, + }, + }; + + // 5. Sync and close all three temp files before atomic publish. + await providerMappingHandle.sync(); + await providerMappingHandle.close(); + providerMappingHandle = null; + + await listingCurrenciesHandle.sync(); + await listingCurrenciesHandle.close(); + listingCurrenciesHandle = null; + + await delistingsHandle.sync(); + await delistingsHandle.close(); + delistingsHandle = null; + + // 6. Atomic publish: back up pre-existing targets, rename all temps, then drop backups. + for (const key of publishOrder) { + if (await fileExists(fsAccess, targets[key])) { + await fsRename(targets[key], backups[key]); + backedUp.add(key); + } + } + + for (const key of publishOrder) { + await fsRename(temps[key], targets[key]); + published.add(key); + } + + for (const key of backedUp) { + await safeUnlink(fsUnlink, backups[key]); + } + + return { + outDir, + chunkSize, + delistingMappingSource, + providerMapping: { + path: targets.providerMapping, + rowsIn: providerMappingRowsIn, + rowsOut: providerMappingRowsOut, + bytesWritten: providerMappingBytes, + }, + listingCurrencies: { + path: targets.listingCurrencies, + rowsIn: listingCurrenciesRowsIn, + rowsOut: listingCurrenciesRowsOut, + bytesWritten: listingCurrenciesBytes, + }, + delistings: { + path: targets.delistings, + rowsIn: delistingsStats.rowsIn, + rowsOut: delistingsStats.rowsOut, + bytesWritten: delistingsBytes, + stats: delistingsStats, + }, + totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes, + }; + } catch (error) { + // Close any still-open temp file handles. + for (const handle of [providerMappingHandle, listingCurrenciesHandle, delistingsHandle]) { + if (handle !== null) { + await handle.close().catch(() => {}); + } + } + + // Roll back any already-published targets or moved backups. + for (const key of [...publishOrder].reverse()) { + if (published.has(key)) { + if (backedUp.has(key)) { + await fsRename(backups[key], targets[key]).catch(() => {}); + } else { + await safeUnlink(fsUnlink, targets[key]).catch(() => {}); + } + } else if (backedUp.has(key)) { + await fsRename(backups[key], targets[key]).catch(() => {}); + } + } + + // Clean up any leftover temp or backup files. + for (const key of publishOrder) { + await safeUnlink(fsUnlink, temps[key]).catch(() => {}); + await safeUnlink(fsUnlink, backups[key]).catch(() => {}); + } + + throw error; + } +} diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 7cefbc51..81fc9094 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -47,6 +47,49 @@ export { type UnresolvedExchangeRecord, } from './exchange-pass1'; +export { + buildDelistingExportRows, + CURATE_INPUT_FILES, + CurateInputExportError, + DEFAULT_DELISTING_MAPPING_SOURCE, + DEFAULT_EXPORT_CHUNK_SIZE, + exportCurateInputs, + formatDelistingsTsv, + formatListingCurrenciesTsv, + formatPlainDecimal, + formatProviderMappingTsv, + isValidStrictYmd, + MAX_EXPORT_CHUNK_SIZE, + type BuildDelistingExportRowsOptions, + type BuildDelistingExportRowsResult, + type ContinuityExportSourceRow, + type CurateInputExportErrorCode, + type CurateInputExportErrorOptions, + type DelistingExportRow, + type DelistingExportSkippedByReason, + type DelistingExportStats, + type ExportCurateInputsFileStats, + type ExportCurateInputsFsHooks, + type ExportCurateInputsOptions, + type ExportCurateInputsResult, + type ListingCurrencyExportRow, + type ListingDelistingSourceRow, + type ProviderMappingExportRow, +} from './export-curate-inputs'; + +export { + assertExportCurateInputsSafety, + EXPORT_CURATE_INPUTS_USAGE, + formatExportCurateInputsSummary, + parseExportCurateInputsArgs, + runCli as runExportCurateInputsCli, + runExportCurateInputs, + type ParsedExportCurateInputsArgs, + type RunExportCurateInputsDeps, + type RunExportCurateInputsOptions, + type RunExportCurateInputsOutput, +} from './run-export-curate-inputs'; + export { escapeSqlLiteral, generateExchangeSeedSql, diff --git a/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts new file mode 100644 index 00000000..b8ccc416 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts @@ -0,0 +1,332 @@ +import { getLogger } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { + assertEnvironmentSafety, + initializeStockConfig, + type StockAppConfig, +} from '@stock-bot/stock-config'; +import { + CURATE_INPUT_FILES, + DEFAULT_DELISTING_MAPPING_SOURCE, + DEFAULT_EXPORT_CHUNK_SIZE, + exportCurateInputs, + MAX_EXPORT_CHUNK_SIZE, + type ExportCurateInputsFsHooks, + type ExportCurateInputsResult, +} from './export-curate-inputs'; +import type { SecurityMasterQueryable, SecurityMasterQueryResult } from './persist'; +import type { SecurityMasterPostgresHandle } from './run-security-master'; + +export const EXPORT_CURATE_INPUTS_USAGE = [ + 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir [--chunk-size ] [--help]', + '', + 'Options:', + ` --out-dir Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`, + ` --chunk-size Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`, + ' --help Show this help message and exit.', +].join('\n'); + +export type ParsedExportCurateInputsArgs = + | { readonly help: true } + | { + readonly help: false; + readonly outDir: string; + readonly chunkSize: number; + }; + +export interface RunExportCurateInputsDeps { + readonly assertSafety?: () => void; + readonly createPostgresClient: () => + | Promise + | SecurityMasterPostgresHandle; + readonly exportFn?: typeof exportCurateInputs; + readonly writeStdout?: (text: string) => void; +} + +export interface RunExportCurateInputsOptions { + readonly outDir: string; + readonly chunkSize?: number; + readonly delistingMappingSource?: string; + readonly fs?: ExportCurateInputsFsHooks; +} + +export interface RunExportCurateInputsOutput { + readonly result: ExportCurateInputsResult; + readonly summary: string; +} + +const STRICT_INT_PATTERN = /^-?\d+$/; + +function usageError(message: string): Error { + return new Error(`${message}\n\n${EXPORT_CURATE_INPUTS_USAGE}`); +} + +function parseChunkSizeArg(raw: string): number { + if (!STRICT_INT_PATTERN.test(raw)) { + throw usageError( + `Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}` + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_EXPORT_CHUNK_SIZE) { + throw usageError( + `Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}` + ); + } + return parsed; +} + +export function parseExportCurateInputsArgs( + argv: readonly string[] +): ParsedExportCurateInputsArgs { + let help = false; + let outDir: string | undefined; + let chunkSize = DEFAULT_EXPORT_CHUNK_SIZE; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help') { + help = true; + continue; + } + if (arg === '--out-dir') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --out-dir'); + } + outDir = value.trim(); + i += 1; + continue; + } + if (arg?.startsWith('--out-dir=')) { + const value = arg.slice('--out-dir='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --out-dir'); + } + outDir = value; + continue; + } + if (arg === '--chunk-size') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --chunk-size'); + } + chunkSize = parseChunkSizeArg(value.trim()); + i += 1; + continue; + } + if (arg?.startsWith('--chunk-size=')) { + const value = arg.slice('--chunk-size='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --chunk-size'); + } + chunkSize = parseChunkSizeArg(value); + continue; + } + throw usageError(`Unknown argument: ${String(arg)}`); + } + + if (help) { + return { help: true }; + } + + if (outDir === undefined || outDir.trim().length === 0) { + throw usageError('Missing required argument: --out-dir '); + } + + return { + help: false, + outDir, + chunkSize, + }; +} + +export function assertExportCurateInputsSafety( + config: StockAppConfig, + env: Record = process.env +): void { + const pg = config.database.postgres; + if (!pg.enabled) { + throw new Error('PostgreSQL is disabled in configuration; cannot export curate-etl inputs'); + } + + const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env; + const pgOnlyConfig: StockAppConfig = { + ...config, + database: { + ...config.database, + mongodb: { + ...config.database.mongodb, + enabled: false, + }, + }, + }; + assertEnvironmentSafety(pgOnlyConfig, 'dataPipeline', safeEnv); +} + +export function formatExportCurateInputsSummary(result: ExportCurateInputsResult): string { + const d = result.delistings.stats; + const s = d.skipped; + const lines = [ + `Curate-ETL TSV export complete (${result.outDir})`, + ` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`, + ` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`, + ` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`, + ` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`, + ]; + return `${lines.join('\n')}\n`; +} + +export async function runExportCurateInputs( + deps: RunExportCurateInputsDeps, + options: RunExportCurateInputsOptions +): Promise { + if (deps.assertSafety) { + deps.assertSafety(); + } + + const pgHandle = await deps.createPostgresClient(); + let result: ExportCurateInputsResult; + let closeError: unknown = null; + try { + const exportFn = deps.exportFn ?? exportCurateInputs; + result = await exportFn(pgHandle.queryable, { + outDir: options.outDir, + chunkSize: options.chunkSize, + delistingMappingSource: options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE, + fs: options.fs, + }); + } finally { + try { + await pgHandle.close(); + } catch (error) { + closeError = error; + } + } + + if (closeError !== null) { + throw closeError; + } + + const summary = formatExportCurateInputsSummary(result); + const writeStdout = + deps.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(summary); + + return { result, summary }; +} + +export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { + const parsed = parseExportCurateInputsArgs(argv); + if (parsed.help) { + process.stdout.write(`${EXPORT_CURATE_INPUTS_USAGE}\n`); + return; + } + + const logger = getLogger('security-master-export-curate-inputs-cli'); + const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + + const assertSafety = (): void => { + assertExportCurateInputsSafety(config, process.env); + }; + + const createPostgresClient = async (): Promise => { + const pg = config.database.postgres; + const pgClient = new PostgreSQLClient( + { + host: pg.host, + port: pg.port, + database: pg.database, + username: pg.user, + password: pg.password, + poolSettings: { + min: 1, + max: Math.max(1, pg.poolSize), + idleTimeoutMillis: pg.idleTimeout, + }, + ssl: { + enabled: pg.ssl, + rejectUnauthorized: true, + }, + timeouts: { + connection: pg.connectionTimeout, + }, + }, + logger + ); + + await pgClient.connect(); + try { + const pool = pgClient.connectionPool; + if (!pool) { + throw new Error('PostgreSQL connection pool was not initialized after connect()'); + } + const poolClient = await pool.connect(); + const queryable: SecurityMasterQueryable = { + query>( + text: string, + values?: readonly unknown[] + ): Promise> { + return poolClient.query( + text, + values === undefined ? undefined : [...values] + ) as unknown as Promise>; + }, + release: () => { + poolClient.release(); + }, + }; + let closed = false; + return { + queryable, + async close(): Promise { + if (closed) { + return; + } + closed = true; + let releaseError: unknown = null; + try { + poolClient.release(); + } catch (error) { + releaseError = error; + } + try { + await pgClient.disconnect(); + } catch (disconnectError) { + if (releaseError === null) { + throw disconnectError; + } + } + if (releaseError !== null) { + throw releaseError; + } + }, + }; + } catch (error) { + await pgClient.disconnect().catch(() => {}); + throw error; + } + }; + + await runExportCurateInputs( + { + assertSafety, + createPostgresClient, + }, + { + outDir: parsed.outDir, + chunkSize: parsed.chunkSize, + } + ); +} + +if (import.meta.main) { + runCli().catch(error => { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`Error: ${message}\n`); + process.exit(1); + }); +} diff --git a/test/postgres/security-master-export-curate-inputs.test.ts b/test/postgres/security-master-export-curate-inputs.test.ts new file mode 100644 index 00000000..23173498 --- /dev/null +++ b/test/postgres/security-master-export-curate-inputs.test.ts @@ -0,0 +1,481 @@ +import { randomUUID } from 'node:crypto'; +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 { Pool, type PoolClient } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + exportCurateInputs, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-export-curate-inputs-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function makeTempDir(prefix = 'curate-inputs-pg-'): Promise { + const dir = await mkdtemp(join(tmpdir(), prefix)); + cleanup.push(() => rm(dir, { recursive: true, force: true })); + return dir; +} + +async function createIsolatedFixture(statementTimeoutMs = 15_000) { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=${statementTimeoutMs} -c lock_timeout=15000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'master' }); + + return { pool, schema, postgres }; +} + +async function withRecordingClient( + pool: Pool, + fn: (queryable: SecurityMasterQueryable, recordedSql: string[]) => Promise +): Promise { + const client: PoolClient = await pool.connect(); + const recordedSql: string[] = []; + const queryable: SecurityMasterQueryable = { + query>( + text: string, + values?: readonly unknown[] + ): Promise> { + recordedSql.push(text.replace(/\s+/g, ' ').trim()); + return client.query( + text, + values === undefined ? undefined : [...values] + ) as unknown as Promise>; + }, + release: () => { + client.release(); + }, + }; + try { + return await fn(queryable, recordedSql); + } finally { + client.release(); + } +} + +async function seedFixtureData(pool: Pool) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + + // Ensure required MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent). + await client.query(` + INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) + VALUES + ('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), + ('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100') + ON CONFLICT (mic) DO NOTHING + `); + + const insertInstrument = async ( + isin: string, + cusip: string, + name: string, + securityType: string, + country: string + ): Promise => { + const res = await client.query<{ instrument_id: number }>( + `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) + VALUES ($1, $2, $3, $4, $5) + RETURNING instrument_id`, + [isin, cusip, name, securityType, country] + ); + return res.rows[0]!.instrument_id; + }; + + const instAapl = await insertInstrument('US0378331005', '037833100', 'Apple Inc.', 'common', 'US'); + const instShop = await insertInstrument('CA82509L1076', '82509L107', 'Shopify Inc.', 'common', 'CA'); + const instFbOld = await insertInstrument('US30303M1027', '30303M102', 'Meta Platforms', 'common', 'US'); + const instFbNew = await insertInstrument('US4642872000', '464287200', 'FB Thematic ETF', 'etf', 'US'); + const instSivb = await insertInstrument('US78486Q1013', '78486Q101', 'SVB Financial Group', 'common', 'US'); + const instSivbReuse = await insertInstrument('US0000000019', '000000001', 'SIVB Reused Corp', 'common', 'US'); + const instDel30 = await insertInstrument('US0000000027', '000000002', 'Delisted 30 Corp', 'common', 'US'); + const instNoListedTo = await insertInstrument('US0000000035', '000000003', 'No ListedTo Corp', 'common', 'US'); + const instNoQm = await insertInstrument('US0000000043', '000000004', 'No QM Mapping Corp', 'common', 'US'); + const instNoSuccQm = await insertInstrument('US0000000050', '000000005', 'No Succ QM Corp', 'common', 'US'); + + const insertListing = async (params: { + instrumentId: number; + mic: string; + tickerRoot: string; + currency: string; + listedFrom: string | null; + listedTo: string | null; + delistReason: string | null; + terminalReturn: string | null; + }): Promise => { + const res = await client.query<{ listing_id: number }>( + `INSERT INTO listing ( + instrument_id, mic, ticker_root, class_suffix, currency, + listed_from, listed_to, delist_reason, terminal_return + ) + VALUES ($1, $2, $3, '', $4, $5::date, $6::date, $7, $8::numeric) + RETURNING listing_id`, + [ + params.instrumentId, + params.mic, + params.tickerRoot, + params.currency, + params.listedFrom, + params.listedTo, + params.delistReason, + params.terminalReturn, + ] + ); + return res.rows[0]!.listing_id; + }; + + const aaplId = await insertListing({ + instrumentId: instAapl, + mic: 'XNAS', + tickerRoot: 'AAPL', + currency: 'USD', + listedFrom: '1980-12-12', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const shopId = await insertListing({ + instrumentId: instShop, + mic: 'XTSE', + tickerRoot: 'SHOP', + currency: 'CAD', + listedFrom: '2015-05-21', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const fbOldId = await insertListing({ + instrumentId: instFbOld, + mic: 'XNAS', + tickerRoot: 'FB', + currency: 'USD', + listedFrom: '2012-05-18', + listedTo: '2022-06-08', + delistReason: null, + terminalReturn: null, + }); + const fbNewId = await insertListing({ + instrumentId: instFbNew, + mic: 'XNYS', + tickerRoot: 'FB', + currency: 'USD', + listedFrom: '2022-06-09', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const sivbId = await insertListing({ + instrumentId: instSivb, + mic: 'XNAS', + tickerRoot: 'SIVB', + currency: 'USD', + listedFrom: '1988-01-04', + listedTo: '2023-03-10', + delistReason: 'moved_to_otc', + terminalReturn: null, + }); + const sivbReuseId = await insertListing({ + instrumentId: instSivbReuse, + mic: 'XNAS', + tickerRoot: 'SIVB', + currency: 'USD', + listedFrom: '2023-03-20', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const sivbqId = await insertListing({ + instrumentId: instSivb, + mic: 'OTCM', + tickerRoot: 'SIVBQ', + currency: 'USD', + listedFrom: '2023-03-28', + listedTo: '2024-11-07', + delistReason: 'bankruptcy_cancelled', + terminalReturn: '-1.000000', + }); + const del30Id = await insertListing({ + instrumentId: instDel30, + mic: 'XNYS', + tickerRoot: 'DEL30', + currency: 'USD', + listedFrom: '2018-01-02', + listedTo: '2023-06-15', + delistReason: 'unknown_involuntary', + terminalReturn: '-0.300000', + }); + const noListedToId = await insertListing({ + instrumentId: instNoListedTo, + mic: 'XNYS', + tickerRoot: 'NLDT', + currency: 'USD', + listedFrom: '2019-01-02', + listedTo: null, + delistReason: 'unknown_involuntary', + terminalReturn: '-0.300000', + }); + const noQmId = await insertListing({ + instrumentId: instNoQm, + mic: 'XNYS', + tickerRoot: 'NOQM', + currency: 'USD', + listedFrom: '2019-01-02', + listedTo: '2023-07-01', + delistReason: 'unknown_involuntary', + terminalReturn: '-0.300000', + }); + const noSuccQmFromId = await insertListing({ + instrumentId: instNoSuccQm, + mic: 'XNYS', + tickerRoot: 'NOSU', + currency: 'USD', + listedFrom: '2019-01-02', + listedTo: '2023-03-10', + delistReason: 'moved_to_otc', + terminalReturn: null, + }); + const noSuccQmToId = await insertListing({ + instrumentId: instNoSuccQm, + mic: 'OTCM', + tickerRoot: 'NOSUQ', + currency: 'USD', + listedFrom: '2023-03-28', + listedTo: null, + delistReason: null, + terminalReturn: null, + }); + + const insertMapping = async ( + source: string, + sourceId: string, + validFrom: string, + validTo: string | null, + listingId: number + ) => { + await client.query( + `INSERT INTO provider_mapping (source, source_id, valid_from, valid_to, listing_id, method, confidence) + VALUES ($1, $2, $3::date, $4::date, $5, 'tier1_isin', 0.990)`, + [source, sourceId, validFrom, validTo, listingId] + ); + }; + + // Active US + CA + await insertMapping('eod', 'AAPL.US', '1980-12-12', null, aaplId); + await insertMapping('qm', 'AAPL', '1980-12-12', null, aaplId); + await insertMapping('eod', 'SHOP.TO', '2015-05-21', null, shopId); + await insertMapping('qm', 'SHOP:CA', '2015-05-21', null, shopId); + + // Ticker reuse FB across two date ranges + await insertMapping('eod', 'FB.US', '2012-05-18', '2022-06-08', fbOldId); + await insertMapping('eod', 'FB.US', '2022-06-09', null, fbNewId); + await insertMapping('qm', 'FB', '2012-05-18', '2022-06-08', fbOldId); + await insertMapping('qm', 'FB', '2022-06-09', null, fbNewId); + + // SIVB -> SIVBQ across ticker reuse + await insertMapping('eod', 'SIVB.US', '1988-01-04', '2023-03-10', sivbId); + await insertMapping('eod', 'SIVB.US', '2023-03-20', null, sivbReuseId); + await insertMapping('eod', 'SIVBQ.US', '2023-03-28', '2024-11-07', sivbqId); + await insertMapping('qm', 'SIVB', '1988-01-04', '2023-03-10', sivbId); + await insertMapping('qm', 'SIVB', '2023-03-20', null, sivbReuseId); + await insertMapping('qm', 'SIVBQ', '2023-03-28', '2024-11-07', sivbqId); + + // DEL30 -0.3 terminal delisting + await insertMapping('eod', 'DEL30.US', '2018-01-02', '2023-06-15', del30Id); + await insertMapping('qm', 'DEL30', '2018-01-02', '2023-06-15', del30Id); + + // Skipped-row mappings: noQm has only eod; noSuccQmFrom has qm, successor has no qm + await insertMapping('eod', 'NOQM.US', '2019-01-02', '2023-07-01', noQmId); + await insertMapping('qm', 'NOSU', '2019-01-02', '2023-03-10', noSuccQmFromId); + + // Continuities + await client.query( + `INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind) + VALUES + ($1, $2, '2023-03-28'::date, 'otc_delist_transfer'), + ($3, $4, '2023-03-28'::date, 'otc_delist_transfer')`, + [sivbId, sivbqId, noSuccQmFromId, noSuccQmToId] + ); + + await client.query('COMMIT'); + + return { + aaplId, + shopId, + fbOldId, + fbNewId, + sivbId, + sivbReuseId, + sivbqId, + del30Id, + noListedToId, + noQmId, + noSuccQmFromId, + noSuccQmToId, + }; + } catch (error) { + await client.query('ROLLBACK').catch(() => {}); + throw error; + } finally { + client.release(); + } +} + +describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*)', () => { + test('exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000', async () => { + const { pool } = await createIsolatedFixture(); + const ids = await seedFixtureData(pool); + + const outDir5000 = await makeTempDir('curate-inputs-pg-5000-'); + const outDir1 = await makeTempDir('curate-inputs-pg-1-'); + + const { result: res5000, sql: sql5000 } = await withRecordingClient( + pool, + async (queryable, recordedSql) => ({ + result: await exportCurateInputs(queryable, { outDir: outDir5000, chunkSize: 5000 }), + sql: recordedSql, + }) + ); + + const { result: res1, sql: sql1 } = await withRecordingClient( + pool, + async (queryable, recordedSql) => ({ + result: await exportCurateInputs(queryable, { outDir: outDir1, chunkSize: 1 }), + sql: recordedSql, + }) + ); + + // Read-only SQL verification: REPEATABLE READ READ ONLY transaction + zero writes/DDL. + for (const sqlLog of [sql5000, sql1]) { + expect(sqlLog[0]).toBe('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'); + expect(sqlLog[sqlLog.length - 1]).toBe('COMMIT'); + for (const stmt of sqlLog) { + expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE)\b/i); + } + } + + // Verify chunkSize=1 actually paginated across multiple queries. + expect(sql1.length).toBeGreaterThan(sql5000.length); + + // Byte-identical outputs between chunkSize=1 and chunkSize=5000. + const pm5000 = await readFile(res5000.providerMapping.path, 'utf8'); + const lc5000 = await readFile(res5000.listingCurrencies.path, 'utf8'); + const dl5000 = await readFile(res5000.delistings.path, 'utf8'); + + expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000); + expect(await readFile(res1.listingCurrencies.path, 'utf8')).toBe(lc5000); + expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000); + + // Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order). + expect(pm5000).toBe( + [ + `eod\tAAPL.US\t1980-12-12\t\t${ids.aaplId}`, + `eod\tDEL30.US\t2018-01-02\t2023-06-15\t${ids.del30Id}`, + `eod\tFB.US\t2012-05-18\t2022-06-08\t${ids.fbOldId}`, + `eod\tFB.US\t2022-06-09\t\t${ids.fbNewId}`, + `eod\tNOQM.US\t2019-01-02\t2023-07-01\t${ids.noQmId}`, + `eod\tSHOP.TO\t2015-05-21\t\t${ids.shopId}`, + `eod\tSIVB.US\t1988-01-04\t2023-03-10\t${ids.sivbId}`, + `eod\tSIVB.US\t2023-03-20\t\t${ids.sivbReuseId}`, + `eod\tSIVBQ.US\t2023-03-28\t2024-11-07\t${ids.sivbqId}`, + `qm\tAAPL\t1980-12-12\t\t${ids.aaplId}`, + `qm\tDEL30\t2018-01-02\t2023-06-15\t${ids.del30Id}`, + `qm\tFB\t2012-05-18\t2022-06-08\t${ids.fbOldId}`, + `qm\tFB\t2022-06-09\t\t${ids.fbNewId}`, + `qm\tNOSU\t2019-01-02\t2023-03-10\t${ids.noSuccQmFromId}`, + `qm\tSHOP:CA\t2015-05-21\t\t${ids.shopId}`, + `qm\tSIVB\t1988-01-04\t2023-03-10\t${ids.sivbId}`, + `qm\tSIVB\t2023-03-20\t\t${ids.sivbReuseId}`, + `qm\tSIVBQ\t2023-03-28\t2024-11-07\t${ids.sivbqId}`, + '', + ].join('\n') + ); + + // Assert exact listing_currencies.tsv content (btrim(CHAR(3)), ascending listing_id). + expect(lc5000).toBe( + [ + `${ids.aaplId}\tUSD`, + `${ids.shopId}\tCAD`, + `${ids.fbOldId}\tUSD`, + `${ids.fbNewId}\tUSD`, + `${ids.sivbId}\tUSD`, + `${ids.sivbReuseId}\tUSD`, + `${ids.sivbqId}\tUSD`, + `${ids.del30Id}\tUSD`, + `${ids.noListedToId}\tUSD`, + `${ids.noQmId}\tUSD`, + `${ids.noSuccQmFromId}\tUSD`, + `${ids.noSuccQmToId}\tUSD`, + '', + ].join('\n') + ); + + // Assert exact delistings.tsv content. + expect(dl5000).toBe( + [ + `DEL30\t2023-06-15\t${ids.del30Id}\t\t-0.3`, + `SIVB\t2023-03-28\t${ids.sivbId}\tSIVBQ\t`, + `SIVBQ\t2024-11-07\t${ids.sivbqId}\t\t-1`, + '', + ].join('\n') + ); + + // Assert exact stats reconciliation. + const stats = res5000.delistings.stats; + expect(stats).toEqual({ + rowsIn: 12, + rowsOut: 3, + otcTransfersOut: 1, + terminalDelistingsOut: 2, + skippedTotal: 9, + skipped: { + active: 4, // AAPL, SHOP, FB new, SIVB reuse + noOutcome: 2, // FB old, NOSUQ + missingListedTo: 1, // NLDT + missingOutgoingQmMapping: 1, // NOQM + missingSuccessorQmMapping: 1, // NOSU -> NOSUQ + nonOtcContinuity: 0, + }, + }); + expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal); + expect(res1.delistings.stats).toEqual(stats); + }); +}); diff --git a/test/unit/security-master-export-curate-inputs.test.ts b/test/unit/security-master-export-curate-inputs.test.ts new file mode 100644 index 00000000..ff5d50c4 --- /dev/null +++ b/test/unit/security-master-export-curate-inputs.test.ts @@ -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 { + 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, + expectedCode: CurateInputExportError['code'], + expectedTable: string, + expectedKeySubstring: string +): Promise { + 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>( + text: string, + values?: readonly unknown[] + ): Promise> { + 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'); + }); +}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index ba3e2c43..5232bf6c 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1239,7 +1239,7 @@ Measured locally (`2026-11-29`): - **Unverified MongoDB `qmDividends` field names:** `bson_qm_actions::FIELD_DIVIDEND_CASH` (`"amount"`) and `FIELD_DIVIDEND_CURRENCY` (`"currency"`) remain isolated constants pending verification against live `mongodump` `qmDividends` exports. - **In-RAM buffering of decoded events:** the single-threaded runner buffers decoded splits, dividends, and delistings in RAM (with `Arc` key interning) before curation — small for real `qmSplits` (~19k) + `qmDividends` (~500k) + Pass 6 delistings, unlike `eodPrices`. -- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connections, and no TypeScript Pass 6 `delistings.tsv` exporter yet. +- **Single-threaded file-to-file execution:** no `rayon` sharding and no direct MongoDB/PostgreSQL connections. The TypeScript read-only PostgreSQL → TSV exporter (`apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts`) generates `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` for all `curate-etl` commands. ## `curate-fx-1d` Command (`M1.2ac`) diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 785adf7d..277f0d49 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -215,3 +215,6 @@ pub use run_curate_events::{ format_curate_events_report, run_curate_events, CurateEventsArgs, CurateEventsRunReport, RunCurateEventsError, DEFAULT_EVENTS_MAPPING_SOURCE, }; + +#[cfg(test)] +mod tsv_fixture_tests; diff --git a/tools/curate-etl/src/tsv_fixture_tests.rs b/tools/curate-etl/src/tsv_fixture_tests.rs new file mode 100644 index 00000000..5b23a7f6 --- /dev/null +++ b/tools/curate-etl/src/tsv_fixture_tests.rs @@ -0,0 +1,95 @@ +//! Cross-language golden fixture tests verifying that TSV files emitted by the TypeScript +//! security-master exporter (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) +//! load cleanly through the real Rust TSV loaders and curate with zero drops. + +use std::path::PathBuf; + +use crate::bson_eod_prices::parse_ymd_strict_days; +use crate::corporate_actions::{CorporateActionKind, DividendActionEvent, SplitActionEvent}; +use crate::curate_corporate_actions::curate_corporate_actions; +use crate::provider_mapping::ProviderMappingTable; +use crate::run_curate_bars::{load_listing_currencies_tsv, load_provider_mapping_tsv}; +use crate::run_curate_corporate_actions::load_delistings_tsv; + +fn fixture_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("curate-inputs") +} + +#[test] +fn loads_ts_golden_curate_inputs_and_curates_delistings_with_zero_drops() { + let dir = fixture_dir(); + + // 1. Load provider_mapping.tsv and build ProviderMappingTable. + let pm_rows = load_provider_mapping_tsv(&dir.join("provider_mapping.tsv")) + .expect("provider_mapping.tsv fixture should load"); + assert_eq!(pm_rows.len(), 16); + let mapping = ProviderMappingTable::from_rows(pm_rows) + .expect("provider_mapping.tsv fixture should build a valid ProviderMappingTable"); + + let fb_old_date = parse_ymd_strict_days("2022-06-08").unwrap(); + let fb_new_date = parse_ymd_strict_days("2022-06-09").unwrap(); + assert_eq!(mapping.resolve("eod", "FB.US", fb_old_date), Some(2)); + assert_eq!(mapping.resolve("eod", "FB.US", fb_new_date), Some(3)); + assert_eq!(mapping.resolve("qm", "SHOP:CA", fb_new_date), Some(8)); + + // 2. Load listing_currencies.tsv. + let currencies = load_listing_currencies_tsv(&dir.join("listing_currencies.tsv")) + .expect("listing_currencies.tsv fixture should load"); + assert_eq!(currencies.len(), 8); + assert_eq!(currencies.get(&1).map(|c| c.as_ref()), Some("USD")); + assert_eq!(currencies.get(&6).map(|c| c.as_ref()), Some("USD")); + assert_eq!(currencies.get(&8).map(|c| c.as_ref()), Some("CAD")); + + // 3. Load delistings.tsv and run curate_corporate_actions against "qm". + let delistings = load_delistings_tsv(&dir.join("delistings.tsv")) + .expect("delistings.tsv fixture should load"); + assert_eq!(delistings.len(), 3); + + let curated = curate_corporate_actions( + Vec::<(String, SplitActionEvent)>::new(), + Vec::<(String, DividendActionEvent)>::new(), + delistings, + "qm", + &mapping, + ) + .expect("curate_corporate_actions should succeed on golden fixtures"); + + assert_eq!(curated.stats.rows_in, 3); + assert_eq!(curated.stats.rows_out, 3); + assert_eq!(curated.stats.dropped_unmapped, 0); + assert_eq!(curated.stats.dropped_unmapped_successor, 0); + assert_eq!(curated.stats.dropped_self_successor, 0); + assert_eq!(curated.stats.dropped_known_at_out_of_range, 0); + assert_eq!(curated.stats.listing_collision_collapsed, 0); + assert_eq!(curated.stats.listing_collision_dropped, 0); + + // Curated rows are sorted by (listing_id, ex_date, kind): + // listing 4: SIVB -> SIVBQ OTC transfer on 2023-03-28 (despite SIVB reuse on 2023-03-20!) + // listing 6: SIVBQ bankruptcy cancellation (-1.0) on 2024-11-07 + // listing 7: DEL30 Shumway terminal delisting (-0.3) on 2023-06-15 + assert_eq!(curated.rows.len(), 3); + + let otc = &curated.rows[0]; + assert_eq!(otc.listing_id, 4); + assert_eq!(otc.ex_date, parse_ymd_strict_days("2023-03-28").unwrap()); + assert_eq!(otc.kind, CorporateActionKind::OtcDelistTransfer); + assert_eq!(otc.successor_listing_id, Some(6)); + assert_eq!(otc.terminal_return, None); + + let sivbq_term = &curated.rows[1]; + assert_eq!(sivbq_term.listing_id, 6); + assert_eq!(sivbq_term.ex_date, parse_ymd_strict_days("2024-11-07").unwrap()); + assert_eq!(sivbq_term.kind, CorporateActionKind::Delisting); + assert_eq!(sivbq_term.successor_listing_id, None); + assert_eq!(sivbq_term.terminal_return, Some(-1.0)); + + let del30_term = &curated.rows[2]; + assert_eq!(del30_term.listing_id, 7); + assert_eq!(del30_term.ex_date, parse_ymd_strict_days("2023-06-15").unwrap()); + assert_eq!(del30_term.kind, CorporateActionKind::Delisting); + assert_eq!(del30_term.successor_listing_id, None); + assert_eq!(del30_term.terminal_return, Some(-0.3)); +} diff --git a/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv b/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv new file mode 100644 index 00000000..cbf74348 --- /dev/null +++ b/tools/curate-etl/tests/fixtures/curate-inputs/delistings.tsv @@ -0,0 +1,3 @@ +DEL30 2023-06-15 7 -0.3 +SIVB 2023-03-28 4 SIVBQ +SIVBQ 2024-11-07 6 -1 diff --git a/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv b/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv new file mode 100644 index 00000000..b52375e1 --- /dev/null +++ b/tools/curate-etl/tests/fixtures/curate-inputs/listing_currencies.tsv @@ -0,0 +1,8 @@ +1 USD +2 USD +3 USD +4 USD +5 USD +6 USD +7 USD +8 CAD diff --git a/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv b/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv new file mode 100644 index 00000000..480fde57 --- /dev/null +++ b/tools/curate-etl/tests/fixtures/curate-inputs/provider_mapping.tsv @@ -0,0 +1,16 @@ +eod AAPL.US 1980-12-12 1 +eod DEL30.US 2018-01-02 2023-06-15 7 +eod FB.US 2012-05-18 2022-06-08 2 +eod FB.US 2022-06-09 3 +eod SHOP.TO 2015-05-21 8 +eod SIVB.US 1988-01-04 2023-03-10 4 +eod SIVB.US 2023-03-20 5 +eod SIVBQ.US 2023-03-28 2024-11-07 6 +qm AAPL 1980-12-12 1 +qm DEL30 2018-01-02 2023-06-15 7 +qm FB 2012-05-18 2022-06-08 2 +qm FB 2022-06-09 3 +qm SHOP:CA 2015-05-21 8 +qm SIVB 1988-01-04 2023-03-10 4 +qm SIVB 2023-03-20 5 +qm SIVBQ 2023-03-28 2024-11-07 6