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