diff --git a/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts b/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts index f23a8a02..9178e0c2 100644 --- a/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts +++ b/apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts @@ -33,6 +33,7 @@ interface BenchContinuityRow { interface BenchListingRow { listing_id: number; currency: string; + mic: string; listed_to: string | null; delist_reason: string | null; terminal_return: string | null; @@ -75,14 +76,21 @@ function buildSyntheticTables(): { }; } + const cadMics = ['XTSE', 'XTSX', 'XCNQ', 'NEOE'] as const; + const usdMics = ['XNYS', 'XNAS', 'ARCX', 'XASE', 'BATS', 'OTCM', 'IEXG'] as const; 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'; + const mic = + currency === 'CAD' + ? cadMics[Math.floor(id / 5) % cadMics.length]! + : usdMics[i % usdMics.length]!; if (id <= OTC_CONTINUITY_COUNT) { listings[i] = { listing_id: id, currency, + mic, listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null, @@ -92,6 +100,7 @@ function buildSyntheticTables(): { listings[i] = { listing_id: id, currency, + mic, listed_to: '2024-11-07', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1.000000', @@ -100,6 +109,7 @@ function buildSyntheticTables(): { listings[i] = { listing_id: id, currency, + mic, listed_to: null, delist_reason: 'active', terminal_return: null, @@ -110,6 +120,7 @@ function buildSyntheticTables(): { listings[i] = { listing_id: id, currency, + mic, listed_to: missingDate ? null : '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.300000', @@ -118,6 +129,7 @@ function buildSyntheticTables(): { listings[i] = { listing_id: id, currency, + mic, listed_to: '2022-12-30', delist_reason: null, terminal_return: null, @@ -126,6 +138,7 @@ function buildSyntheticTables(): { listings[i] = { listing_id: id, currency, + mic, listed_to: null, delist_reason: 'active', terminal_return: null, @@ -266,7 +279,10 @@ async function main(): Promise { } const totalRowsExported = - result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut; + result.providerMapping.rowsOut + + result.listingCurrencies.rowsOut + + result.listingVenues.rowsOut + + result.delistings.rowsOut; const rowsPerSec = totalRowsExported / (elapsedMs / 1000); // process.resourceUsage().maxRSS is reported in KiB on Linux. const peakRssMiB = process.resourceUsage().maxRSS / 1024; @@ -276,7 +292,7 @@ async function main(): Promise { ` 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` + ` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} listing_venues=${result.listingVenues.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` 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 index 299bac4d..f32bac97 100644 --- a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts +++ b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts @@ -20,9 +20,34 @@ import type { SecurityMasterQueryable } from './persist'; export const CURATE_INPUT_FILES = Object.freeze({ providerMapping: 'provider_mapping.tsv', listingCurrencies: 'listing_currencies.tsv', + listingVenues: 'listing_venues.tsv', delistings: 'delistings.tsv', } as const); +export const LISTING_STATUTORY_LAG_VENUES = Object.freeze(['us_tsx', 'tsxv_cse'] as const); + +export type ListingStatutoryLagVenue = (typeof LISTING_STATUTORY_LAG_VENUES)[number]; + +/** + * Maps ISO 10383 exchange MICs in `ISO_EXCHANGE_SEEDS` to `curate-fundamentals` statutory-lag + * classes (`us_tsx`: +45d quarterly / +90d annual; `tsxv_cse`: +60d quarterly / +120d annual). + */ +export const LISTING_VENUE_BY_MIC: Readonly> = Object.freeze( + { + ARCX: 'us_tsx', + BATS: 'us_tsx', + IEXG: 'us_tsx', + NEOE: 'us_tsx', + OTCM: 'us_tsx', + XASE: 'us_tsx', + XCNQ: 'tsxv_cse', + XNAS: 'us_tsx', + XNYS: 'us_tsx', + XTSE: 'us_tsx', + XTSX: 'tsxv_cse', + } +); + export const CURATE_INPUT_GENERATIONS_DIR = 'generations'; export const CURATE_INPUT_CURRENT_LINK = 'current'; export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock'; @@ -50,6 +75,9 @@ export type CurateInputExportErrorCode = | 'OVERLAPPING_PROVIDER_MAPPING' | 'UNSORTED_PROVIDER_MAPPING_STREAM' | 'DUPLICATE_LISTING_CURRENCY' + | 'UNKNOWN_LISTING_MIC' + | 'INVALID_LISTING_VENUE' + | 'DUPLICATE_LISTING_VENUE' | 'UNSORTED_LISTING_STREAM' | 'INVALID_TERMINAL_RETURN' | 'INVALID_DELISTING_OUTCOME' @@ -59,7 +87,8 @@ export type CurateInputExportErrorCode = | 'DUPLICATE_OTC_CONTINUITY' | 'OUT_OF_ORDER_CONTINUITY_STREAM' | 'PUBLISH_LOCK_TIMEOUT' - | 'PUBLISH_ROLLBACK_FAILED'; + | 'PUBLISH_ROLLBACK_FAILED' + | 'INCOMPLETE_SNAPSHOT'; export interface CurateInputExportErrorOptions { readonly code: CurateInputExportErrorCode; @@ -105,6 +134,11 @@ export interface ListingCurrencyExportRow { readonly currency: string; } +export interface ListingVenueExportRow { + readonly listingId: number; + readonly venue: ListingStatutoryLagVenue; +} + export interface DelistingExportRow { readonly sourceId: string; readonly delistDate: string; @@ -189,6 +223,7 @@ export interface PinnedCurateInputSnapshot { readonly generationDir: string; readonly providerMapping: string; readonly listingCurrencies: string; + readonly listingVenues: string; readonly delistings: string; } @@ -201,6 +236,7 @@ export interface ExportCurateInputsResult { readonly delistingMappingSource: string; readonly providerMapping: ExportCurateInputsFileStats; readonly listingCurrencies: ExportCurateInputsFileStats; + readonly listingVenues: ExportCurateInputsFileStats; readonly delistings: ExportCurateInputsFileStats & { readonly stats: DelistingExportStats; }; @@ -232,6 +268,7 @@ interface DbContinuityRow { interface DbListingRow { listing_id: number; + mic: string | null; currency: string | null; listed_to: string | null; delist_reason: string | null; @@ -596,6 +633,95 @@ export function formatListingCurrenciesTsv(rows: readonly ListingCurrencyExportR return joinLinesInChunks(lines); } +/** + * Resolves a persisted ISO 10383 `listing.mic` to its `curate-fundamentals` statutory-lag venue + * class (`us_tsx` vs `tsxv_cse`). Fails closed on blank, control-character, whitespace-padded, + * prototype-key, or unmapped MIC values. + */ +export function resolveListingVenueForMic( + mic: unknown, + table = 'listing', + key = 'mic' +): ListingStatutoryLagVenue { + const validatedMic = assertNonBlankVerbatim(mic, table, key, 'mic'); + const venue = Object.hasOwn(LISTING_VENUE_BY_MIC, validatedMic) + ? LISTING_VENUE_BY_MIC[validatedMic] + : undefined; + if (venue === undefined) { + throw new CurateInputExportError({ + code: 'UNKNOWN_LISTING_MIC', + table, + key, + field: 'mic', + detail: `unknown listing mic "${validatedMic}" (expected one of: ${Object.keys(LISTING_VENUE_BY_MIC).join(', ')})`, + }); + } + return venue; +} + +function assertListingVenue( + value: unknown, + table: string, + key: string, + field: string +): ListingStatutoryLagVenue { + if (typeof value === 'string') { + assertNoTsvControlChars(value, table, key, field); + } + if (value !== 'us_tsx' && value !== 'tsxv_cse') { + throw new CurateInputExportError({ + code: 'INVALID_LISTING_VENUE', + table, + key, + field, + detail: `invalid ${field} "${String(value)}" (expected one of: ${LISTING_STATUTORY_LAG_VENUES.join(', ')})`, + }); + } + return value; +} + +/** + * Validates, sorts by ascending `listing_id`, rejects duplicate `listing_id`s, and formats + * `listing_venues.tsv`. Headerless 2-column TSV: `listing_id\tvenue` (`us_tsx` | `tsxv_cse`), + * matching `tools/curate-etl/src/run_curate_fundamentals.rs::load_listing_venues_tsv`. + */ +export function formatListingVenuesTsv(rows: readonly ListingVenueExportRow[]): string { + if (rows.length === 0) { + return ''; + } + + const validated: ListingVenueExportRow[] = []; + 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 venue = assertListingVenue(row.venue, 'listing', `listing_id=${listingId}`, 'venue'); + validated.push({ listingId, venue }); + } + + 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_VENUE', + table: 'listing', + key: `listing_id=${curr.listingId}`, + field: 'listing_id', + detail: `duplicate listing_id ${curr.listingId} in listing_venues`, + }); + } + lines.push(`${curr.listingId}\t${curr.venue}`); + 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'); @@ -1189,12 +1315,12 @@ async function acquirePublishLock( /** * Resolves and pins the currently active immutable generation directory via `/current` - * before a consumer opens any TSV file. All three returned paths belong to the same atomic + * before a consumer opens any TSV file. All four returned paths belong to the same atomic * PostgreSQL snapshot and remain immutable even if a concurrent export refreshes `/current`. */ export async function pinCurateInputSnapshot( outDir: string, - fsHooks?: Pick + fsHooks?: Pick ): Promise { if (typeof outDir !== 'string' || outDir.trim().length === 0) { throw new CurateInputExportError({ @@ -1207,16 +1333,41 @@ export async function pinCurateInputSnapshot( } const normalizedOutDir = outDir.trim(); const fsRealpath = fsHooks?.realpath ?? realpath; + const fsAccess = fsHooks?.access ?? access; const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK); const generationDir = await fsRealpath(currentLink); const generationId = basename(generationDir); + const providerMapping = join(generationDir, CURATE_INPUT_FILES.providerMapping); + const listingCurrencies = join(generationDir, CURATE_INPUT_FILES.listingCurrencies); + const listingVenues = join(generationDir, CURATE_INPUT_FILES.listingVenues); + const delistings = join(generationDir, CURATE_INPUT_FILES.delistings); + + try { + await fsAccess(listingVenues); + } catch (error) { + if ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') { + throw new CurateInputExportError({ + code: 'INCOMPLETE_SNAPSHOT', + table: 'publish', + key: generationId, + field: CURATE_INPUT_FILES.listingVenues, + detail: + `generation "${generationId}" under "${normalizedOutDir}" is missing ${CURATE_INPUT_FILES.listingVenues} ` + + '(legacy M1 three-file snapshot); re-run exportCurateInputs to refresh the export', + cause: error, + }); + } + throw error; + } + return { outDir: normalizedOutDir, generationId, generationDir, - providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping), - listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies), - delistings: join(generationDir, CURATE_INPUT_FILES.delistings), + providerMapping, + listingCurrencies, + listingVenues, + delistings, }; } @@ -1225,7 +1376,7 @@ export async function pinCurateInputSnapshot( * transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable * generation directory under `/generations/`, and atomically commits * `/current` (plus top-level symlinks `provider_mapping.tsv`, `listing_currencies.tsv`, - * and `delistings.tsv` pointing through `current/`). + * `listing_venues.tsv`, and `delistings.tsv` pointing through `current/`). */ export async function exportCurateInputs( queryable: SecurityMasterQueryable, @@ -1299,31 +1450,37 @@ export async function exportCurateInputs( const targets = { providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(outDir, CURATE_INPUT_FILES.listingVenues), delistings: join(outDir, CURATE_INPUT_FILES.delistings), }; const stagedFiles = { providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(stagingDir, CURATE_INPUT_FILES.listingVenues), delistings: join(stagingDir, CURATE_INPUT_FILES.delistings), }; const generationFiles = { providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(generationDir, CURATE_INPUT_FILES.listingVenues), delistings: join(generationDir, CURATE_INPUT_FILES.delistings), }; const backups = { providerMapping: `${targets.providerMapping}.${runTag}.bak`, listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`, + listingVenues: `${targets.listingVenues}.${runTag}.bak`, delistings: `${targets.delistings}.${runTag}.bak`, }; const linkTemps = { providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`, listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`, + listingVenues: `${targets.listingVenues}.${runTag}.link.tmp`, delistings: `${targets.delistings}.${runTag}.link.tmp`, }; let providerMappingHandle: FileHandle | null = null; let listingCurrenciesHandle: FileHandle | null = null; + let listingVenuesHandle: FileHandle | null = null; let delistingsHandle: FileHandle | null = null; let providerMappingRowsIn = 0; @@ -1334,11 +1491,20 @@ export async function exportCurateInputs( let listingCurrenciesRowsOut = 0; let listingCurrenciesBytes = 0; + let listingVenuesRowsIn = 0; + let listingVenuesRowsOut = 0; + let listingVenuesBytes = 0; + let delistingsBytes = 0; let delistingsStats!: DelistingExportStats; - type PublishKey = 'providerMapping' | 'listingCurrencies' | 'delistings'; - const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings']; + type PublishKey = 'providerMapping' | 'listingCurrencies' | 'listingVenues' | 'delistings'; + const publishOrder: PublishKey[] = [ + 'providerMapping', + 'listingCurrencies', + 'listingVenues', + 'delistings', + ]; let stagingCreated = false; let publishLockAcquired = false; @@ -1353,6 +1519,7 @@ export async function exportCurateInputs( providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx'); listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx'); + listingVenuesHandle = await fsOpen(stagedFiles.listingVenues, 'wx'); delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx'); const otcByFromListingId = new Map(); @@ -1481,7 +1648,7 @@ export async function exportCurateInputs( } } - // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv directly. + // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv and listing_venues.tsv directly. let lastListingId: number | null = null; for (;;) { const res = @@ -1489,6 +1656,7 @@ export async function exportCurateInputs( ? await queryable.query( `SELECT listing_id, + mic, btrim(currency) AS currency, to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, @@ -1501,6 +1669,7 @@ export async function exportCurateInputs( : await queryable.query( `SELECT listing_id, + mic, btrim(currency) AS currency, to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, @@ -1517,6 +1686,7 @@ export async function exportCurateInputs( } const chunkLines: string[] = []; + const venueChunkLines: string[] = []; for (const row of res.rows) { const listingId = assertPositiveI32( row.listing_id, @@ -1548,9 +1718,13 @@ export async function exportCurateInputs( } const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency'); + const venue = resolveListingVenueForMic(row.mic, 'listing', listingKey); chunkLines.push(`${listingId}\t${currency}`); + venueChunkLines.push(`${listingId}\t${venue}`); listingCurrenciesRowsIn += 1; listingCurrenciesRowsOut += 1; + listingVenuesRowsIn += 1; + listingVenuesRowsOut += 1; const otc = otcByFromListingId.get(listingId); const hasTerminalReturn = @@ -1607,6 +1781,11 @@ export async function exportCurateInputs( await writeAll(listingCurrenciesHandle, buf); listingCurrenciesBytes += buf.byteLength; + const venueChunkText = `${venueChunkLines.join('\n')}\n`; + const venueBuf = Buffer.from(venueChunkText, 'utf8'); + await writeAll(listingVenuesHandle, venueBuf); + listingVenuesBytes += venueBuf.byteLength; + if (res.rows.length < chunkSize) { break; } @@ -1842,7 +2021,7 @@ export async function exportCurateInputs( }, }; - // 5. Sync and close all three staged files before atomic generation publish. + // 5. Sync and close all four staged files before atomic generation publish. await providerMappingHandle.sync(); await providerMappingHandle.close(); providerMappingHandle = null; @@ -1851,6 +2030,10 @@ export async function exportCurateInputs( await listingCurrenciesHandle.close(); listingCurrenciesHandle = null; + await listingVenuesHandle.sync(); + await listingVenuesHandle.close(); + listingVenuesHandle = null; + await delistingsHandle.sync(); await delistingsHandle.close(); delistingsHandle = null; @@ -1915,7 +2098,12 @@ export async function exportCurateInputs( currentTempCreated = false; } catch (error) { // Close any still-open staged file handles. - for (const handle of [providerMappingHandle, listingCurrenciesHandle, delistingsHandle]) { + for (const handle of [ + providerMappingHandle, + listingCurrenciesHandle, + listingVenuesHandle, + delistingsHandle, + ]) { if (handle !== null) { await handle.close().catch(() => {}); } @@ -2027,6 +2215,12 @@ export async function exportCurateInputs( rowsOut: listingCurrenciesRowsOut, bytesWritten: listingCurrenciesBytes, }, + listingVenues: { + path: generationFiles.listingVenues, + rowsIn: listingVenuesRowsIn, + rowsOut: listingVenuesRowsOut, + bytesWritten: listingVenuesBytes, + }, delistings: { path: generationFiles.delistings, rowsIn: delistingsStats.rowsIn, @@ -2034,7 +2228,8 @@ export async function exportCurateInputs( bytesWritten: delistingsBytes, stats: delistingsStats, }, - totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes, + totalBytesWritten: + providerMappingBytes + listingCurrenciesBytes + listingVenuesBytes + delistingsBytes, cleanupWarnings, }; } diff --git a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts index 8ba7e632..bfa6a765 100644 --- a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts +++ b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts @@ -4,9 +4,10 @@ import { join } from 'node:path'; import type { MongoDBClient } from '@stock-bot/mongodb'; /** - * M1 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by + * M1+M2 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by * `tools/curate-etl` (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, - * `curate-fx-1d`, `curate-shorts`, `curate-events`). + * `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-fundamentals`, `curate-sentiment`, + * `curate-macro`, `curate-intraday`). */ export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([ 'eodPrices', @@ -17,6 +18,12 @@ export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([ 'ceoShorts', 'qmFilings', 'qmEarnings', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', ] as const); export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number]; @@ -390,7 +397,7 @@ function validateExportOptions(options: ExportRawBsonCollectionOptions): Validat throw new RawBsonExportError({ code: 'DISALLOWED_COLLECTION', collection: collectionName || '', - detail: `collection "${collectionName}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, + detail: `collection "${collectionName}" is not in the M1+M2 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, }); } diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 85707ca8..0c3c500b 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -60,11 +60,15 @@ export { exportCurateInputs, formatDelistingsTsv, formatListingCurrenciesTsv, + formatListingVenuesTsv, formatPlainDecimal, formatProviderMappingTsv, isValidStrictYmd, + LISTING_STATUTORY_LAG_VENUES, + LISTING_VENUE_BY_MIC, MAX_EXPORT_CHUNK_SIZE, pinCurateInputSnapshot, + resolveListingVenueForMic, type BuildDelistingExportRowsOptions, type BuildDelistingExportRowsResult, type ContinuityExportSourceRow, @@ -79,6 +83,8 @@ export { type ExportCurateInputsResult, type ListingCurrencyExportRow, type ListingDelistingSourceRow, + type ListingStatutoryLagVenue, + type ListingVenueExportRow, type PinnedCurateInputSnapshot, type ProviderMappingExportRow, } from './export-curate-inputs'; @@ -128,6 +134,7 @@ export { export { assertExportRawBsonSafety, + DEFAULT_RAW_BSON_EXPORT_COLLECTIONS, EXPORT_RAW_BSON_USAGE, formatExportRawBsonSummary, parseExportRawBsonArgs, @@ -141,6 +148,11 @@ export { type RunExportRawBsonOutput, } from './run-export-raw-bson'; +export { + assertReadOnlyMongoDiagnosticSafety, + type ReadOnlyMongoDiagnosticSafetyOptions, +} from './read-only-mongo-safety'; + export { escapeSqlLiteral, generateExchangeSeedSql, @@ -360,11 +372,13 @@ export { } from './security-type'; export { + assertProbeSourceFieldShapesSafety, parseProbeSourceFieldShapesArgs, PROBE_SOURCE_FIELD_SHAPES_USAGE, runCli as runProbeSourceFieldShapesCli, runSourceFieldShapesProbe, type ParsedProbeSourceFieldShapesArgs, + type RunProbeSourceFieldShapesCliOverrides, type RunSourceFieldShapesProbeDeps, type RunSourceFieldShapesProbeOptions, type RunSourceFieldShapesProbeOutput, diff --git a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts index b3fbcfca..d1912496 100644 --- a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts +++ b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts @@ -2,8 +2,9 @@ import { mkdir, writeFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { getLogger } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; -import { initializeStockConfig } from '@stock-bot/stock-config'; +import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config'; import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; +import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety'; import { DEFAULT_FIELD_SHAPE_LIMIT, FIELD_SHAPE_PROBE_COLLECTIONS, @@ -45,6 +46,22 @@ export interface RunSourceFieldShapesProbeDeps { readonly writeStdout?: (text: string) => void; } +export interface RunProbeSourceFieldShapesCliOverrides { + readonly initializeConfig?: typeof initializeStockConfig; + readonly assertSafety?: () => void; + readonly createMongoClient?: () => + | Promise<{ + readonly client: ReadOnlyMongoCollectionClient; + readonly close: () => Promise | void; + }> + | { + readonly client: ReadOnlyMongoCollectionClient; + readonly close: () => Promise | void; + }; + readonly writeFile?: (filePath: string, content: string) => Promise | void; + readonly writeStdout?: (text: string) => void; +} + export interface RunSourceFieldShapesProbeOptions { readonly outPath: string; readonly limit?: number; @@ -256,23 +273,72 @@ export async function runSourceFieldShapesProbe( return output; } -export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { +export function assertProbeSourceFieldShapesSafety( + config: StockAppConfig, + env: Record = process.env +): void { + assertReadOnlyMongoDiagnosticSafety( + config, + { + operationLabel: 'probe source field shapes', + diagnosticLabel: 'Source field-shape probe', + }, + env + ); +} + +export async function runCli( + argv: readonly string[] = process.argv.slice(2), + overrides?: RunProbeSourceFieldShapesCliOverrides +): Promise { const parsed = parseProbeSourceFieldShapesArgs(argv); if (parsed.help) { - process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); + const writeStdout = + overrides?.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); return; } const logger = getLogger('source-field-shapes-probe'); - const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); - const mongoConfig = resolveReadOnlyMongoClientConfig(config); - const mongo = new MongoDBClient(mongoConfig, logger); + const initConfig = overrides?.initializeConfig ?? initializeStockConfig; + const config = initConfig('dataPipeline', { mongoReadOnly: true }); - await mongo.connect(); + const assertSafety = + overrides?.assertSafety ?? + (() => { + assertProbeSourceFieldShapesSafety(config, process.env); + }); + assertSafety(); + + const createMongoClient = + overrides?.createMongoClient ?? + (async () => { + const mongoConfig = resolveReadOnlyMongoClientConfig(config); + const mongo = new MongoDBClient(mongoConfig, logger); + await mongo.connect(); + let closed = false; + return { + client: mongo, + async close(): Promise { + if (closed) { + return; + } + closed = true; + await mongo.disconnect(); + }, + }; + }); + + const mongoHandle = await createMongoClient(); await runSourceFieldShapesProbe( { - mongoCollectionClient: mongo, - closeMongo: () => mongo.disconnect(), + mongoCollectionClient: mongoHandle.client, + closeMongo: mongoHandle.close, + writeFile: overrides?.writeFile, + writeStdout: overrides?.writeStdout, }, { outPath: parsed.outPath, diff --git a/apps/stock/data-pipeline/src/security-master/read-only-mongo-safety.ts b/apps/stock/data-pipeline/src/security-master/read-only-mongo-safety.ts new file mode 100644 index 00000000..2fd02527 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/read-only-mongo-safety.ts @@ -0,0 +1,164 @@ +import { assertEnvironmentSafety, type StockAppConfig } from '@stock-bot/stock-config'; +import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; + +export interface ReadOnlyMongoDiagnosticSafetyOptions { + readonly operationLabel: string; + readonly diagnosticLabel: string; +} + +const FORBIDDEN_DIAGNOSTIC_MONGO_USERNAMES: ReadonlySet = new Set(['trading_admin']); + +function hasAsciiControlChar(value: string): boolean { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) { + return true; + } + } + return false; +} + +function extractMongoUsernameFromUri(uri: string): string | undefined { + if (hasAsciiControlChar(uri)) { + throw new Error( + 'Safety guard: MongoDB URI contains forbidden whitespace or control characters.' + ); + } + const trimmed = uri.trim(); + if (!trimmed || /\s/.test(trimmed)) { + throw new Error('Safety guard: MongoDB URI is empty or contains forbidden whitespace.'); + } + + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/is.exec(trimmed); + const rest = schemeMatch?.[2]; + if (!schemeMatch?.[1] || rest === undefined) { + throw new Error('Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.'); + } + + const delimiterMatch = /[/?]/.exec(rest); + const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; + if (!authority) { + throw new Error('Safety guard: MongoDB URI authority is empty.'); + } + if (authority.includes('#')) { + throw new Error( + 'Safety guard: MongoDB URI authority cannot contain an unencoded "#" character.' + ); + } + + const firstAtIndex = authority.indexOf('@'); + if (firstAtIndex === 0) { + throw new Error('Safety guard: MongoDB URI authority cannot have empty userinfo before "@".'); + } + if (firstAtIndex !== -1 && authority.indexOf('@', firstAtIndex + 1) !== -1) { + throw new Error( + 'Safety guard: MongoDB URI authority cannot contain multiple unencoded "@" characters.' + ); + } + if (firstAtIndex < 0) { + return undefined; + } + + const userinfo = authority.slice(0, firstAtIndex); + const colonIndex = userinfo.indexOf(':'); + const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo; + if (!rawUsername) { + return undefined; + } + + try { + return decodeURIComponent(rawUsername); + } catch (error) { + if (error instanceof URIError) { + throw new Error('Safety guard: invalid percent-encoding in MongoDB URI username.'); + } + throw error; + } +} + +/** + * Shared safety guard for strictly read-only MongoDB diagnostic CLIs + * (`probe-source-field-shapes` and `run-export-raw-bson`). + * + * Enforces: + * 1. MongoDB is enabled and configured with `readOnly === true`. + * 2. The exact effective URI resolved by `resolveReadOnlyMongoClientConfig` + * (falling back from unset/blank `readUri` to `uri`) cannot authenticate + * as the QA admin principal (`trading_admin`), regardless of hostname + * (localhost, Compose service `mongodb`, or remote) or `NODE_ENV`. + * 3. Environment safety for `dataPipeline` (with PostgreSQL disabled and + * `STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE` stripped). + */ +export function assertReadOnlyMongoDiagnosticSafety( + config: StockAppConfig, + options: ReadOnlyMongoDiagnosticSafetyOptions, + env: Record = process.env +): void { + const mongo = config.database.mongodb; + if (!mongo.enabled) { + throw new Error(`MongoDB is disabled in configuration; cannot ${options.operationLabel}`); + } + if (mongo.readOnly !== true) { + throw new Error( + `${options.diagnosticLabel} requires read-only MongoDB configuration (database.mongodb.readOnly === true)` + ); + } + + const effectiveMongoConfig = resolveReadOnlyMongoClientConfig(config); + const effectiveUri = effectiveMongoConfig.uri; + const effectiveUsername = + (effectiveUri ? extractMongoUsernameFromUri(effectiveUri) : undefined) ?? + effectiveMongoConfig.username?.trim(); + + if (effectiveUsername && FORBIDDEN_DIAGNOSTIC_MONGO_USERNAMES.has(effectiveUsername)) { + throw new Error( + `Safety guard: ${config.environment} ${options.diagnosticLabel} cannot connect to MongoDB ` + + `with admin credentials ("${effectiveUsername}"). ` + + 'Configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) and enable mongoReadOnly: true.' + ); + } + + const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env; + const mongoOnlyConfig: StockAppConfig = { + ...config, + database: { + ...config.database, + postgres: { + ...config.database.postgres, + enabled: false, + }, + mongodb: { + ...mongo, + uri: effectiveUri ?? mongo.uri, + readUri: effectiveUri, + }, + }, + }; + + assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv); + + if (mongoOnlyConfig.environment !== 'development') { + try { + assertEnvironmentSafety( + { + ...mongoOnlyConfig, + environment: 'development', + }, + 'dataPipeline', + safeEnv + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + if (detail.includes('development data-pipeline')) { + throw new Error( + detail.replace( + 'development data-pipeline', + `${config.environment} ${options.diagnosticLabel}` + ), + { cause: error } + ); + } + throw error; + } + } +} 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 index 38d15920..1f6afaf7 100644 --- 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 @@ -21,7 +21,7 @@ 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}.`, + ` --out-dir Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, ${CURATE_INPUT_FILES.listingVenues}, 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'); @@ -171,6 +171,7 @@ export function formatExportCurateInputsSummary(result: ExportCurateInputsResult `Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`, ` ${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.listingVenues}: rows_in=${result.listingVenues.rowsIn} rows_out=${result.listingVenues.rowsOut} bytes=${result.listingVenues.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}`, ]; diff --git a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts index 17ba87cf..42b32c86 100644 --- a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts +++ b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts @@ -1,10 +1,6 @@ import { getLogger } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; -import { - assertEnvironmentSafety, - initializeStockConfig, - type StockAppConfig, -} from '@stock-bot/stock-config'; +import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config'; import { createReadOnlyMongoRawBsonSource, DEFAULT_RAW_BSON_BATCH_SIZE, @@ -19,13 +15,32 @@ import { type ReadOnlyMongoRawBsonClient, } from './export-raw-bson'; import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; +import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety'; + +/** + * Default collection set when `--collections` is omitted. Preserves the bounded + * M1 set so omitting `--collections` does not trigger an unbounded dump of M2 + * collections (e.g. `eodIntraday1M`). All 14 M1+M2 collections remain + * selectable via `--collections`. + */ +export const DEFAULT_RAW_BSON_EXPORT_COLLECTIONS: readonly RawBsonExportCollection[] = + Object.freeze([ + 'eodPrices', + 'qmSplits', + 'qmDividends', + 'qmPrices', + 'teMarketData', + 'ceoShorts', + 'qmFilings', + 'qmEarnings', + ] as const); export const EXPORT_RAW_BSON_USAGE = [ 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir [--collections ] [--eod-symbol ] [--te-symbol ] [--limit ] [--batch-size ] [--help]', '', 'Options:', ' --out-dir Required. Output directory for .bson files.', - ` --collections Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`, + ` --collections Optional. Comma-separated allowlisted collections (default: ${DEFAULT_RAW_BSON_EXPORT_COLLECTIONS.join(',')}; M2 collections require explicit selection: qmFinancials,qmFinancials-old,ceoPosts,teData,eodIntraday1M,qmIntraday).`, ' --eod-symbol Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).', ' --te-symbol Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).', ' --limit Optional. Max documents to export per collection (positive integer, for smoke runs).', @@ -121,7 +136,7 @@ function parseCollectionsList(raw: string): RawBsonExportCollection[] { throw new RawBsonExportError({ code: 'DISALLOWED_COLLECTION', collection: trimmed, - detail: `collection "${trimmed}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, + detail: `collection "${trimmed}" is not in the M1+M2 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, }); } if (seen.has(trimmed)) { @@ -242,7 +257,7 @@ export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRaw } const resolvedCollections: readonly RawBsonExportCollection[] = - collections ?? [...RAW_BSON_EXPORT_COLLECTIONS]; + collections ?? [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS]; if (eodSymbol !== undefined) { if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') { @@ -275,28 +290,14 @@ export function assertExportRawBsonSafety( config: StockAppConfig, env: Record = process.env ): void { - const mongo = config.database.mongodb; - if (!mongo.enabled) { - throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections'); - } - if (mongo.readOnly !== true) { - throw new Error( - 'Raw BSON exporter requires read-only MongoDB configuration (database.mongodb.readOnly === true)' - ); - } - - const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env; - const mongoOnlyConfig: StockAppConfig = { - ...config, - database: { - ...config.database, - postgres: { - ...config.database.postgres, - enabled: false, - }, + assertReadOnlyMongoDiagnosticSafety( + config, + { + operationLabel: 'export raw BSON collections', + diagnosticLabel: 'Raw BSON exporter', }, - }; - assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv); + env + ); } export function formatExportRawBsonSummary( @@ -327,7 +328,7 @@ export async function runExportRawBson( throw new RawBsonExportError({ code: 'DISALLOWED_COLLECTION', collection: String(collection), - detail: `collection "${String(collection)}" is not in the M1 allowlist`, + detail: `collection "${String(collection)}" is not in the M1+M2 allowlist`, }); } } diff --git a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts index da009d68..02f1a1bf 100644 --- a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts +++ b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts @@ -14,6 +14,12 @@ export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([ 'qmPrices', 'eodPrices', 'teMarketData', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', ] as const); export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]; diff --git a/apps/stock/data-pipeline/test/export-raw-bson.test.ts b/apps/stock/data-pipeline/test/export-raw-bson.test.ts index e1fc3b59..e1c856b6 100644 --- a/apps/stock/data-pipeline/test/export-raw-bson.test.ts +++ b/apps/stock/data-pipeline/test/export-raw-bson.test.ts @@ -446,12 +446,27 @@ describe('exportRawBsonCollection', () => { }; const fsHooks: ExportRawBsonFsHooks = { open: openMock }; - for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) { + for (const disallowed of [ + 'symbols', + 'eodSymbols', + 'eodFundamentalsOLD', + 'eodFinancialsOLD', + 'ttFutures', + ]) { await expect( exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks }) ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed }); } + await expect( + exportRawBsonCollection(source, { + collection: 'eodIntraday1M', + outDir: '/tmp/unused', + eodSymbol: 'AAPL.US', + fs: fsHooks, + }) + ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); + await expect( exportRawBsonCollection(source, { collection: 'teMarketData', @@ -650,7 +665,41 @@ describe('exportRawBsonCollection', () => { }); }); - test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { + test('exports all 6 M2 allowlisted collections including hyphenated qmFinancials-old.bson with valid BSON framing', async () => { + const m2Collections = [ + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ] as const; + + await withTempDir(async outDir => { + for (const collection of m2Collections) { + const doc = { collection, seq: 1 }; + const serialized = Uint8Array.from(BSON.serialize(doc)); + const source = createFakeSource([serialized]); + + const res = await exportRawBsonCollection(source, { collection, outDir }); + expect(res.collection).toBe(collection); + expect(res.outPath).toBe(join(outDir, `${collection}.bson`)); + expect(res.docsWritten).toBe(1); + expect(res.bytesWritten).toBe(serialized.byteLength); + + const bytes = Uint8Array.from(await readFile(res.outPath)); + const frames = walkRawBsonFrames(bytes); + expect(frames).toHaveLength(1); + expect(BSON.deserialize(frames[0]!)).toEqual(doc); + } + + expect((await readdir(outDir)).sort()).toEqual( + m2Collections.map(c => `${c}.bson`).sort() + ); + }); + }); + + test('exports exact M1+M2 allowlist of 14 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([ 'eodPrices', 'qmSplits', @@ -660,6 +709,12 @@ describe('exportRawBsonCollection', () => { 'ceoShorts', 'qmFilings', 'qmEarnings', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', ]); const emptyBson = new Uint8Array([5, 0, 0, 0, 0]); expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson); diff --git a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts index a0c6ab21..56ded565 100644 --- a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts +++ b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts @@ -12,6 +12,7 @@ import { } from '../src/security-master/export-raw-bson'; import { assertExportRawBsonSafety, + DEFAULT_RAW_BSON_EXPORT_COLLECTIONS, EXPORT_RAW_BSON_USAGE, parseExportRawBsonArgs, runCli, @@ -99,9 +100,52 @@ describe('parseExportRawBsonArgs', () => { expect(parsedDefault).toEqual({ help: false, outDir: './tmp/all', + collections: [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS], + batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, + }); + expect(parsedDefault.help).toBe(false); + if (!parsedDefault.help) { + expect(parsedDefault.collections).toHaveLength(8); + expect(parsedDefault.collections).not.toContain('eodIntraday1M'); + expect(parsedDefault.collections).not.toContain('qmFinancials'); + expect(parsedDefault.collections).not.toContain('ceoPosts'); + } + + const parsedAll14 = parseExportRawBsonArgs([ + '--out-dir', + './tmp/all-14', + '--collections', + RAW_BSON_EXPORT_COLLECTIONS.join(','), + ]); + expect(parsedAll14).toEqual({ + help: false, + outDir: './tmp/all-14', collections: [...RAW_BSON_EXPORT_COLLECTIONS], batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, }); + if (!parsedAll14.help) { + expect(parsedAll14.collections).toHaveLength(14); + } + + const parsedM2 = parseExportRawBsonArgs([ + '--out-dir', + './tmp/m2', + '--collections', + 'qmFinancials,qmFinancials-old,ceoPosts,teData,eodIntraday1M,qmIntraday', + ]); + expect(parsedM2).toEqual({ + help: false, + outDir: './tmp/m2', + collections: [ + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ], + batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, + }); expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true }); }); @@ -149,12 +193,20 @@ describe('parseExportRawBsonArgs', () => { }); test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => { + for (const disallowed of [ + 'symbols', + 'eodSymbols', + 'eodFundamentalsOLD', + 'eodFinancialsOLD', + 'ttFutures', + ]) { + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', disallowed]) + ).toThrow(RawBsonExportError); + } expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M']) - ).toThrow(RawBsonExportError); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols']) - ).toThrow(RawBsonExportError); + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M', '--eod-symbol', 'AAPL.US']) + ).toThrow(/--eod-symbol is only permitted/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX']) ).toThrow(/--eod-symbol is only permitted/); @@ -193,9 +245,74 @@ describe('assertExportRawBsonSafety', () => { readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', readOnly: true, }), - {} + { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' } ) ).toThrow(/Safety guard/); + + // QA profile with no MONGODB_READ_URI (or blank readUri) falls back to trading_admin + // and must be rejected regardless of NODE_ENV=qa. + const qaAdminNoReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaAdminBlankReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: ' ', + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaWithReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + + expect(() => assertExportRawBsonSafety(qaAdminNoReadUri, {})).toThrow(/Safety guard/); + expect(() => assertExportRawBsonSafety(qaAdminBlankReadUri, {})).toThrow(/Safety guard/); + expect(() => assertExportRawBsonSafety(qaWithReadUri, {})).not.toThrow(); + + // QA Compose hostname (`mongodb`) with trading_admin (plain or percent-encoded) must also + // be rejected regardless of NODE_ENV, while studio_stock_bot_read@mongodb is permitted. + const qaComposeAdminNoReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaComposeEncodedAdmin = { + ...createBaseConfig({ + uri: 'mongodb://trading%5Fadmin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaComposeWithReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: 'mongodb://studio_stock_bot_read:pw@mongodb:27017/stock?authSource=stock', + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + + expect(() => assertExportRawBsonSafety(qaComposeAdminNoReadUri, {})).toThrow(/Safety guard/); + expect(() => assertExportRawBsonSafety(qaComposeEncodedAdmin, {})).toThrow(/Safety guard/); + expect(() => assertExportRawBsonSafety(qaComposeWithReadUri, {})).not.toThrow(); }); }); @@ -350,7 +467,7 @@ describe('runExportRawBson & runCli', () => { }, { outDir: '/tmp/unused', - collections: ['eodIntraday1M' as never], + collections: ['eodFundamentalsOLD' as never], } ) ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' }); @@ -396,4 +513,43 @@ describe('runExportRawBson & runCli', () => { await rm(outDir, { recursive: true, force: true }); } }); + + test('runCli rejects QA profile with no MONGODB_READ_URI (localhost and Compose mongodb hostname) before connecting to MongoDB', async () => { + const createClientMock = mock(() => { + throw new Error('createMongoClient must not be called when QA admin credentials are active'); + }); + const qaAdminNoReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaComposeAdminNoReadUri = { + ...createBaseConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + + await expect( + runCli(['--out-dir', '/tmp/unused-qa-bson', '--collections', 'eodPrices'], { + initializeConfig: (() => qaAdminNoReadUri) as never, + createMongoClient: createClientMock, + }) + ).rejects.toThrow(/Safety guard/); + + await expect( + runCli(['--out-dir', '/tmp/unused-qa-compose-bson', '--collections', 'eodPrices'], { + initializeConfig: (() => qaComposeAdminNoReadUri) as never, + createMongoClient: createClientMock, + }) + ).rejects.toThrow(/Safety guard/); + + expect(createClientMock).not.toHaveBeenCalled(); + }); }); diff --git a/apps/stock/data-pipeline/test/source-field-shapes.test.ts b/apps/stock/data-pipeline/test/source-field-shapes.test.ts index 47e150e9..f061a076 100644 --- a/apps/stock/data-pipeline/test/source-field-shapes.test.ts +++ b/apps/stock/data-pipeline/test/source-field-shapes.test.ts @@ -1,9 +1,11 @@ -import { describe, expect, test } from 'bun:test'; +import { describe, expect, mock, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; +import type { StockAppConfig } from '@stock-bot/stock-config'; import type { ParserOptions } from 'prettier'; import * as markdownPlugin from 'prettier/plugins/markdown'; import { + assertProbeSourceFieldShapesSafety, DEFAULT_FIELD_SHAPE_LIMIT, DEFAULT_MAX_EXAMPLE_LENGTH, DEFAULT_MAX_EXAMPLES, @@ -13,8 +15,10 @@ import { MAX_EXAMPLES_CAP, MAX_FIELD_SHAPE_LIMIT, parseProbeSourceFieldShapesArgs, + PROBE_SOURCE_FIELD_SHAPES_USAGE, readFieldShapes, renderFieldShapesMarkdown, + runProbeSourceFieldShapesCli, runSourceFieldShapesProbe, STRING_PATTERN_CLASSES, summarizeFieldShapes, @@ -444,14 +448,31 @@ describe('readFieldShapes', () => { expect(amountField.typeCounts.double).toBe(2); }); - test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { + test('defaults to all 14 M1+M2 allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { + expect([...FIELD_SHAPE_PROBE_COLLECTIONS]).toEqual([ + 'ceoShorts', + 'qmSplits', + 'qmDividends', + 'qmFilings', + 'qmEarnings', + 'qmPrices', + 'eodPrices', + 'teMarketData', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ]); + const { reader, calls } = createFakeReader({}); const result = await readFieldShapes(reader); expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT); expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES); expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH); - expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length); + expect(calls.length).toBe(14); for (const call of calls) { expect(call.options).toEqual({ limit: DEFAULT_FIELD_SHAPE_LIMIT, @@ -461,7 +482,45 @@ describe('readFieldShapes', () => { } }); - test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => { + test('probes all 6 M2 collections including hyphenated qmFinancials-old', async () => { + const m2Collections = [ + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ] as const; + + const docsByCollection: Record[]> = { + qmFinancials: [{ qmSearchCode: 'AAPL', periodEndDate: '2024-09-30', revenue: 100 }], + 'qmFinancials-old': [{ qmSearchCode: 'SHOP:CA', periodEndDate: '2023-12-31', revenue: 50 }], + ceoPosts: [{ channel: 'abc', body: 'drilling update', createdAt: new Date('2025-01-02T14:30:00Z') }], + teData: [{ country: 'Canada', indicator: 'CPI', value: 2.1 }], + eodIntraday1M: [{ eodSearchCode: 'AAPL.US', timestamp: 1735828200, close: 243.5 }], + qmIntraday: [{ symbol: 'SHOP:CA', timestamp: '2025-01-02T14:30:00Z', close: 150.2 }], + }; + + const { reader, calls, closedCollections } = createFakeReader(docsByCollection); + const result = await readFieldShapes(reader, { + collections: m2Collections, + limit: 5, + }); + + expect(calls.map(c => c.collectionName)).toEqual([ + 'ceoPosts', + 'eodIntraday1M', + 'qmFinancials', + 'qmFinancials-old', + 'qmIntraday', + 'teData', + ]); + expect(closedCollections).toEqual(calls.map(c => c.collectionName)); + expect(result.totalDocsSampled).toBe(6); + expect(result.collections.map(c => c.collection)).toEqual(calls.map(c => c.collectionName)); + }); + + test('rejects invalid limit, unknown/quarantined collections, and non-read-only reader before any query', async () => { const nonRo = createFakeReader({}, { readOnly: false }); await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i); expect(nonRo.calls.length).toBe(0); @@ -476,16 +535,25 @@ describe('readFieldShapes', () => { await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError); expect(badLimitZero.calls.length).toBe(0); - const unknownCol = createFakeReader({}); - let caught: unknown; - try { - await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] }); - } catch (err) { - caught = err; + for (const disallowed of [ + 'notACollection', + 'symbols', + 'eodSymbols', + 'eodFundamentalsOLD', + 'eodFinancialsOLD', + 'ttFutures', + ]) { + const unknownCol = createFakeReader({}); + let caught: unknown; + try { + await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', disallowed] }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(UnknownProbeCollectionError); + expect((caught as UnknownProbeCollectionError).collectionName).toBe(disallowed); + expect(unknownCol.calls.length).toBe(0); } - expect(caught).toBeInstanceOf(UnknownProbeCollectionError); - expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection'); - expect(unknownCol.calls.length).toBe(0); }); test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => { @@ -809,4 +877,220 @@ describe('CLI arg parsing and headless probe runner', () => { expect(writtenFiles[0]!.content).toBe(output.markdown); expect(stdoutChunks.join('')).toContain('Documents sampled: 1'); }); + + test('assertProbeSourceFieldShapesSafety and runProbeSourceFieldShapesCli enforce mongoReadOnly: true and block QA write bypass', async () => { + const createConfig = ( + overrides: Partial = {} + ): StockAppConfig => + ({ + environment: 'development', + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5432, + database: 'trading_bot', + user: 'trading_user', + password: 'pw', + ssl: false, + poolSize: 5, + idleTimeout: 10000, + connectionTimeout: 5000, + }, + mongodb: { + enabled: true, + uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readOnly: true, + host: 'localhost', + port: 27017, + database: 'stock', + poolSize: 5, + ...overrides, + }, + dragonfly: { enabled: false, host: 'localhost', port: 6380 }, + questdb: { enabled: false, host: 'localhost', port: 9100 }, + }, + }) as unknown as StockAppConfig; + + // Allows read-only dev MongoDB even if Postgres config points to QA. + expect(() => assertProbeSourceFieldShapesSafety(createConfig(), {})).not.toThrow(); + + // Rejects disabled MongoDB, readOnly: false, and admin/writable QA MongoDB even with override env var. + expect(() => assertProbeSourceFieldShapesSafety(createConfig({ enabled: false }), {})).toThrow( + /MongoDB is disabled/ + ); + expect(() => assertProbeSourceFieldShapesSafety(createConfig({ readOnly: false }), {})).toThrow( + /read-only MongoDB configuration/ + ); + expect(() => + assertProbeSourceFieldShapesSafety( + createConfig({ + readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', + readOnly: true, + }), + { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' } + ) + ).toThrow(/Safety guard/); + + // --help performs zero config or Mongo I/O. + const helpStdout: string[] = []; + const initNeverMock = mock(() => { + throw new Error('initializeConfig must not be called on --help'); + }); + const clientNeverMock = mock(() => { + throw new Error('createMongoClient must not be called on --help'); + }); + await runProbeSourceFieldShapesCli(['--help'], { + initializeConfig: initNeverMock as never, + createMongoClient: clientNeverMock, + writeStdout: text => helpStdout.push(text), + }); + expect(helpStdout.join('')).toBe(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); + expect(initNeverMock).not.toHaveBeenCalled(); + expect(clientNeverMock).not.toHaveBeenCalled(); + + // Normal CLI run initializes config with mongoReadOnly: true and probes M2 collection. + const initCalls: Array<{ service: string; opts: unknown }> = []; + const written: Array<{ filePath: string; content: string }> = []; + const stdout: string[] = []; + let closed = 0; + + await runProbeSourceFieldShapesCli( + ['--out', './tmp/m2-probe.md', '--limit', '5', '--collections', 'qmFinancials-old,teData'], + { + initializeConfig: ((service: string, opts?: unknown) => { + initCalls.push({ service, opts }); + return createConfig(); + }) as never, + createMongoClient: async () => ({ + client: { + isReadOnly: () => true, + getCollection: (name: string) => ({ + find: () => ({ + async *[Symbol.asyncIterator]() { + yield { collectionTag: name, v: 1 }; + }, + async close() {}, + }), + }), + }, + close: () => { + closed += 1; + }, + }), + writeFile: (filePath, content) => { + written.push({ filePath, content }); + }, + writeStdout: text => { + stdout.push(text); + }, + } + ); + + expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]); + expect(closed).toBe(1); + expect(written).toHaveLength(1); + expect(written[0]!.filePath).toBe('./tmp/m2-probe.md'); + expect(written[0]!.content).toContain('qmFinancials-old'); + expect(written[0]!.content).toContain('teData'); + expect(stdout.join('')).toContain('Documents sampled: 2'); + + // Safety failure blocks createMongoClient. + await expect( + runProbeSourceFieldShapesCli(['--out', './tmp/blocked.md', '--collections', 'ceoPosts'], { + initializeConfig: (() => createConfig({ readOnly: false })) as never, + createMongoClient: clientNeverMock, + }) + ).rejects.toThrow(/read-only MongoDB configuration/); + expect(clientNeverMock).not.toHaveBeenCalled(); + + // QA profile with no MONGODB_READ_URI (or whitespace-only readUri) falls back to trading_admin + // and must be rejected before connecting, regardless of NODE_ENV=qa. + const qaAdminNoReadUri = { + ...createConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaAdminBlankReadUri = { + ...createConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: ' ', + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaWithReadUri = { + ...createConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readOnly: true, + }), + environment: 'qa', + } as unknown as StockAppConfig; + + expect(() => assertProbeSourceFieldShapesSafety(qaAdminNoReadUri, {})).toThrow(/Safety guard/); + expect(() => assertProbeSourceFieldShapesSafety(qaAdminBlankReadUri, {})).toThrow( + /Safety guard/ + ); + expect(() => assertProbeSourceFieldShapesSafety(qaWithReadUri, {})).not.toThrow(); + + // QA Compose hostname (`mongodb`) with trading_admin (plain or percent-encoded) must also + // be rejected regardless of NODE_ENV, while studio_stock_bot_read@mongodb is permitted. + const qaComposeAdminNoReadUri = { + ...createConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaComposeEncodedAdmin = { + ...createConfig({ + uri: 'mongodb://trading%5Fadmin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: undefined, + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + const qaComposeWithReadUri = { + ...createConfig({ + uri: 'mongodb://trading_admin:trading_mongo_dev@mongodb:27017/stock?authSource=admin', + readUri: 'mongodb://studio_stock_bot_read:pw@mongodb:27017/stock?authSource=stock', + readOnly: true, + host: 'mongodb', + }), + environment: 'qa', + } as unknown as StockAppConfig; + + expect(() => assertProbeSourceFieldShapesSafety(qaComposeAdminNoReadUri, {})).toThrow( + /Safety guard/ + ); + expect(() => assertProbeSourceFieldShapesSafety(qaComposeEncodedAdmin, {})).toThrow( + /Safety guard/ + ); + expect(() => assertProbeSourceFieldShapesSafety(qaComposeWithReadUri, {})).not.toThrow(); + + await expect( + runProbeSourceFieldShapesCli(['--out', './tmp/qa-blocked.md', '--collections', 'ceoPosts'], { + initializeConfig: (() => qaAdminNoReadUri) as never, + createMongoClient: clientNeverMock, + }) + ).rejects.toThrow(/Safety guard/); + await expect( + runProbeSourceFieldShapesCli( + ['--out', './tmp/qa-compose-blocked.md', '--collections', 'ceoPosts'], + { + initializeConfig: (() => qaComposeAdminNoReadUri) as never, + createMongoClient: clientNeverMock, + } + ) + ).rejects.toThrow(/Safety guard/); + expect(clientNeverMock).not.toHaveBeenCalled(); + }); }); diff --git a/bun.lock b/bun.lock index 9a537c0b..fef35d9e 100644 --- a/bun.lock +++ b/bun.lock @@ -360,6 +360,7 @@ "version": "1.0.0", "dependencies": { "@duckdb/node-api": "^1.4.4-r.1", + "@stock-bot/questdb": "workspace:*", "@stock-bot/research": "workspace:*", }, "devDependencies": { diff --git a/libs/data/duckdb/package.json b/libs/data/duckdb/package.json index 7636fd30..c509a91f 100644 --- a/libs/data/duckdb/package.json +++ b/libs/data/duckdb/package.json @@ -15,6 +15,7 @@ }, "dependencies": { "@duckdb/node-api": "^1.4.4-r.1", + "@stock-bot/questdb": "workspace:*", "@stock-bot/research": "workspace:*" }, "devDependencies": { diff --git a/libs/data/duckdb/src/research-copilot-store.ts b/libs/data/duckdb/src/research-copilot-store.ts index 941c2c53..c44d4802 100644 --- a/libs/data/duckdb/src/research-copilot-store.ts +++ b/libs/data/duckdb/src/research-copilot-store.ts @@ -3,15 +3,23 @@ * (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`). * * - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared - * between the host and the underlying DuckDB store, and hardcodes - * `vaultOperatorAuthorized: false` so every query remains strictly - * `'vault_fenced'`. + * between the host, the underlying DuckDB store, and (when configured) the + * QuestDB intraday reader, hardcoding `vaultOperatorAuthorized: false` so + * every query remains strictly `'vault_fenced'`. * - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose - * `close()` releases the underlying DuckDB connection and instance. - * - Any failure during open (native connection creation or store validation) - * releases already-acquired DuckDB resources before rejecting. + * `close()` idempotently releases all acquired DuckDB and QuestDB resources. + * - Any failure during open (native connection creation, store validation, or + * optional QuestDB executor startup) releases already-acquired resources + * before rejecting. */ +import { + openQuestDbPgExecutor, + type QuestDbPgExecutorConfig, + type QuestDbPgExecutorHandle, +} from '@stock-bot/questdb'; +import { createQuestDbIntradayReader } from '@stock-bot/research/market-data-store-questdb'; +import { createRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; import type { ManagedMarketDataStore, ResearchCopilotHostConfig, @@ -19,16 +27,23 @@ import type { } from '@stock-bot/research/mcp'; import { openDuckDbMarketDataStore } from './index'; +export type QuestDbExecutorOpener = ( + config: QuestDbPgExecutorConfig +) => Promise; + export interface OpenResearchCopilotStoreOptions { /** Optional DuckDB database path; defaults to `':memory:'`. */ readonly databasePath?: string; /** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */ readonly env?: Readonly>; + /** Optional override for opening the QuestDB intraday executor (defaults to `openQuestDbPgExecutor`). */ + readonly openQuestDbExecutor?: QuestDbExecutorOpener; } /** - * Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a - * validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`. + * Opens a Vault-fenced DuckDB-backed (and optionally QuestDB-routed for 1m + * intraday `bars` and `fx`) {@link ManagedMarketDataStore} from a validated + * {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`. */ export const openResearchCopilotStore = (async ( config: ResearchCopilotHostConfig, @@ -42,8 +57,66 @@ export const openResearchCopilotStore = (async ( ...(options?.env !== undefined ? { env: options.env } : {}), }); + if (config.questdb === undefined) { + return { + store: opened.store, + close: opened.close, + }; + } + + const opener = options?.openQuestDbExecutor ?? openQuestDbPgExecutor; + let questHandle: QuestDbPgExecutorHandle; + try { + questHandle = await opener(config.questdb); + } catch (err: unknown) { + await opened.close().catch(() => undefined); + throw err; + } + + let routedStore: ManagedMarketDataStore['store']; + try { + const intraday = createQuestDbIntradayReader({ + executor: questHandle.executor, + vaultCutoffTs: config.vaultCutoffTs, + vaultOperatorAuthorized: false, + }); + routedStore = createRoutedMarketDataStore({ + daily: opened.store, + intraday, + }); + } catch (err: unknown) { + await questHandle.close().catch(() => undefined); + await opened.close().catch(() => undefined); + throw err; + } + + let closePromise: Promise | null = null; + const close = (): Promise => { + if (closePromise === null) { + closePromise = (async () => { + let firstError: unknown; + try { + await questHandle.close(); + } catch (err: unknown) { + firstError = err; + } + try { + await opened.close(); + } catch (err: unknown) { + if (firstError === undefined) { + firstError = err; + } + } + if (firstError !== undefined) { + throw firstError; + } + })(); + } + return closePromise; + }; + return { - store: opened.store, - close: opened.close, + store: routedStore, + close, }; }) satisfies ResearchCopilotStdioHostDeps['openStore']; diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts index dfe3259c..330287f0 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -1,12 +1,19 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rm } from 'node:fs/promises'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { computeVaultCutoffTs, + MarketDataStoreValidationError, VaultHoldoutFenceError, type BarRecord, } from '@stock-bot/research/market-data-store'; +import { + createEventStudyTool, + createMcpServer, + type EventStudyResultPayload, +} from '@stock-bot/research/mcp'; +import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger'; import { createNodeDuckDbExecutor, openDuckDbMarketDataStore, @@ -929,3 +936,844 @@ describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-ap } }); }); + +function createInMemoryTrialLedger(): TrialLedgerExecutor { + const rows: Array> = []; + let nextTrialId = 1; + return { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const trialId = String(nextTrialId++); + const createdAt = new Date(Date.UTC(2024, 5, 20, 12, 0, nextTrialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored = { + trial_id: trialId, + created_at: createdAt, + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: dailySeries, + }; + rows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + rowCount: 1, + }; + } + if (trimmed.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = rows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = rows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + return { rows: [], rowCount: 0 }; + }, + }; +} + +describe('co-published events (part.parquet + part-posts.parquet) via real DuckDB & MCP event_study', () => { + test('queries filing, earnings, and edited ceo_post together with PIT known_at anchoring and Vault isolation', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-events-copub-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + + await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true }); + await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + // Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z + const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); + const sessions = [ + '2024-06-03', + '2024-06-04', + '2024-06-05', + '2024-06-06', + '2024-06-07', + '2024-06-10', + '2024-06-11', + '2024-06-12', + '2024-06-13', + '2024-06-14', + ]; + // Deterministic close paths: + // listing 101: +2% on 06-05 (filing), +3% on 06-07 (earnings), +1% on 06-11 (filing) + // listing 202: +4% on 06-06 (filing), +5% on 06-10 (earnings), 0% on 06-12 (posted_at), +10% on 06-13 (known_at anchor) + const closes101 = [100, 101, 103.02, 103.02, 106.1106, 106.1106, 107.171706, 107.171706, 107.171706, 107.171706]; + const closes202 = [100, 100, 100, 104, 104, 109.2, 109.2, 109.2, 120.12, 120.12]; + + const barValues: string[] = []; + for (let i = 0; i < sessions.length; i += 1) { + const d = sessions[i]!; + const c1 = closes101[i]!; + const c2 = closes202[i]!; + barValues.push( + `(101::INTEGER, DATE '${d}', TIMESTAMPTZ '${d} 20:00:00+00', ${c1}::DOUBLE, ${c1}::DOUBLE, ${c1}::DOUBLE, ${c1}::DOUBLE, 100000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '${d} 20:00:00+00')`, + `(202::INTEGER, DATE '${d}', TIMESTAMPTZ '${d} 20:00:00+00', ${c2}::DOUBLE, ${c2}::DOUBLE, ${c2}::DOUBLE, ${c2}::DOUBLE, 100000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '${d} 20:00:00+00')` + ); + } + + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ${barValues.join(',\n ')} + ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) + `); + + // Co-published filings & earnings in events/year=2024/part.parquet + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, '8-k'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR), + (202::INTEGER, TIMESTAMPTZ '2024-06-06 14:30:00+00', TIMESTAMPTZ '2024-06-06 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, '8-k'::VARCHAR, '{"filing_id":"f2"}'::VARCHAR), + (101::INTEGER, TIMESTAMPTZ '2024-06-07 14:30:00+00', TIMESTAMPTZ '2024-06-07 14:30:00+00', 'filing_timestamp'::VARCHAR, 'earnings'::VARCHAR, 'bto'::VARCHAR, '{"quarter":"Q1"}'::VARCHAR), + (202::INTEGER, TIMESTAMPTZ '2024-06-10 14:30:00+00', TIMESTAMPTZ '2024-06-10 14:30:00+00', 'filing_timestamp'::VARCHAR, 'earnings'::VARCHAR, 'bto'::VARCHAR, '{"quarter":"Q1"}'::VARCHAR), + (101::INTEGER, TIMESTAMPTZ '2024-06-11 14:30:00+00', TIMESTAMPTZ '2024-06-11 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'md&a'::VARCHAR, '{"filing_id":"f3"}'::VARCHAR) + ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) + ) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) + `); + + // Co-published ceoPosts in events/year=2024/part-posts.parquet: + // 1. Edited ceo_post: posted 2024-06-12 15:00 UTC (11:00 EDT, BEFORE 16:00 ET close), + // edited 2024-06-12 21:30 UTC (17:30 EDT, AFTER 16:00 ET close) -> anchors to 2024-06-13. + // 2. Post-cutoff Vault holdout row: ts in 2024, known_at = 2025-02-14 >= vaultCutoffTs. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (202::INTEGER, TIMESTAMPTZ '2024-06-12 15:00:00+00', TIMESTAMPTZ '2024-06-12 21:30:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"sp-edit-1","user_id":"u1","is_edited":true,"source":"ceo_posts","text":"edited after close"}'::VARCHAR), + (202::INTEGER, TIMESTAMPTZ '2024-12-30 15:00:00+00', TIMESTAMPTZ '2025-02-14 15:00:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"sp-vault-1","user_id":"u2","is_edited":true,"source":"ceo_posts","text":"vault holdout"}'::VARCHAR) + ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) + ) TO '${join(curatedRoot, 'events', 'year=2024', 'part-posts.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + // Place dummy transient files (.tmp, .bak, .write.lock) to prove events/year=*/*.parquet ignores them. + await writeFile(join(curatedRoot, 'events', 'year=2024', 'part.parquet.99999-0.tmp'), 'not-parquet'); + await writeFile(join(curatedRoot, 'events', 'year=2024', 'part.parquet.99999-0.bak'), 'not-parquet'); + await writeFile(join(curatedRoot, 'events', '.write.lock'), '99999\n'); + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + + try { + // 1. store.events with asOf < edited hides the edited ceo_post. + const beforeEdit = await opened.store.events({ + kinds: ['filing', 'earnings', 'ceo_post'], + from: '2024-06-01', + to: '2024-12-31', + asOf: '2024-06-12T21:00:00Z', + }); + expect(beforeEdit.rows.length).toBe(5); + expect(beforeEdit.rows.map(r => r.kind)).toEqual([ + 'filing', + 'earnings', + 'filing', + 'filing', + 'earnings', + ]); + + // 2. store.events with asOf >= edited returns filing, earnings, and edited ceo_post together, + // while excluding the post-cutoff Vault row (known_at = 2025-02-14 >= vaultCutoffTs). + const afterEdit = await opened.store.events({ + kinds: ['filing', 'earnings', 'ceo_post'], + from: '2024-06-01', + to: '2024-12-31', + asOf: '2025-02-12T23:59:59Z', + }); + expect(afterEdit.rows.length).toBe(6); + expect(afterEdit.rows.map(r => [r.listing_id, r.kind, r.known_at_source])).toEqual([ + [101, 'filing', 'filing_timestamp'], + [101, 'earnings', 'filing_timestamp'], + [101, 'filing', 'filing_timestamp'], + [202, 'filing', 'filing_timestamp'], + [202, 'earnings', 'filing_timestamp'], + [202, 'ceo_post', 'post_edited'], + ]); + const postRow = afterEdit.rows[5]!; + expect(postRow.ts).toBe(Date.parse('2024-06-12T15:00:00.000Z')); + expect(postRow.known_at).toBe(Date.parse('2024-06-12T21:30:00.000Z')); + expect(afterEdit.rows.some(r => String(r.payload_json).includes('sp-vault-1'))).toBe(false); + + // 3. MCP event_study over real DuckDB store: + // - asOf < edited excludes the edited ceo_post (5 events, offset-0 AAR = 0.15 / 5 = 0.03) + // - asOf >= edited includes all 6 events and anchors the post-close edit to 2024-06-13 + // (+10% return -> offset-0 AAR = 0.25 / 6, NOT 0.15 / 6 from 2024-06-12's 0% return). + const tool = createEventStudyTool({ + store: opened.store, + ledger: createInMemoryTrialLedger(), + vaultContext: { vaultCutoffTs }, + principalId: 'agent:11111111-2222-4333-8444-555555555555', + resolveExchangeCalendars: q => ({ + calendars: { + XTSE: sessions + .filter(date => date >= q.fromDate && date <= q.toDate) + .map(date => ({ date, closeTs: Date.parse(`${date}T20:00:00.000Z`) })), + }, + listingCalendarId: { 101: 'XTSE', 202: 'XTSE' }, + }), + }); + const server = createMcpServer({ name: 'test-copub-mcp', version: '0.1.0', tools: [tool] }); + + const runStudy = async (asOf: string, id: number): Promise => { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { + name: 'event_study', + arguments: { + listingIds: [101, 202], + from: '2024-06-03', + to: '2024-06-14', + asOf, + event: { kinds: ['filing', 'earnings', 'ceo_post'] }, + preDays: 1, + postDays: 1, + benchmark: 'none', + adjustment: 'raw', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }, + }) + ); + const rpc = JSON.parse(raw!) as { + result: { content: Array<{ type: string; text: string }>; isError?: boolean }; + }; + expect(rpc.result.isError).not.toBe(true); + return JSON.parse(rpc.result.content[0]!.text) as EventStudyResultPayload; + }; + + const studyBeforeEdit = await runStudy('2024-06-12T21:00:00Z', 1); + expect(studyBeforeEdit.status).toBe('ok'); + expect(studyBeforeEdit.eventCount).toBe(5); + expect(studyBeforeEdit.study.diagnostics.eventsUsed).toBe(5); + expect(studyBeforeEdit.study.clustered?.nDates).toBe(5); + const aar0Before = studyBeforeEdit.study.offsets.find(o => o.offset === 0)!.aar; + expect(aar0Before).toBeCloseTo(0.15 / 5, 10); + + const studyAfterEdit = await runStudy('2024-06-14T23:59:59Z', 2); + expect(studyAfterEdit.status).toBe('ok'); + expect(studyAfterEdit.eventCount).toBe(6); + expect(studyAfterEdit.study.diagnostics.eventsUsed).toBe(6); + expect(studyAfterEdit.study.clustered?.nDates).toBe(6); + const aar0After = studyAfterEdit.study.offsets.find(o => o.offset === 0)!.aar; + // Anchoring to 2024-06-13 (+10%) yields 0.25 / 6; anchoring to 2024-06-12 (0%) would yield 0.15 / 6. + expect(aar0After).toBeCloseTo(0.25 / 6, 10); + } finally { + await opened.close(); + } + }); +}); + +describe('co-published ceo_post Vault boundary via real DuckDB (store.events + MCP event_study)', () => { + test('posts-only partition is read; known_at/ts at the cutoff are fenced; from >= cutoff is rejected', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-events-vault-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); + await mkdir(join(curatedRoot, 'events', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + // Vault cutoff = 2025-02-13T00:00:00.000Z + const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); + expect(vaultCutoffTs).toBe(Date.parse('2025-02-13T00:00:00.000Z')); + const sessions = ['2025-02-06', '2025-02-07', '2025-02-10', '2025-02-11', '2025-02-12']; + + const writer = await createNodeDuckDbExecutor(); + try { + const barValues = sessions.map( + d => + `(303::INTEGER, DATE '${d}', TIMESTAMPTZ '${d} 21:00:00+00', 10.0::DOUBLE, 10.0::DOUBLE, 10.0::DOUBLE, 10.0::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '${d} 21:00:00+00')` + ); + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${barValues.join(',')}) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + // Posts-only year partition: no events/year=2025/part.parquet exists at all. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (303::INTEGER, TIMESTAMPTZ '2025-02-10 15:00:00+00', TIMESTAMPTZ '2025-02-10 15:00:00+00', 'post_timestamp'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"in-1"}'::VARCHAR), + (303::INTEGER, TIMESTAMPTZ '2025-02-12 15:00:00+00', TIMESTAMPTZ '2025-02-12 23:59:59.999+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"edge-in"}'::VARCHAR), + (303::INTEGER, TIMESTAMPTZ '2025-02-12 16:00:00+00', TIMESTAMPTZ '2025-02-13 00:00:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"edge-known-at-cutoff"}'::VARCHAR), + (303::INTEGER, TIMESTAMPTZ '2025-02-13 00:00:00+00', TIMESTAMPTZ '2025-02-13 00:00:00+00', 'post_timestamp'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{"spiel_id":"edge-ts-at-cutoff"}'::VARCHAR) + ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) + ) TO '${join(curatedRoot, 'events', 'year=2025', 'part-posts.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + // asOf and to both beyond the cutoff: the fence clamps them to cutoff - 1 ms, so only rows with + // ts < cutoff AND known_at < cutoff survive (the edit landing exactly on the cutoff is hidden). + const clamped = await opened.store.events({ + kinds: ['ceo_post'], + from: '2025-01-01', + to: '2025-12-31', + asOf: '2025-08-01T00:00:00Z', + }); + expect( + clamped.rows.map(r => (JSON.parse(String(r.payload_json)) as { spiel_id: string }).spiel_id) + ).toEqual(['in-1', 'edge-in']); + expect(clamped.rows.every(r => r.ts < vaultCutoffTs && r.known_at < vaultCutoffTs)).toBe(true); + + // Omitted asOf behaves the same way (defaults to cutoff - 1 ms). + const defaulted = await opened.store.events({ + kinds: ['ceo_post', 'filing', 'earnings'], + from: '2025-01-01', + to: '2025-12-31', + }); + expect(defaulted.rows.length).toBe(2); + + // Requests starting at the cutoff are rejected, not silently empty. + let rejectedError: unknown; + try { + await opened.store.events({ kinds: ['ceo_post'], from: '2025-02-13', to: '2025-03-01' }); + } catch (err) { + rejectedError = err; + } + expect(rejectedError).toBeInstanceOf(VaultHoldoutFenceError); + + const tool = createEventStudyTool({ + store: opened.store, + ledger: createInMemoryTrialLedger(), + vaultContext: { vaultCutoffTs }, + principalId: 'agent:11111111-2222-4333-8444-555555555555', + resolveExchangeCalendars: q => ({ + calendars: { + XTSE: sessions + .filter(date => date >= q.fromDate && date <= q.toDate) + .map(date => ({ date, closeTs: Date.parse(`${date}T21:00:00.000Z`) })), + }, + listingCalendarId: { 303: 'XTSE' }, + }), + }); + const server = createMcpServer({ name: 'test-vault-mcp', version: '0.1.0', tools: [tool] }); + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'event_study', + arguments: { + listingIds: [303], + from: '2025-02-13', + to: '2025-03-01', + event: { kinds: ['ceo_post'] }, + preDays: 1, + postDays: 1, + benchmark: 'none', + adjustment: 'raw', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }, + }) + ); + const rpc = JSON.parse(raw!) as { + result?: { content: Array<{ type: string; text: string }>; isError?: boolean }; + error?: { message: string }; + }; + // MCP must refuse a study window that starts inside the Vault (JSON-RPC error or tool error), + // never return an 'ok' study, and never leak the at-cutoff post. + expect(rpc.error !== undefined || rpc.result?.isError === true).toBe(true); + expect(raw!).not.toContain('edge-ts-at-cutoff'); + expect(raw!).not.toContain('edge-known-at-cutoff'); + } finally { + await opened.close(); + } + }); +}); + +describe('macroAsOf and crossSection via real DuckDB', () => { + test('macroAsOf enforces country/indicator/date filtering, known_at <= asOf lag, Vault fence, and fail-closed provenance', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-macro-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'macro'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 4, 1, 0, 0, 0, 0); // 2025-05-01T00:00:00Z + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.50::DOUBLE), + ('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 3.00::DOUBLE), + ('CA'::VARCHAR, 'gdp_qoq'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-04-06 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 1.80::DOUBLE), + ('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-04-30', TIMESTAMPTZ '2025-05-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.25::DOUBLE) + ) AS t(country_iso, indicator, period_date, known_at, known_at_source, value) + ) TO '${join(curatedRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + // Early asOf sees +1d policy_rate, hides +35d cpi_yoy and +65d gdp_qoq. + const feb = await opened.store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'], + from: '2025-01-01', + to: '2025-06-01', + asOf: '2025-02-15', + }); + expect(feb.rows.map(r => `${r.country_iso}:${r.indicator}`)).toEqual(['US:policy_rate']); + + // Post-cutoff to/asOf clamps strictly below 2025-05-01T00:00:00Z, hiding the at-cutoff row. + const clamped = await opened.store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['policy_rate', 'cpi_yoy', 'gdp_qoq'], + from: '2025-01-01', + to: '2025-06-01', + asOf: '2025-06-01', + }); + expect(clamped.rows.map(r => `${r.country_iso}:${r.indicator}:${r.period_date}`)).toEqual([ + 'CA:gdp_qoq:2025-01-31', + 'US:cpi_yoy:2025-01-31', + 'US:policy_rate:2025-01-31', + ]); + + // from >= vaultCutoffTs throws VaultHoldoutFenceError. + await expect( + opened.store.macroAsOf({ + countries: ['US'], + indicators: ['policy_rate'], + from: '2025-05-01', + to: '2025-05-15', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + } finally { + await opened.close(); + } + + // Corrupt provenance row fails closed with MarketDataStoreValidationError. + const corruptRoot = join(root, 'corrupt-curated'); + await mkdir(join(corruptRoot, 'macro'), { recursive: true }); + const corruptWriter = await createNodeDuckDbExecutor(); + try { + await corruptWriter.run(` + COPY ( + SELECT * FROM (VALUES + ('US'::VARCHAR, 'cpi_yoy'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-03-07 00:00:00+00', 'bad_source'::VARCHAR, 3.00::DOUBLE) + ) AS t(country_iso, indicator, period_date, known_at, known_at_source, value) + ) TO '${join(corruptRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await corruptWriter.close(); + } + const corruptOpened = await openDuckDbMarketDataStore({ + curatedRoot: corruptRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + await expect( + corruptOpened.store.macroAsOf({ + countries: ['US'], + indicators: ['cpi_yoy'], + from: '2025-01-01', + to: '2025-04-01', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + } finally { + await corruptOpened.close(); + } + }); + + test('crossSection joins versioned features to survivorship-free universe, null-fills missing/delayed rows, and enforces Vault fence', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); + await mkdir(join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025'), { recursive: true }); + await mkdir(join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 4, 15, 0, 0, 0, 0); // 2025-05-15T00:00:00Z + const writer = await createNodeDuckDbExecutor(); + try { + // Active on 2025-05-10: 101 (USD), 102 (USD), 201 (CAD). Delisted earlier: 103 (USD, 2025-04-01). + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 10.0::DOUBLE, 11.0::DOUBLE, 9.5::DOUBLE, 10.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'), + (102::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 20.0::DOUBLE, 21.0::DOUBLE, 19.5::DOUBLE, 20.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00'), + (103::INTEGER, DATE '2025-04-01', TIMESTAMPTZ '2025-04-01 20:00:00+00', 5.0::DOUBLE, 5.5::DOUBLE, 4.5::DOUBLE, 5.0::DOUBLE, 500.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-04-01 20:00:00+00'), + (201::INTEGER, DATE '2025-05-09', TIMESTAMPTZ '2025-05-09 20:00:00+00', 30.0::DOUBLE, 31.0::DOUBLE, 29.5::DOUBLE, 30.5::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2025-05-09 20:00:00+00') + ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + + // ret_1d@v1: 101 known on 2025-05-09; 102 delayed until 2025-05-12; 201 known on 2025-05-09. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 0.02::DOUBLE), + (102::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-12 20:00:00+00', 0.05::DOUBLE), + (201::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', -0.01::DOUBLE) + ) AS t(listing_id, ts, known_at, value) + ) TO '${join(curatedRoot, 'features', 'ret_1d', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + + // rsi_14@v1: only listing 101 present. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, TIMESTAMPTZ '2025-05-09 20:00:00+00', TIMESTAMPTZ '2025-05-09 20:00:00+00', 62.5::DOUBLE) + ) AS t(listing_id, ts, known_at, value) + ) TO '${join(curatedRoot, 'features', 'rsi_14', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + try { + // Omitted asOf defaults to q.date (2025-05-09) so 102's delayed ret_1d (known 2025-05-12) is NULL. + const usSameDay = await opened.store.crossSection({ + features: ['ret_1d@v1', 'rsi_14@v1'], + date: '2025-05-09', + universe: 'US_EQ', + }); + expect(usSameDay.columns).toEqual(['listing_id', 'ret_1d@v1', 'rsi_14@v1']); + expect(usSameDay.rows).toEqual([ + { listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 }, + { listing_id: 102, 'ret_1d@v1': null, 'rsi_14@v1': null }, + ]); + + // Explicit later asOf (2025-05-13) reveals 102's delayed ret_1d@v1 while US_CA_EQ includes 201. + const usCaLater = await opened.store.crossSection({ + features: ['ret_1d@v1', 'rsi_14@v1'], + date: '2025-05-09', + universe: 'US_CA_EQ', + asOf: '2025-05-13', + }); + expect(usCaLater.rows).toEqual([ + { listing_id: 101, 'ret_1d@v1': 0.02, 'rsi_14@v1': 62.5 }, + { listing_id: 102, 'ret_1d@v1': 0.05, 'rsi_14@v1': null }, + { listing_id: 201, 'ret_1d@v1': -0.01, 'rsi_14@v1': null }, + ]); + + // Post-cutoff date throws VaultHoldoutFenceError. + await expect( + opened.store.crossSection({ + features: ['ret_1d@v1'], + date: '2025-05-15', + universe: 'US_EQ', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + } finally { + await opened.close(); + } + }); +}); + +describe('macroAsOf and crossSection point-in-time edge cases via real DuckDB (QA)', () => { + const budgetEnv = (duckTempDir: string) => ({ + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }); + + test('crossSection keeps recently delisted listings, picks latest pre-asOf restatement, and never leaks post-cutoff bars or feature revisions', async () => { + // Arrange + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-pit-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); + await mkdir(join(curatedRoot, 'features', 'mom_5d', 'v2', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 4, 15, 0, 0, 0, 0); // 2025-05-15T00:00:00Z + const writer = await createNodeDuckDbExecutor(); + try { + // 301: last bar 2025-05-08 (inside 7-day lookback from 2025-05-14) -> recently delisted, kept. + // 302: last bar 2025-05-06 (outside lookback) -> excluded. + // 303: first bar 2025-05-15 (post-cutoff session) -> excluded. + // 304: 2025-05-14 bar whose known_at lands after the cutoff -> excluded even with a late asOf. + // 305: active 2025-05-14. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (301::INTEGER, DATE '2025-05-08', TIMESTAMPTZ '2025-05-08 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-08 20:00:00+00'), + (302::INTEGER, DATE '2025-05-06', TIMESTAMPTZ '2025-05-06 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-06 20:00:00+00'), + (303::INTEGER, DATE '2025-05-15', TIMESTAMPTZ '2025-05-15 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-15 20:00:00+00'), + (304::INTEGER, DATE '2025-05-14', TIMESTAMPTZ '2025-05-14 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-15 01:00:00+00'), + (305::INTEGER, DATE '2025-05-14', TIMESTAMPTZ '2025-05-14 20:00:00+00', 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 1.0::DOUBLE, 10.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-14 20:00:00+00') + ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + + // mom_5d@v2: + // - 305: original (known 20:00, 1.0), restatement (known 22:00, 1.5), post-cutoff restatement (9.9). + // - 301: prior-day and next-day rows only -> no same-day value. + // - 304: same-day value, but listing is outside the PIT universe. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (305::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-14 20:00:00+00', 1.0::DOUBLE), + (305::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-14 22:00:00+00', 1.5::DOUBLE), + (305::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-15 01:00:00+00', 9.9::DOUBLE), + (301::INTEGER, TIMESTAMPTZ '2025-05-13 20:00:00+00', TIMESTAMPTZ '2025-05-13 20:00:00+00', 2.0::DOUBLE), + (301::INTEGER, TIMESTAMPTZ '2025-05-15 20:00:00+00', TIMESTAMPTZ '2025-05-15 20:00:00+00', 3.0::DOUBLE), + (304::INTEGER, TIMESTAMPTZ '2025-05-14 20:00:00+00', TIMESTAMPTZ '2025-05-14 20:00:00+00', 4.0::DOUBLE) + ) AS t(listing_id, ts, known_at, value) + ) TO '${join(curatedRoot, 'features', 'mom_5d', 'v2', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: budgetEnv(duckTempDir), + }); + try { + // Act: asOf requested past the cutoff must clamp strictly below it. + const late = await opened.store.crossSection({ + features: ['mom_5d@v2'], + date: '2025-05-14', + universe: 'US_EQ', + asOf: '2025-06-30', + }); + // Act: asOf between original and restatement sees only the original. + const early = await opened.store.crossSection({ + features: ['mom_5d@v2'], + date: '2025-05-14', + universe: 'US_EQ', + asOf: '2025-05-14T21:00:00Z', + }); + // Act: CA universe has no CAD listings at all. + const ca = await opened.store.crossSection({ + features: ['mom_5d@v2'], + date: '2025-05-14', + universe: 'CA_EQ', + }); + + // Assert + expect(late.columns).toEqual(['listing_id', 'mom_5d@v2']); + expect(late.rows).toEqual([ + { listing_id: 301, 'mom_5d@v2': null }, + { listing_id: 305, 'mom_5d@v2': 1.5 }, + ]); + expect(early.rows).toEqual([ + { listing_id: 301, 'mom_5d@v2': null }, + { listing_id: 305, 'mom_5d@v2': 1.0 }, + ]); + expect(ca.rows).toEqual([]); + + // Path-traversal refs are rejected by validation. + await expect( + opened.store.crossSection({ + features: ['../mom_5d@v2'], + date: '2025-05-14', + universe: 'US_EQ', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + } finally { + await opened.close(); + } + }); + + test('crossSection caps universe membership at end-of-date when asOf is later, while returning revised features', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-xsec-late-bar-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true }); + await mkdir(join(curatedRoot, 'features', 'rev_feat', 'v1', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 5, 20, 0, 0, 0, 0); // 2025-06-20T00:00:00Z + const writer = await createNodeDuckDbExecutor(); + try { + // Listing 401: June 7 bar known on June 7 -> member of June 7 universe. + // Listing 402: only qualifying June 7 bar was first known on June 10 -> must NOT enter June 7 universe even when asOf is June 10. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (401::INTEGER, DATE '2025-06-07', TIMESTAMPTZ '2025-06-07 20:00:00+00', 10.0::DOUBLE, 10.5::DOUBLE, 9.5::DOUBLE, 10.2::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-07 20:00:00+00'), + (402::INTEGER, DATE '2025-06-07', TIMESTAMPTZ '2025-06-07 20:00:00+00', 20.0::DOUBLE, 20.5::DOUBLE, 19.5::DOUBLE, 20.2::DOUBLE, 1000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-10 12:00:00+00') + ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + + // rev_feat@v1: listing 401 has original (1.0 on June 7) and revision (2.5 on June 10); + // listing 402 also has a feature row on June 7/10, but must stay excluded from the universe. + await writer.run(` + COPY ( + SELECT * FROM (VALUES + (401::INTEGER, TIMESTAMPTZ '2025-06-07 20:00:00+00', TIMESTAMPTZ '2025-06-07 20:00:00+00', 1.0::DOUBLE), + (401::INTEGER, TIMESTAMPTZ '2025-06-07 20:00:00+00', TIMESTAMPTZ '2025-06-10 12:00:00+00', 2.5::DOUBLE), + (402::INTEGER, TIMESTAMPTZ '2025-06-07 20:00:00+00', TIMESTAMPTZ '2025-06-10 12:00:00+00', 9.9::DOUBLE) + ) AS t(listing_id, ts, known_at, value) + ) TO '${join(curatedRoot, 'features', 'rev_feat', 'v1', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: budgetEnv(duckTempDir), + }); + try { + const sameDay = await opened.store.crossSection({ + features: ['rev_feat@v1'], + date: '2025-06-07', + universe: 'US_EQ', + }); + expect(sameDay.rows).toEqual([{ listing_id: 401, 'rev_feat@v1': 1.0 }]); + + const laterAsOf = await opened.store.crossSection({ + features: ['rev_feat@v1'], + date: '2025-06-07', + universe: 'US_EQ', + asOf: '2025-06-10', + }); + expect(laterAsOf.rows).toEqual([{ listing_id: 401, 'rev_feat@v1': 2.5 }]); + } finally { + await opened.close(); + } + }); + + test('macroAsOf treats known_at == asOf as visible and honours the period_date from bound and country filter', async () => { + // Arrange + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-macro-pit-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(join(curatedRoot, 'macro'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + const vaultCutoffTs = Date.UTC(2025, 4, 1, 0, 0, 0, 0); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2024-12-31', TIMESTAMPTZ '2025-01-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.75::DOUBLE), + ('US'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.50::DOUBLE), + ('GB'::VARCHAR, 'policy_rate'::VARCHAR, DATE '2025-01-31', TIMESTAMPTZ '2025-02-01 00:00:00+00', 'publication_lag_estimate'::VARCHAR, 4.00::DOUBLE) + ) AS t(country_iso, indicator, period_date, known_at, known_at_source, value) + ) TO '${join(curatedRoot, 'macro', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: budgetEnv(duckTempDir), + }); + try { + // Act + const atBoundary = await opened.store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['policy_rate'], + from: '2025-01-01', + to: '2025-03-01', + asOf: '2025-02-01T00:00:00Z', + }); + const justBefore = await opened.store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['policy_rate'], + from: '2025-01-01', + to: '2025-03-01', + asOf: '2025-01-31T23:59:59.999Z', + }); + + // Assert + expect(atBoundary.rows).toEqual([ + { + country_iso: 'US', + indicator: 'policy_rate', + period_date: '2025-01-31', + known_at: Date.UTC(2025, 1, 1), + known_at_source: 'publication_lag_estimate', + value: 4.5, + }, + ]); + expect(justBefore.rows).toEqual([]); + } finally { + await opened.close(); + } + }); +}); diff --git a/libs/data/duckdb/test/research-copilot-store.test.ts b/libs/data/duckdb/test/research-copilot-store.test.ts index 2c1acc40..5b15c8ba 100644 --- a/libs/data/duckdb/test/research-copilot-store.test.ts +++ b/libs/data/duckdb/test/research-copilot-store.test.ts @@ -527,4 +527,158 @@ describe('openResearchCopilotStore (@duckdb/node-api)', () => { expect(connCloseSpy).toHaveBeenCalledTimes(0); expect(instCloseSpy).toHaveBeenCalledTimes(1); }); + + test('composes QuestDB intraday bars(1m) and fx(1m) routing when config.questdb is set, enforces vaultOperatorAuthorized: false, and closes both handles idempotently', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const questQueries: Array<{ readonly sql: string; readonly params: readonly unknown[] | undefined }> = + []; + let questCloses = 0; + + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + const config = buildHostConfig(curatedRoot, { + questdb: { + host: '127.0.0.1', + port: 8812, + database: 'qdb', + }, + }); + + const handle = await openResearchCopilotStore(config, { + env: buildDuckDbBudgetEnv(duckTempDir), + openQuestDbExecutor: async qCfg => { + expect(qCfg).toEqual(config.questdb); + return { + executor: { + async query(sql, params) { + questQueries.push({ sql, params }); + if (sql.includes('FROM fx_1m')) { + return { + rows: [ + { + pair: 'USDCAD', + ts_us: (BigInt(Date.UTC(2025, 4, 30, 14, 30, 0)) * 1000n).toString(), + open: 1.36, + high: 1.362, + low: 1.359, + close: 1.361, + source: 'polygon', + }, + ], + }; + } + return { + rows: [ + { + listing_id: String(LISTING_ID), + ts_us: (BigInt(Date.UTC(2025, 4, 30, 14, 30, 0)) * 1000n).toString(), + open: 100.5, + high: 101.0, + low: 100.0, + close: 100.8, + volume: 5000, + vwap: 100.7, + known_at_us: (BigInt(Date.UTC(2025, 4, 30, 14, 31, 0)) * 1000n).toString(), + }, + ], + }; + }, + }, + async close() { + questCloses += 1; + }, + }; + }, + }); + + try { + expect(Object.keys(handle).sort()).toEqual(['close', 'store']); + + // Daily 1d bars route to DuckDB. + const bars1d = await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-05-28', + to: '2025-06-05', + adjustment: 'raw', + }) + ); + expect(bars1d).toEqual([EXPECTED_VISIBLE_BAR]); + expect(questQueries).toHaveLength(0); + + // Intraday 1m bars route to QuestDB. + const bars1m = await collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-05-30T14:30:00Z', + to: '2025-05-30T14:35:00Z', + adjustment: 'raw', + }) + ); + expect(bars1m).toHaveLength(1); + expect(questQueries).toHaveLength(1); + + // Intraday 1m fx routes to QuestDB. + const fx1m = await handle.store.fx({ + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-05-30T14:30:00Z', + to: '2025-05-30T14:35:00Z', + }); + expect(fx1m.rows).toHaveLength(1); + expect(questQueries).toHaveLength(2); + + // Vault evaluation scope remains blocked on 1m bars. + await expect( + collectBars( + handle.store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-01T14:30:00Z', + to: '2025-06-01T14:35:00Z', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }) + ) + ).rejects.toBeInstanceOf(VaultScopeNotAuthorizedError); + } finally { + await handle.close(); + await handle.close(); // idempotent + } + + expect(questCloses).toBe(1); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); + + test('fail-closed: closes DuckDB connection and instance when QuestDB executor open fails', async () => { + const { curatedRoot, duckTempDir } = await buildBarsFixture(); + const questFailure = new Error('QuestDB PGWire unreachable'); + const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync')); + const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync')); + + let openErr: unknown; + try { + await openResearchCopilotStore( + buildHostConfig(curatedRoot, { + questdb: { host: '127.0.0.1', port: 8812, database: 'qdb' }, + }), + { + env: buildDuckDbBudgetEnv(duckTempDir), + openQuestDbExecutor: async () => { + throw questFailure; + }, + } + ); + } catch (err) { + openErr = err; + } + + expect(openErr).toBe(questFailure); + expect(connCloseSpy).toHaveBeenCalledTimes(1); + expect(instCloseSpy).toHaveBeenCalledTimes(1); + }); }); diff --git a/libs/data/duckdb/tsconfig.json b/libs/data/duckdb/tsconfig.json index 49cb7b59..ca6e0320 100644 --- a/libs/data/duckdb/tsconfig.json +++ b/libs/data/duckdb/tsconfig.json @@ -9,6 +9,9 @@ "references": [ { "path": "../../research" + }, + { + "path": "../questdb" } ] } diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 6036ae94..ffc055d1 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -27,12 +27,27 @@ export { type IlpV2EncodeErrorKind, } from './ilp-v2-writer'; export { + applyM2IntradayDDL, formatCreateTableSQL, getM2IntradayDDL, M2_INTRADAY_SCHEMAS, + M2_INTRADAY_TABLE_NAMES, QuestDBSchemaManager, + type ApplyM2IntradayDDLOptions, + type ApplyM2IntradayDDLResult, type M2IntradayTableName, } from './schema'; +export { + assertNoConflictingQuestDbSsl, + hasConflictingQuestDbUrlSsl, + hasQuestDbUrlTlsOptions, + openQuestDbPgExecutor, + type OpenQuestDbPgExecutorOptions, + type QuestDbPgExecutorConfig, + type QuestDbPgExecutorHandle, + type QuestDbPgPoolLike, + type QuestDbPgQueryExecutor, +} from './pg-executor'; // Types export type { diff --git a/libs/data/questdb/src/pg-executor.ts b/libs/data/questdb/src/pg-executor.ts new file mode 100644 index 00000000..f1281acc --- /dev/null +++ b/libs/data/questdb/src/pg-executor.ts @@ -0,0 +1,248 @@ +import { Pool, type PoolConfig } from 'pg'; + +export interface QuestDbPgExecutorConfig { + readonly url?: string; + readonly host?: string; + readonly port?: number; + readonly database?: string; + readonly user?: string; + readonly password?: string; + readonly ssl?: boolean; + readonly max?: number; + readonly connectionTimeoutMillis?: number; + readonly idleTimeoutMillis?: number; +} + +export interface QuestDbPgQueryExecutor { + query( + sql: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }>; +} + +export interface QuestDbPgExecutorHandle { + readonly executor: QuestDbPgQueryExecutor; + close(): Promise; +} + +/** Minimal `pg.Pool` surface used by {@link openQuestDbPgExecutor}. */ +export interface QuestDbPgPoolLike { + on(event: 'error', listener: (err: Error) => void): unknown; + query( + sql: string, + params?: unknown[] + ): Promise<{ readonly rows: readonly unknown[] }>; + end(): Promise; +} + +export interface OpenQuestDbPgExecutorOptions { + /** Optional pool factory override for unit tests; defaults to `new Pool(cfg)`. */ + readonly createPool?: (poolConfig: PoolConfig) => QuestDbPgPoolLike; + /** + * Optional diagnostic callback invoked when an idle pool client emits `'error'`. + * Always receives a credential-safe `Error`. + */ + readonly onPoolError?: (error: Error) => void; +} + +const SAFE_ERROR_CODE_RE = /^[A-Z0-9_]{1,32}$/; + +function isQuestDbUrlTlsParamKey(rawKey: string): boolean { + const key = rawKey.trim().toLowerCase(); + return key === 'uselibpqcompat' || key === 'ssl' || key.startsWith('ssl'); +} + +/** + * Returns `true` when `rawUrl` contains any TLS/SSL query parameter + * (`ssl`, `sslmode`, `sslcert`, `sslkey`, `sslrootcert`, `uselibpqcompat`, or + * any other `ssl*` parameter). + * + * TLS settings must have a single source of truth: either configure TLS in the + * URL query string (omitting the explicit `ssl` flag) or pass the explicit + * `ssl` flag with a URL that contains no TLS query parameters. + */ +export function hasQuestDbUrlTlsOptions(rawUrl: string): boolean { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + try { + parsed = new URL(rawUrl, 'postgres://base'); + } catch { + return false; + } + } + + for (const [rawKey] of parsed.searchParams.entries()) { + if (isQuestDbUrlTlsParamKey(rawKey)) { + return true; + } + } + + return false; +} + +/** + * Returns `true` when an explicit boolean `ssl` setting is combined with any + * TLS/SSL query parameter embedded in `rawUrl`. + */ +export function hasConflictingQuestDbUrlSsl(rawUrl: string, _explicitSsl?: boolean): boolean { + return hasQuestDbUrlTlsOptions(rawUrl); +} + +/** + * Throws a credential-free `RangeError` if an explicit `ssl` option is combined + * with any TLS/SSL query parameter in `rawUrl`. + */ +export function assertNoConflictingQuestDbSsl(rawUrl: string, _explicitSsl?: boolean): void { + if (hasQuestDbUrlTlsOptions(rawUrl)) { + throw new RangeError( + 'Conflicting QuestDB TLS/SSL configuration: cannot combine an explicit "ssl" option with TLS/SSL query parameters in the QuestDB URL. Configure TLS in either the URL or the explicit "ssl" option, not both.' + ); + } +} + +function addRawAndDecodedNeedle(needles: Set, raw: string): void { + if (raw.length === 0) { + return; + } + needles.add(raw); + try { + const decoded = decodeURIComponent(raw); + if (decoded.length > 0) { + needles.add(decoded); + } + } catch { + // Malformed percent-encoding: raw needle is already registered. + } +} + +function collectConfigSecretNeedles(config: QuestDbPgExecutorConfig): readonly string[] { + const needles = new Set(); + if (typeof config.password === 'string' && config.password.length > 0) { + addRawAndDecodedNeedle(needles, config.password); + } + if (typeof config.url === 'string' && config.url.length > 0) { + needles.add(config.url); + try { + const parsed = new URL(config.url); + if (parsed.href.length > 0) { + needles.add(parsed.href); + } + addRawAndDecodedNeedle(needles, parsed.password); + for (const [key, value] of parsed.searchParams.entries()) { + if (key.toLowerCase() === 'password' && value.length > 0) { + addRawAndDecodedNeedle(needles, value); + } + } + } catch { + // Non-URL string: raw string is already covered. + } + } + return Array.from(needles); +} + +function sanitizePoolError(err: unknown, needles: readonly string[]): Error { + const rawCode = + typeof err === 'object' && err !== null && 'code' in err + ? (err as { readonly code?: unknown }).code + : undefined; + const safeCode = + typeof rawCode === 'string' && SAFE_ERROR_CODE_RE.test(rawCode) ? rawCode : undefined; + + if (err instanceof Error) { + const messageHasSecret = needles.some(needle => err.message.includes(needle)); + const stackHasSecret = + typeof err.stack === 'string' && needles.some(needle => err.stack?.includes(needle) === true); + if (!messageHasSecret && !stackHasSecret) { + return err; + } + } + + const message = + safeCode !== undefined + ? `QuestDB PGWire idle pool client error (${safeCode}; details redacted).` + : 'QuestDB PGWire idle pool client error (details redacted).'; + const sanitized = new Error(message); + if (safeCode !== undefined) { + (sanitized as Error & { code?: string }).code = safeCode; + } + return sanitized; +} + +/** + * Opens a lightweight PGWire `pg.Pool` executor for QuestDB read queries or + * opt-in DDL without creating legacy tables or starting background health timers. + */ +export async function openQuestDbPgExecutor( + config: QuestDbPgExecutorConfig, + options?: OpenQuestDbPgExecutorOptions +): Promise { + if (config.url !== undefined && config.ssl !== undefined) { + assertNoConflictingQuestDbSsl(config.url, config.ssl); + } + + const poolConfig: PoolConfig = { + max: config.max ?? 4, + connectionTimeoutMillis: config.connectionTimeoutMillis ?? 5_000, + idleTimeoutMillis: config.idleTimeoutMillis ?? 30_000, + ...(config.url !== undefined + ? { connectionString: config.url } + : { + host: config.host ?? 'localhost', + port: config.port ?? 8812, + database: config.database ?? 'qdb', + ...(config.user !== undefined ? { user: config.user } : {}), + ...(config.password !== undefined ? { password: config.password } : {}), + }), + ...(config.ssl !== undefined ? { ssl: config.ssl } : {}), + }; + + const secretNeedles = collectConfigSecretNeedles(config); + const createPool = options?.createPool ?? ((cfg: PoolConfig) => new Pool(cfg)); + const pool = createPool(poolConfig); + + // Register an idle-client error listener before the startup probe so backend + // restarts or network disconnects on idle connections cannot crash the host + // with an unhandled EventEmitter 'error' event; pg-pool automatically drops + // the failed idle client and opens a fresh connection on the next query. + pool.on('error', (err: Error) => { + if (options?.onPoolError !== undefined) { + const safeError = sanitizePoolError(err, secretNeedles); + try { + options.onPoolError(safeError); + } catch { + // Never allow diagnostic callbacks to re-throw from an EventEmitter error handler. + } + } + }); + + try { + await pool.query('SELECT 1'); + } catch (err: unknown) { + await pool.end().catch(() => undefined); + throw err; + } + + let closePromise: Promise | null = null; + const close = (): Promise => { + if (closePromise === null) { + closePromise = pool.end(); + } + return closePromise; + }; + + const executor: QuestDbPgQueryExecutor = { + async query(sql: string, params?: readonly unknown[]) { + const result = + params !== undefined && params.length > 0 + ? await pool.query(sql, [...params]) + : await pool.query(sql); + return { + rows: result.rows as readonly Record[], + }; + }, + }; + + return { executor, close }; +} diff --git a/libs/data/questdb/src/schema.ts b/libs/data/questdb/src/schema.ts index 6e8458d2..65462776 100644 --- a/libs/data/questdb/src/schema.ts +++ b/libs/data/questdb/src/schema.ts @@ -6,6 +6,14 @@ import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types'; export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions'; +export const M2_INTRADAY_TABLE_NAMES = [ + 'bars_1m', + 'fx_1m', + 'bar_revisions', +] as const satisfies readonly M2IntradayTableName[]; + +const M2_INTRADAY_TABLE_NAME_SET: ReadonlySet = new Set(M2_INTRADAY_TABLE_NAMES); + /** * Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B). * Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`). @@ -144,6 +152,68 @@ export function getM2IntradayDDL(): Record { }; } +export interface ApplyM2IntradayDDLOptions { + /** Subset of M2 intraday tables to initialize. Defaults to all three (`bars_1m`, `fx_1m`, `bar_revisions`). */ + readonly tables?: readonly M2IntradayTableName[]; +} + +export interface ApplyM2IntradayDDLResult { + readonly appliedTables: readonly M2IntradayTableName[]; + readonly statements: readonly string[]; +} + +/** + * Opt-in initializer that executes `CREATE TABLE IF NOT EXISTS` DDL from + * {@link getM2IntradayDDL} for `bars_1m`, `fx_1m`, and `bar_revisions`. + * + * Kept strictly opt-in and never invoked by `QuestDBSchemaManager.initializeDatabase()` + * or `QuestDBClient.connect()`. + */ +export async function applyM2IntradayDDL( + client: { query(sql: string, params?: readonly unknown[]): Promise }, + options?: ApplyM2IntradayDDLOptions +): Promise { + if (typeof client !== 'object' || client === null || typeof client.query !== 'function') { + throw new Error('Expected a QuestDB queryable client with a query(sql) method.'); + } + + let tables: M2IntradayTableName[]; + if (options?.tables === undefined) { + tables = [...M2_INTRADAY_TABLE_NAMES]; + } else { + if (!Array.isArray(options.tables) || options.tables.length === 0) { + throw new Error('Expected a non-empty array of M2 intraday table names.'); + } + const seen = new Set(); + tables = []; + for (const rawName of options.tables) { + if (typeof rawName !== 'string' || !M2_INTRADAY_TABLE_NAME_SET.has(rawName)) { + throw new Error( + `Unknown M2 intraday table "${String(rawName)}". Expected one of: ${M2_INTRADAY_TABLE_NAMES.join(', ')}.` + ); + } + const name = rawName as M2IntradayTableName; + if (!seen.has(name)) { + seen.add(name); + tables.push(name); + } + } + } + + const ddl = getM2IntradayDDL(); + const statements: string[] = []; + for (const table of tables) { + const sql = ddl[table]; + await client.query(sql); + statements.push(sql); + } + + return { + appliedTables: tables, + statements, + }; +} + /** * QuestDB Schema Manager * diff --git a/libs/data/questdb/test/questdb.test.ts b/libs/data/questdb/test/questdb.test.ts index 80a682f3..79e45b4e 100644 --- a/libs/data/questdb/test/questdb.test.ts +++ b/libs/data/questdb/test/questdb.test.ts @@ -1,8 +1,19 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { EventEmitter } from 'node:events'; +import { Client, type PoolConfig } from 'pg'; import { QuestDBHealthMonitor } from '../src/health'; import { QuestDBInfluxWriter } from '../src/influx-writer'; +import { + openQuestDbPgExecutor, + type QuestDbPgPoolLike, +} from '../src/pg-executor'; import { QuestDBQueryBuilder } from '../src/query-builder'; -import { QuestDBSchemaManager } from '../src/schema'; +import { + applyM2IntradayDDL, + getM2IntradayDDL, + M2_INTRADAY_TABLE_NAMES, + QuestDBSchemaManager, +} from '../src/schema'; import type { OHLCVData, QuestDBClientConfig, TradeData } from '../src/types'; // Simple in-memory QuestDB client for testing @@ -474,6 +485,41 @@ describe('QuestDB', () => { expect(stats.min_timestamp).toBeDefined(); expect(stats.max_timestamp).toBeDefined(); }); + + it('applyM2IntradayDDL executes getM2IntradayDDL() for bars_1m, fx_1m, and bar_revisions without altering initializeDatabase()', async () => { + const executed: string[] = []; + const mockQueryable = { + query: mock(async (sql: string) => { + executed.push(sql); + return { rows: [], count: 0 }; + }), + }; + + const expectedDdl = getM2IntradayDDL(); + const result = await applyM2IntradayDDL(mockQueryable); + expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]); + expect(executed).toEqual([ + expectedDdl.bars_1m, + expectedDdl.fx_1m, + expectedDdl.bar_revisions, + ]); + + // Subset option executes only requested tables in deduplicated order. + executed.length = 0; + const subset = await applyM2IntradayDDL(mockQueryable, { + tables: ['fx_1m', 'bars_1m', 'fx_1m'], + }); + expect(subset.appliedTables).toEqual(['fx_1m', 'bars_1m']); + expect(executed).toEqual([expectedDdl.fx_1m, expectedDdl.bars_1m]); + + // Rejects unknown or empty table lists. + await expect(applyM2IntradayDDL(mockQueryable, { tables: [] })).rejects.toThrow(); + await expect( + applyM2IntradayDDL(mockQueryable, { + tables: ['unknown_table' as unknown as 'bars_1m'], + }) + ).rejects.toThrow(); + }); }); describe('QuestDBHealthMonitor', () => { @@ -531,4 +577,189 @@ describe('QuestDB', () => { monitor.stopMonitoring(); }); }); + + describe('openQuestDbPgExecutor', () => { + it('registers pool error listener before SELECT 1, redacts credentials, and recovers on next query after idle disconnect', async () => { + const secret = 'qdb_idle_s3cr3t!'; + const url = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`; + + class FakePool extends EventEmitter implements QuestDbPgPoolLike { + connectionEpoch = 1; + probeSawErrorListener = false; + ended = false; + readonly queries: Array<{ readonly sql: string; readonly epoch: number }> = []; + + async query(sql: string): Promise<{ readonly rows: readonly unknown[] }> { + if (sql === 'SELECT 1') { + this.probeSawErrorListener = this.listenerCount('error') > 0; + this.queries.push({ sql, epoch: this.connectionEpoch }); + return { rows: [{ '?column?': 1 }] }; + } + this.queries.push({ sql, epoch: this.connectionEpoch }); + return { rows: [{ ok: true, epoch: this.connectionEpoch }] }; + } + + async end(): Promise { + this.ended = true; + } + } + + const fakePool = new FakePool(); + const observedErrors: Error[] = []; + + const handle = await openQuestDbPgExecutor( + { url }, + { + createPool: () => fakePool, + onPoolError: err => { + observedErrors.push(err); + }, + } + ); + + try { + // Listener must be attached before the startup probe runs. + expect(fakePool.probeSawErrorListener).toBe(true); + expect(fakePool.listenerCount('error')).toBeGreaterThan(0); + + // Simulate QuestDB restarting while the connection opened by SELECT 1 is idle. + const idleErr = Object.assign( + new Error(`idle connection dropped for ${url} (password=${secret})`), + { code: 'ECONNRESET' } + ); + expect(() => fakePool.emit('error', idleErr)).not.toThrow(); + + // Diagnostic callback receives a credential-free Error with the safe error code. + expect(observedErrors).toHaveLength(1); + expect(observedErrors[0]?.message).not.toContain(secret); + expect(observedErrors[0]?.message).not.toContain(url); + expect(observedErrors[0]?.message).toContain('ECONNRESET'); + expect((observedErrors[0] as Error & { code?: string }).code).toBe('ECONNRESET'); + + // Pool replaces the failed idle client and serves the next query cleanly. + fakePool.connectionEpoch = 2; + const result = await handle.executor.query('SELECT pair FROM fx_1m LIMIT 1'); + expect(result.rows).toEqual([{ ok: true, epoch: 2 }]); + expect(fakePool.queries).toEqual([ + { sql: 'SELECT 1', epoch: 1 }, + { sql: 'SELECT pair FROM fx_1m LIMIT 1', epoch: 2 }, + ]); + } finally { + await handle.close(); + await handle.close(); + } + expect(fakePool.ended).toBe(true); + }); + + it('rejects any URL TLS/SSL query parameter when explicit ssl is set and verifies pinned pg effective TLS config without connecting', async () => { + const secret = 'qdb_ssl_s3cr3t!'; + const base = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`; + + const conflictingCases: ReadonlyArray = [ + [`${base}?sslmode=no-verify`, true], + [`${base}?sslmode=no-verify`, false], + [`${base}?sslmode=disable`, true], + [`${base}?sslmode=disable`, false], + [`${base}?SSLMODE=DISABLE`, true], + [`${base}?sslmode=require`, true], + [`${base}?sslmode=require`, false], + [`${base}?sslmode=verify-ca`, true], + [`${base}?sslmode=verify-ca`, false], + [`${base}?sslmode=verify-full`, true], + [`${base}?sslmode=verify-full`, false], + [`${base}?sslmode=prefer`, true], + [`${base}?sslmode=prefer`, false], + [`${base}?sslmode=allow`, true], + [`${base}?ssl=false`, true], + [`${base}?ssl=false`, false], + [`${base}?ssl=0`, true], + [`${base}?ssl=0`, false], + [`${base}?ssl=true`, true], + [`${base}?ssl=true`, false], + [`${base}?ssl=1`, true], + [`${base}?ssl=1`, false], + [`${base}?ssl=`, true], + [`${base}?sslrootcert=/etc/ssl/ca.pem`, true], + [`${base}?sslrootcert=/etc/ssl/ca.pem`, false], + [`${base}?uselibpqcompat=true`, true], + [`${base}?uselibpqcompat=true`, false], + ]; + + let createPoolCalls = 0; + for (const [url, ssl] of conflictingCases) { + let caught: unknown; + try { + await openQuestDbPgExecutor( + { url, ssl }, + { + createPool: () => { + createPoolCalls += 1; + throw new Error('createPool must not be called on conflicting SSL config'); + }, + } + ); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(RangeError); + expect((caught as Error).message).toContain('SSL'); + expect((caught as Error).message).not.toContain(secret); + expect((caught as Error).message).not.toContain(url); + } + expect(createPoolCalls).toBe(0); + + // Single-source-of-truth configs proceed to pool creation and produce the + // expected effective TLS settings in the pinned `pg` driver without opening + // a network connection. + const effectiveCases: ReadonlyArray<{ + readonly config: Parameters[0]; + readonly expectedSsl: unknown; + }> = [ + { config: { url: base, ssl: true }, expectedSsl: true }, + { + config: { url: `${base}?application_name=copilot`, ssl: false }, + expectedSsl: false, + }, + { config: { url: `${base}?sslmode=require` }, expectedSsl: {} }, + { config: { url: `${base}?sslmode=disable` }, expectedSsl: false }, + { + config: { url: `${base}?sslmode=no-verify` }, + expectedSsl: { rejectUnauthorized: false }, + }, + { + config: { host: '10.0.0.51', port: 8812, database: 'qdb', ssl: true }, + expectedSsl: true, + }, + { + config: { host: '10.0.0.51', port: 8812, database: 'qdb', ssl: false }, + expectedSsl: false, + }, + ]; + + for (const { config, expectedSsl } of effectiveCases) { + let capturedPoolConfig: PoolConfig | undefined; + const pool = Object.assign(new EventEmitter(), { + query: async () => ({ rows: [{ '?column?': 1 }] }), + end: async () => {}, + }) as unknown as QuestDbPgPoolLike; + const handle = await openQuestDbPgExecutor(config, { + createPool: poolConfig => { + capturedPoolConfig = poolConfig; + return pool; + }, + }); + await handle.close(); + + expect(capturedPoolConfig).toBeDefined(); + // Instantiate pg.Client without calling connect() to inspect the pinned + // driver's effective ConnectionParameters.ssl resolution. + const client = new Client(capturedPoolConfig); + const effectiveSsl: unknown = ( + client as unknown as { connectionParameters: { ssl: unknown } } + ).connectionParameters.ssl; + expect(effectiveSsl).toEqual(expectedSsl); + expect(client.ssl as unknown).toEqual(expectedSsl); + } + }); + }); }); diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts index 680a3bf1..9cdacf43 100644 --- a/libs/research/src/feature-library.ts +++ b/libs/research/src/feature-library.ts @@ -61,10 +61,12 @@ export type FeatureKind = (typeof FEATURE_KINDS)[number]; export const FEATURE_INPUT_DATASETS = [ 'bars_1d', 'adj_factors', + 'corporate_actions', 'events', 'shorts', 'fx_1d', 'fundamentals_pit', + 'macro', ] as const; export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number]; @@ -553,7 +555,7 @@ type SqlToken = interface DatasetScanSpec { readonly relativePath: string; readonly hivePartitioning: boolean; - readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at'; + readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at' | 'macro_known_at'; } const DATASET_SCAN_SPECS: Readonly> = { @@ -567,6 +569,11 @@ const DATASET_SCAN_SPECS: Readonly> hivePartitioning: false, predicateKind: 'known_at', }, + corporate_actions: { + relativePath: 'corporate_actions/part.parquet', + hivePartitioning: false, + predicateKind: 'known_at', + }, events: { relativePath: 'events/year=*/part.parquet', hivePartitioning: true, @@ -587,6 +594,11 @@ const DATASET_SCAN_SPECS: Readonly> hivePartitioning: true, predicateKind: 'effective_known_at', }, + macro: { + relativePath: 'macro/part.parquet', + hivePartitioning: false, + predicateKind: 'macro_known_at', + }, }; function isPlainRecord(value: unknown): value is Record { @@ -1959,6 +1971,11 @@ function expandSqlForYear( } else if (spec.predicateKind === 'effective_known_at') { parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`); scanParams.push(knownAtUpperIso); + } else if (spec.predicateKind === 'macro_known_at') { + parts.push( + `(SELECT * FROM ${readCall} WHERE known_at <= ? AND known_at_source = 'publication_lag_estimate')` + ); + scanParams.push(knownAtUpperIso); } else { parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`); scanParams.push(knownAtUpperIso); diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index 5e4aac3a..cf7bd2c0 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -11,7 +11,7 @@ * - `/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`) * - `/adj_factors/part.parquet` (point-in-time fenced snapshot with * `stock_bot.adj_factors.*` Parquet footer metadata) - * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) + * - `/events/year=*\/\*.parquet` (`hive_partitioning = true`) * - `/shorts/part.parquet` * - `/fx_1d/part.parquet` * - `/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`) @@ -94,6 +94,8 @@ const STRICT_INT_RE = /^-?\d+$/; const STRICT_UINT_RE = /^\d+$/; const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/; const FD_HANDLE_PATH_RE = /^\/(?:proc\/self|dev)\/fd\/[1-9]\d*$/; +const CROSS_SECTION_FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; +const MACRO_REQUIRED_KNOWN_AT_SOURCE = 'publication_lag_estimate'; export const ADJ_SNAPSHOT_FORMAT_VERSION = 1; export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.'; @@ -157,6 +159,15 @@ export const FX_1D_COLUMNS = [ 'known_at', ] as const; +export const MACRO_COLUMNS = [ + 'country_iso', + 'indicator', + 'period_date', + 'known_at', + 'known_at_source', + 'value', +] as const; + export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ 'revenue', 'net_income', @@ -219,6 +230,15 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ { name: 'known_at', kind: 'safe_int', nullable: false }, ]; +const MACRO_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'country_iso', kind: 'string', nullable: false }, + { name: 'indicator', kind: 'string', nullable: false }, + { name: 'period_date', kind: 'string', nullable: false }, + { name: 'known_at', kind: 'safe_int', nullable: false }, + { name: 'known_at_source', kind: 'string', nullable: false }, + { name: 'value', kind: 'number', nullable: false }, +]; + const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ { name: 'listing_id', kind: 'int32', nullable: false }, { name: 'effective_known_at', kind: 'safe_int', nullable: false }, @@ -399,6 +419,8 @@ export type ShortsAsOfQuery = Parameters[0]; export type FxQuery = Parameters[0]; export type UniverseQuery = Parameters[0]; export type FundamentalsAsOfQuery = Parameters[0]; +export type MacroAsOfQuery = Parameters[0]; +export type CrossSectionQuery = Parameters[0]; /** * Thrown when a `MarketDataStore` method or timeframe is outside the curated @@ -693,6 +715,79 @@ function validateUniverseRef(raw: unknown, field = 'ref'): readonly string[] { ); } +function validateNonEmptyStringArray(raw: unknown, field: 'countries' | 'indicators'): string[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty array of non-empty strings for "${field}".`, + field + ); + } + + const seen = new Set(); + const normalized: string[] = []; + for (let i = 0; i < raw.length; i += 1) { + const item: unknown = raw[i]; + if (typeof item !== 'string' || item.trim().length === 0) { + throw new MarketDataStoreValidationError( + `Invalid non-empty string at ${field}[${i}]: ${String(item)}.`, + field + ); + } + if (!seen.has(item)) { + seen.add(item); + normalized.push(item); + } + } + return normalized; +} + +interface ParsedCrossSectionFeatureRef { + readonly ref: string; + readonly name: string; + readonly version: number; +} + +function validateCrossSectionFeatures(raw: unknown): ParsedCrossSectionFeatureRef[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + 'Expected a non-empty array of versioned feature refs ("@v") for "features".', + 'features' + ); + } + + const seen = new Set(); + const parsed: ParsedCrossSectionFeatureRef[] = []; + for (let i = 0; i < raw.length; i += 1) { + const item: unknown = raw[i]; + if (typeof item !== 'string') { + throw new MarketDataStoreValidationError( + `Invalid feature ref at features[${i}]: ${String(item)}. Expected "@v".`, + 'features' + ); + } + const match = CROSS_SECTION_FEATURE_REF_RE.exec(item); + if (match === null) { + throw new MarketDataStoreValidationError( + `Invalid feature ref "${item}" at features[${i}]. Expected "@v" with lowercase name and canonical positive integer version.`, + 'features' + ); + } + const name = match[1] as string; + const version = Number(match[2]); + if (!Number.isSafeInteger(version) || version < 1) { + throw new MarketDataStoreValidationError( + `Invalid feature version in ref "${item}" at features[${i}]. Expected a positive safe integer.`, + 'features' + ); + } + if (!seen.has(item)) { + seen.add(item); + parsed.push({ ref: item, name, version }); + } + } + return parsed; +} + function validateUniverseLookbackDays(raw: unknown, vaultCutoffTs?: number): number { const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw; if (typeof days !== 'number' || !Number.isSafeInteger(days) || days < 1) { @@ -1445,7 +1540,7 @@ export function planEventsQuery(q: EventsQuery, ctx: DuckDbPlanContext): Planned const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/part.parquet'); + const eventsPath = joinCuratedPath(curatedRoot, 'events/year=*/*.parquet'); const kindPlaceholders = buildPlaceholders(kinds.length); const orderBy = 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC'; @@ -1813,6 +1908,182 @@ export function planFundamentalsAsOfQuery( return planFundamentalsAsOfInternal(q, ctx).planned; } +/** + * Plans a Vault-fenced DuckDB SQL query for point-in-time curated macro series + * (`macro/part.parquet`). + */ +export function planMacroAsOfQuery(q: MacroAsOfQuery, ctx: DuckDbPlanContext): PlannedDuckDbQuery { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a macroAsOf query object.', 'query'); + } + + const countries = validateNonEmptyStringArray(q.countries, 'countries'); + const indicators = validateNonEmptyStringArray(q.indicators, 'indicators'); + const fenced = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.to, fenced); + const fromDate = formatUtcDate(fenced.fromMs); + const toDate = formatUtcDate(fenced.toMs); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); + const macroPath = joinCuratedPath(curatedRoot, 'macro/part.parquet'); + const countryPlaceholders = buildPlaceholders(countries.length); + const indicatorPlaceholders = buildPlaceholders(indicators.length); + + const sql = + 'SELECT m.country_iso, m.indicator, CAST(m.period_date AS VARCHAR) AS period_date, epoch_ms(m.known_at) AS known_at, m.known_at_source, m.value ' + + `FROM read_parquet('${macroPath}') AS m ` + + `WHERE m.country_iso IN (${countryPlaceholders}) AND m.indicator IN (${indicatorPlaceholders}) AND m.period_date >= ? AND m.period_date <= ? AND m.known_at <= ? ` + + 'ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC'; + const params: DuckDbParam[] = [...countries, ...indicators, fromDate, toDate, asOfIso]; + return { sql, params, fenced }; +} + +interface PlannedCrossSectionInternal { + readonly planned: PlannedDuckDbQuery; + readonly columns: readonly string[]; + readonly schema: readonly TableColumnSpec[]; +} + +function planCrossSectionInternal( + q: CrossSectionQuery, + ctx: DuckDbPlanContext +): PlannedCrossSectionInternal { + const curatedRoot = validateContext(ctx); + const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a crossSection query object.', 'query'); + } + + const features = validateCrossSectionFeatures(q.features); + const currencies = validateUniverseRef(q.universe, 'universe'); + if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) { + throw new MarketDataStoreValidationError( + `Invalid crossSection date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`, + 'date' + ); + } + + const rawAsOf = q.asOf ?? q.date; + let fenced: FencedTimeRange; + try { + fenced = applyVaultFence( + { + from: q.date, + to: q.date, + asOf: rawAsOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + } catch (err: unknown) { + if ( + err instanceof MarketDataStoreValidationError && + (err.field === 'from' || err.field === 'to' || (err.field === 'asOf' && q.asOf === undefined)) + ) { + throw new MarketDataStoreValidationError(err.message, 'date'); + } + throw err; + } + + const lookbackStartMs = fenced.fromMs - lookbackDays * MS_PER_DAY; + if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`, + 'universeLookbackDays' + ); + } + + const lookbackStartDate = formatUtcDate(lookbackStartMs); + const endDate = formatUtcDate(fenced.toMs); + const fromIso = formatUtcIsoWithMicros(fenced.fromMs, 0); + const toSubMsMicros = resolveToSubMsMicros(q.date, fenced); + const asOfSubMsMicros = resolveAsOfSubMsMicros(rawAsOf, q.date, fenced); + const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMsMicros); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMsMicros); + const universeKnownAtIso = + fenced.asOfMs < fenced.toMs || + (fenced.asOfMs === fenced.toMs && asOfSubMsMicros < toSubMsMicros) + ? asOfIso + : toIso; + const featureYear = new Date(fenced.fromMs).getUTCFullYear(); + + const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); + const currencyPredicate = + currencies.length === 1 + ? 'b.currency = ?' + : `b.currency IN (${buildPlaceholders(currencies.length)})`; + + const ctes: string[] = [ + `u AS (SELECT DISTINCT b.listing_id FROM read_parquet('${barsPath}', hive_partitioning = true) AS b WHERE ${currencyPredicate} AND b.session_date >= ? AND b.session_date <= ? AND b.ts <= ? AND b.known_at <= ?)`, + ]; + const params: DuckDbParam[] = [ + ...currencies, + lookbackStartDate, + endDate, + toIso, + universeKnownAtIso, + ]; + + const selectCols: string[] = ['u.listing_id']; + const joins: string[] = []; + const columns: string[] = ['listing_id']; + const schema: TableColumnSpec[] = [{ name: 'listing_id', kind: 'int32', nullable: false }]; + + for (let i = 0; i < features.length; i += 1) { + const feat = features[i] as ParsedCrossSectionFeatureRef; + const alias = `f_${i}`; + const featurePath = joinCuratedPath( + curatedRoot, + `features/${feat.name}/v${feat.version}/year=*/part.parquet` + ); + ctes.push( + `${alias} AS (SELECT f.listing_id, f.value FROM read_parquet('${featurePath}', hive_partitioning = true) AS f WHERE CAST(f.year AS BIGINT) = ? AND f.ts >= ? AND f.ts <= ? AND f.known_at <= ? QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.ts DESC, f.known_at DESC) = 1)` + ); + params.push(featureYear, fromIso, toIso, asOfIso); + selectCols.push(`${alias}.value AS "${feat.ref}"`); + joins.push(`LEFT JOIN ${alias} ON u.listing_id = ${alias}.listing_id`); + columns.push(feat.ref); + schema.push({ name: feat.ref, kind: 'number', nullable: true }); + } + + const sql = + `WITH ${ctes.join(', ')} ` + + `SELECT ${selectCols.join(', ')} ` + + `FROM u ${joins.join(' ')} ` + + 'ORDER BY u.listing_id ASC'; + + return { + planned: { sql, params, fenced }, + columns, + schema, + }; +} + +/** + * Plans a Vault-fenced DuckDB SQL query joining versioned curated feature + * Parquet datasets (`features//v/year=*\/part.parquet`) onto the + * survivorship-free active universe on `q.date`. + */ +export function planCrossSectionQuery( + q: CrossSectionQuery, + ctx: DuckDbPlanContext +): PlannedDuckDbQuery { + return planCrossSectionInternal(q, ctx).planned; +} + function readRequiredInt32(row: Record, key: string, rowIndex: number): number { const val = row[key]; if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { @@ -1996,6 +2267,66 @@ function mapTableRows( }; } +function parseStrictPeriodDateMs(periodDate: string, rowIndex: number): number { + if (!DATE_ONLY_RE.test(periodDate)) { + throw new MarketDataStoreValidationError( + `Invalid macro period_date "${periodDate}" in result row ${rowIndex}. Expected YYYY-MM-DD.`, + 'period_date' + ); + } + try { + return applyVaultFence( + { from: periodDate, to: periodDate, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ).fromMs; + } catch { + throw new MarketDataStoreValidationError( + `Invalid macro period_date "${periodDate}" in result row ${rowIndex}.`, + 'period_date' + ); + } +} + +function mapMacroRows( + rows: readonly TableRow[], + vaultCutoffTs: number, + asOfMs: number +): Table { + const table = mapTableRows(MACRO_COLUMNS, MACRO_SCHEMA, rows); + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i] as TableRow; + const knownAtSource = row.known_at_source as string; + if (knownAtSource !== MACRO_REQUIRED_KNOWN_AT_SOURCE) { + throw new MarketDataStoreValidationError( + `Invalid macro provenance known_at_source "${knownAtSource}" in result row ${i}. Expected "${MACRO_REQUIRED_KNOWN_AT_SOURCE}".`, + 'known_at_source' + ); + } + const periodDate = row.period_date as string; + const periodDateMs = parseStrictPeriodDateMs(periodDate, i); + const knownAt = row.known_at as number; + if (knownAt < periodDateMs + MS_PER_DAY) { + throw new MarketDataStoreValidationError( + `Unlagged macro row ${i}: known_at (${knownAt}) precedes period_date + 1d (${periodDateMs + MS_PER_DAY}).`, + 'known_at' + ); + } + if (knownAt >= vaultCutoffTs) { + throw new MarketDataStoreValidationError( + `Macro row ${i} known_at (${knownAt}) reaches or exceeds Vault cutoff (${vaultCutoffTs}).`, + 'known_at' + ); + } + if (knownAt > asOfMs) { + throw new MarketDataStoreValidationError( + `Macro row ${i} known_at (${knownAt}) exceeds fenced asOf (${asOfMs}).`, + 'known_at' + ); + } + } + return table; +} + function mapUniverseRows(rows: readonly TableRow[]): number[] { if (!Array.isArray(rows)) { throw new MarketDataStoreValidationError( @@ -2281,7 +2612,10 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption }, async crossSection(q: CrossSectionQuery): Promise { - return executeCrossSection(q, planCtx, ensureBudgetInitialized, typedExecutor); + const { planned, columns, schema } = planCrossSectionInternal(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapTableRows(columns, schema, rawRows); }, async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ @@ -2291,8 +2625,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return mapTableRows(columns, schema, rawRows); }, - macroAsOf(): Promise
{ - return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf')); + async macroAsOf(q: MacroAsOfQuery): Promise
{ + const planned = planMacroAsOfQuery(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapMacroRows(rawRows, planCtx.vaultCutoffTs, planned.fenced.asOfMs); }, async universe(q: UniverseQuery): Promise { @@ -2303,246 +2640,3 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption }, }; } - -export type CrossSectionQuery = Parameters[0]; - -const CROSS_SECTION_FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; - -interface ParsedCrossSectionFeatureRef { - readonly canonical: string; - readonly name: string; - readonly version: number; -} - -function validateCrossSectionFeatures( - raw: readonly string[], - field = 'features' -): ParsedCrossSectionFeatureRef[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - 'Expected a non-empty array of canonical "@v" feature refs.', - field - ); - } - - const seen = new Set(); - const parsed: ParsedCrossSectionFeatureRef[] = []; - for (let i = 0; i < raw.length; i += 1) { - if (!(i in raw)) { - throw new MarketDataStoreValidationError( - `Invalid sparse feature ref at index ${i}. Expected canonical "@v".`, - field - ); - } - const item: unknown = raw[i]; - if (typeof item !== 'string') { - throw new MarketDataStoreValidationError( - `Invalid feature ref at index ${i}. Expected canonical "@v".`, - field - ); - } - const match = CROSS_SECTION_FEATURE_REF_RE.exec(item); - if (match === null) { - throw new MarketDataStoreValidationError( - `Invalid feature ref "${item}". Expected canonical "@v".`, - field - ); - } - const name = match[1]; - const versionStr = match[2]; - if (name === undefined || versionStr === undefined) { - throw new MarketDataStoreValidationError( - `Invalid feature ref "${item}". Expected canonical "@v".`, - field - ); - } - const version = Number(versionStr); - if (!Number.isSafeInteger(version) || version < 1) { - throw new MarketDataStoreValidationError( - `Invalid feature version in ref "${item}". Expected a positive safe integer.`, - field - ); - } - const canonical = `${name}@v${version}`; - if (!seen.has(canonical)) { - seen.add(canonical); - parsed.push({ canonical, name, version }); - } - } - return parsed; -} - -interface PlannedCrossSectionInternal { - readonly planned: PlannedDuckDbQuery; - readonly columns: readonly string[]; - readonly schema: readonly TableColumnSpec[]; -} - -function planCrossSectionInternal( - q: CrossSectionQuery, - ctx: DuckDbPlanContext -): PlannedCrossSectionInternal { - const curatedRoot = validateContext(ctx); - const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a crossSection query object.', 'query'); - } - - const parsedRefs = validateCrossSectionFeatures(q.features, 'features'); - const currencies = validateUniverseRef(q.universe, 'universe'); - - if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) { - throw new MarketDataStoreValidationError( - `Invalid crossSection date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`, - 'date' - ); - } - if (q.asOf !== undefined && typeof q.asOf !== 'string') { - throw new MarketDataStoreValidationError( - 'Invalid crossSection asOf timestamp. Expected a UTC date or ISO-8601 instant string.', - 'asOf' - ); - } - - let fenced: FencedTimeRange; - try { - fenced = applyVaultFence( - { - from: q.date, - to: q.date, - ...(q.asOf !== undefined ? { asOf: q.asOf } : {}), - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - } catch (err: unknown) { - if ( - err instanceof MarketDataStoreValidationError && - (err.field === 'from' || err.field === 'to') - ) { - throw new MarketDataStoreValidationError(err.message, 'date'); - } - throw err; - } - - const lookbackStartMs = fenced.fromMs - lookbackDays * MS_PER_DAY; - if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) { - throw new MarketDataStoreValidationError( - `Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`, - 'universeLookbackDays' - ); - } - - const lookbackStartDate = formatUtcDate(lookbackStartMs); - const endDate = formatUtcDate(fenced.toMs); - const fromSubMs = resolveFromSubMsMicros(q.date); - const toSubMs = resolveToSubMsMicros(q.date, fenced); - const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.date, fenced); - const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); - const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const universeKnownAtIso = - fenced.toMs < fenced.asOfMs || (fenced.toMs === fenced.asOfMs && toSubMs <= asOfSubMs) - ? toIso - : asOfIso; - - const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet'); - const currencyPredicate = - currencies.length === 1 - ? 'b.currency = ?' - : `b.currency IN (${buildPlaceholders(currencies.length)})`; - - const ctes: string[] = [ - 'u AS (' + - 'SELECT DISTINCT b.listing_id ' + - `FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` + - `WHERE ${currencyPredicate} ` + - 'AND b.session_date >= ? ' + - 'AND b.session_date <= ? ' + - 'AND b.ts <= ? ' + - 'AND b.known_at <= ?)', - ]; - const params: DuckDbParam[] = [ - ...currencies, - lookbackStartDate, - endDate, - toIso, - universeKnownAtIso, - ]; - const selectCols: string[] = ['CAST(u.listing_id AS INTEGER) AS listing_id']; - const joins: string[] = []; - const columns: string[] = ['listing_id']; - const schema: TableColumnSpec[] = [{ name: 'listing_id', kind: 'int32', nullable: false }]; - - for (let i = 0; i < parsedRefs.length; i += 1) { - const parsed = parsedRefs[i]; - if (parsed === undefined) { - continue; - } - const alias = `f_${i}`; - const featPath = joinCuratedPath( - curatedRoot, - `features/${parsed.name}/v${parsed.version}/year=*/part.parquet` - ); - ctes.push( - `${alias} AS (` + - 'SELECT listing_id, CAST(value AS DOUBLE) AS value ' + - `FROM read_parquet('${featPath}', hive_partitioning = true) ` + - 'WHERE ts >= ? ' + - 'AND ts <= ? ' + - 'AND known_at <= ? ' + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY ts DESC, known_at DESC) = 1)' - ); - params.push(fromIso, toIso, asOfIso); - const escapedCol = parsed.canonical.replace(/"/g, '""'); - selectCols.push(`${alias}.value AS "${escapedCol}"`); - joins.push(`LEFT JOIN ${alias} ON u.listing_id = ${alias}.listing_id`); - columns.push(parsed.canonical); - schema.push({ name: parsed.canonical, kind: 'number', nullable: true }); - } - - const sql = - `WITH ${ctes.join(', ')} ` + - `SELECT ${selectCols.join(', ')} ` + - `FROM u ${joins.join(' ')} ` + - 'ORDER BY u.listing_id ASC'; - - return { - planned: { - sql, - params, - fenced: { - ...fenced, - fromMs: lookbackStartMs, - }, - }, - columns, - schema, - }; -} - -/** - * Plans a Vault-fenced, survivorship-free cross-section DuckDB SQL query over - * materialized feature Parquet partitions (`features//v/year=*\/part.parquet`) - * LEFT JOINed onto the active universe on `q.date`. - */ -export function planCrossSectionQuery( - q: CrossSectionQuery, - ctx: DuckDbPlanContext -): PlannedDuckDbQuery { - return planCrossSectionInternal(q, ctx).planned; -} - -async function executeCrossSection( - q: CrossSectionQuery, - planCtx: DuckDbPlanContext, - ensureBudgetInitialized: () => Promise, - typedExecutor: DuckDbExecutor -): Promise
{ - const { planned, columns, schema } = planCrossSectionInternal(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(columns, schema, rawRows); -} diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts index c6da320c..dc0f94f0 100644 --- a/libs/research/src/market-data-store-questdb.ts +++ b/libs/research/src/market-data-store-questdb.ts @@ -29,6 +29,8 @@ import { type FencedTimeRange, type MarketDataStore, MarketDataStoreValidationError, + type Table, + type TableRow, type VaultFenceContext, applyVaultFence, } from './market-data-store'; @@ -42,9 +44,17 @@ const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; /** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; +/** Output columns for QuestDB `fx_1m` queries. */ +export const FX_1M_COLUMNS = ['pair', 'ts', 'open', 'high', 'low', 'close', 'source'] as const; + +const FX_1M_ACCEPTED_PAIRS: ReadonlySet = new Set(['USDCAD', 'USD.CAD']); + /** Input query type derived from `MarketDataStore['bars']`. */ export type QuestDbBars1mQuery = Parameters[0]; +/** Input query type derived from `MarketDataStore['fx']`. */ +export type QuestDbFx1mQuery = Parameters[0]; + /** * Injected PGWire SQL executor port, structurally compatible with * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. @@ -63,6 +73,13 @@ export interface PlannedQuestDbBars1mQuery { readonly fence: FencedTimeRange; } +/** Pure output of {@link planFx1mQuery}. */ +export interface PlannedQuestDbFx1mQuery { + readonly sql: string; + readonly params: readonly string[]; + readonly fence: FencedTimeRange; +} + /** Configuration for {@link createQuestDbIntradayBarsReader}. */ export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { readonly executor: QuestDbQueryExecutor; @@ -70,6 +87,11 @@ export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { readonly batchSize?: number; } +/** Configuration for {@link createQuestDbIntradayFxReader}. */ +export interface QuestDbIntradayFxReaderOptions extends VaultFenceContext { + readonly executor: QuestDbQueryExecutor; +} + interface InternalPlannedBars1mQuery { readonly planned: PlannedQuestDbBars1mQuery; readonly requestedListingIds: ReadonlySet; @@ -215,6 +237,67 @@ export function planBars1mQuery( return planBars1mQueryInternal(q, ctx).planned; } +/** + * Pure, Vault-fenced, parameterized SQL planner for QuestDB `fx_1m`. + * + * Always fences under `scope: 'vault_fenced'` with `vaultOperatorAuthorized: false` + * and binds both `'USDCAD'` and `'USD.CAD'` pair symbols via `$3, $4`. + */ +export function planFx1mQuery( + q: QuestDbFx1mQuery, + ctx: VaultFenceContext +): PlannedQuestDbFx1mQuery { + if (!isPlainRecord(ctx)) { + throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); + } + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected an fx query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe !== '1m') { + throw new MarketDataStoreValidationError( + `Invalid fx timeframe "${String(timeframe)}". Expected '1m'.`, + 'timeframe' + ); + } + + const pair: unknown = q.pair; + if (pair !== 'USD.CAD') { + throw new MarketDataStoreValidationError( + `Unsupported FX pair "${String(pair)}". Expected 'USD.CAD'.`, + 'pair' + ); + } + + const fence = applyVaultFence( + { + from: q.from, + to: q.to, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + vaultOperatorAuthorized: false, + } + ); + + const sql = + 'SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source ' + + 'FROM fx_1m ' + + 'WHERE ts >= $1 AND ts <= $2 AND pair IN ($3, $4) ' + + 'ORDER BY ts ASC'; + + const params: string[] = [ + formatUtcIsoMs(fence.fromMs), + formatUtcIsoMs(fence.toMs), + 'USDCAD', + 'USD.CAD', + ]; + + return { sql, params, fence }; +} + function parseListingIdSymbol( row: Record, rowIndex: number, @@ -460,3 +543,140 @@ export function createQuestDbIntradayBarsReader( }, }; } + +function mapFx1mRows( + rows: readonly Record[], + fence: FencedTimeRange, + vaultCutoffTs: number +): Table { + const fromUs = BigInt(fence.fromMs) * 1000n; + const toUs = BigInt(fence.toMs) * 1000n; + const vaultCutoffUs = BigInt(vaultCutoffTs) * 1000n; + + const out: TableRow[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object fx_1m row at index ${i}.`, + 'rows' + ); + } + + const pair = raw.pair; + if (typeof pair !== 'string' || !FX_1M_ACCEPTED_PAIRS.has(pair)) { + throw new MarketDataStoreValidationError( + `Invalid fx_1m pair in result row ${i}: ${String(pair)}.`, + 'pair' + ); + } + + const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); + if (tsUs < fromUs || tsUs > toUs || tsUs >= vaultCutoffUs) { + throw new MarketDataStoreValidationError( + `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us (cutoff ${vaultCutoffUs.toString()} us).`, + 'ts' + ); + } + + const source = raw.source; + if (typeof source !== 'string' || source.length === 0) { + throw new MarketDataStoreValidationError( + `Invalid fx_1m source in result row ${i}: ${String(source)}.`, + 'source' + ); + } + + out[i] = { + pair, + ts: microsToEpochMs(tsUs, 'ts', i, 'floor'), + open: readRequiredFiniteNumber(raw, 'open', i), + high: readRequiredFiniteNumber(raw, 'high', i), + low: readRequiredFiniteNumber(raw, 'low', i), + close: readRequiredFiniteNumber(raw, 'close', i), + source, + }; + } + + return { + columns: [...FX_1M_COLUMNS], + rows: out, + }; +} + +/** + * Creates a read-only Vault-fenced intraday `fx` reader backed by an injected + * {@link QuestDbQueryExecutor} over QuestDB `fx_1m`. + */ +export function createQuestDbIntradayFxReader( + options: QuestDbIntradayFxReaderOptions +): Pick { + if (!isPlainRecord(options)) { + throw new MarketDataStoreValidationError( + 'Expected a QuestDbIntradayFxReaderOptions object.', + 'options' + ); + } + + const executor: unknown = options.executor; + if (!isPlainRecord(executor) || typeof executor.query !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `executor` with a `query(sql, params)` method.', + 'executor' + ); + } + const typedExecutor = executor as unknown as QuestDbQueryExecutor; + const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); + + if ( + options.vaultOperatorAuthorized !== undefined && + typeof options.vaultOperatorAuthorized !== 'boolean' + ) { + throw new MarketDataStoreValidationError( + `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, + 'vaultOperatorAuthorized' + ); + } + + const planCtx: VaultFenceContext = { + vaultCutoffTs, + vaultOperatorAuthorized: false, + }; + + return { + async fx(q: QuestDbFx1mQuery): Promise
{ + const planned = planFx1mQuery(q, planCtx); + const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); + if (!isPlainRecord(result) || !Array.isArray(result.rows)) { + throw new MarketDataStoreValidationError( + 'Executor returned a malformed result; expected `{ rows: Record[] }`.', + 'rows' + ); + } + return mapFx1mRows( + result.rows as readonly Record[], + planned.fence, + vaultCutoffTs + ); + }, + }; +} + +/** + * Creates a combined read-only intraday `bars` + `fx` reader backed by an + * injected {@link QuestDbQueryExecutor} over QuestDB `bars_1m` and `fx_1m`. + */ +export function createQuestDbIntradayReader( + options: QuestDbIntradayBarsReaderOptions +): Pick { + const barsReader = createQuestDbIntradayBarsReader(options); + const fxReader = createQuestDbIntradayFxReader(options); + return { + bars(q) { + return barsReader.bars(q); + }, + fx(q) { + return fxReader.fx(q); + }, + }; +} diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts index a7b52608..4f7492a7 100644 --- a/libs/research/src/market-data-store-routed.ts +++ b/libs/research/src/market-data-store-routed.ts @@ -28,8 +28,8 @@ import { type MarketDataStore, MarketDataStoreValidationError } from './market-d export interface RoutedMarketDataStoreOptions { /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ readonly daily: MarketDataStore; - /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ - readonly intraday: Pick; + /** Backing intraday reader for `bars` (and optional `fx`) queries with `timeframe: '1m'`. */ + readonly intraday: Pick & Partial>; } const REQUIRED_DAILY_METHODS = [ @@ -55,7 +55,7 @@ function isDelegateObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } -function isIntraday1mBarsQuery(q: unknown): boolean { +function isIntraday1mQuery(q: unknown): boolean { return ( typeof q === 'object' && q !== null && @@ -150,12 +150,19 @@ export function createRoutedMarketDataStore( ); } + if (rawIntraday.fx !== undefined && typeof rawIntraday.fx !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `intraday.fx` to be a function when provided.', + 'intraday.fx' + ); + } + const daily = options.daily; const intraday = options.intraday; return { bars(q) { - if (isIntraday1mBarsQuery(q)) { + if (isIntraday1mQuery(q)) { return intraday.bars(q); } return daily.bars(q); @@ -182,6 +189,9 @@ export function createRoutedMarketDataStore( }, fx(q) { + if (intraday.fx !== undefined && isIntraday1mQuery(q)) { + return intraday.fx(q); + } return daily.fx(q); }, diff --git a/libs/research/src/mcp/host/stdio-host.ts b/libs/research/src/mcp/host/stdio-host.ts index b7ff3c3a..2077f60b 100644 --- a/libs/research/src/mcp/host/stdio-host.ts +++ b/libs/research/src/mcp/host/stdio-host.ts @@ -54,6 +54,17 @@ const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID'; const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT'; const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS'; const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES'; +const ENV_QUESTDB_URL = 'RESEARCH_MCP_QUESTDB_URL'; +const ENV_QUESTDB_HOST = 'RESEARCH_MCP_QUESTDB_HOST'; +const ENV_QUESTDB_PG_PORT = 'RESEARCH_MCP_QUESTDB_PG_PORT'; +const ENV_QUESTDB_DATABASE = 'RESEARCH_MCP_QUESTDB_DATABASE'; +const ENV_QUESTDB_USER = 'RESEARCH_MCP_QUESTDB_USER'; +const ENV_QUESTDB_PASSWORD = 'RESEARCH_MCP_QUESTDB_PASSWORD'; +const ENV_QUESTDB_SSL = 'RESEARCH_MCP_QUESTDB_SSL'; + +const DEFAULT_QUESTDB_PG_PORT = 8812; +const DEFAULT_QUESTDB_DATABASE = 'qdb'; +const STRICT_UINT_PORT_RE = /^\d+$/; const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; const AGENT_PRINCIPAL_RE = @@ -75,9 +86,27 @@ const rawHostEnvSchema = z [ENV_LIBRARY_ROOT]: nonBlankEnvString, [ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString, [ENV_EARLY_CLOSES]: nonBlankEnvString.optional(), + [ENV_QUESTDB_URL]: nonBlankEnvString.optional(), + [ENV_QUESTDB_HOST]: nonBlankEnvString.optional(), + [ENV_QUESTDB_PG_PORT]: nonBlankEnvString.optional(), + [ENV_QUESTDB_DATABASE]: nonBlankEnvString.optional(), + [ENV_QUESTDB_USER]: nonBlankEnvString.optional(), + [ENV_QUESTDB_PASSWORD]: nonBlankEnvString.optional(), + [ENV_QUESTDB_SSL]: nonBlankEnvString.optional(), }) .strict(); +/** Optional QuestDB intraday connection settings parsed from `RESEARCH_MCP_QUESTDB_*`. */ +export interface ResearchCopilotQuestDbConfig { + readonly url?: string; + readonly host?: string; + readonly port?: number; + readonly database?: string; + readonly user?: string; + readonly password?: string; + readonly ssl?: boolean; +} + /** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */ export interface ResearchCopilotHostConfig { readonly postgresUrl: string; @@ -88,6 +117,7 @@ export interface ResearchCopilotHostConfig { readonly libraryRoot: string; readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds']; readonly earlyCloses?: EarlyCloseOverrides; + readonly questdb?: ResearchCopilotQuestDbConfig; } /** @@ -175,11 +205,11 @@ function defineDataProperty(target: Record, key: string, value: T) }); } -function parsePostgresUrl(raw: string): string { +function parsePgWireUrl(raw: string, variable: string): string { if (raw !== raw.trim()) { throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.` + variable, + `Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.` ); } let parsed: URL; @@ -187,8 +217,8 @@ function parsePostgresUrl(raw: string): string { parsed = new URL(raw); } catch { throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.` + variable, + `Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL.` ); } if ( @@ -196,8 +226,8 @@ function parsePostgresUrl(raw: string): string { parsed.hostname.length === 0 ) { throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.` + variable, + `Invalid configuration variable "${variable}": expected a postgres:// or postgresql:// URL with a non-empty host.` ); } try { @@ -209,13 +239,152 @@ function parsePostgresUrl(raw: string): string { } } catch { throw new ResearchCopilotHostConfigError( - ENV_POSTGRES_URL, - `Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.` + variable, + `Invalid configuration variable "${variable}": URL credentials contain invalid percent-encoding.` ); } return raw; } +function parsePostgresUrl(raw: string): string { + return parsePgWireUrl(raw, ENV_POSTGRES_URL); +} + +function parseQuestDbSsl(raw: string): boolean { + const normalized = raw.trim().toLowerCase(); + if (normalized === 'true' || normalized === '1') { + return true; + } + if (normalized === 'false' || normalized === '0') { + return false; + } + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_SSL, + `Invalid configuration variable "${ENV_QUESTDB_SSL}": expected "true", "false", "1", or "0".` + ); +} + +function parseQuestDbPort(raw: string): number { + const trimmed = raw.trim(); + if (!STRICT_UINT_PORT_RE.test(trimmed)) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_PG_PORT, + `Invalid configuration variable "${ENV_QUESTDB_PG_PORT}": expected an integer port from 1 through 65535.` + ); + } + const port = Number(trimmed); + if (!Number.isSafeInteger(port) || port < 1 || port > 65535) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_PG_PORT, + `Invalid configuration variable "${ENV_QUESTDB_PG_PORT}": expected an integer port from 1 through 65535.` + ); + } + return port; +} + +function isQuestDbUrlTlsParamKey(rawKey: string): boolean { + const key = rawKey.trim().toLowerCase(); + return key === 'uselibpqcompat' || key === 'ssl' || key.startsWith('ssl'); +} + +function hasQuestDbUrlTlsOptions(rawUrl: string): boolean { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return false; + } + + for (const [rawKey] of parsed.searchParams.entries()) { + if (isQuestDbUrlTlsParamKey(rawKey)) { + return true; + } + } + + return false; +} + +function parseQuestDbConfig(data: { + readonly [ENV_QUESTDB_URL]?: string; + readonly [ENV_QUESTDB_HOST]?: string; + readonly [ENV_QUESTDB_PG_PORT]?: string; + readonly [ENV_QUESTDB_DATABASE]?: string; + readonly [ENV_QUESTDB_USER]?: string; + readonly [ENV_QUESTDB_PASSWORD]?: string; + readonly [ENV_QUESTDB_SSL]?: string; +}): ResearchCopilotQuestDbConfig | undefined { + const rawUrl = data[ENV_QUESTDB_URL]; + const rawHost = data[ENV_QUESTDB_HOST]; + const rawPort = data[ENV_QUESTDB_PG_PORT]; + const rawDatabase = data[ENV_QUESTDB_DATABASE]; + const rawUser = data[ENV_QUESTDB_USER]; + const rawPassword = data[ENV_QUESTDB_PASSWORD]; + const rawSsl = data[ENV_QUESTDB_SSL]; + + const hasAnyDiscrete = + rawHost !== undefined || + rawPort !== undefined || + rawDatabase !== undefined || + rawUser !== undefined || + rawPassword !== undefined; + + if (rawUrl === undefined && !hasAnyDiscrete && rawSsl === undefined) { + return undefined; + } + + const ssl = rawSsl !== undefined ? parseQuestDbSsl(rawSsl) : undefined; + + if (rawUrl !== undefined) { + if (hasAnyDiscrete) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_URL, + `Conflicting configuration variable "${ENV_QUESTDB_URL}": cannot be combined with discrete RESEARCH_MCP_QUESTDB_HOST/PG_PORT/DATABASE/USER/PASSWORD variables.` + ); + } + const url = parsePgWireUrl(rawUrl, ENV_QUESTDB_URL); + if (ssl !== undefined && hasQuestDbUrlTlsOptions(url)) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_SSL, + `Conflicting configuration variable "${ENV_QUESTDB_SSL}": cannot be combined with TLS/SSL query parameters in "${ENV_QUESTDB_URL}". Configure TLS in either the URL or "${ENV_QUESTDB_SSL}", not both.` + ); + } + return { + url, + ...(ssl !== undefined ? { ssl } : {}), + }; + } + + if (rawHost === undefined) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_HOST, + `Missing required configuration variable "${ENV_QUESTDB_HOST}" when other RESEARCH_MCP_QUESTDB_* variables are set.` + ); + } + + const host = rawHost.trim(); + if (host !== rawHost || /\s/.test(host)) { + throw new ResearchCopilotHostConfigError( + ENV_QUESTDB_HOST, + `Invalid configuration variable "${ENV_QUESTDB_HOST}": expected a hostname without whitespace.` + ); + } + + const port = rawPort !== undefined ? parseQuestDbPort(rawPort) : DEFAULT_QUESTDB_PG_PORT; + const database = + rawDatabase !== undefined ? rawDatabase.trim() : DEFAULT_QUESTDB_DATABASE; + const user = rawUser !== undefined ? rawUser.trim() : undefined; + const password = rawPassword; + + return { + host, + port, + database, + ...(user !== undefined ? { user } : {}), + ...(password !== undefined ? { password } : {}), + ...(ssl !== undefined ? { ssl } : {}), + }; +} + function parsePostgresSchema(raw: string): string { if (!SCHEMA_IDENT_RE.test(raw)) { throw new ResearchCopilotHostConfigError( @@ -526,6 +695,7 @@ export function parseResearchCopilotHostConfig( data[ENV_EARLY_CLOSES] !== undefined ? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES]) : undefined; + const questdb = parseQuestDbConfig(data); return { postgresUrl, @@ -536,6 +706,7 @@ export function parseResearchCopilotHostConfig( libraryRoot, referenceListingIds, ...(earlyCloses !== undefined ? { earlyCloses } : {}), + ...(questdb !== undefined ? { questdb } : {}), }; } @@ -554,13 +725,12 @@ function addRawAndDecodedNeedle(needles: Set, raw: string): void { } } -function collectSecretNeedles(postgresUrl: string): readonly string[] { - const needles = new Set(); - if (postgresUrl.length > 0) { - needles.add(postgresUrl); +function collectUrlSecretNeedles(needles: Set, rawUrl: string): void { + if (rawUrl.length > 0) { + needles.add(rawUrl); } try { - const parsed = new URL(postgresUrl); + const parsed = new URL(rawUrl); if (parsed.href.length > 0) { needles.add(parsed.href); } @@ -591,7 +761,23 @@ function collectSecretNeedles(postgresUrl: string): readonly string[] { } } } catch { - // Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered. + // Non-URL string passed directly: raw string is already covered. + } +} + +function collectSecretNeedles( + postgresUrl: string, + questdb?: ResearchCopilotQuestDbConfig +): readonly string[] { + const needles = new Set(); + collectUrlSecretNeedles(needles, postgresUrl); + if (questdb !== undefined) { + if (typeof questdb.url === 'string' && questdb.url.length > 0) { + collectUrlSecretNeedles(needles, questdb.url); + } + if (typeof questdb.password === 'string' && questdb.password.length > 0) { + addRawAndDecodedNeedle(needles, questdb.password); + } } return Array.from(needles); } @@ -708,7 +894,8 @@ export async function runResearchCopilotStdioHost( const { config } = deps; const secretNeedles = collectSecretNeedles( - typeof config.postgresUrl === 'string' ? config.postgresUrl : '' + typeof config.postgresUrl === 'string' ? config.postgresUrl : '', + config.questdb ); const closers: Array<() => Promise | void> = []; diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 0103f10a..98022160 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -6,12 +6,14 @@ import { analyzeSignalPanel, } from '@stock-bot/calculations'; import { z } from 'zod'; +import { parseFeatureRef } from '../../feature-library'; import { type BarRecord, type MarketDataStore, MarketDataStoreValidationError, type Table, type TableRow, + type UniverseRef, type VaultFenceContext, } from '../../market-data-store'; import { @@ -77,6 +79,9 @@ export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; /** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; +/** Hard maximum number of per-session feature cross-section queries in a single study. */ +export const ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES = 5_500; + const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const AGENT_PRINCIPAL_RE = /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; @@ -90,6 +95,15 @@ function canonicalDailyHorizonBucket(horizonSessions: number): HorizonBucket { const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); +function isValidFeatureRef(raw: string): boolean { + try { + parseFeatureRef(raw); + return true; + } catch { + return false; + } +} + const shortsSignalSpecSchema = z .object({ source: z.literal('shorts').describe('Signal data source ("shorts").'), @@ -118,9 +132,30 @@ const fundamentalsSignalSpecSchema = z .strict() .describe('Point-in-time fundamentals signal specification.'); +const featureSignalSpecSchema = z + .object({ + source: z.literal('feature').describe('Signal data source ("feature").'), + featureRef: z + .string() + .min(1) + .refine( + isValidFeatureRef, + 'Expected canonical versioned feature reference "@v" (e.g. "ret_1d@v1").' + ) + .describe('Canonical versioned feature reference ("@v"), e.g. "ret_1d@v1".'), + }) + .strict() + .describe('Versioned curated feature signal specification.'); + const signalSpecSchema = z - .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) - .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); + .discriminatedUnion('source', [ + shortsSignalSpecSchema, + fundamentalsSignalSpecSchema, + featureSignalSpecSchema, + ]) + .describe( + 'Discriminated signal source specification ("shorts", "fundamentals", or "feature").' + ); const analyzeSignalSharedFieldsSchema = z .object({ @@ -227,7 +262,9 @@ export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema message: data.signal.source === 'shorts' ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' - : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', + : data.signal.source === 'fundamentals' + ? 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' + : 'Feature signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', }); } }); @@ -238,29 +275,35 @@ function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); + const featureBranch = zodObjectToJsonSchema(featureSignalSpecSchema); const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { type: 'boolean' as const, default: false, }; + const featureRefProp = featureBranch.properties.featureRef ?? { + type: 'string' as const, + minLength: 1, + }; const signalProperty: JsonSchemaProperty = { type: 'object', description: signalSpecSchema.description, properties: { source: { type: 'string', - enum: ['shorts', 'fundamentals'], - description: 'Signal data source ("shorts" or "fundamentals").', + enum: ['shorts', 'fundamentals', 'feature'], + description: 'Signal data source ("shorts", "fundamentals", or "feature").', }, field: { type: 'string', enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], - description: 'Signal field name valid for the chosen source.', + description: 'Signal field name valid for "shorts" or "fundamentals".', }, allowEstimatedLag: allowEstimatedLagProp, + featureRef: featureRefProp, }, - required: ['source', 'field'], + required: ['source'], additionalProperties: false, - anyOf: [shortsBranch, fundamentalsBranch], + anyOf: [shortsBranch, fundamentalsBranch, featureBranch], }; return { @@ -732,6 +775,94 @@ function appendEligibleFundamentalsObservations(params: { return latestKnownAtByListing; } +function deriveFeatureSessionQueries( + bars: readonly BarRecord[], + fencedAsOfMs: number, + vaultCutoffTs: number, + vaultCutoffDate: string +): Array<{ readonly sessionDate: string; readonly asOfMs: number }> { + const unique = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + const sessionDate = utcDateOf(bar.ts); + if (sessionDate >= vaultCutoffDate) { + continue; + } + const asOfMs = Math.min(bar.ts, fencedAsOfMs); + if (asOfMs >= vaultCutoffTs) { + continue; + } + const key = `${sessionDate}:${asOfMs}`; + if (!unique.has(key)) { + unique.set(key, { sessionDate, asOfMs }); + } + } + return [...unique.values()].sort((a, b) => + a.sessionDate !== b.sessionDate ? (a.sessionDate < b.sessionDate ? -1 : 1) : a.asOfMs - b.asOfMs + ); +} + +function appendEligibleFeatureObservations(params: { + readonly table: Table; + readonly featureRef: string; + readonly listingIdSet: ReadonlySet; + readonly sessionQueryAsOfMs: number; + readonly seenKeys: Set; + readonly out: SignalObservation[]; +}): void { + const { table, featureRef, listingIdSet, sessionQueryAsOfMs, seenKeys, out } = params; + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + throw new SignalPanelError( + 'invalid_input', + 'Expected a crossSection Table object with array columns and rows.' + ); + } + + const normalizedKnownAt = sessionQueryAsOfMs === 0 ? 0 : sessionQueryAsOfMs; + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null) { + continue; + } + const listingId = row.listing_id; + if ( + typeof listingId !== 'number' || + !Number.isSafeInteger(listingId) || + !listingIdSet.has(listingId) + ) { + continue; + } + const rawValue = row[featureRef]; + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + continue; + } + const normalizedListingId = listingId === 0 ? 0 : listingId; + const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; + if (seenKeys.has(dedupeKey)) { + continue; + } + seenKeys.add(dedupeKey); + out.push({ + listingId: normalizedListingId, + knownAt: normalizedKnownAt, + value: rawValue === 0 ? 0 : rawValue, + }); + } +} + function buildCanonicalStudyExpression(params: { readonly input: AnalyzeSignalInput; readonly listingIds: readonly number[]; @@ -742,15 +873,23 @@ function buildCanonicalStudyExpression(params: { }): SignalStudyExpression { const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } = params; + const signalExprSuffix = + input.signal.source === 'feature' + ? `feature:${input.signal.featureRef}` + : `${input.signal.source}:${input.signal.field}`; return { - expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`, + expression: `mcp:analyze_signal:v1:${signalExprSuffix}`, params: { version: 1, signalSource: input.signal.source, - signalField: input.signal.field, - ...(input.signal.source === 'fundamentals' - ? { allowEstimatedLag: input.signal.allowEstimatedLag } - : {}), + ...(input.signal.source === 'feature' + ? { featureRef: input.signal.featureRef } + : { + signalField: input.signal.field, + ...(input.signal.source === 'fundamentals' + ? { allowEstimatedLag: input.signal.allowEstimatedLag } + : {}), + }), horizonSessions: input.horizonSessions, maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, adjustment: input.adjustment, @@ -824,12 +963,13 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { typeof options.store !== 'object' || options.store === null || typeof options.store.bars !== 'function' || + typeof options.store.crossSection !== 'function' || typeof options.store.shortsAsOf !== 'function' || typeof options.store.fundamentalsAsOf !== 'function' || typeof options.store.universe !== 'function' ) { throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `crossSection`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', 'store' ); } @@ -875,7 +1015,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT return defineMcpTool({ name: 'analyze_signal', description: - 'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', + 'Run a Vault-fenced cross-sectional short-interest, point-in-time fundamentals, or versioned feature signal study and record eligible trials to trial_ledger.', inputSchema: analyzeSignalInputSchema, jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, async handler(input: AnalyzeSignalInput): Promise { @@ -913,11 +1053,16 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT source: 'shorts', field: input.signal.field, } - : { - source: 'fundamentals', - field: input.signal.field, - allowEstimatedLag: input.signal.allowEstimatedLag, - }; + : input.signal.source === 'fundamentals' + ? { + source: 'fundamentals', + field: input.signal.field, + allowEstimatedLag: input.signal.allowEstimatedLag, + } + : { + source: 'feature', + featureRef: input.signal.featureRef, + }; const basePayloadFields = { scope: 'vault_fenced' as const, @@ -996,6 +1141,50 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT fenced.vaultCutoffDate ); signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); + } else if (input.signal.source === 'feature') { + const { featureRef } = input.signal; + const sessionQueries = deriveFeatureSessionQueries( + eligibleBars, + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + if (sessionQueries.length > ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES) { + return { + content: [ + { + type: 'text', + text: `Invalid arguments for tool "analyze_signal": Feature study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FEATURE_SESSION_QUERIES} session queries.`, + }, + ], + isError: true, + }; + } + + const featureUniverse: UniverseRef = + input.universe ?? (input.universeMarket as UniverseRef); + signals = []; + const seenKeys = new Set(); + for (const sessionQuery of sessionQueries) { + const sessionQueryAsOfIso = + sessionQuery.asOfMs === fenced.asOfMs + ? fenced.canonicalAsOf + : formatUtcIsoWithMicros(sessionQuery.asOfMs, 0); + const rawCrossSection = await store.crossSection({ + features: [featureRef], + date: sessionQuery.sessionDate, + universe: featureUniverse, + asOf: sessionQueryAsOfIso, + }); + appendEligibleFeatureObservations({ + table: rawCrossSection, + featureRef, + listingIdSet, + sessionQueryAsOfMs: sessionQuery.asOfMs, + seenKeys, + out: signals, + }); + } } else { const { field: fundamentalsField, allowEstimatedLag } = input.signal; const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); diff --git a/libs/research/src/mcp/tools/vault-fenced-input.ts b/libs/research/src/mcp/tools/vault-fenced-input.ts index 3eaa97c7..fe2620d2 100644 --- a/libs/research/src/mcp/tools/vault-fenced-input.ts +++ b/libs/research/src/mcp/tools/vault-fenced-input.ts @@ -249,6 +249,10 @@ const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ 'adjustment', 'scope', 'limit', + 'countries', + 'indicators', + 'features', + 'universe', ]); const SAFE_STORE_METHODS: ReadonlySet = new Set([ diff --git a/libs/research/test/event-panel-e2e.test.ts b/libs/research/test/event-panel-e2e.test.ts index 4ac07daa..270520b9 100644 --- a/libs/research/test/event-panel-e2e.test.ts +++ b/libs/research/test/event-panel-e2e.test.ts @@ -498,7 +498,7 @@ function createFakeDuckDbExecutor(fixture: QmFilingsFixture): { return out; } - if (sql.includes('events/year=*/part.parquet')) { + if (sql.includes('events/year=*/*.parquet')) { // Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso] const nIds = fixture.listingIds.length; const nKinds = params.length - nIds - 3; @@ -608,7 +608,7 @@ describe('qmFilings end-to-end event study (headless, no database)', () => { expect(clean.duck.queries).toHaveLength(3); expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata'); expect(clean.duck.queries[1]!.sql).toContain('cum_total_factor'); - expect(clean.duck.queries[2]!.sql).toContain('events/year=*/part.parquet'); + expect(clean.duck.queries[2]!.sql).toContain('events/year=*/*.parquet'); // Every bound timestamp parameter (`asOfIso`, `fromIso`, `toIso`) in every data query // is strictly `< vaultCutoffTs`. diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts index 9315471d..6bebfcc6 100644 --- a/libs/research/test/feature-library.test.ts +++ b/libs/research/test/feature-library.test.ts @@ -446,8 +446,8 @@ describe('validateFeatureDefinition', () => { () => validateFeatureDefinition( makeSimpleDef({ - inputs: ['macro' as FeatureDefinition['inputs'][number]], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}', + inputs: ['bars_1m' as FeatureDefinition['inputs'][number]], + sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1m}}', }) ), 'UNSUPPORTED_INPUT_DATASET' @@ -800,6 +800,54 @@ describe('planFeatureBatch', () => { } }); + it('expands {{input:macro}} with lagged regime-only provenance and {{input:corporate_actions}} with Vault-fenced known_at', () => { + const macroAndCaDef: FeatureDefinition = { + name: 'macro_ca_regime', + version: 1, + family: 'regime', + kind: 'duckdb_sql', + inputs: ['bars_1d', 'corporate_actions', 'macro'], + warmupBars: 0, + knownAtRule: 'max_input_known_at', + sql: ` + SELECT + b.listing_id, + b.ts, + GREATEST(b.known_at, ca.known_at, m.known_at) AS known_at, + m.value AS value + FROM {{input:bars_1d}} AS b + LEFT JOIN {{input:corporate_actions}} AS ca ON b.listing_id = ca.listing_id + LEFT JOIN {{input:macro}} AS m ON m.country_iso = 'US' AND m.indicator = 'cpi_yoy' + `, + }; + + const [write] = planFeatureBatch(macroAndCaDef, { + curatedRoot: '/data', + fromYear: 2022, + toYear: 2022, + vaultCutoffDate: '2023-06-01', + }); + expect(write).toBeDefined(); + expect(write?.outputPath).toBe('/data/features/macro_ca_regime/v1/year=2022/part.parquet'); + expect(write?.sql).toContain( + "read_parquet('/data/corporate_actions/part.parquet') WHERE known_at <= ?" + ); + expect(write?.sql).toContain( + "read_parquet('/data/macro/part.parquet') WHERE known_at <= ? AND known_at_source = 'publication_lag_estimate'" + ); + const ts2022 = '2022-12-31T23:59:59.999999Z'; + const vaultCeiling = '2023-05-31T23:59:59.999999Z'; + expect(write?.params).toEqual([ + ts2022, + vaultCeiling, // bars_1d + vaultCeiling, // corporate_actions + vaultCeiling, // macro + 2022, + ts2022, + vaultCeiling, // outer filter + ]); + }); + it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => { // Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z. const midyear = planFeatureBatch(RET_1D_V1, { diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index 5ad2bd8c..9a10c2f0 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -16,6 +16,7 @@ import { FUNDAMENTALS_PIT_VALUE_FIELDS, FX_1D_COLUMNS, FX_PAIR_MAP, + MACRO_COLUMNS, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, type PinnedAdjFactorsArtifact, @@ -32,6 +33,7 @@ import { planEventsQuery, planFundamentalsAsOfQuery, planFx1dQuery, + planMacroAsOfQuery, planShortsAsOfQuery, planUniverseQuery, resolveDuckDbConnectionBudget, @@ -386,7 +388,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => expect(kinds).toEqual(['filing', 'earnings', 'filing']); expect(withListings.sql).toBe( 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + - `FROM read_parquet('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` + + `FROM read_parquet('${CURATED_ROOT}/events/year=*/*.parquet', hive_partitioning = true) AS e ` + 'WHERE e.kind IN (?, ?) AND e.listing_id IN (?, ?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' + 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' ); @@ -410,7 +412,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () => ); expect(withoutListings.sql).toBe( 'SELECT e.listing_id, epoch_ms(e.ts) AS ts, epoch_ms(e.known_at) AS known_at, e.known_at_source, e.kind, e.subtype, e.payload_json ' + - `FROM read_parquet('${CURATED_ROOT}/events/year=*/part.parquet', hive_partitioning = true) AS e ` + + `FROM read_parquet('${CURATED_ROOT}/events/year=*/*.parquet', hive_partitioning = true) AS e ` + 'WHERE e.kind IN (?) AND e.ts >= ? AND e.ts <= ? AND e.known_at <= ? ' + 'ORDER BY e.listing_id ASC, e.ts ASC, e.kind ASC, e.subtype ASC, e.payload_json ASC, e.known_at ASC, e.known_at_source ASC' ); @@ -2420,16 +2422,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { to: '2025-02-01', }), }, - { - method: 'macroAsOf', - run: () => - store.macroAsOf({ - countries: ['US'], - indicators: ['CPI'], - from: '2025-01-01', - to: '2025-02-01', - }), - }, ]; for (const c of cases) { @@ -3271,44 +3263,254 @@ describe('fundamentalsAsOf hostile request inputs', () => { }); }); -describe('planCrossSectionQuery & createDuckDbMarketDataStore().crossSection()', () => { - it('plans Vault-fenced survivorship-free crossSection SQL and maps nullable feature values', async () => { +describe('planMacroAsOfQuery and store.macroAsOf', () => { + it('plans parameterized Vault-fenced SQL, deduplicates countries/indicators, and rejects post-cutoff from', () => { + const planned = planMacroAsOfQuery( + { + countries: ['US', 'CA', 'US'], + indicators: ['cpi_yoy', 'policy_rate', 'cpi_yoy'], + from: '2025-01-01', + to: '2026-08-01', + asOf: '2026-08-01', + }, + DEFAULT_CTX + ); + + expect(planned.sql).toContain(`read_parquet('${CURATED_ROOT}/macro/part.parquet') AS m`); + expect(planned.sql).toContain( + 'WHERE m.country_iso IN (?, ?) AND m.indicator IN (?, ?) AND m.period_date >= ? AND m.period_date <= ? AND m.known_at <= ?' + ); + expect(planned.sql).toContain( + 'ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC' + ); + expect(planned.sql).not.toContain('cpi_yoy'); + expect(planned.sql).not.toContain('policy_rate'); + expect(planned.params).toEqual([ + 'US', + 'CA', + 'cpi_yoy', + 'policy_rate', + '2025-01-01', + '2026-05-27', + MAX_ALLOWED_ISO_MICROS, + ]); + expect(planned.fenced.clampedTo).toBe(true); + expect(planned.fenced.clampedAsOf).toBe(true); + + expect(() => + planMacroAsOfQuery( + { + countries: ['US'], + indicators: ['cpi_yoy'], + from: '2026-05-28', + to: '2026-06-01', + }, + DEFAULT_CTX + ) + ).toThrow(VaultHoldoutFenceError); + }); + + it('fails closed on invalid inputs and corrupt macro provenance/unlagged/post-cutoff rows', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + await expect( + store.macroAsOf({ countries: [], indicators: ['cpi_yoy'], from: '2025-01-01', to: '2025-06-01' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + await expect( + store.macroAsOf({ countries: ['US'], indicators: [' '], from: '2025-01-01', to: '2025-06-01' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + await expect( + store.macroAsOf({ countries: ['US'], indicators: ['cpi_yoy'], from: '2026-05-28', to: '2026-06-01' }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + expect(fake.calls).toHaveLength(0); + + const periodMs = Date.UTC(2025, 0, 1); + const badSourceStore = createDuckDbMarketDataStore({ + executor: createRecordingExecutor({ + onQuery: () => [ + { + country_iso: 'US', + indicator: 'cpi_yoy', + period_date: '2025-01-01', + known_at: periodMs + 35 * 86_400_000, + known_at_source: 'release_timestamp', + value: 2.9, + }, + ], + }).executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + await expect( + badSourceStore.macroAsOf({ + countries: ['US'], + indicators: ['cpi_yoy'], + from: '2025-01-01', + to: '2025-06-01', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + + const unlaggedStore = createDuckDbMarketDataStore({ + executor: createRecordingExecutor({ + onQuery: () => [ + { + country_iso: 'US', + indicator: 'policy_rate', + period_date: '2025-01-01', + known_at: periodMs + 86_400_000 - 1, + known_at_source: 'publication_lag_estimate', + value: 4.5, + }, + ], + }).executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + await expect( + unlaggedStore.macroAsOf({ + countries: ['US'], + indicators: ['policy_rate'], + from: '2025-01-01', + to: '2025-06-01', + }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + + const validStore = createDuckDbMarketDataStore({ + executor: createRecordingExecutor({ + onQuery: () => [ + { + country_iso: 'US', + indicator: 'policy_rate', + period_date: '2025-01-01', + known_at: periodMs + 86_400_000, + known_at_source: 'publication_lag_estimate', + value: 4.5, + }, + ], + }).executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + const result = await validStore.macroAsOf({ + countries: ['US'], + indicators: ['policy_rate'], + from: '2025-01-01', + to: '2025-06-01', + }); + expect(result.columns).toEqual([...MACRO_COLUMNS]); + expect(result.rows).toHaveLength(1); + expect(result.rows[0]?.value).toBe(4.5); + }); +}); + +describe('planCrossSectionQuery and store.crossSection', () => { + it('plans survivorship-free universe join with versioned features, defaults omitted asOf to date, and rejects invalid/post-cutoff inputs', () => { expect(subpathPlanCrossSectionQuery).toBe(planCrossSectionQuery); const planned = planCrossSectionQuery( { - features: ['ret_1d@v1', 'mom_diff@v1', 'ret_1d@v1'], - date: '2025-01-02', - universe: 'US_EQ', - asOf: '2025-01-02T22:00:00Z', + features: ['ret_1d@v1', 'rsi_14@v2', 'ret_1d@v1'], + date: '2025-06-10', + universe: 'US_CA_EQ', }, DEFAULT_CTX ); expect(planned.sql).toContain( - `FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b` + `read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b` ); expect(planned.sql).toContain( - `FROM read_parquet('${CURATED_ROOT}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true)` + `read_parquet('${CURATED_ROOT}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true) AS f` ); expect(planned.sql).toContain( - `FROM read_parquet('${CURATED_ROOT}/features/mom_diff/v1/year=*/part.parquet', hive_partitioning = true)` + `read_parquet('${CURATED_ROOT}/features/rsi_14/v2/year=*/part.parquet', hive_partitioning = true) AS f` ); + expect(planned.sql).toContain('SELECT u.listing_id, f_0.value AS "ret_1d@v1", f_1.value AS "rsi_14@v2"'); expect(planned.sql).toContain('ORDER BY u.listing_id ASC'); expect(planned.params).toEqual([ 'USD', - '2024-12-26', - '2025-01-02', - '2025-01-02T23:59:59.999999Z', - '2025-01-02T22:00:00.000Z', - '2025-01-02T00:00:00.000Z', - '2025-01-02T23:59:59.999999Z', - '2025-01-02T22:00:00.000Z', - '2025-01-02T00:00:00.000Z', - '2025-01-02T23:59:59.999999Z', - '2025-01-02T22:00:00.000Z', + 'CAD', + '2025-06-03', + '2025-06-10', + '2025-06-10T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', + 2025, + '2025-06-10T00:00:00.000Z', + '2025-06-10T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', + 2025, + '2025-06-10T00:00:00.000Z', + '2025-06-10T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', ]); + for (const badRef of ['ret_1d', 'ret_1d@v0', 'ret_1d@v01', '../evil@v1', 'RET_1D@v1', '']) { + expect(() => + planCrossSectionQuery( + { features: [badRef], date: '2025-06-10', universe: 'US_EQ' }, + DEFAULT_CTX + ) + ).toThrow(MarketDataStoreValidationError); + } + + expect(() => + planCrossSectionQuery( + { features: ['ret_1d@v1'], date: '2026-05-28', universe: 'US_EQ' }, + DEFAULT_CTX + ) + ).toThrow(VaultHoldoutFenceError); + + // Later explicit asOf caps universe membership at end-of-date while retaining asOf for features. + const laterAsOf = planCrossSectionQuery( + { + features: ['ret_1d@v1'], + date: '2025-06-07', + universe: 'US_EQ', + asOf: '2025-06-10', + }, + DEFAULT_CTX + ); + expect(laterAsOf.params).toEqual([ + 'USD', + '2025-05-31', + '2025-06-07', + '2025-06-07T23:59:59.999999Z', + '2025-06-07T23:59:59.999999Z', + 2025, + '2025-06-07T00:00:00.000Z', + '2025-06-07T23:59:59.999999Z', + '2025-06-10T23:59:59.999999Z', + ]); + + // Earlier explicit intraday asOf applies to both universe membership and features. + const earlierAsOf = planCrossSectionQuery( + { + features: ['ret_1d@v1'], + date: '2025-06-07', + universe: 'US_EQ', + asOf: '2025-06-07T21:00:00Z', + }, + DEFAULT_CTX + ); + expect(earlierAsOf.params).toEqual([ + 'USD', + '2025-05-31', + '2025-06-07', + '2025-06-07T23:59:59.999999Z', + '2025-06-07T21:00:00.000Z', + 2025, + '2025-06-07T00:00:00.000Z', + '2025-06-07T23:59:59.999999Z', + '2025-06-07T21:00:00.000Z', + ]); + }); + + it('maps nullable feature values via store.crossSection and rejects invalid/post-cutoff requests with zero extra calls', async () => { const fake = createRecordingExecutor({ onQuery: () => [ { listing_id: 1, 'ret_1d@v1': 0.1, 'mom_diff@v1': 1.0 }, @@ -3334,7 +3536,6 @@ describe('planCrossSectionQuery & createDuckDbMarketDataStore().crossSection()', { listing_id: 2, 'ret_1d@v1': null, 'mom_diff@v1': -5.0 }, ]); - // Rejects post-cutoff date and invalid feature refs with 0 additional executor calls const beforeCalls = fake.calls.length; await expect( store.crossSection({ diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts index b17e06a2..3e6aba05 100644 --- a/libs/research/test/market-data-store-questdb.test.ts +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -3,14 +3,19 @@ import { type BarBatch, type BarRecord, DEFAULT_QUESTDB_BARS_BATCH_SIZE, + FX_1M_COLUMNS, MarketDataStoreNotImplementedError, MarketDataStoreValidationError, type QuestDbBars1mQuery, + type QuestDbFx1mQuery, type QuestDbQueryExecutor, VaultHoldoutFenceError, VaultScopeNotAuthorizedError, createQuestDbIntradayBarsReader, + createQuestDbIntradayFxReader, + createQuestDbIntradayReader, planBars1mQuery, + planFx1mQuery, } from '@stock-bot/research'; interface RecordedCall { @@ -766,3 +771,111 @@ describe('Malformed and out-of-fence row defence-in-depth', () => { expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true); }); }); + +describe('QuestDB fx_1m planner and reader', () => { + it('plans parameterized $1..$4 SQL binding USDCAD and USD.CAD and enforces Vault fence', () => { + const planned = planFx1mQuery( + { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-30T23:55:00.000Z', + to: '2025-07-05T00:00:00.000Z', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS, vaultOperatorAuthorized: true } + ); + + expect(planned.sql).toBe( + 'SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source FROM fx_1m WHERE ts >= $1 AND ts <= $2 AND pair IN ($3, $4) ORDER BY ts ASC' + ); + expect(planned.params).toEqual([ + '2025-06-30T23:55:00.000Z', + '2025-06-30T23:59:59.999Z', + 'USDCAD', + 'USD.CAD', + ]); + expect(planned.fence.clampedTo).toBe(true); + + expect(() => + planFx1mQuery( + { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-07-01T00:00:00.000Z', + to: '2025-07-02T00:00:00.000Z', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ) + ).toThrow(VaultHoldoutFenceError); + }); + + it('reads both USDCAD and USD.CAD rows via createQuestDbIntradayFxReader / createQuestDbIntradayReader and rejects post-cutoff microsecond rows', async () => { + const executor = new RecordingQuestDbExecutor(); + const ts1Ms = Date.UTC(2025, 5, 30, 23, 55, 0, 0); + const ts2Ms = Date.UTC(2025, 5, 30, 23, 56, 0, 0); + executor.setRows([ + { + pair: 'USDCAD', + ts_us: (BigInt(ts1Ms) * 1000n).toString(), + open: 1.36, + high: 1.362, + low: 1.359, + close: 1.361, + source: 'polygon', + }, + { + pair: 'USD.CAD', + ts_us: BigInt(ts2Ms) * 1000n, + open: 1.361, + high: 1.363, + low: 1.36, + close: 1.362, + source: 'polygon', + }, + ]); + + const reader = createQuestDbIntradayReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const q: QuestDbFx1mQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-30T23:55:00.000Z', + to: '2025-07-02T00:00:00.000Z', + }; + const table = await reader.fx(q); + expect(table.columns).toEqual([...FX_1M_COLUMNS]); + expect(table.rows).toHaveLength(2); + expect(table.rows[0]?.pair).toBe('USDCAD'); + expect(table.rows[1]?.pair).toBe('USD.CAD'); + + // Post-cutoff from rejects with zero additional executor calls. + await expect( + reader.fx({ + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-07-01T00:00:00.000Z', + to: '2025-07-02T00:00:00.000Z', + }) + ).rejects.toBeInstanceOf(VaultHoldoutFenceError); + expect(executor.calls).toHaveLength(1); + + // Row at exact vaultCutoffTs microsecond fails closed. + const fxReader = createQuestDbIntradayFxReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + executor.setRows([ + { + pair: 'USDCAD', + ts_us: (BigInt(VAULT_CUTOFF_TS) * 1000n).toString(), + open: 1.37, + high: 1.37, + low: 1.37, + close: 1.37, + source: 'polygon', + }, + ]); + await expect(fxReader.fx(q)).rejects.toBeInstanceOf(MarketDataStoreValidationError); + }); +}); diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts index 81b38fb6..f8734e17 100644 --- a/libs/research/test/market-data-store-routed.test.ts +++ b/libs/research/test/market-data-store-routed.test.ts @@ -13,6 +13,7 @@ import { type TableRow, createDuckDbMarketDataStore, createQuestDbIntradayBarsReader, + createQuestDbIntradayReader, createRoutedMarketDataStore, } from '@stock-bot/research'; import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; @@ -1094,5 +1095,97 @@ describe('createRoutedMarketDataStore', () => { expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); } }); + + it('routes fx(1m) to intraday.fx when provided while keeping fx(1d) on daily, and validates intraday.fx', async () => { + const intradayFxCalls: FxQuery[] = []; + const intradayFxTable: Table = { + columns: ['pair', 'ts', 'open', 'high', 'low', 'close', 'source'], + rows: [ + { + pair: 'USDCAD', + ts: Date.UTC(2025, 5, 30, 14, 30, 0), + open: 1.36, + high: 1.361, + low: 1.359, + close: 1.3605, + source: 'polygon', + }, + ], + }; + + const daily = new PrototypeDailyStore(); + const baseIntraday = new PrototypeIntradayReader(); + const intraday = { + bars: baseIntraday.bars.bind(baseIntraday), + async fx(q: FxQuery): Promise
{ + intradayFxCalls.push(q); + return intradayFxTable; + }, + }; + const store = createRoutedMarketDataStore({ daily, intraday }); + + const qFx1m: FxQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-30T14:30:00Z', + to: '2025-06-30T14:35:00Z', + }; + const qFx1d: FxQuery = { + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-06-01', + to: '2025-06-30', + }; + + const res1m = await store.fx(qFx1m); + expect(res1m).toBe(intradayFxTable); + expect(intradayFxCalls).toEqual([qFx1m]); + expect(daily.calls).toHaveLength(0); + + const res1d = await store.fx(qFx1d); + expect(res1d).toEqual({ columns: ['pair', 'close'], rows: [] }); + expect(daily.calls).toHaveLength(1); + expect(daily.calls[0]?.method).toBe('fx'); + expect(daily.calls[0]?.arg).toBe(qFx1d); + + // Invalid non-callable intraday.fx is rejected eagerly. + expect(() => + createRoutedMarketDataStore({ + daily, + intraday: { + bars: intraday.bars, + fx: 'not-a-fn' as unknown as MarketDataStore['fx'], + }, + }) + ).toThrow(MarketDataStoreValidationError); + + // Composed with real QuestDB intraday reader. + const questExec: QuestDbQueryExecutor = { + async query() { + return { + rows: [ + { + pair: 'USDCAD', + ts_us: (BigInt(Date.UTC(2025, 5, 30, 14, 30, 0)) * 1000n).toString(), + open: 1.36, + high: 1.361, + low: 1.359, + close: 1.3605, + source: 'polygon', + }, + ], + }; + }, + }; + const routedReal = createRoutedMarketDataStore({ + daily, + intraday: createQuestDbIntradayReader({ + executor: questExec, + vaultCutoffTs: VAULT_CUTOFF_TS, + }), + }); + const realFx1m = await routedReal.fx(qFx1m); + expect(realFx1m.rows).toHaveLength(1); + }); }); }); diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index e871fdeb..536f5e5d 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -10,6 +10,7 @@ import { } from '../src/market-data-store'; import { type BarsQuery, + type CrossSectionQuery, FUNDAMENTALS_PIT_VALUE_FIELDS, type FundamentalsAsOfQuery, MarketDataStoreNotImplementedError, @@ -288,6 +289,7 @@ interface FakeStoreState { readonly barsCalls: BarsQuery[]; readonly shortsCalls: ShortsAsOfQuery[]; readonly fundamentalsCalls: FundamentalsAsOfQuery[]; + readonly crossSectionCalls: CrossSectionQuery[]; readonly universeCalls: UniverseQuery[]; readonly store: MarketDataStore; } @@ -296,17 +298,20 @@ function createFakeStore(options?: { bars?: readonly BarRecord[]; shortsTable?: Table; fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise
; + crossSectionResolver?: (q: CrossSectionQuery) => Table | Promise
; universeIds?: readonly number[]; universeResolver?: (q: UniverseQuery) => number[]; leaky?: boolean; barsError?: Error; shortsError?: Error; fundamentalsError?: Error; + crossSectionError?: Error; universeError?: Error; }): FakeStoreState { const barsCalls: BarsQuery[] = []; const shortsCalls: ShortsAsOfQuery[] = []; const fundamentalsCalls: FundamentalsAsOfQuery[] = []; + const crossSectionCalls: CrossSectionQuery[] = []; const universeCalls: UniverseQuery[] = []; const allBars = options?.bars ?? []; @@ -402,7 +407,14 @@ function createFakeStore(options?: { return [...(options?.universeIds ?? [])]; }, - crossSection() { + async crossSection(q: CrossSectionQuery): Promise
{ + crossSectionCalls.push(q); + if (options?.crossSectionError !== undefined) { + throw options.crossSectionError; + } + if (options?.crossSectionResolver !== undefined) { + return options.crossSectionResolver(q); + } throw new MarketDataStoreNotImplementedError('crossSection'); }, async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ @@ -426,7 +438,7 @@ function createFakeStore(options?: { }, }; - return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; + return { barsCalls, shortsCalls, fundamentalsCalls, crossSectionCalls, universeCalls, store }; } async function callAnalyzeSignal(params: { @@ -1898,16 +1910,19 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(signalSchema.additionalProperties).toBe(false); expect(Object.keys(signalSchema.properties).sort()).toEqual([ 'allowEstimatedLag', + 'featureRef', 'field', 'source', ]); - expect(signalSchema.anyOf).toHaveLength(2); + expect(signalSchema.anyOf).toHaveLength(3); expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); + expect(signalSchema.anyOf[2]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[2]?.properties.source?.const).toBe('feature'); const validBase = { listingIds: [70_001, 70_002], @@ -3400,4 +3415,168 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); expect(badTableLedger.rows).toHaveLength(0); }); + + test('signal.source === "feature" evaluates versioned crossSection features PIT, matches direct baseline, and logs trial_ledger', async () => { + const fixture = buildCeoShortsFixture({ + preCutoffSessions: 45, + postCutoffSessions: 5, + listingCount: 16, + }); + const featureRef = 'ret_1d@v1'; + const from = fixture.allDates[0]!; + const lastPreCutoff = fixture.allDates[44]!; + const postCutoff = fixture.allDates[49]!; + + // Deterministic synthetic feature values per (date, listing_id). + const valueFor = (date: string, lid: number): number => { + const dayIdx = fixture.allDates.indexOf(date); + return ((lid * 17 + dayIdx * 13) % 29) / 100 - 0.14; + }; + + const fakeStore = createFakeStore({ + bars: fixture.bars, + crossSectionResolver: q => { + expect(q.features).toEqual([featureRef]); + expect(q.universe).toBe('US_EQ'); + return { + columns: ['listing_id', featureRef], + rows: [ + ...fixture.listingIds.map(lid => ({ + listing_id: lid, + [featureRef]: valueFor(q.date, lid), + })), + // Extra unrequested listing and non-finite/null rows should be ignored cleanly. + { listing_id: 999_999, [featureRef]: 999.0 }, + ], + }; + }, + }); + const fakeLedger = createFakeTrialLedger(); + + // 1. Invalid featureRef and FX universeMarket are rejected with zero store/ledger calls. + for (const badArgs of [ + { + listingIds: fixture.listingIds, + from, + to: lastPreCutoff, + signal: { source: 'feature', featureRef: 'bad_no_version' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + { + listingIds: fixture.listingIds, + from, + to: lastPreCutoff, + signal: { source: 'feature', featureRef }, + horizonSessions: 5, + universeMarket: 'FX', + horizonBucket: 'swing_1_10d', + }, + ]) { + const rejected = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: badArgs, + }); + expect(rejected.isError).toBe(true); + } + expect(fakeStore.barsCalls).toHaveLength(0); + expect(fakeStore.crossSectionCalls).toHaveLength(0); + expect(fakeLedger.rows).toHaveLength(0); + + // 2. Valid feature study spanning past vaultCutoffTs fences crossSection queries strictly < vaultCutoffTs. + const res = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + listingIds: fixture.listingIds, + from, + to: postCutoff, + asOf: postCutoff, + signal: { source: 'feature', featureRef }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + expect(payload.signal).toEqual({ source: 'feature', featureRef }); + expect(fakeStore.crossSectionCalls.length).toBe(45); + for (const call of fakeStore.crossSectionCalls) { + expect(call.date < fixture.vaultCutoffDate).toBe(true); + expect(call.asOf).toBeDefined(); + expect(Date.parse(call.asOf!)).toBeLessThan(fixture.vaultCutoffTs); + } + + // 3. Direct baseline equivalence & deterministic expression hash. + const preBars = fixture.bars.filter( + b => b.ts < fixture.vaultCutoffTs && b.knownAt < fixture.vaultCutoffTs + ); + const directSignals: SignalObservation[] = []; + for (const bar of preBars) { + const sessionDate = new Date(bar.ts).toISOString().slice(0, 10); + directSignals.push({ + listingId: bar.listingId, + knownAt: bar.ts, + value: valueFor(sessionDate, bar.listingId), + }); + } + const directBuilt = buildForwardReturnPanel({ + bars: preBars, + signals: directSignals, + horizonSessions: 5, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + const baselineLedger = createFakeTrialLedger(); + const expectedExpr = { + expression: `mcp:analyze_signal:v1:feature:${featureRef}`, + params: { + version: 1, + signalSource: 'feature', + featureRef, + horizonSessions: 5, + maxSignalAgeSessions: null, + adjustment: 'raw', + ledgerSeries: 'rank_ic', + effectiveFrom: payload.effectiveFrom, + effectiveTo: payload.effectiveTo, + effectiveAsOf: payload.effectiveAsOf, + }, + universe: { + kind: 'listingIds', + listingIds: [...fixture.listingIds].sort((a, b) => a - b), + }, + horizon: '5d', + }; + const directStudy = await analyzeSignal(baselineLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: expectedExpr, + panel: directBuilt.panel, + vaultCutoffDate: fixture.vaultCutoffDate, + ledgerSeries: 'rank_ic', + }); + + expect(directStudy.status).toBe('ok'); + if (payload.status === 'ok' && directStudy.status === 'ok') { + const expectedHash = canonicalExpressionHash({ + ...expectedExpr, + sampleStart: payload.trial.sampleStart, + sampleEnd: payload.trial.sampleEnd, + }); + expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(payload.trial.expressionHash).toBe(expectedHash); + expect(payload.trial.expressionHash).toBe(directStudy.trial.expressionHash); + expect(fakeLedger.rows).toHaveLength(1); + expect(fakeLedger.rows[0]?.stage).toBe('signal_ic'); + expect(fakeLedger.rows[0]?.expression_hash).toBe(expectedHash); + } + }); }); diff --git a/libs/research/test/mcp-stdio-host.test.ts b/libs/research/test/mcp-stdio-host.test.ts index 3dd7cdee..56b5cc7a 100644 --- a/libs/research/test/mcp-stdio-host.test.ts +++ b/libs/research/test/mcp-stdio-host.test.ts @@ -1190,6 +1190,178 @@ describe('runResearchCopilotStdioHost', () => { expect(caughtSafe).toBe(safeAggregate); }); + + test('parses optional RESEARCH_MCP_QUESTDB_* URL or host/port/user/password/database, rejects conflicting/partial configs, and redacts QuestDB secrets', async () => { + // 1. DuckDB-only startup omits questdb when unset. + const baseConfig = parseResearchCopilotHostConfig(buildValidEnv()); + expect(baseConfig.questdb).toBeUndefined(); + expect('questdb' in baseConfig).toBe(false); + + // 2. URL mode (+ optional SSL). + const questSecret = 'qdb_s3cr!t#42'; + const questUrl = `postgresql://admin:${encodeURIComponent(questSecret)}@10.0.0.51:8812/qdb`; + const urlConfig = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: questUrl, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }) + ); + expect(urlConfig.questdb).toEqual({ + url: questUrl, + ssl: true, + }); + + // 3. Discrete host mode with defaults and explicit overrides. + const hostDefaultConfig = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', + }) + ); + expect(hostDefaultConfig.questdb).toEqual({ + host: '10.0.0.51', + port: 8812, + database: 'qdb', + }); + + const hostFullConfig = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', + RESEARCH_MCP_QUESTDB_PG_PORT: '18812', + RESEARCH_MCP_QUESTDB_DATABASE: 'qdb_m2', + RESEARCH_MCP_QUESTDB_USER: 'reader', + RESEARCH_MCP_QUESTDB_PASSWORD: questSecret, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }) + ); + expect(hostFullConfig.questdb).toEqual({ + host: '10.0.0.51', + port: 18812, + database: 'qdb_m2', + user: 'reader', + password: questSecret, + ssl: false, + }); + + // 4. Rejects conflicting URL + host, partial port-without-host, bad port, bad ssl, unknown var, + // and any URL TLS/SSL query parameters combined with RESEARCH_MCP_QUESTDB_SSL without leaking secrets. + const invalidEnvs: Array> = [ + { RESEARCH_MCP_QUESTDB_URL: questUrl, RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51' }, + { RESEARCH_MCP_QUESTDB_PG_PORT: '8812' }, + { RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_PG_PORT: '99999' }, + { RESEARCH_MCP_QUESTDB_HOST: '10.0.0.51', RESEARCH_MCP_QUESTDB_SSL: 'maybe' }, + { RESEARCH_MCP_QUESTDB_UNKNOWN: '1' }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=no-verify`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=false`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=false`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?ssl=true`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=prefer`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslrootcert=/etc/ssl/ca.pem`, + RESEARCH_MCP_QUESTDB_SSL: 'false', + }, + { + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?uselibpqcompat=true`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }, + ]; + for (const override of invalidEnvs) { + let caughtInvalid: unknown; + try { + parseResearchCopilotHostConfig(buildValidEnv(override)); + } catch (err) { + caughtInvalid = err; + } + expect(caughtInvalid).toBeInstanceOf(ResearchCopilotHostConfigError); + expect((caughtInvalid as Error).message).not.toContain(questSecret); + expect((caughtInvalid as Error).message).not.toContain(questUrl); + } + + // Single-source-of-truth TLS configs are accepted (URL-only TLS params without + // RESEARCH_MCP_QUESTDB_SSL, or clean URL with non-TLS query params + RESEARCH_MCP_QUESTDB_SSL). + const urlOnlyTlsEnable = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=require`, + }) + ); + expect(urlOnlyTlsEnable.questdb).toEqual({ + url: `${questUrl}?sslmode=require`, + }); + const urlOnlyTlsDisable = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?sslmode=disable`, + }) + ); + expect(urlOnlyTlsDisable.questdb).toEqual({ + url: `${questUrl}?sslmode=disable`, + }); + const flagOnlyTls = parseResearchCopilotHostConfig( + buildValidEnv({ + RESEARCH_MCP_QUESTDB_URL: `${questUrl}?application_name=copilot`, + RESEARCH_MCP_QUESTDB_SSL: 'true', + }) + ); + expect(flagOnlyTls.questdb).toEqual({ + url: `${questUrl}?application_name=copilot`, + ssl: true, + }); + + // 5. Redacts QuestDB URL / password on openStore and cleanup errors. + for (const cfg of [urlConfig, hostFullConfig]) { + let caught: unknown; + try { + await runResearchCopilotStdioHost({ + config: cfg, + openExecutor: async () => ({ + executor: createFakeExecutor().executor, + close: async () => {}, + }), + openStore: async () => { + throw new Error(`connect failed for ${cfg.questdb?.url ?? cfg.questdb?.password}`); + }, + createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }), + newId: () => 'id-1', + now: () => FIXED_NOW_MS, + stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output }, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).not.toContain(questSecret); + expect((caught as Error).message).not.toContain(questUrl); + } + }); }); describe('stdio-host dependency-free source invariants', () => { diff --git a/python/tests/test_events_copublish.py b/python/tests/test_events_copublish.py new file mode 100644 index 00000000..aa22394f --- /dev/null +++ b/python/tests/test_events_copublish.py @@ -0,0 +1,215 @@ +"""Offline co-publication tests for MarketDataStore.events and event studies.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import duckdb + +from stockbot.calculations import compute_event_study +from stockbot.data import MarketDataStore +from stockbot.signals import run_event_study_trial +from stockbot.vault import compute_vault_cutoff_ts, resolve_duckdb_budget, vault_cutoff_date_str + + +@dataclass(frozen=True) +class _FakeRecordedTrial: + trial_id: int + expression_hash: str + sample_start: str + sample_end: str + + +class _InMemoryLedger: + def __init__(self) -> None: + self.recorded: list[_FakeRecordedTrial] = [] + + def record_trial(self, **kwargs: Any) -> _FakeRecordedTrial: + trial = _FakeRecordedTrial( + trial_id=len(self.recorded) + 1, + expression_hash=str(kwargs["expression_hash"]), + sample_start=str(kwargs["sample_start"]), + sample_end=str(kwargs["sample_end"]), + ) + self.recorded.append(trial) + return trial + + def cluster_deflated_sharpe( + self, + *, + trial_id: int, + observation_dates_by_trial_id: dict[int, list[str]], + ) -> dict[str, Any]: + return { + "trial_id": trial_id, + "n_dates": len(observation_dates_by_trial_id[trial_id]), + } + + +def _build_copublished_curated_root(tmp_path: Path) -> tuple[Path, int, str]: + curated_root = tmp_path / "curated" + bars_dir = curated_root / "bars_1d" / "year=2024" + events_dir = curated_root / "events" / "year=2024" + bars_dir.mkdir(parents=True) + events_dir.mkdir(parents=True) + + vault_cutoff_ts = compute_vault_cutoff_ts("2025-08-13") + vault_cutoff_date = vault_cutoff_date_str(vault_cutoff_ts) + + sessions = [ + "2024-06-03", + "2024-06-04", + "2024-06-05", + "2024-06-06", + "2024-06-07", + "2024-06-10", + "2024-06-11", + "2024-06-12", + "2024-06-13", + "2024-06-14", + ] + closes_101 = [100.0, 101.0, 103.02, 103.02, 106.1106, 106.1106, 107.171706, 107.171706, 107.171706, 107.171706] + closes_202 = [100.0, 100.0, 100.0, 104.0, 104.0, 109.2, 109.2, 109.2, 120.12, 120.12] + + bar_rows: list[str] = [] + for s_date, c1, c2 in zip(sessions, closes_101, closes_202): + bar_rows.append( + f"(101::INTEGER, DATE '{s_date}', TIMESTAMPTZ '{s_date} 20:00:00+00', " + f"{c1}::DOUBLE, {c1}::DOUBLE, {c1}::DOUBLE, {c1}::DOUBLE, " + f"100000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, 'eod_unadj'::VARCHAR, TIMESTAMPTZ '{s_date} 20:00:00+00')" + ) + bar_rows.append( + f"(202::INTEGER, DATE '{s_date}', TIMESTAMPTZ '{s_date} 20:00:00+00', " + f"{c2}::DOUBLE, {c2}::DOUBLE, {c2}::DOUBLE, {c2}::DOUBLE, " + f"100000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, 'eod_unadj'::VARCHAR, TIMESTAMPTZ '{s_date} 20:00:00+00')" + ) + + con = duckdb.connect(":memory:") + try: + con.execute( + f""" + COPY ( + SELECT * FROM (VALUES + {", ".join(bar_rows)} + ) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, source, known_at) + ) TO '{bars_dir / "part.parquet"}' (FORMAT PARQUET) + """ + ) + + # Co-published filings & earnings in events/year=2024/part.parquet + con.execute( + f""" + COPY ( + SELECT * FROM (VALUES + (101::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, '8-k'::VARCHAR, '{{"filing_id":"f1"}}'::VARCHAR), + (202::INTEGER, TIMESTAMPTZ '2024-06-06 14:30:00+00', TIMESTAMPTZ '2024-06-06 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, '8-k'::VARCHAR, '{{"filing_id":"f2"}}'::VARCHAR), + (101::INTEGER, TIMESTAMPTZ '2024-06-07 14:30:00+00', TIMESTAMPTZ '2024-06-07 14:30:00+00', 'filing_timestamp'::VARCHAR, 'earnings'::VARCHAR, 'bto'::VARCHAR, '{{"quarter":"Q1"}}'::VARCHAR), + (202::INTEGER, TIMESTAMPTZ '2024-06-10 14:30:00+00', TIMESTAMPTZ '2024-06-10 14:30:00+00', 'filing_timestamp'::VARCHAR, 'earnings'::VARCHAR, 'bto'::VARCHAR, '{{"quarter":"Q1"}}'::VARCHAR), + (101::INTEGER, TIMESTAMPTZ '2024-06-11 14:30:00+00', TIMESTAMPTZ '2024-06-11 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'md&a'::VARCHAR, '{{"filing_id":"f3"}}'::VARCHAR) + ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) + ) TO '{events_dir / "part.parquet"}' (FORMAT PARQUET) + """ + ) + + # Co-published ceoPosts in events/year=2024/part-posts.parquet: + # 1. Edited ceo_post (posted before 16:00 ET close on 2024-06-12, edited after close at 21:30 UTC) + # 2. Vault holdout row (known_at = 2025-02-14 >= vault_cutoff_ts) + con.execute( + f""" + COPY ( + SELECT * FROM (VALUES + (202::INTEGER, TIMESTAMPTZ '2024-06-12 15:00:00+00', TIMESTAMPTZ '2024-06-12 21:30:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{{"spiel_id":"sp-edit-1","is_edited":true,"text":"edited after close"}}'::VARCHAR), + (202::INTEGER, TIMESTAMPTZ '2024-12-30 15:00:00+00', TIMESTAMPTZ '2025-02-14 15:00:00+00', 'post_edited'::VARCHAR, 'ceo_post'::VARCHAR, 'retail'::VARCHAR, '{{"spiel_id":"sp-vault-1","is_edited":true,"text":"vault holdout"}}'::VARCHAR) + ) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json) + ) TO '{events_dir / "part-posts.parquet"}' (FORMAT PARQUET) + """ + ) + finally: + con.close() + + # Transient publish files must be ignored by events/year=*/*.parquet + (events_dir / "part.parquet.99999-0.tmp").write_text("not-parquet") + (events_dir / "part.parquet.99999-0.bak").write_text("not-parquet") + (curated_root / "events" / ".write.lock").write_text("99999\n") + + return curated_root, vault_cutoff_ts, vault_cutoff_date + + +def test_events_copublish_pit_vault_and_event_study(tmp_path: Path) -> None: + curated_root, vault_cutoff_ts, vault_cutoff_date = _build_copublished_curated_root(tmp_path) + budget = resolve_duckdb_budget( + memory_limit="2GB", + threads=2, + temp_directory=str(tmp_path / "duckdb-tmp"), + ) + + with MarketDataStore(curated_root, vault_cutoff_ts=vault_cutoff_ts, budget=budget) as store: + assert store._events_glob().endswith("/events/year=*/*.parquet") + + before_edit = store.events( + kinds=["filing", "earnings", "ceo_post"], + from_date="2024-06-01", + to_date="2024-12-31", + as_of="2024-06-12T21:00:00Z", + ) + assert before_edit.height == 5 + assert before_edit["kind"].to_list() == ["filing", "earnings", "filing", "filing", "earnings"] + + after_edit = store.events( + kinds=["filing", "earnings", "ceo_post"], + from_date="2024-06-01", + to_date="2024-12-31", + as_of="2025-02-12T23:59:59Z", + ) + assert after_edit.height == 6 + assert after_edit["kind"].to_list() == [ + "filing", + "earnings", + "filing", + "filing", + "earnings", + "ceo_post", + ] + assert after_edit["known_at_source"].to_list()[-1] == "post_edited" + assert all("sp-vault-1" not in p for p in after_edit["payload_json"].to_list()) + + bars_df = store.bars( + listing_ids=[101, 202], + from_date="2024-06-03", + to_date="2024-06-14", + as_of="2024-06-14T23:59:59Z", + ) + + study_before = compute_event_study( + bars_df, + before_edit, + vault_cutoff_date=vault_cutoff_date, + pre_days=1, + post_days=1, + min_events=5, + ) + assert study_before["status"] == "ok" + assert study_before["events_used"] == 5 + assert "2024-06-13" not in study_before["clustered_dates"] + + ledger = _InMemoryLedger() + trial_after = run_event_study_trial( + bars_df=bars_df, + events_df=after_edit, + ledger=ledger, # type: ignore[arg-type] + universe_market="CA_EQ", + horizon_bucket="swing_1_10d", + expression="copub_events_filing_earnings_ceo_post", + params={"kinds": ["filing", "earnings", "ceo_post"]}, + vault_cutoff_date=vault_cutoff_date, + pre_days=1, + post_days=1, + min_events=5, + ) + assert trial_after["status"] == "ok" + assert trial_after["study"]["events_used"] == 6 + assert "2024-06-13" in trial_after["study"]["clustered_dates"] + assert "2024-06-12" not in trial_after["study"]["clustered_dates"] + assert len(ledger.recorded) == 1 diff --git a/scripts/questdb-init-m2.ts b/scripts/questdb-init-m2.ts new file mode 100644 index 00000000..696a3450 --- /dev/null +++ b/scripts/questdb-init-m2.ts @@ -0,0 +1,113 @@ +#!/usr/bin/env bun +/** + * Opt-in CLI to initialize M2 QuestDB 10.2.0 intraday tables (`bars_1m`, + * `fx_1m`, `bar_revisions`) via PGWire using `applyM2IntradayDDL()`. + * + * Connection env vars (checked in order): + * - `QUESTDB_URL` or `RESEARCH_MCP_QUESTDB_URL` + * - `QUESTDB_HOST` / `RESEARCH_MCP_QUESTDB_HOST` (default `localhost`) + * - `QUESTDB_PG_PORT` / `RESEARCH_MCP_QUESTDB_PG_PORT` (default `8812`) + * - `QUESTDB_DATABASE` / `RESEARCH_MCP_QUESTDB_DATABASE` (default `qdb`) + * - `QUESTDB_USER` / `RESEARCH_MCP_QUESTDB_USER` + * - `QUESTDB_PASSWORD` / `RESEARCH_MCP_QUESTDB_PASSWORD` + * - `QUESTDB_SSL` / `RESEARCH_MCP_QUESTDB_SSL` (`true` | `false`) + */ + +import { + applyM2IntradayDDL, + assertNoConflictingQuestDbSsl, + openQuestDbPgExecutor, + type QuestDbPgExecutorConfig, +} from '@stock-bot/questdb'; + +function readEnv( + env: Readonly>, + primary: string, + fallback: string +): string | undefined { + const value = env[primary] ?? env[fallback]; + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +function parseSslFlag(raw: string): boolean { + const normalized = raw.trim().toLowerCase(); + if (normalized === 'true' || normalized === '1') { + return true; + } + if (normalized === 'false' || normalized === '0') { + return false; + } + throw new RangeError( + 'Invalid QuestDB SSL configuration: expected "true", "false", "1", or "0".' + ); +} + +export function resolveQuestDbInitM2Config( + env: Readonly> = process.env +): QuestDbPgExecutorConfig { + const url = readEnv(env, 'QUESTDB_URL', 'RESEARCH_MCP_QUESTDB_URL'); + const sslRaw = readEnv(env, 'QUESTDB_SSL', 'RESEARCH_MCP_QUESTDB_SSL'); + const ssl = sslRaw !== undefined ? parseSslFlag(sslRaw) : undefined; + + if (url !== undefined) { + if (ssl !== undefined) { + assertNoConflictingQuestDbSsl(url, ssl); + } + return { + url, + ...(ssl !== undefined ? { ssl } : {}), + }; + } + + const host = readEnv(env, 'QUESTDB_HOST', 'RESEARCH_MCP_QUESTDB_HOST') ?? 'localhost'; + const portRaw = readEnv(env, 'QUESTDB_PG_PORT', 'RESEARCH_MCP_QUESTDB_PG_PORT'); + const port = portRaw !== undefined ? Number(portRaw) : 8812; + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new RangeError( + `Invalid QuestDB PGWire port "${String(portRaw)}". Expected 1..65535.` + ); + } + const database = readEnv(env, 'QUESTDB_DATABASE', 'RESEARCH_MCP_QUESTDB_DATABASE') ?? 'qdb'; + const user = readEnv(env, 'QUESTDB_USER', 'RESEARCH_MCP_QUESTDB_USER'); + const password = readEnv(env, 'QUESTDB_PASSWORD', 'RESEARCH_MCP_QUESTDB_PASSWORD'); + + return { + host, + port, + database, + ...(user !== undefined ? { user } : {}), + ...(password !== undefined ? { password } : {}), + ...(ssl !== undefined ? { ssl } : {}), + }; +} + +export async function runQuestDbInitM2( + env: Readonly> = process.env, + openExecutor: typeof openQuestDbPgExecutor = openQuestDbPgExecutor +): Promise<{ readonly appliedTables: readonly string[] }> { + const config = resolveQuestDbInitM2Config(env); + const handle = await openExecutor(config); + try { + return await applyM2IntradayDDL(handle.executor); + } finally { + await handle.close(); + } +} + +if (import.meta.main) { + runQuestDbInitM2() + .then(result => { + process.stdout.write( + `Initialized QuestDB M2 intraday tables: ${result.appliedTables.join(', ')}\n` + ); + }) + .catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`questdb-init-m2 failed: ${message}\n`); + process.exit(1); + }); +} diff --git a/scripts/test/m2-gap-audit.test.ts b/scripts/test/m2-gap-audit.test.ts index 84742687..ed2967b7 100644 --- a/scripts/test/m2-gap-audit.test.ts +++ b/scripts/test/m2-gap-audit.test.ts @@ -70,7 +70,6 @@ describe('design/m2-gap-audit.md citations', () => { ['tools/curate-etl/src/cli.rs', 'CurateBars1m('], ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], ['tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes'], - ['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'], ['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/], ['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'], ]; diff --git a/scripts/test/m2-master-audit.test.ts b/scripts/test/m2-master-audit.test.ts index 2191ff51..ab0f6166 100644 --- a/scripts/test/m2-master-audit.test.ts +++ b/scripts/test/m2-master-audit.test.ts @@ -41,8 +41,8 @@ function citedRepoPaths(markdown: string): string[] { .sort(); } -function lineAt(file: string, line: number): string { - return readFileSync(join(repoRoot, file), 'utf8').split('\n')[line - 1] ?? ''; +function fileContents(file: string): string { + return readFileSync(join(repoRoot, file), 'utf8'); } describe('design/m2-master-audit.md citations', () => { @@ -59,102 +59,93 @@ describe('design/m2-master-audit.md citations', () => { expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); }); - // [file, 1-based line the audit cites, text that line must contain] - const lineCitations: Array<[file: string, line: number, expected: string]> = [ - ['tools/curate-etl/src/parquet_posts.rs', 22, 'EVENT_KIND_POST'], - ['tools/curate-etl/src/run_curate_posts.rs', 133, 'EventsDatasetExists'], - ['tools/curate-etl/src/mongo_stream.rs', 53, 'pub enum SourceCollection'], - ['tools/curate-etl/src/run_curate_fundamentals.rs', 113, 'pub struct CurateFundamentalsArgs'], - ['tools/curate-etl/src/cli.rs', 98, 'CurateBars1m('], - ['tools/curate-etl/src/cli.rs', 99, 'CurateQmBars1m('], - ['tools/curate-etl/src/cli.rs', 100, 'CurateFx1m('], - ['tools/curate-etl/src/cli.rs', 101, 'CuratePosts('], - ['tools/curate-etl/src/cli.rs', 102, 'CurateFundamentals('], - ['tools/curate-etl/src/cli.rs', 103, 'CurateMacro('], - ['tools/curate-etl/src/cli.rs', 104, 'SendIlp('], - ['tools/curate-etl/src/cli.rs', 1317, 'CliAction::CuratePosts'], - ['tools/curate-etl/src/cli.rs', 1636, 'CliAction::CurateFundamentals'], - ['tools/curate-etl/src/cli.rs', 1689, 'CliAction::CurateMacro'], - ['tools/curate-etl/src/cli.rs', 2110, 'CliAction::CurateBars1m'], - ['tools/curate-etl/src/cli.rs', 2277, 'CliAction::CurateQmBars1m'], - ['tools/curate-etl/src/cli.rs', 2381, 'CliAction::CurateFx1m'], - ['tools/curate-etl/src/cli.rs', 2461, 'CliAction::SendIlp'], - ['tools/curate-etl/src/main.rs', 22, 'run_send_ilp'], - ['tools/curate-etl/src/main.rs', 39, 'run_curate_qm_bars_1m'], + // [file, symbol or test reported as landed that must still exist in the file] + // Gaps reported by the audit (such as `EventsDatasetExists` or the old `events/year=*/part.parquet` + // glob) are intentionally omitted so closing those gaps does not break this citation guard. + const symbolCitations: Array<[file: string, expected: string]> = [ + ['tools/curate-etl/src/parquet_posts.rs', 'EVENT_KIND_POST'], + ['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'], + ['tools/curate-etl/src/run_curate_fundamentals.rs', 'pub struct CurateFundamentalsArgs'], + ['tools/curate-etl/src/cli.rs', 'CurateBars1m('], + ['tools/curate-etl/src/cli.rs', 'CurateQmBars1m('], + ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], + ['tools/curate-etl/src/cli.rs', 'CuratePosts('], + ['tools/curate-etl/src/cli.rs', 'CurateFundamentals('], + ['tools/curate-etl/src/cli.rs', 'CurateMacro('], + ['tools/curate-etl/src/cli.rs', 'SendIlp('], + ['tools/curate-etl/src/cli.rs', 'CliAction::CuratePosts'], + ['tools/curate-etl/src/cli.rs', 'CliAction::CurateFundamentals'], + ['tools/curate-etl/src/cli.rs', 'CliAction::CurateMacro'], + ['tools/curate-etl/src/cli.rs', 'CliAction::CurateBars1m'], + ['tools/curate-etl/src/cli.rs', 'CliAction::CurateQmBars1m'], + ['tools/curate-etl/src/cli.rs', 'CliAction::CurateFx1m'], + ['tools/curate-etl/src/cli.rs', 'CliAction::SendIlp'], + ['tools/curate-etl/src/main.rs', 'run_send_ilp'], + ['tools/curate-etl/src/main.rs', 'run_curate_qm_bars_1m'], [ 'tools/curate-etl/src/fundamentals_tests.rs', - 104, 'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2', ], [ 'tools/curate-etl/src/parquet_fundamentals_tests.rs', - 1107, 'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm', ], [ 'tools/curate-etl/src/run_curate_bars_1m_tests.rs', - 402, 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes', ], - ['tools/curate-etl/tests/cli.rs', 1747, 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'], - ['tools/curate-etl/tests/cli.rs', 1787, 'TcpListener::bind("127.0.0.1:0")'], + ['tools/curate-etl/tests/cli.rs', 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'], + ['tools/curate-etl/tests/cli.rs', 'TcpListener::bind("127.0.0.1:0")'], [ 'tools/curate-etl/tests/cli.rs', - 1877, 'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage', ], - ['tools/curate-etl/tests/cli.rs', 1939, 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'], + ['tools/curate-etl/tests/cli.rs', 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'], [ 'tools/curate-etl/tests/curate_macro.rs', - 178, 'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage', ], [ 'tools/curate-etl/tests/curate_macro.rs', - 471, 'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel', ], - ['tools/curate-etl/tests/curate_macro.rs', 709, 'fn cli_rerun_on_same_inputs_is_byte_deterministic'], + ['tools/curate-etl/tests/curate_macro.rs', 'fn cli_rerun_on_same_inputs_is_byte_deterministic'], [ 'tools/curate-etl/tests/curate_qm_bars_1m.rs', - 336, 'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants', ], [ 'tools/curate-etl/tests/curate_qm_bars_1m.rs', - 527, 'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards', ], [ 'tools/curate-etl/tests/curate_qm_bars_1m.rs', - 622, 'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped', ], - ['tools/curate-etl/src/run_curate_fx_1m.rs', 24, 'bar-start `ts`'], - ['libs/data/questdb/src/schema.ts', 33, 'fx_1m: {'], - ['libs/data/questdb/src/schema.ts', 139, 'export function getM2IntradayDDL'], - ['libs/data/duckdb/src/research-copilot-store.ts', 33, 'export const openResearchCopilotStore'], - ['libs/data/duckdb/src/research-copilot-store.ts', 40, 'vaultOperatorAuthorized: false'], - ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 251, 'fundamentalsAsOf enforces restatement non-overwrite'], - ['libs/research/src/market-data-store-duckdb.ts', 1448, "'events/year=*/part.parquet'"], - ['libs/research/src/market-data-store-duckdb.ts', 1529, "timeframe === '1m'"], - ['libs/research/src/market-data-store-duckdb.ts', 2283, 'crossSection('], - ['libs/research/src/market-data-store-duckdb.ts', 2287, 'async fundamentalsAsOf('], - ['libs/research/src/market-data-store-duckdb.ts', 2294, 'macroAsOf('], - ['libs/research/src/market-data-store-routed.ts', 185, 'return daily.fx(q)'], - ['libs/research/src/mcp/tools/analyze-signal.ts', 122, 'discriminatedUnion'], - ['libs/research/src/feature-library.ts', 29, 'RET_1D_V1'], - ['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'], - ['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'], - ['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'], - ['package.json', 56, '"mcp:research-copilot"'], - ['design/MILESTONES.md', 96, 'eodIntraday1M'], - ['docker-compose.quant.yml', 35, '1048576'], + ['tools/curate-etl/src/run_curate_fx_1m.rs', 'bar-start `ts`'], + ['libs/data/questdb/src/schema.ts', 'fx_1m: {'], + ['libs/data/questdb/src/schema.ts', 'export function getM2IntradayDDL'], + ['libs/data/duckdb/src/research-copilot-store.ts', 'export const openResearchCopilotStore'], + ['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'], + ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'fundamentalsAsOf enforces restatement non-overwrite'], + ['libs/research/src/market-data-store-duckdb.ts', "timeframe === '1m'"], + ['libs/research/src/market-data-store-duckdb.ts', 'crossSection('], + ['libs/research/src/market-data-store-duckdb.ts', 'async fundamentalsAsOf('], + ['libs/research/src/market-data-store-duckdb.ts', 'macroAsOf('], + ['libs/research/src/market-data-store-routed.ts', 'return daily.fx(q)'], + ['libs/research/src/mcp/tools/analyze-signal.ts', 'discriminatedUnion'], + ['libs/research/src/feature-library.ts', 'RET_1D_V1'], + ['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'], + ['libs/research/src/notebook-snapshot-node.ts', 'export function createNodeNotebookCommandRunner'], + ['scripts/research-copilot-mcp.ts', 'export async function runResearchCopilotMcp'], + ['package.json', '"mcp:research-copilot"'], + ['design/MILESTONES.md', 'eodIntraday1M'], + ['docker-compose.quant.yml', '1048576'], ]; - test.each(lineCitations)('%s:%d contains %p as cited', (file, line, expected) => { + test.each(symbolCitations)('%s contains %p as cited', (file, expected) => { expect(audit).toContain(file.split('/').pop()!); - expect(lineAt(file, line)).toContain(expected); + expect(fileContents(file)).toContain(expected); }); test('pins the audited master baseline and accepted M1 separately from the review branch', () => { diff --git a/scripts/test/questdb-init-m2.test.ts b/scripts/test/questdb-init-m2.test.ts new file mode 100644 index 00000000..00a3e804 --- /dev/null +++ b/scripts/test/questdb-init-m2.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, test } from 'bun:test'; +import { M2_INTRADAY_TABLE_NAMES } from '@stock-bot/questdb'; +import { resolveQuestDbInitM2Config, runQuestDbInitM2 } from '../questdb-init-m2'; + +describe('scripts/questdb-init-m2', () => { + test('rejects conflicting URL SSL settings before opening a QuestDB connection', async () => { + const secret = 'ddl_init_s3cr3t!'; + const baseUrl = `postgresql://admin:${encodeURIComponent(secret)}@10.0.0.51:8812/qdb`; + + const conflictingEnvs: Array> = [ + { QUESTDB_URL: `${baseUrl}?sslmode=no-verify`, QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?sslmode=disable`, QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?sslmode=disable`, QUESTDB_SSL: 'false' }, + { RESEARCH_MCP_QUESTDB_URL: `${baseUrl}?sslmode=disable`, RESEARCH_MCP_QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?sslmode=require`, QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?sslmode=require`, QUESTDB_SSL: 'false' }, + { QUESTDB_URL: `${baseUrl}?ssl=false`, QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?ssl=false`, QUESTDB_SSL: 'false' }, + { QUESTDB_URL: `${baseUrl}?sslmode=prefer`, QUESTDB_SSL: 'true' }, + { QUESTDB_URL: `${baseUrl}?uselibpqcompat=true`, QUESTDB_SSL: 'true' }, + ]; + + let openCalls = 0; + for (const env of conflictingEnvs) { + let caught: unknown; + try { + await runQuestDbInitM2(env, async () => { + openCalls += 1; + throw new Error('openExecutor must not be called on conflicting SSL config'); + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(RangeError); + expect((caught as Error).message).toContain('SSL'); + expect((caught as Error).message).not.toContain(secret); + expect((caught as Error).message).not.toContain(baseUrl); + } + expect(openCalls).toBe(0); + }); + + test('rejects invalid SSL flag values and accepts single-source-of-truth URL or flag TLS configs', async () => { + expect(() => + resolveQuestDbInitM2Config({ + QUESTDB_HOST: '10.0.0.51', + QUESTDB_SSL: 'maybe', + }) + ).toThrow(RangeError); + + const urlOnlyTls = resolveQuestDbInitM2Config({ + QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require', + }); + expect(urlOnlyTls).toEqual({ + url: 'postgresql://admin:pass@10.0.0.51:8812/qdb?sslmode=require', + }); + + const flagOnlyTls = resolveQuestDbInitM2Config({ + QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb?application_name=init-m2', + QUESTDB_SSL: 'true', + }); + expect(flagOnlyTls).toEqual({ + url: 'postgresql://admin:pass@10.0.0.51:8812/qdb?application_name=init-m2', + ssl: true, + }); + + const executed: string[] = []; + let closed = false; + const result = await runQuestDbInitM2( + { + QUESTDB_URL: 'postgresql://admin:pass@10.0.0.51:8812/qdb', + QUESTDB_SSL: 'false', + }, + async () => ({ + executor: { + async query(sql: string) { + executed.push(sql); + return { rows: [] }; + }, + }, + async close() { + closed = true; + }, + }) + ); + + expect(result.appliedTables).toEqual([...M2_INTRADAY_TABLE_NAMES]); + expect(executed).toHaveLength(3); + expect(closed).toBe(true); + }); +}); diff --git a/test/postgres/security-master-export-curate-inputs.test.ts b/test/postgres/security-master-export-curate-inputs.test.ts index 51705ecd..822fd7a2 100644 --- a/test/postgres/security-master-export-curate-inputs.test.ts +++ b/test/postgres/security-master-export-curate-inputs.test.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto'; -import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, test } from 'bun:test'; @@ -7,6 +7,8 @@ import { Pool, type PoolClient } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { + CURATE_INPUT_FILES, + CurateInputExportError, exportCurateInputs, pinCurateInputSnapshot, type SecurityMasterQueryable, @@ -95,14 +97,21 @@ async function seedFixtureData(pool: Pool) { try { await client.query('BEGIN'); - // Ensure required MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent). + // Ensure all 11 ISO 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 + ('ARCX', 'XNYS', 'NYSE Arca', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('BATS', 'BATS', 'Cboe BZX Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('IEXG', 'IEXG', 'Investors Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('NEOE', 'NEOE', 'Cboe Canada (NEO Exchange)', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), + ('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XASE', 'XNYS', 'NYSE American', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XCNQ', 'XCNQ', 'Canadian Securities Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), ('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') + ('XTSX', 'XTSX', 'TSX Venture Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered') ON CONFLICT (mic) DO NOTHING `); @@ -132,6 +141,13 @@ async function seedFixtureData(pool: Pool) { 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 instArcx = await insertInstrument('US0000000068', '000000006', 'Arca ETF Corp', 'etf', 'US'); + const instXase = await insertInstrument('US0000000076', '000000007', 'American Corp', 'common', 'US'); + const instBats = await insertInstrument('US0000000084', '000000008', 'BZX ETF Corp', 'etf', 'US'); + const instIexg = await insertInstrument('US0000000092', '000000009', 'IEX Corp', 'common', 'US'); + const instNeoe = await insertInstrument('CA0000000109', '000000010', 'NEO Corp', 'common', 'CA'); + const instXtsx = await insertInstrument('CA0000000117', '000000011', 'Venture Mining Corp', 'common', 'CA'); + const instXcnq = await insertInstrument('CA0000000125', '000000012', 'CSE Junior Corp', 'common', 'CA'); const insertListing = async (params: { instrumentId: number; @@ -284,6 +300,76 @@ async function seedFixtureData(pool: Pool) { delistReason: null, terminalReturn: null, }); + const arcxId = await insertListing({ + instrumentId: instArcx, + mic: 'ARCX', + tickerRoot: 'ARCA', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const xaseId = await insertListing({ + instrumentId: instXase, + mic: 'XASE', + tickerRoot: 'AMEX', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const batsId = await insertListing({ + instrumentId: instBats, + mic: 'BATS', + tickerRoot: 'CBOE', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const iexgId = await insertListing({ + instrumentId: instIexg, + mic: 'IEXG', + tickerRoot: 'IEXX', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const neoeId = await insertListing({ + instrumentId: instNeoe, + mic: 'NEOE', + tickerRoot: 'NEOC', + currency: 'CAD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const xtsxId = await insertListing({ + instrumentId: instXtsx, + mic: 'XTSX', + tickerRoot: 'VMIN', + currency: 'CAD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const xcnqId = await insertListing({ + instrumentId: instXcnq, + mic: 'XCNQ', + tickerRoot: 'CSEJ', + currency: 'CAD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); const insertMapping = async ( source: string, @@ -351,6 +437,13 @@ async function seedFixtureData(pool: Pool) { noQmId, noSuccQmFromId, noSuccQmToId, + arcxId, + xaseId, + batsId, + iexgId, + neoeId, + xtsxId, + xcnqId, }; } catch (error) { await client.query('ROLLBACK').catch(() => {}); @@ -402,6 +495,7 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* expect(pinned5000.generationId).toBe(res5000.generationId); expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path); expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path); + expect(pinned5000.listingVenues).toBe(res5000.listingVenues.path); expect(pinned5000.delistings).toBe(res5000.delistings.path); // Verify chunkSize=1 actually paginated across multiple queries. @@ -410,10 +504,12 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* // 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 lv5000 = await readFile(res5000.listingVenues.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.listingVenues.path, 'utf8')).toBe(lv5000); expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000); // Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order). @@ -456,10 +552,60 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* `${ids.noQmId}\tUSD`, `${ids.noSuccQmFromId}\tUSD`, `${ids.noSuccQmToId}\tUSD`, + `${ids.arcxId}\tUSD`, + `${ids.xaseId}\tUSD`, + `${ids.batsId}\tUSD`, + `${ids.iexgId}\tUSD`, + `${ids.neoeId}\tCAD`, + `${ids.xtsxId}\tCAD`, + `${ids.xcnqId}\tCAD`, '', ].join('\n') ); + // Assert exact listing_venues.tsv content covering all 11 ISO MICs (us_tsx vs tsxv_cse). + expect(lv5000).toBe( + [ + `${ids.aaplId}\tus_tsx`, + `${ids.shopId}\tus_tsx`, + `${ids.fbOldId}\tus_tsx`, + `${ids.fbNewId}\tus_tsx`, + `${ids.sivbId}\tus_tsx`, + `${ids.sivbReuseId}\tus_tsx`, + `${ids.sivbqId}\tus_tsx`, + `${ids.del30Id}\tus_tsx`, + `${ids.noListedToId}\tus_tsx`, + `${ids.noQmId}\tus_tsx`, + `${ids.noSuccQmFromId}\tus_tsx`, + `${ids.noSuccQmToId}\tus_tsx`, + `${ids.arcxId}\tus_tsx`, + `${ids.xaseId}\tus_tsx`, + `${ids.batsId}\tus_tsx`, + `${ids.iexgId}\tus_tsx`, + `${ids.neoeId}\tus_tsx`, + `${ids.xtsxId}\ttsxv_cse`, + `${ids.xcnqId}\ttsxv_cse`, + '', + ].join('\n') + ); + + // Verify strict load_listing_venues_tsv compliance (headerless 2-col LF TSV, ascending positive i32). + expect(lv5000.includes('\r')).toBe(false); + expect(lv5000.endsWith('\n')).toBe(true); + const lvLines = lv5000.slice(0, -1).split('\n'); + expect(lvLines).toHaveLength(19); + let prevListingId = 0; + for (const line of lvLines) { + const cols = line.split('\t'); + expect(cols).toHaveLength(2); + expect(cols[0]).toMatch(/^[1-9]\d*$/); + const id = Number(cols[0]); + expect(id).toBeGreaterThan(prevListingId); + expect(id).toBeLessThanOrEqual(2_147_483_647); + expect(cols[1] === 'us_tsx' || cols[1] === 'tsxv_cse').toBe(true); + prevListingId = id; + } + // Assert exact delistings.tsv content. expect(dl5000).toBe( [ @@ -473,13 +619,13 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* // Assert exact stats reconciliation. const stats = res5000.delistings.stats; expect(stats).toEqual({ - rowsIn: 12, + rowsIn: 19, rowsOut: 3, otcTransfersOut: 1, terminalDelistingsOut: 2, - skippedTotal: 9, + skippedTotal: 16, skipped: { - active: 4, // AAPL, SHOP, FB new, SIVB reuse + active: 11, // AAPL, SHOP, FB new, SIVB reuse + 7 MIC-coverage active listings noOutcome: 2, // FB old, NOSUQ missingListedTo: 1, // NLDT missingOutgoingQmMapping: 1, // NOQM @@ -489,5 +635,80 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* }); expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal); expect(res1.delistings.stats).toEqual(stats); + expect(res5000.listingVenues.rowsIn).toBe(19); + expect(res5000.listingVenues.rowsOut).toBe(19); + expect(res1.listingVenues.bytesWritten).toBe(res5000.listingVenues.bytesWritten); + }); + + test('fails closed with UNKNOWN_LISTING_MIC on an unmapped exchange MIC (XLON) and leaves existing outDir files intact', async () => { + const { pool } = await createIsolatedFixture(); + const client = await pool.connect(); + let xlonListingId = 0; + try { + await client.query('BEGIN'); + await client.query(` + INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) + VALUES ('XLON', 'XLON', 'London Stock Exchange', 'GB', 'GBP', 'Europe/London', 'XLON', 'us_100') + ON CONFLICT (mic) DO NOTHING + `); + const instRes = await client.query<{ instrument_id: number }>( + `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) + VALUES ('GB0000000011', 'G00000001', 'London Test PLC', 'common', 'GB') + RETURNING instrument_id` + ); + const listRes = 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, 'XLON', 'LSE', '', 'GBP', '2020-01-02'::date, NULL, 'active', NULL) + RETURNING listing_id`, + [instRes.rows[0]!.instrument_id] + ); + xlonListingId = listRes.rows[0]!.listing_id; + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => {}); + throw error; + } finally { + client.release(); + } + + const outDir = await makeTempDir('curate-inputs-pg-unknown-mic-'); + const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; + const origLc = '1\tUSD\n'; + const origLv = '1\tus_tsx\n'; + const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; + await writeFile(join(outDir, CURATE_INPUT_FILES.providerMapping), origPm, 'utf8'); + await writeFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), origLc, 'utf8'); + await writeFile(join(outDir, CURATE_INPUT_FILES.listingVenues), origLv, 'utf8'); + await writeFile(join(outDir, CURATE_INPUT_FILES.delistings), origDl, 'utf8'); + + let caught: unknown; + try { + await withRecordingClient(pool, async queryable => { + await exportCurateInputs(queryable, { outDir }); + }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(CurateInputExportError); + const err = caught as CurateInputExportError; + expect(err.code).toBe('UNKNOWN_LISTING_MIC'); + expect(err.table).toBe('listing'); + expect(err.key).toBe(`listing_id=${xlonListingId}`); + expect(err.message).toContain('XLON'); + + expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(origPm); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(origLc); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(origLv); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(origDl); + expect((await readdir(outDir)).sort()).toEqual([ + CURATE_INPUT_FILES.delistings, + CURATE_INPUT_FILES.listingCurrencies, + CURATE_INPUT_FILES.listingVenues, + CURATE_INPUT_FILES.providerMapping, + ]); }); }); diff --git a/test/unit/m2-completion-audit-doc.test.ts b/test/unit/m2-completion-audit-doc.test.ts index 66017991..39c6ceab 100644 --- a/test/unit/m2-completion-audit-doc.test.ts +++ b/test/unit/m2-completion-audit-doc.test.ts @@ -93,7 +93,6 @@ describe('design/m2-completion-audit.md citations', () => { ['tools/curate-etl/src/cli.rs', 'CurateFx1m('], ['tools/curate-etl/src/main.rs', 'run_send_ilp('], ['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'], - ['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'], ['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/], ['tools/curate-etl/src/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'], [ diff --git a/test/unit/security-master-export-curate-inputs-parity.test.ts b/test/unit/security-master-export-curate-inputs-parity.test.ts index 88052c91..284a51ec 100644 --- a/test/unit/security-master-export-curate-inputs-parity.test.ts +++ b/test/unit/security-master-export-curate-inputs-parity.test.ts @@ -2,9 +2,10 @@ * QA differential tests for the curate-etl TSV exporter (T-116). * * - The streaming PostgreSQL exporter (`exportCurateInputs`) and the pure core - * (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `buildDelistingExportRows` + - * `formatDelistingsTsv`) must produce byte-identical TSVs and identical skip stats on the same - * seeded random security master, for every chunk size (including exact chunk-boundary sizes). + * (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `formatListingVenuesTsv`, + * `buildDelistingExportRows` + `formatDelistingsTsv`) must produce byte-identical TSVs and + * identical skip stats on the same seeded random security master, for every chunk size + * (including exact chunk-boundary sizes). * - Every emitted `delistings.tsv` row must resolve under the exact Rust `curate-corporate-actions` * lookup rules (`cursor.resolve(delist_date) == from_listing_id` for terminal rows, * `resolve_for_listing_on_or_before` + successor `resolve(effective_date)` for OTC rows) against the @@ -20,7 +21,9 @@ import { exportCurateInputs, formatDelistingsTsv, formatListingCurrenciesTsv, + formatListingVenuesTsv, formatProviderMappingTsv, + resolveListingVenueForMic, type ContinuityExportSourceRow, type ListingDelistingSourceRow, type ProviderMappingExportRow, @@ -68,6 +71,7 @@ function ymdToDay(ymd: string): number { interface DbListing { listing_id: number; currency: string; + mic: string; listed_to: string | null; delist_reason: string | null; terminal_return: string | null; @@ -150,6 +154,12 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset { } // Listings are generated in chronological "start" order so reuse can find free tickers. + const usMics = ['XNYS', 'XNAS', 'ARCX', 'XASE', 'BATS', 'IEXG', 'OTCM'] as const; + const caMics = ['XTSE', 'NEOE', 'XTSX', 'XCNQ'] as const; + const micForListing = (listingId: number, currency: string): string => { + const pool = currency === 'CAD' ? caMics : usMics; + return pool[listingId % pool.length] as string; + }; const otcSuccessorIds = new Set(); for (let i = 0; i < ids.length; i++) { const listingId = ids[i] as number; @@ -159,11 +169,13 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset { const startDay = Math.floor(rng() * 3000); const roll = rng(); const currency = pick(['USD', 'USD', 'CAD']); + const mic = micForListing(listingId, currency); if (roll < 0.35) { listings.push({ listing_id: listingId, currency, + mic, listed_to: null, delist_reason: 'active', terminal_return: null, @@ -183,6 +195,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset { listings.push({ listing_id: listingId, currency, + mic, listed_to: dayToYmd(endDay), delist_reason: 'moved_to_otc', terminal_return: null, @@ -203,6 +216,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset { listings.push({ listing_id: successorId, currency, + mic: micForListing(successorId, currency), listed_to: successorCancelled ? dayToYmd(successorEnd) : null, delist_reason: successorCancelled ? 'bankruptcy_cancelled' : 'active', terminal_return: successorCancelled ? '-1.000000' : null, @@ -230,6 +244,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset { listings.push({ listing_id: listingId, currency, + mic, listed_to: missingDate ? null : dayToYmd(endDay), delist_reason: pick(['unknown_involuntary', 'bankruptcy_cancelled', 'merger_cash']), terminal_return: terminalReturn, @@ -248,6 +263,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset { listings.push({ listing_id: listingId, currency, + mic, listed_to: dayToYmd(endDay), delist_reason: rng() < 0.5 ? null : 'unknown', terminal_return: null, @@ -454,6 +470,7 @@ async function runExport(data: Dataset, chunkSize: number) { recordedSql, providerMapping: await read(CURATE_INPUT_FILES.providerMapping), listingCurrencies: await read(CURATE_INPUT_FILES.listingCurrencies), + listingVenues: await read(CURATE_INPUT_FILES.listingVenues), delistings: await read(CURATE_INPUT_FILES.delistings), }; } @@ -472,6 +489,15 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi rng ) ); + const expectedListingVenues = formatListingVenuesTsv( + shuffle( + data.listings.map(l => ({ + listingId: l.listing_id, + venue: resolveListingVenueForMic(l.mic), + })), + rng + ) + ); const built = buildDelistingExportRows( shuffle(pure.delistingListings, rng), shuffle(pure.continuities, rng), @@ -493,6 +519,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi const out = await runExport(data, Math.min(chunkSize, 5000)); expect(out.providerMapping).toBe(expectedProviderMapping); expect(out.listingCurrencies).toBe(expectedListingCurrencies); + expect(out.listingVenues).toBe(expectedListingVenues); expect(out.delistings).toBe(expectedDelistings); const s = out.result.delistings.stats; @@ -513,9 +540,12 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi expect(out.result.providerMapping.rowsIn).toBe(mappingRows); expect(out.result.providerMapping.rowsOut).toBe(mappingRows); expect(out.result.listingCurrencies.rowsOut).toBe(listingRows); + expect(out.result.listingVenues.rowsIn).toBe(listingRows); + expect(out.result.listingVenues.rowsOut).toBe(listingRows); expect(out.result.totalBytesWritten).toBe( Buffer.byteLength(out.providerMapping) + Buffer.byteLength(out.listingCurrencies) + + Buffer.byteLength(out.listingVenues) + Buffer.byteLength(out.delistings) ); @@ -599,6 +629,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 1, currency: 'USD', + mic: 'XNYS', listed_to: '2023-01-03', delist_reason: 'x', terminal_return: '0.000000', @@ -606,6 +637,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 2, currency: 'USD', + mic: 'XNAS', listed_to: '2023-01-03', delist_reason: 'x', terminal_return: '-0.000000', @@ -613,6 +645,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 3, currency: 'USD', + mic: 'ARCX', listed_to: '2023-01-03', delist_reason: 'x', terminal_return: '-0.000001', @@ -620,6 +653,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 4, currency: 'USD', + mic: 'XASE', listed_to: '2023-01-03', delist_reason: 'x', terminal_return: '-1.000000', @@ -627,6 +661,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 5, currency: 'USD', + mic: 'OTCM', listed_to: '2023-01-03', delist_reason: 'x', terminal_return: '-0.300000', @@ -665,6 +700,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 10, currency: 'USD', + mic: 'XNYS', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null, @@ -672,6 +708,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 11, currency: 'USD', + mic: 'OTCM', listed_to: null, delist_reason: 'active', terminal_return: null, @@ -679,6 +716,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 20, currency: 'CAD', + mic: 'XTSX', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null, @@ -686,6 +724,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi { listing_id: 21, currency: 'CAD', + mic: 'XCNQ', listed_to: null, delist_reason: 'active', terminal_return: null, @@ -730,6 +769,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi // Assert expect(out.listingCurrencies).toBe('10\tUSD\n11\tUSD\n20\tCAD\n21\tCAD\n'); + expect(out.listingVenues).toBe('10\tus_tsx\n11\tus_tsx\n20\ttsxv_cse\n21\ttsxv_cse\n'); expect(out.providerMapping).toBe( 'qm\tA\t2000-01-03\t2023-03-10\t10\nqm\tAQ\t2023-03-28\t\t11\nqm\tB\t2000-01-03\t2023-03-10\t20\nqm\tBQ\t2023-03-28\t\t21\n' ); diff --git a/test/unit/security-master-export-curate-inputs.test.ts b/test/unit/security-master-export-curate-inputs.test.ts index 9d3f728d..825cf6fb 100644 --- a/test/unit/security-master-export-curate-inputs.test.ts +++ b/test/unit/security-master-export-curate-inputs.test.ts @@ -1,5 +1,16 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtemp, open, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises'; +import { + mkdir, + mkdtemp, + open, + readdir, + readFile, + rename, + rm, + symlink, + unlink, + writeFile, +} from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { @@ -10,7 +21,9 @@ import { import { assertExportCurateInputsSafety, buildDelistingExportRows, + CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES, + CURATE_INPUT_GENERATIONS_DIR, CURATE_INPUT_PUBLISH_LOCK, CurateInputExportError, DEFAULT_EXPORT_CHUNK_SIZE, @@ -19,16 +32,22 @@ import { formatDelistingsTsv, formatExportCurateInputsSummary, formatListingCurrenciesTsv, + formatListingVenuesTsv, formatPlainDecimal, formatProviderMappingTsv, + ISO_EXCHANGE_SEEDS, + LISTING_STATUTORY_LAG_VENUES, + LISTING_VENUE_BY_MIC, parseExportCurateInputsArgs, pinCurateInputSnapshot, + resolveListingVenueForMic, runExportCurateInputs, runExportCurateInputsCli, type ContinuityExportSourceRow, type DelistingExportRow, type ListingCurrencyExportRow, type ListingDelistingSourceRow, + type ListingVenueExportRow, type ProviderMappingExportRow, type SecurityMasterQueryable, type SecurityMasterQueryResult, @@ -93,6 +112,7 @@ async function expectExportErrorAsync( interface InMemorySecurityMasterData { readonly listings: readonly { readonly listing_id: number; + readonly mic: string | null; readonly currency: string | null; readonly listed_to: string | null; readonly delist_reason: string | null; @@ -579,6 +599,135 @@ describe('formatListingCurrenciesTsv', () => { }); }); +describe('resolveListingVenueForMic and formatListingVenuesTsv', () => { + test('maps all 11 ISO_EXCHANGE_SEEDS MICs to us_tsx or tsxv_cse with 100% coverage', () => { + const usTsxMics = ['XTSE', 'XNYS', 'XNAS', 'ARCX', 'XASE', 'BATS', 'NEOE', 'OTCM', 'IEXG']; + const tsxvCseMics = ['XTSX', 'XCNQ']; + + for (const mic of usTsxMics) { + expect(resolveListingVenueForMic(mic)).toBe('us_tsx'); + } + for (const mic of tsxvCseMics) { + expect(resolveListingVenueForMic(mic)).toBe('tsxv_cse'); + } + + const seededMics = ISO_EXCHANGE_SEEDS.map(s => s.mic).sort(compareAscii); + const mappedMics = Object.keys(LISTING_VENUE_BY_MIC).sort(compareAscii); + expect(mappedMics).toEqual(seededMics); + expect(seededMics).toHaveLength(11); + for (const seed of ISO_EXCHANGE_SEEDS) { + expect(LISTING_STATUTORY_LAG_VENUES).toContain(resolveListingVenueForMic(seed.mic)); + } + }); + + test('resolveListingVenueForMic fails closed on unknown, blank, whitespace-padded, control-char, and prototype-key MICs', () => { + for (const unknownMic of ['XLON', 'xtse', ' XTSE ', 'XTSX ', '__proto__', 'toString', 'constructor']) { + expectExportError( + () => resolveListingVenueForMic(unknownMic, 'listing', 'listing_id=42'), + 'UNKNOWN_LISTING_MIC', + 'listing', + 'listing_id=42' + ); + } + + for (const blankMic of ['', ' ', null, undefined]) { + expectExportError( + () => resolveListingVenueForMic(blankMic, 'listing', 'listing_id=42'), + 'BLANK_FIELD', + 'listing', + 'listing_id=42' + ); + } + + for (const controlMic of ['XT\tSE', 'XT\nSE', 'XT\rSE']) { + expectExportError( + () => resolveListingVenueForMic(controlMic, 'listing', 'listing_id=42'), + 'FORBIDDEN_CONTROL_CHAR', + 'listing', + 'listing_id=42' + ); + } + }); + + test('formatListingVenuesTsv sorts by ascending listing_id, handles empty input, and satisfies load_listing_venues_tsv rules', () => { + expect(formatListingVenuesTsv([])).toBe(''); + + const rows: ListingVenueExportRow[] = [ + { listingId: 10, venue: 'tsxv_cse' }, + { listingId: 2, venue: 'us_tsx' }, + { listingId: 5, venue: 'tsxv_cse' }, + { listingId: 2_147_483_647, venue: 'us_tsx' }, + ]; + const expected = '2\tus_tsx\n5\ttsxv_cse\n10\ttsxv_cse\n2147483647\tus_tsx\n'; + const actual = formatListingVenuesTsv(rows); + expect(actual).toBe(expected); + expect(formatListingVenuesTsv([...rows].reverse())).toBe(expected); + + // Cross-language load_listing_venues_tsv format verification + expect(actual.includes('\r')).toBe(false); + expect(actual.endsWith('\n')).toBe(true); + const lines = actual.slice(0, -1).split('\n'); + expect(lines).toHaveLength(rows.length); + let prevId = 0; + for (const line of lines) { + const cols = line.split('\t'); + expect(cols).toHaveLength(2); + expect(cols[0]).toMatch(/^[1-9]\d*$/); + const id = Number(cols[0]); + expect(id).toBeGreaterThan(prevId); + expect(id).toBeLessThanOrEqual(2_147_483_647); + expect(cols[1] === 'us_tsx' || cols[1] === 'tsxv_cse').toBe(true); + prevId = id; + } + }); + + test('formatListingVenuesTsv fails closed on invalid listing_id, invalid venue, control chars, and duplicate listing_id', () => { + for (const badId of [0, -3, 2_147_483_648]) { + expectExportError( + () => formatListingVenuesTsv([{ listingId: badId, venue: 'us_tsx' }]), + 'INVALID_LISTING_ID', + 'listing', + 'row#0' + ); + } + + for (const badVenue of ['', 'NYSE', 'US_TSX', ' us_tsx ', null, undefined]) { + expectExportError( + () => + formatListingVenuesTsv([ + { listingId: 1, venue: badVenue as unknown as ListingVenueExportRow['venue'] }, + ]), + 'INVALID_LISTING_VENUE', + 'listing', + 'listing_id=1' + ); + } + + for (const ctrlVenue of ['us_tsx\t', 'us_tsx\n', 'tsxv_cse\r']) { + expectExportError( + () => + formatListingVenuesTsv([ + { listingId: 1, venue: ctrlVenue as unknown as ListingVenueExportRow['venue'] }, + ]), + 'FORBIDDEN_CONTROL_CHAR', + 'listing', + 'listing_id=1' + ); + } + + expectExportError( + () => + formatListingVenuesTsv([ + { listingId: 7, venue: 'us_tsx' }, + { listingId: 7, venue: 'tsxv_cse' }, + ]), + 'DUPLICATE_LISTING_VENUE', + '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[] = [ @@ -760,18 +909,21 @@ describe('exportCurateInputs atomic publish and streaming', () => { const outDir = await makeTempDir('curate-inputs-atomic-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); + const lvPath = join(outDir, CURATE_INPUT_FILES.listingVenues); 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 origLv = '1\tus_tsx\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(lvPath, origLv, 'utf8'); await writeFile(dlPath, origDl, 'utf8'); const baseData: InMemorySecurityMasterData = { listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 1, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -782,11 +934,13 @@ describe('exportCurateInputs atomic publish and streaming', () => { const assertIntact = async () => { expect(await readFile(pmPath, 'utf8')).toBe(origPm); expect(await readFile(lcPath, 'utf8')).toBe(origLc); + expect(await readFile(lvPath, 'utf8')).toBe(origLv); 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.listingVenues, CURATE_INPUT_FILES.providerMapping, ]); }; @@ -798,7 +952,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { ); await assertIntact(); - // 2. Mid-validation failure (tab inside source_id) + // 2a. Mid-validation failure (tab inside source_id) const badDataClient = createInMemoryQueryable({ ...baseData, providerMappings: [ @@ -813,6 +967,21 @@ describe('exportCurateInputs atomic publish and streaming', () => { ); await assertIntact(); + // 2b. Mid-validation failure (unmapped listing MIC) + const badMicClient = createInMemoryQueryable({ + ...baseData, + listings: [ + { listing_id: 1, mic: 'XLON', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + ], + }); + await expectExportErrorAsync( + () => exportCurateInputs(badMicClient, { outDir }), + 'UNKNOWN_LISTING_MIC', + 'listing', + 'listing_id=1' + ); + await assertIntact(); + // 3. Mid-rename failure on the 2nd top-level target symlink replacement (after staging->gen + 1st backup/link + 2nd backup) let renameCalls = 0; const goodClient = createInMemoryQueryable(baseData); @@ -832,7 +1001,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { ).rejects.toThrow('Simulated EIO on 2nd target publish rename'); await assertIntact(); - // 4. Failure at the atomic `current` commit rename restores all 3 pre-existing files cleanly + // 4. Failure at the atomic `current` commit rename restores all 4 pre-existing files cleanly const commitFailClient = createInMemoryQueryable(baseData); await expect( exportCurateInputs(commitFailClient, { @@ -854,15 +1023,17 @@ describe('exportCurateInputs atomic publish and streaming', () => { const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); + const lvPath = join(outDir, CURATE_INPUT_FILES.listingVenues); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8'); await writeFile(lcPath, '1\tUSD\n', 'utf8'); + await writeFile(lvPath, '1\tus_tsx\n', 'utf8'); await writeFile(dlPath, 'OLD\t2023-01-01\t1\t\t-0.3\n', 'utf8'); const newData: InMemorySecurityMasterData = { listings: [ - { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 2, mic: 'XTSX', currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -886,13 +1057,14 @@ describe('exportCurateInputs atomic publish and streaming', () => { }, }); - // All three live paths reflect the new committed snapshot (no partial rollback). + // All four live paths reflect the new committed snapshot (no partial rollback). expect(await readFile(pmPath, 'utf8')).toBe('eod\tNEW.TO\t2022-01-01\t\t2\n'); expect(await readFile(lcPath, 'utf8')).toBe('2\tCAD\n'); + expect(await readFile(lvPath, 'utf8')).toBe('2\ttsxv_cse\n'); expect(await readFile(dlPath, 'utf8')).toBe(''); - // Backup #1 and #3 were deleted; #2 failed and is reported in cleanupWarnings. - expect(backupUnlinkCalls).toBe(3); + // Backups #1, #3, #4 were deleted; #2 failed and is reported in cleanupWarnings. + expect(backupUnlinkCalls).toBe(4); expect(result.cleanupWarnings).toHaveLength(1); expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup'); expect(result.cleanupWarnings[0]).toContain('.bak'); @@ -903,18 +1075,21 @@ describe('exportCurateInputs atomic publish and streaming', () => { const outDir = await makeTempDir('curate-inputs-restore-fail-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); + const lvPath = join(outDir, CURATE_INPUT_FILES.listingVenues); 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 origLv = '1\tus_tsx\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(lvPath, origLv, 'utf8'); await writeFile(dlPath, origDl, 'utf8'); const newData: InMemorySecurityMasterData = { listings: [ - { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 2, mic: 'XTSE', currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -928,7 +1103,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { outDir, fs: { rename: async (oldPath, newPath) => { - // Fail at the atomic commit point to trigger rollback of all 3 backups. + // Fail at the atomic commit point to trigger rollback of all 4 backups. if (String(newPath) === join(outDir, 'current')) { throw new Error('Simulated commit EIO'); } @@ -953,8 +1128,9 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(err.message).toContain('Simulated restore EIO'); expect(err.message).toContain('.bak'); - // The other two targets were restored intact. + // The other three targets were restored intact. expect(await readFile(lcPath, 'utf8')).toBe(origLc); + expect(await readFile(lvPath, 'utf8')).toBe(origLv); expect(await readFile(dlPath, 'utf8')).toBe(origDl); // The unrestored provider_mapping backup MUST still exist on disk with original bytes! @@ -972,7 +1148,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { // Generation 1: only SIVB active (no SIVBQ successor yet). const gen1Data: InMemorySecurityMasterData = { listings: [ - { listing_id: 4, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 4, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -983,8 +1159,8 @@ describe('exportCurateInputs atomic publish and streaming', () => { // Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings. const gen2Data: InMemorySecurityMasterData = { listings: [ - { listing_id: 4, currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null }, - { listing_id: 6, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 4, mic: 'XNAS', currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null }, + { listing_id: 6, mic: 'OTCM', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [ { from_listing_id: 4, to_listing_id: 6, effective_date: '2023-03-28', kind: 'otc_delist_transfer' }, @@ -1007,10 +1183,12 @@ describe('exportCurateInputs atomic publish and streaming', () => { const res2 = await exportCurateInputs(createInMemoryQueryable(gen2Data), { outDir }); expect(res2.generationId).not.toBe(res1.generationId); - // Consumer 1 finishes reading listing_currencies.tsv and delistings.tsv from its pinned generation 1. + // Consumer 1 finishes reading listing_currencies.tsv, listing_venues.tsv, and delistings.tsv from its pinned generation 1. const consumer1Lc = await readFile(pinned1.listingCurrencies, 'utf8'); + const consumer1Lv = await readFile(pinned1.listingVenues, 'utf8'); const consumer1Dl = await readFile(pinned1.delistings, 'utf8'); expect(consumer1Lc).toBe('4\tUSD\n'); + expect(consumer1Lv).toBe('4\tus_tsx\n'); expect(consumer1Dl).toBe(''); // Consistent with gen1 (no SIVBQ transfer referencing missing SIVBQ!) // Consumer 2 pins after Generation 2 committed and sees the full Generation 2 snapshot. @@ -1020,6 +1198,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { 'qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n' ); expect(await readFile(pinned2.listingCurrencies, 'utf8')).toBe('4\tUSD\n6\tUSD\n'); + expect(await readFile(pinned2.listingVenues, 'utf8')).toBe('4\tus_tsx\n6\tus_tsx\n'); expect(await readFile(pinned2.delistings, 'utf8')).toBe('SIVB\t2023-03-28\t4\tSIVBQ\t\n'); }); @@ -1028,7 +1207,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { const snapA: InMemorySecurityMasterData = { listings: [ - { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, + { listing_id: 10, mic: 'XNAS', currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, ], continuities: [], providerMappings: [ @@ -1037,7 +1216,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { }; const snapB: InMemorySecurityMasterData = { listings: [ - { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, + { listing_id: 20, mic: 'XTSX', currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, ], continuities: [], providerMappings: [ @@ -1053,17 +1232,20 @@ describe('exportCurateInputs atomic publish and streaming', () => { const pinned = await pinCurateInputSnapshot(outDir); const pm = await readFile(pinned.providerMapping, 'utf8'); const lc = await readFile(pinned.listingCurrencies, 'utf8'); + const lv = await readFile(pinned.listingVenues, 'utf8'); const dl = await readFile(pinned.delistings, 'utf8'); const isAllA = pinned.generationId === resA.generationId && pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' && lc === '10\tUSD\n' && + lv === '10\tus_tsx\n' && dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n'; const isAllB = pinned.generationId === resB.generationId && pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' && lc === '20\tCAD\n' && + lv === '20\ttsxv_cse\n' && dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n'; expect(isAllA || isAllB).toBe(true); @@ -1072,7 +1254,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { test('concurrent fresh-dir exports serialize publish/rollback so a failed export never deletes a committed export top-level links', async () => { const snapA: InMemorySecurityMasterData = { listings: [ - { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, + { listing_id: 10, mic: 'XNAS', currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, ], continuities: [], providerMappings: [ @@ -1081,7 +1263,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { }; const snapB: InMemorySecurityMasterData = { listings: [ - { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, + { listing_id: 20, mic: 'XTSX', currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, ], continuities: [], providerMappings: [ @@ -1145,10 +1327,14 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( '20\tCAD\n' ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + '20\ttsxv_cse\n' + ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( 'SNAP_B\t2024-01-15\t20\t\t-1\n' ); const pinned = await pinCurateInputSnapshot(outDir); + expect(await readFile(pinned.listingVenues, 'utf8')).toBe('20\ttsxv_cse\n'); expect(await readFile(pinned.delistings, 'utf8')).toBe('SNAP_B\t2024-01-15\t20\t\t-1\n'); const entries = await readdir(outDir); expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false); @@ -1215,10 +1401,14 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( '20\tCAD\n' ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + '20\ttsxv_cse\n' + ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( 'SNAP_B\t2024-01-15\t20\t\t-1\n' ); const pinned = await pinCurateInputSnapshot(outDir); + expect(await readFile(pinned.listingVenues, 'utf8')).toBe('20\ttsxv_cse\n'); expect(await readFile(pinned.providerMapping, 'utf8')).toBe( 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' ); @@ -1258,6 +1448,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { listings: [ { listing_id: 1, + mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', @@ -1343,6 +1534,63 @@ describe('exportCurateInputs atomic publish and streaming', () => { 'chunkSize' ); }); + + test('pinCurateInputSnapshot fails closed with INCOMPLETE_SNAPSHOT on legacy M1 three-file generation and succeeds after refresh', async () => { + const outDir = await makeTempDir('curate-inputs-legacy-m1-'); + const legacyGenId = 'gen-m1-legacy'; + const legacyGenDir = join(outDir, CURATE_INPUT_GENERATIONS_DIR, legacyGenId); + await mkdir(legacyGenDir, { recursive: true }); + await writeFile(join(legacyGenDir, CURATE_INPUT_FILES.providerMapping), 'qm\tAAPL\t2020-01-01\t\t1\n', 'utf8'); + await writeFile(join(legacyGenDir, CURATE_INPUT_FILES.listingCurrencies), '1\tUSD\n', 'utf8'); + await writeFile(join(legacyGenDir, CURATE_INPUT_FILES.delistings), '', 'utf8'); + await symlink( + join(CURATE_INPUT_GENERATIONS_DIR, legacyGenId), + join(outDir, CURATE_INPUT_CURRENT_LINK) + ); + + let caught: unknown; + try { + await pinCurateInputSnapshot(outDir); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(CurateInputExportError); + const err = caught as CurateInputExportError; + expect(err.code).toBe('INCOMPLETE_SNAPSHOT'); + expect(err.table).toBe('publish'); + expect(err.key).toBe(legacyGenId); + expect(err.field).toBe(CURATE_INPUT_FILES.listingVenues); + expect(err.message).toContain('listing_venues.tsv'); + expect(err.message).toContain('refresh the export'); + + // Refreshing the export publishes a complete 4-file generation that pins cleanly. + const refreshedClient = createInMemoryQueryable({ + listings: [ + { + listing_id: 1, + mic: 'XNAS', + 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, + }, + ], + }); + await exportCurateInputs(refreshedClient, { outDir }); + const pinned = await pinCurateInputSnapshot(outDir); + expect(await readFile(pinned.listingVenues, 'utf8')).toBe('1\tus_tsx\n'); + expect(await readFile(pinned.providerMapping, 'utf8')).toBe('qm\tAAPL\t2020-01-01\t\t1\n'); + }); }); describe('golden fixtures cross-language parity', () => { @@ -1373,10 +1621,18 @@ describe('golden fixtures cross-language parity', () => { ); // Also verify streaming exportCurateInputs produces identical bytes with chunkSize=2. + const goldenMics = ['XNAS', 'XNAS', 'XNYS', 'XNAS', 'XNAS', 'OTCM', 'XNYS', 'XTSE'] as const; + const expectedLv = formatListingVenuesTsv( + dataset.listings.map((l, idx) => ({ + listingId: l.listingId, + venue: resolveListingVenueForMic(goldenMics[idx]!), + })) + ); const outDir = await makeTempDir('curate-inputs-golden-'); const queryable = createInMemoryQueryable({ listings: dataset.delistingListings.map((l, idx) => ({ listing_id: l.listingId, + mic: goldenMics[idx]!, currency: dataset.listings[idx]!.currency, listed_to: l.listedTo, delist_reason: l.delistReason, @@ -1400,8 +1656,15 @@ describe('golden fixtures cross-language parity', () => { 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.listingVenues.path, 'utf8')).toBe(expectedLv); expect(await readFile(result.delistings.path, 'utf8')).toBe(expectedDl); expect(result.delistings.stats).toEqual(builtDelistings.stats); + expect(result.totalBytesWritten).toBe( + result.providerMapping.bytesWritten + + result.listingCurrencies.bytesWritten + + result.listingVenues.bytesWritten + + result.delistings.bytesWritten + ); }); }); @@ -1483,7 +1746,7 @@ describe('CLI args, safety guard, and runner', () => { const queryable = createInMemoryQueryable({ listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 1, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -1514,6 +1777,7 @@ describe('CLI args, safety guard, and runner', () => { 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('listing_venues.tsv: rows_in=1 rows_out=1'); expect(stdoutText).toContain('delistings.tsv: rows_in=1 rows_out=0'); }); @@ -1563,7 +1827,7 @@ describe('CLI args, safety guard, and runner', () => { const queryable = createInMemoryQueryable({ listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 1, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -1586,6 +1850,9 @@ describe('CLI args, safety guard, and runner', () => { expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( 'qm\tAAPL\t2020-01-01\t\t1\n' ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + '1\tus_tsx\n' + ); // Still rejects dev -> QA PostgreSQL even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true! resetStockConfig(); diff --git a/test/unit/security-master-export-listing-venues-qa.test.ts b/test/unit/security-master-export-listing-venues-qa.test.ts new file mode 100644 index 00000000..5b18efc5 --- /dev/null +++ b/test/unit/security-master-export-listing-venues-qa.test.ts @@ -0,0 +1,386 @@ +/** + * QA edge-case coverage for T-211 (M2.2v): `listing_venues.tsv` produced by `exportCurateInputs`. + * + * Complements `security-master-export-curate-inputs.test.ts` with: + * - end-to-end streaming parity against the pure `formatListingVenuesTsv` core for a seeded + * random security master across chunk sizes (incl. exact chunk boundaries), + * - the 1:1 join invariant between `listing_currencies.tsv` and `listing_venues.tsv` + * (curate-fundamentals must never see a listing with a currency but no statutory-lag class), + * - a TS port of `tools/curate-etl/src/run_curate_fundamentals.rs::load_listing_venues_tsv` + * (+ `read_tsv_lines` / `parse_strict_positive_i32`) applied to the exported bytes, + * - fail-closed rollback for null / blank / padded / lowercase MICs read from PostgreSQL, + * - i32 max listing_id, empty listing table, and the `current/` top-level symlink layout. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdtemp, readdir, readFile, readlink, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + CURATE_INPUT_CURRENT_LINK, + CURATE_INPUT_FILES, + CURATE_INPUT_GENERATIONS_DIR, + CurateInputExportError, + exportCurateInputs, + formatListingVenuesTsv, + ISO_EXCHANGE_SEEDS, + LISTING_VENUE_BY_MIC, + pinCurateInputSnapshot, + type ListingStatutoryLagVenue, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const tempDirs: string[] = []; +afterEach(async () => { + for (const dir of tempDirs.splice(0).reverse()) { + await rm(dir, { recursive: true, force: true }); + } +}); + +async function makeTempDir(prefix: string): Promise { + const dir = await mkdtemp(join(tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +interface ListingRow { + readonly listing_id: number; + readonly mic: string | null; + readonly currency: string | null; + readonly listed_to: string | null; + readonly delist_reason: string | null; + readonly terminal_return: string | null; +} + +/** + * Minimal in-memory stand-in for the read-only PostgreSQL snapshot: empty provider_mapping and + * continuity tables, keyset-paginated listing table. Records every SQL statement. + */ +function createListingOnlyQueryable( + listings: readonly ListingRow[], + recordedSql: string[] = [] +): SecurityMasterQueryable { + const sorted = [...listings].sort((a, b) => a.listing_id - b.listing_id); + return { + async query>( + text: string, + values?: readonly unknown[] + ): Promise> { + const normalized = text.replace(/\s+/g, ' ').trim(); + recordedSql.push(normalized); + if ( + normalized.startsWith('BEGIN') || + normalized === 'COMMIT' || + normalized === 'ROLLBACK' || + normalized.startsWith('DECLARE ') || + /^CLOSE \S+$/i.test(normalized) || + /^FETCH FORWARD \d+ FROM \S+$/i.test(normalized) + ) { + return { rows: [] }; + } + if (normalized.includes('FROM corporate_action_continuity')) { + return { rows: [] }; + } + if (normalized.includes('FROM provider_mapping')) { + return { rows: [] }; + } + if (normalized.includes('FROM listing')) { + if (values && values.length === 1) { + return { rows: sorted.slice(0, values[0] as number) as unknown as Row[] }; + } + const [lastId, limit] = values as [number, number]; + return { + rows: sorted.filter(l => l.listing_id > lastId).slice(0, limit) as unknown as Row[], + }; + } + throw new Error(`Unexpected SQL in listing-only queryable: ${normalized}`); + }, + release: () => {}, + }; +} + +function activeListing(listingId: number, mic: string | null, currency = 'USD'): ListingRow { + return { + listing_id: listingId, + mic, + currency, + listed_to: null, + delist_reason: 'active', + terminal_return: null, + }; +} + +/** mulberry32 — deterministic seeded PRNG. */ +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** TS port of Rust `parse_strict_positive_i32` (run_curate_bars.rs). */ +function parseStrictPositiveI32(raw: string): number | null { + if (raw.length === 0 || !/^[0-9]+$/.test(raw)) { + return null; + } + const val = Number(raw); + if (!Number.isSafeInteger(val) || val > 2_147_483_647 || val <= 0) { + return null; + } + return val; +} + +/** + * TS port of Rust `load_listing_venues_tsv` + `read_tsv_lines`: strict headerless 2-column TSV, + * at most one trailing blank line, strictly positive i32 listing_id, `us_tsx|tsxv_cse`, no dups. + * Additionally asserts the stricter exporter contract (LF only, ascending listing_id). + */ +function loadListingVenuesTsvStrict(text: string): Map { + const venues = new Map(); + if (text.length === 0) { + return venues; + } + if (text.includes('\r')) { + throw new Error('exporter must emit LF-only line endings'); + } + if (!text.endsWith('\n')) { + throw new Error('exporter must terminate the last line with LF'); + } + const lines = text.slice(0, -1).split('\n'); + let prev = 0; + for (const [i, line] of lines.entries()) { + if (line.length === 0) { + throw new Error(`line ${i + 1}: interior blank line`); + } + const cols = line.split('\t'); + if (cols.length !== 2) { + throw new Error(`line ${i + 1}: expected 2 tab-separated columns, got ${cols.length}`); + } + const id = parseStrictPositiveI32(cols[0]!); + if (id === null) { + throw new Error(`line ${i + 1}: invalid listing_id '${cols[0]}'`); + } + const venue = cols[1]; + if (venue !== 'us_tsx' && venue !== 'tsxv_cse') { + throw new Error(`line ${i + 1}: unknown venue '${venue}'`); + } + if (venues.has(id)) { + throw new Error(`line ${i + 1}: duplicate listing_id ${id}`); + } + if (id <= prev) { + throw new Error(`line ${i + 1}: listing_id ${id} not strictly ascending after ${prev}`); + } + prev = id; + venues.set(id, venue); + } + return venues; +} + +function buildRandomListings(seed: number, count: number): ListingRow[] { + const rand = mulberry32(seed); + const mics = ISO_EXCHANGE_SEEDS.map(e => e.mic); + const usedIds = new Set(); + const rows: ListingRow[] = []; + while (rows.length < count) { + // Sparse ids (gaps) up to i32 max to exercise keyset pagination on non-contiguous keys. + const id = 1 + Math.floor(rand() * 2_147_483_646); + if (usedIds.has(id)) { + continue; + } + usedIds.add(id); + const mic = mics[Math.floor(rand() * mics.length)]!; + rows.push(activeListing(id, mic, rand() < 0.5 ? 'CAD' : 'USD')); + } + // Shuffle insertion order so only the DB ORDER BY can produce sorted output. + for (let i = rows.length - 1; i > 0; i--) { + const j = Math.floor(rand() * (i + 1)); + [rows[i], rows[j]] = [rows[j]!, rows[i]!]; + } + return rows; +} + +describe('listing_venues.tsv QA: streaming parity and Rust loader compliance', () => { + for (const seed of [7, 2026, 31337]) { + test(`seed ${seed}: streamed listing_venues.tsv is byte-identical to the pure formatter across chunk sizes and joins 1:1 with listing_currencies.tsv`, async () => { + // Arrange + const listings = buildRandomListings(seed, 257); + const expected = formatListingVenuesTsv( + listings.map(l => ({ listingId: l.listing_id, venue: LISTING_VENUE_BY_MIC[l.mic!]! })) + ); + + // Act / Assert + for (const chunkSize of [1, 16, 256, 257, 258, 5000]) { + const outDir = await makeTempDir(`curate-venues-parity-${seed}-${chunkSize}-`); + const res = await exportCurateInputs(createListingOnlyQueryable(listings), { + outDir, + chunkSize, + }); + + const venuesText = await readFile(res.listingVenues.path, 'utf8'); + const currenciesText = await readFile(res.listingCurrencies.path, 'utf8'); + expect(venuesText).toBe(expected); + expect(res.listingVenues.rowsIn).toBe(257); + expect(res.listingVenues.rowsOut).toBe(257); + expect(res.listingVenues.bytesWritten).toBe(Buffer.byteLength(expected, 'utf8')); + expect(res.totalBytesWritten).toBe( + res.providerMapping.bytesWritten + + res.listingCurrencies.bytesWritten + + res.listingVenues.bytesWritten + + res.delistings.bytesWritten + ); + + const venues = loadListingVenuesTsvStrict(venuesText); + const currencyIds = currenciesText + .slice(0, -1) + .split('\n') + .map(line => Number(line.split('\t')[0])); + expect([...venues.keys()]).toEqual(currencyIds); + + const micById = new Map(listings.map(l => [l.listing_id, l.mic!])); + for (const [id, venue] of venues) { + const mic = micById.get(id)!; + expect(venue).toBe(mic === 'XTSX' || mic === 'XCNQ' ? 'tsxv_cse' : 'us_tsx'); + } + } + }); + } + + test('empty listing table publishes a 0-byte listing_venues.tsv that the Rust loader accepts as an empty map', async () => { + // Arrange + const outDir = await makeTempDir('curate-venues-empty-'); + + // Act + const res = await exportCurateInputs(createListingOnlyQueryable([]), { outDir }); + + // Assert + const text = await readFile(res.listingVenues.path, 'utf8'); + expect(text).toBe(''); + expect(res.listingVenues).toMatchObject({ rowsIn: 0, rowsOut: 0, bytesWritten: 0 }); + expect(loadListingVenuesTsvStrict(text).size).toBe(0); + }); + + test('i32-max listing_id is exported verbatim and parses under the Rust strict positive i32 rule', async () => { + // Arrange + const outDir = await makeTempDir('curate-venues-i32max-'); + const listings = [activeListing(2_147_483_647, 'XCNQ', 'CAD'), activeListing(1, 'XTSE', 'CAD')]; + + // Act + const res = await exportCurateInputs(createListingOnlyQueryable(listings), { + outDir, + chunkSize: 1, + }); + + // Assert + const text = await readFile(res.listingVenues.path, 'utf8'); + expect(text).toBe('1\tus_tsx\n2147483647\ttsxv_cse\n'); + expect([...loadListingVenuesTsvStrict(text)]).toEqual([ + [1, 'us_tsx'], + [2147483647, 'tsxv_cse'], + ]); + }); + + test('top-level listing_venues.tsv resolves through current/ to the same generation pinned by pinCurateInputSnapshot, and only read-only SQL is issued', async () => { + // Arrange + const outDir = await makeTempDir('curate-venues-layout-'); + const sql: string[] = []; + const listings = [activeListing(10, 'XTSX', 'CAD'), activeListing(20, 'XNYS')]; + + // Act + const res = await exportCurateInputs(createListingOnlyQueryable(listings, sql), { outDir }); + const pinned = await pinCurateInputSnapshot(outDir); + + // Assert + const topLevel = join(outDir, CURATE_INPUT_FILES.listingVenues); + expect(await readlink(topLevel)).toBe( + join(CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES.listingVenues) + ); + expect(await realpath(topLevel)).toBe(await realpath(res.listingVenues.path)); + expect(pinned.listingVenues).toBe(res.listingVenues.path); + expect(pinned.generationDir).toBe( + await realpath(join(outDir, CURATE_INPUT_GENERATIONS_DIR, res.generationId)) + ); + expect(await readFile(topLevel, 'utf8')).toBe('10\ttsxv_cse\n20\tus_tsx\n'); + + expect(sql[0]).toMatch(/^BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY/i); + for (const stmt of sql) { + expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT)\b/i); + } + expect(sql.filter(s => s.includes('FROM listing')).every(s => /\bmic\b/.test(s))).toBe(true); + }); +}); + +describe('listing_venues.tsv QA: fail-closed MIC values from PostgreSQL', () => { + const badMics: ReadonlyArray<{ readonly mic: string | null; readonly code: string }> = [ + { mic: null, code: 'BLANK_FIELD' }, + { mic: '', code: 'BLANK_FIELD' }, + { mic: ' ', code: 'BLANK_FIELD' }, + { mic: ' XTSX', code: 'UNKNOWN_LISTING_MIC' }, + { mic: 'xtsx', code: 'UNKNOWN_LISTING_MIC' }, + { mic: 'XLON', code: 'UNKNOWN_LISTING_MIC' }, + { mic: 'hasOwnProperty', code: 'UNKNOWN_LISTING_MIC' }, + { mic: 'XT\tSX', code: 'FORBIDDEN_CONTROL_CHAR' }, + ]; + + for (const { mic, code } of badMics) { + test(`mic=${JSON.stringify(mic)} on a later page aborts with ${code} and leaves the previous 4-file generation byte-identical`, async () => { + // Arrange: publish a good generation first. + const outDir = await makeTempDir('curate-venues-badmic-'); + const good = [activeListing(1, 'XTSE', 'CAD'), activeListing(2, 'XNAS')]; + const first = await exportCurateInputs(createListingOnlyQueryable(good), { outDir }); + const before = { + venues: await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8'), + currencies: await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8'), + generations: (await readdir(join(outDir, CURATE_INPUT_GENERATIONS_DIR))).sort(), + entries: (await readdir(outDir)).sort(), + }; + + // Act: the bad row sits on the 3rd chunk (chunkSize=1) after good rows were already staged. + const bad = [...good, activeListing(3, mic)]; + let caught: unknown; + try { + await exportCurateInputs(createListingOnlyQueryable(bad), { outDir, chunkSize: 1 }); + } catch (error) { + caught = error; + } + + // Assert + expect(caught).toBeInstanceOf(CurateInputExportError); + expect((caught as CurateInputExportError).code).toBe(code as CurateInputExportError['code']); + expect((caught as CurateInputExportError).key).toContain('listing_id=3'); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + before.venues + ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( + before.currencies + ); + expect((await readdir(join(outDir, CURATE_INPUT_GENERATIONS_DIR))).sort()).toEqual( + before.generations + ); + expect((await readdir(outDir)).sort()).toEqual(before.entries); + expect((await pinCurateInputSnapshot(outDir)).generationId).toBe(first.generationId); + }); + } + + test('a pre-existing regular listing_venues.tsv (pre-generation layout) survives a failed export untouched', async () => { + // Arrange + const outDir = await makeTempDir('curate-venues-legacy-file-'); + const legacy = '5\tus_tsx\n'; + await writeFile(join(outDir, CURATE_INPUT_FILES.listingVenues), legacy, 'utf8'); + + // Act + await expect( + exportCurateInputs(createListingOnlyQueryable([activeListing(1, 'XLON')]), { outDir }) + ).rejects.toMatchObject({ code: 'UNKNOWN_LISTING_MIC' }); + + // Assert + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(legacy); + const leftovers = (await readdir(outDir)).filter( + e => e.endsWith('.tmp') || e.endsWith('.bak') || e === '.publish.lock' + ); + expect(leftovers).toEqual([]); + }); +}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 55969f32..cdf45a95 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1540,9 +1540,9 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi - **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers. - **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. -## `curate-posts` Command (`M2.2j`) +## `curate-posts` Command (`M2.2j` / `M2.2u`) -End-to-end file-to-Parquet CLI command (`src/run_curate_posts.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming a concatenated raw BSON `ceoPosts` dump alongside `provider_mapping.tsv` into atomically published `/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (`--from-mongo` is not supported yet and is rejected as an unknown flag). +End-to-end file-to-Parquet CLI command (`src/run_curate_posts.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming a concatenated raw BSON `ceoPosts` dump alongside `provider_mapping.tsv` into atomically published `/events/year=YYYY/part-posts.parquet` partitions (`kind = "ceo_post"`) with zero extra crates and no database connections (`--from-mongo` is not supported yet and is rejected as an unknown flag). ### Invocation @@ -1550,14 +1550,14 @@ End-to-end file-to-Parquet CLI command (`src/run_curate_posts.rs`, wired in `src curate-etl curate-posts \ --ceo-posts ceoPosts.bson \ --provider-mapping provider_mapping.tsv \ - --out ./out-posts \ + --out ./out \ --timestamp-unit seconds ``` Inputs, defaults, and output rules: - `--ceo-posts ` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`). - `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). -- `--out ` *(required, dedicated output directory)*: dataset root where `/events/year=YYYY/part.parquet` is atomically published. Because `curate-events` (filings + earnings) writes to the same `/events` directory layout, `curate-posts` requires a dedicated `--out` directory and fails closed before any write if `/events` already contains any `year=*` entry (leaving existing partitions byte-identical). +- `--out ` *(required)*: dataset root where `/events/year=YYYY/part-posts.parquet` (`kind = "ceo_post"`) is atomically published. Co-publishes cleanly alongside `curate-events` (`/events/year=YYYY/part.parquet`) under the shared `/events/.write.lock` so filings, earnings, and CEO.ca posts coexist in one `curatedRoot` and remain independently re-runnable without clobbering each other's files. Upfront and pre-publish path validation rejects `--out` or `/events` being a regular file, `..` after a missing component, or any input path overlapping `--out`, `/events/...`, or a target `events/year=YYYY/part-posts.parquet`. - `--timestamp-unit ` *(required, **no default**)*: explicit numeric epoch unit (`seconds` or `millis`) for numeric `timestamp` and `edited` fields. There is intentionally no default because the live MongoDB `ceoPosts` numeric timestamp unit is unverified in the repository; BSON `DateTime` values are always epoch milliseconds regardless of unit. - Optional field-name overrides (defaults from `src/bson_ceo_posts.rs` / `get-posts.action.ts`): - `--key-field` (default `ceoId`) diff --git a/tools/curate-etl/src/bars_1m_sort.rs b/tools/curate-etl/src/bars_1m_sort.rs new file mode 100644 index 00000000..5d7919bc --- /dev/null +++ b/tools/curate-etl/src/bars_1m_sort.rs @@ -0,0 +1,808 @@ +//! Shared bounded-memory external sort and k-way merge for 1-minute bar runners +//! (`run_curate_bars_1m` and `run_curate_qm_bars_1m`). +//! +//! # Memory Bound & Determinism +//! - Decoded bars are validated and mapped to `(is_mapped, listing_id, ts, key_id)` immediately +//! into a fixed-size `CompactBar1mRecord` buffer (64 bytes/row in RAM, 62 bytes/row on disk). +//! - Whenever the in-memory run buffer reaches `max_run_rows` (default `2_000_000` rows ≈ 128 MiB), +//! it is sorted in place and spilled to an exclusively created binary run file +//! (`..sort-run--.tmp`, never BSON) guarded by [`StagingFileGuard`]. +//! - At EOF: +//! - If no run spilled, the in-memory buffer is sorted once and merged with zero disk I/O. +//! - If runs spilled, the sort buffer and key-interner map are freed before k-way merging at most +//! `max_merge_fan_in` (default `64`) run files at once (`~4 MiB` read buffers), using multi-pass +//! merges when `runs.len() > max_merge_fan_in` so file descriptors and RAM remain strictly +//! bounded even on 3.40B+ row backfills. +//! - Because every `(key_id, ts)` deterministically maps to one `Option` (via Eastern +//! Time `session_date`), sorting by `(is_mapped, listing_id, ts, key_id)` guarantees that all +//! same-key duplicates sit contiguously inside each `(is_mapped, listing_id, ts)` group, allowing +//! exact Stage-B same-key deduplication, listing-keyed split un-adjustment, and Stage-C +//! cross-`source_id` collision resolution in a single streaming merge pass. + +use std::cmp::{Ordering, Reverse}; +use std::collections::{BinaryHeap, HashMap}; +use std::fs::{File, OpenOptions}; +use std::io::{self, BufReader, BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; + +use crate::bars_1m::{Bar1mRow, Bars1mStats, IntradaySession}; +use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteReport}; +use crate::ilp::{IlpShardedWriter, IlpWriterError}; +use crate::parquet_publish::{next_run_id, StagingFileGuard}; +use crate::provider_mapping::ProviderMappingTable; +use crate::session_close::utc_micros_to_et_local; +use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; + +/// Fixed on-disk binary record size for spilled sorted runs (zero padding, little-endian). +pub(crate) const COMPACT_BAR_RECORD_BYTES: usize = 62; + +/// Default maximum rows buffered in RAM per sorted run (`2_000_000 * 64 B ≈ 128 MiB`). +pub(crate) const DEFAULT_SORT_RUN_MAX_ROWS: usize = 2_000_000; + +/// Default maximum number of run files opened simultaneously during a k-way merge pass. +pub(crate) const DEFAULT_MERGE_FAN_IN: usize = 64; + +/// Per-run buffered I/O capacity during spill and k-way merge (`64 KiB`). +const RUN_IO_BUF_BYTES: usize = 64 * 1024; + +/// Configuration for [`Bars1mExternalSorter`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Bars1mSortConfig { + /// Directory for temporary binary run files when spilling (`None` falls back to `std::env::temp_dir()`). + pub spill_dir: Option, + /// Filename prefix for temporary run files (e.g. `"bars_1m"` or `"bars_1m_qm"`). + pub spill_prefix: &'static str, + /// Maximum validated records held in RAM before spilling a sorted run. + pub max_run_rows: usize, + /// Maximum run files opened simultaneously per k-way merge pass (`>= 2`). + pub max_merge_fan_in: usize, +} + +impl Bars1mSortConfig { + pub(crate) fn new(spill_dir: Option, spill_prefix: &'static str) -> Self { + Self { + spill_dir, + spill_prefix, + max_run_rows: DEFAULT_SORT_RUN_MAX_ROWS, + max_merge_fan_in: DEFAULT_MERGE_FAN_IN, + } + } +} + +/// Typed error returned by [`Bars1mExternalSorter`]. +#[derive(Debug)] +pub(crate) enum Bars1mExternalSortError { + Io { path: PathBuf, source: io::Error }, + Ilp(IlpWriterError), +} + +/// Diagnostic summary of external-sort execution (used by tests to verify bounded memory/spilling). +#[allow(dead_code)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct ExternalSortMetrics { + pub peak_buffer_rows: usize, + pub runs_spilled: usize, + pub merge_passes: usize, +} + +/// Output of [`Bars1mExternalSorter::finish_and_write`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct ExternalSortWriteOutcome { + pub write_report: CurateBars1mWriteReport, + #[allow(dead_code)] + pub metrics: ExternalSortMetrics, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +struct CompactBar1mRecord { + /// `0` = unmapped, `1` = mapped to `listing_id`. + is_mapped: u8, + /// `0` = Pre, `1` = Rth, `2` = Post. + session: u8, + listing_id: i32, + ts: i64, + key_id: u32, + session_date: i32, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +} + +impl CompactBar1mRecord { + #[inline] + fn sort_key(&self) -> (u8, i32, i64, u32) { + (self.is_mapped, self.listing_id, self.ts, self.key_id) + } + + #[inline] + fn values_bit_eq(&self, other: &Self) -> bool { + self.open.to_bits() == other.open.to_bits() + && self.high.to_bits() == other.high.to_bits() + && self.low.to_bits() == other.low.to_bits() + && self.close.to_bits() == other.close.to_bits() + && self.volume.to_bits() == other.volume.to_bits() + } + + #[inline] + fn intraday_session(self) -> IntradaySession { + match self.session { + 0 => IntradaySession::Pre, + 1 => IntradaySession::Rth, + _ => IntradaySession::Post, + } + } + + #[inline] + fn encode_to(&self, buf: &mut [u8; COMPACT_BAR_RECORD_BYTES]) { + buf[0] = self.is_mapped; + buf[1] = self.session; + buf[2..6].copy_from_slice(&self.listing_id.to_le_bytes()); + buf[6..14].copy_from_slice(&self.ts.to_le_bytes()); + buf[14..18].copy_from_slice(&self.key_id.to_le_bytes()); + buf[18..22].copy_from_slice(&self.session_date.to_le_bytes()); + buf[22..30].copy_from_slice(&self.open.to_le_bytes()); + buf[30..38].copy_from_slice(&self.high.to_le_bytes()); + buf[38..46].copy_from_slice(&self.low.to_le_bytes()); + buf[46..54].copy_from_slice(&self.close.to_le_bytes()); + buf[54..62].copy_from_slice(&self.volume.to_le_bytes()); + } + + #[inline] + fn decode_from(buf: &[u8; COMPACT_BAR_RECORD_BYTES]) -> Self { + Self { + is_mapped: buf[0], + session: buf[1], + listing_id: i32::from_le_bytes(buf[2..6].try_into().unwrap()), + ts: i64::from_le_bytes(buf[6..14].try_into().unwrap()), + key_id: u32::from_le_bytes(buf[14..18].try_into().unwrap()), + session_date: i32::from_le_bytes(buf[18..22].try_into().unwrap()), + open: f64::from_le_bytes(buf[22..30].try_into().unwrap()), + high: f64::from_le_bytes(buf[30..38].try_into().unwrap()), + low: f64::from_le_bytes(buf[38..46].try_into().unwrap()), + close: f64::from_le_bytes(buf[46..54].try_into().unwrap()), + volume: f64::from_le_bytes(buf[54..62].try_into().unwrap()), + } + } +} + +struct SpilledRun { + path: PathBuf, + _guard: StagingFileGuard, + record_count: u64, +} + +struct RunReader { + path: PathBuf, + reader: BufReader, + remaining: u64, +} + +impl RunReader { + fn open(run: &SpilledRun) -> Result { + let file = File::open(&run.path).map_err(|source| Bars1mExternalSortError::Io { + path: run.path.clone(), + source, + })?; + Ok(Self { + path: run.path.clone(), + reader: BufReader::with_capacity(RUN_IO_BUF_BYTES, file), + remaining: run.record_count, + }) + } + + fn read_next(&mut self) -> Result, Bars1mExternalSortError> { + if self.remaining == 0 { + return Ok(None); + } + let mut buf = [0u8; COMPACT_BAR_RECORD_BYTES]; + self.reader + .read_exact(&mut buf) + .map_err(|source| Bars1mExternalSortError::Io { + path: self.path.clone(), + source, + })?; + self.remaining -= 1; + Ok(Some(CompactBar1mRecord::decode_from(&buf))) + } +} + +struct HeapEntry { + record: CompactBar1mRecord, + run_idx: usize, +} + +impl PartialEq for HeapEntry { + fn eq(&self, other: &Self) -> bool { + self.record.sort_key() == other.record.sort_key() && self.run_idx == other.run_idx + } +} + +impl Eq for HeapEntry {} + +impl PartialOrd for HeapEntry { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for HeapEntry { + fn cmp(&self, other: &Self) -> Ordering { + self.record + .sort_key() + .cmp(&other.record.sort_key()) + .then_with(|| self.run_idx.cmp(&other.run_idx)) + } +} + +#[inline] +fn is_valid_price(price: f64) -> bool { + price.is_finite() && price > 0.0 +} + +#[inline] +fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { + high >= low && open >= low && open <= high && close >= low && close <= high +} + +#[inline] +fn increment_builder_session_count(stats: &mut Bars1mStats, session: IntradaySession) { + match session { + IntradaySession::Pre => stats.pre_rows_out += 1, + IntradaySession::Rth => stats.rth_rows_out += 1, + IntradaySession::Post => stats.post_rows_out += 1, + } +} + +#[inline] +fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() + && a.volume.to_bits() == b.volume.to_bits() + && a.session == b.session +} + +fn create_exclusive_spill_file( + dir: &Path, + prefix: &str, + run_id: &str, + seq: u64, +) -> Result<(PathBuf, File), Bars1mExternalSortError> { + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!(".{prefix}.sort-run-{run_id}-{seq:06}.tmp") + } else { + format!(".{prefix}.sort-run-{run_id}-{seq:06}.{attempt}.tmp") + }; + let path = dir.join(file_name); + match OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(file) => return Ok((path, file)), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => return Err(Bars1mExternalSortError::Io { path, source }), + } + } + let path = dir.join(format!(".{prefix}.sort-run-{run_id}-{seq:06}.tmp")); + Err(Bars1mExternalSortError::Io { + path, + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique sort-run spill filenames", + ), + }) +} + +fn merge_runs_to_spill( + runs: &[SpilledRun], + spill_dir: &Path, + spill_prefix: &str, + run_id: &str, + seq: u64, +) -> Result { + let mut readers = Vec::with_capacity(runs.len()); + let mut heap: BinaryHeap> = BinaryHeap::with_capacity(runs.len()); + for (run_idx, run) in runs.iter().enumerate() { + let mut reader = RunReader::open(run)?; + if let Some(record) = reader.read_next()? { + heap.push(Reverse(HeapEntry { record, run_idx })); + } + readers.push(reader); + } + + let (out_path, out_file) = create_exclusive_spill_file(spill_dir, spill_prefix, run_id, seq)?; + let guard = StagingFileGuard::new(out_path.clone()); + let mut writer = BufWriter::with_capacity(RUN_IO_BUF_BYTES, out_file); + let mut rec_buf = [0u8; COMPACT_BAR_RECORD_BYTES]; + let mut record_count = 0u64; + + while let Some(Reverse(HeapEntry { record, run_idx })) = heap.pop() { + record.encode_to(&mut rec_buf); + writer + .write_all(&rec_buf) + .map_err(|source| Bars1mExternalSortError::Io { + path: out_path.clone(), + source, + })?; + record_count += 1; + if let Some(next_rec) = readers[run_idx].read_next()? { + heap.push(Reverse(HeapEntry { + record: next_rec, + run_idx, + })); + } + } + + writer.flush().map_err(|source| Bars1mExternalSortError::Io { + path: out_path.clone(), + source, + })?; + drop(writer); + + Ok(SpilledRun { + path: out_path, + _guard: guard, + record_count, + }) +} + +struct GroupMerger<'a> { + curate_stats: CurateBars1mStats, + rows_written: usize, + key_had_row_out: Vec, + last_listing_id: Option, + current_group_key: Option<(u8, i32, i64)>, + current_group: Vec, + listing_survivors: Vec>, + listing_splits: Option<&'a SplitTable>, + source: &'static str, + known_at_micros: i64, +} + +impl<'a> GroupMerger<'a> { + fn new( + builder_stats: Bars1mStats, + num_keys: usize, + listing_splits: Option<&'a SplitTable>, + source: &'static str, + known_at_micros: i64, + ) -> Self { + Self { + curate_stats: CurateBars1mStats { + builder: builder_stats, + ..CurateBars1mStats::default() + }, + rows_written: 0, + key_had_row_out: vec![false; num_keys], + last_listing_id: None, + current_group_key: None, + current_group: Vec::new(), + listing_survivors: Vec::new(), + listing_splits, + source, + known_at_micros, + } + } + + fn push( + &mut self, + record: CompactBar1mRecord, + writer: &mut IlpShardedWriter, + ) -> Result<(), Bars1mExternalSortError> { + let gk = (record.is_mapped, record.listing_id, record.ts); + if self.current_group_key != Some(gk) { + self.flush_group(writer)?; + self.current_group_key = Some(gk); + } + self.current_group.push(record); + Ok(()) + } + + fn flush_group( + &mut self, + writer: &mut IlpShardedWriter, + ) -> Result<(), Bars1mExternalSortError> { + if self.current_group.is_empty() { + return Ok(()); + } + let (is_mapped, listing_id, ts) = self.current_group_key.unwrap(); + self.listing_survivors.clear(); + + let len = self.current_group.len(); + let mut i = 0usize; + while i < len { + let key_id = self.current_group[i].key_id; + let sub_start = i; + i += 1; + while i < len && self.current_group[i].key_id == key_id { + i += 1; + } + let sub_len = i - sub_start; + let first = self.current_group[sub_start]; + let all_identical = self.current_group[sub_start + 1..i] + .iter() + .all(|other| first.values_bit_eq(other)); + if !all_identical { + self.curate_stats.builder.duplicate_conflict_dropped += sub_len; + continue; + } + self.curate_stats.builder.duplicate_collapsed += sub_len - 1; + + let session = first.intraday_session(); + if is_mapped == 0 { + self.curate_stats.builder.rows_out += 1; + increment_builder_session_count(&mut self.curate_stats.builder, session); + self.curate_stats.rows_in += 1; + self.curate_stats.dropped_unmapped += 1; + self.key_had_row_out[key_id as usize] = true; + continue; + } + + let (open, high, low, close, volume) = if let Some(splits) = self.listing_splits { + let factor = splits.cum_factor_after(&listing_id, first.session_date); + if factor != 1.0 { + let mut unadj = unadjust_ohlcv( + OhlcvBar { + open: first.open, + high: first.high, + low: first.low, + close: first.close, + volume: first.volume, + }, + factor, + ); + if !is_valid_price(unadj.open) + || !is_valid_price(unadj.high) + || !is_valid_price(unadj.low) + || !is_valid_price(unadj.close) + { + self.curate_stats.builder.dropped_invalid_ohlc += 1; + continue; + } + if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { + self.curate_stats.builder.dropped_inconsistent_ohlc += 1; + continue; + } + if !unadj.volume.is_finite() + || unadj.volume < 0.0 + || (first.volume > 0.0 && unadj.volume == 0.0) + { + self.curate_stats.builder.dropped_invalid_volume += 1; + continue; + } + if unadj.volume == 0.0 { + unadj.volume = 0.0; + } + (unadj.open, unadj.high, unadj.low, unadj.close, unadj.volume) + } else { + (first.open, first.high, first.low, first.close, first.volume) + } + } else { + (first.open, first.high, first.low, first.close, first.volume) + }; + + self.curate_stats.builder.rows_out += 1; + increment_builder_session_count(&mut self.curate_stats.builder, session); + self.curate_stats.rows_in += 1; + self.key_had_row_out[key_id as usize] = true; + + self.listing_survivors.push(Bar1mRow { + key: listing_id, + ts, + session_date: first.session_date, + open, + high, + low, + close, + volume, + session, + source: self.source, + }); + } + + if !self.listing_survivors.is_empty() { + let retain = if self.listing_survivors.len() == 1 { + true + } else { + let first = &self.listing_survivors[0]; + let all_identical = self.listing_survivors[1..] + .iter() + .all(|other| bar_1m_values_bit_eq(first, other)); + if all_identical { + self.curate_stats.listing_collision_collapsed += + self.listing_survivors.len() - 1; + true + } else { + self.curate_stats.listing_collision_dropped += self.listing_survivors.len(); + false + } + }; + + if retain { + let row = &self.listing_survivors[0]; + writer + .write_bar_1m(row, self.known_at_micros) + .map_err(Bars1mExternalSortError::Ilp)?; + self.rows_written += 1; + self.curate_stats.rows_out += 1; + if self.last_listing_id != Some(listing_id) { + self.curate_stats.listings_out += 1; + self.last_listing_id = Some(listing_id); + } + match row.session { + IntradaySession::Pre => self.curate_stats.pre_rows_out += 1, + IntradaySession::Rth => self.curate_stats.rth_rows_out += 1, + IntradaySession::Post => self.curate_stats.post_rows_out += 1, + } + } + self.listing_survivors.clear(); + } + + self.current_group.clear(); + Ok(()) + } + + fn finish( + mut self, + writer: &mut IlpShardedWriter, + ) -> Result { + self.flush_group(writer)?; + self.curate_stats.builder.keys_out = self.key_had_row_out.iter().filter(|&&b| b).count(); + Ok(CurateBars1mWriteReport { + curate_stats: self.curate_stats, + rows_written: self.rows_written, + }) + } +} + +/// Bounded-memory external sorter/merger shared by `bars_1m` and `bars_1m_qm` runners. +pub(crate) struct Bars1mExternalSorter<'a> { + mapping: &'a ProviderMappingTable, + mapping_source: &'a str, + config: Bars1mSortConfig, + run_id: String, + next_spill_seq: u64, + key_ids: HashMap, + buffer: Vec, + runs: Vec, + builder_stats: Bars1mStats, + metrics: ExternalSortMetrics, +} + +impl<'a> Bars1mExternalSorter<'a> { + pub(crate) fn new( + mapping: &'a ProviderMappingTable, + mapping_source: &'a str, + mut config: Bars1mSortConfig, + ) -> Self { + config.max_run_rows = config.max_run_rows.max(1); + config.max_merge_fan_in = config.max_merge_fan_in.max(2); + Self { + mapping, + mapping_source, + config, + run_id: next_run_id(), + next_spill_seq: 0, + key_ids: HashMap::new(), + buffer: Vec::new(), + runs: Vec::new(), + builder_stats: Bars1mStats::default(), + metrics: ExternalSortMetrics::default(), + } + } + + fn effective_spill_dir(&self) -> PathBuf { + self.config + .spill_dir + .clone() + .unwrap_or_else(std::env::temp_dir) + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn push_raw( + &mut self, + source_key: &str, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, + ) -> Result<(), Bars1mExternalSortError> { + self.builder_stats.bars_in += 1; + + if !is_valid_price(open) + || !is_valid_price(high) + || !is_valid_price(low) + || !is_valid_price(close) + { + self.builder_stats.dropped_invalid_ohlc += 1; + return Ok(()); + } + if !is_consistent_ohlc(open, high, low, close) { + self.builder_stats.dropped_inconsistent_ohlc += 1; + return Ok(()); + } + if !volume.is_finite() || volume < 0.0 { + self.builder_stats.dropped_invalid_volume += 1; + return Ok(()); + } + let Ok(et_local) = utc_micros_to_et_local(ts) else { + self.builder_stats.dropped_ts_out_of_range += 1; + return Ok(()); + }; + + let volume = if volume == 0.0 { 0.0 } else { volume }; + let session = match IntradaySession::from_et_minute(et_local.minute_of_day) { + IntradaySession::Pre => 0u8, + IntradaySession::Rth => 1u8, + IntradaySession::Post => 2u8, + }; + let (is_mapped, listing_id) = + match self + .mapping + .resolve(self.mapping_source, source_key, et_local.session_date) + { + Some(id) => (1u8, id), + None => (0u8, 0i32), + }; + + let key_id = if let Some(&id) = self.key_ids.get(source_key) { + id + } else { + let id = u32::try_from(self.key_ids.len()).map_err(|_| Bars1mExternalSortError::Io { + path: self.effective_spill_dir(), + source: io::Error::other("exceeded u32::MAX distinct intraday source keys"), + })?; + self.key_ids.insert(source_key.to_owned(), id); + id + }; + + self.buffer.push(CompactBar1mRecord { + is_mapped, + session, + listing_id, + ts, + key_id, + session_date: et_local.session_date, + open, + high, + low, + close, + volume, + }); + if self.buffer.len() > self.metrics.peak_buffer_rows { + self.metrics.peak_buffer_rows = self.buffer.len(); + } + if self.buffer.len() >= self.config.max_run_rows { + self.spill_buffer()?; + } + Ok(()) + } + + fn spill_buffer(&mut self) -> Result<(), Bars1mExternalSortError> { + if self.buffer.is_empty() { + return Ok(()); + } + self.buffer.sort_unstable_by_key(CompactBar1mRecord::sort_key); + + let spill_dir = self.effective_spill_dir(); + let seq = self.next_spill_seq; + self.next_spill_seq += 1; + let (path, file) = + create_exclusive_spill_file(&spill_dir, self.config.spill_prefix, &self.run_id, seq)?; + let guard = StagingFileGuard::new(path.clone()); + let mut writer = BufWriter::with_capacity(RUN_IO_BUF_BYTES, file); + let mut rec_buf = [0u8; COMPACT_BAR_RECORD_BYTES]; + + for rec in &self.buffer { + rec.encode_to(&mut rec_buf); + writer + .write_all(&rec_buf) + .map_err(|source| Bars1mExternalSortError::Io { + path: path.clone(), + source, + })?; + } + writer + .flush() + .map_err(|source| Bars1mExternalSortError::Io { + path: path.clone(), + source, + })?; + drop(writer); + + self.runs.push(SpilledRun { + path, + _guard: guard, + record_count: self.buffer.len() as u64, + }); + self.metrics.runs_spilled += 1; + self.buffer.clear(); + Ok(()) + } + + pub(crate) fn finish_and_write( + mut self, + listing_splits: Option<&SplitTable>, + source: &'static str, + writer: &mut IlpShardedWriter, + known_at_micros: i64, + ) -> Result { + let num_keys = self.key_ids.len(); + self.key_ids = HashMap::new(); + + let mut merger = GroupMerger::new( + self.builder_stats, + num_keys, + listing_splits, + source, + known_at_micros, + ); + + if self.runs.is_empty() { + self.buffer.sort_unstable_by_key(CompactBar1mRecord::sort_key); + for rec in self.buffer { + merger.push(rec, writer)?; + } + let write_report = merger.finish(writer)?; + return Ok(ExternalSortWriteOutcome { + write_report, + metrics: self.metrics, + }); + } + + if !self.buffer.is_empty() { + self.spill_buffer()?; + } + // Release the in-memory sort buffer before opening k-way merge readers. + self.buffer = Vec::new(); + + let spill_dir = self.effective_spill_dir(); + let fan_in = self.config.max_merge_fan_in; + while self.runs.len() > fan_in { + let batch: Vec = self.runs.drain(..fan_in).collect(); + let seq = self.next_spill_seq; + self.next_spill_seq += 1; + let merged = merge_runs_to_spill( + &batch, + &spill_dir, + self.config.spill_prefix, + &self.run_id, + seq, + )?; + // Dropping `batch` unlinks its consumed temporary run files immediately. + drop(batch); + self.runs.push(merged); + self.metrics.merge_passes += 1; + } + + let mut readers = Vec::with_capacity(self.runs.len()); + let mut heap: BinaryHeap> = BinaryHeap::with_capacity(self.runs.len()); + for (run_idx, run) in self.runs.iter().enumerate() { + let mut reader = RunReader::open(run)?; + if let Some(record) = reader.read_next()? { + heap.push(Reverse(HeapEntry { record, run_idx })); + } + readers.push(reader); + } + self.metrics.merge_passes += 1; + + while let Some(Reverse(HeapEntry { record, run_idx })) = heap.pop() { + merger.push(record, writer)?; + if let Some(next_rec) = readers[run_idx].read_next()? { + heap.push(Reverse(HeapEntry { + record: next_rec, + run_idx, + })); + } + } + + let write_report = merger.finish(writer)?; + Ok(ExternalSortWriteOutcome { + write_report, + metrics: self.metrics, + }) + } +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 27d4d76a..aebd72c8 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -51,8 +51,8 @@ use crate::fundamentals::FiscalPeriod; use crate::ilp::IlpWriterOptions; use crate::ilp_send::SendIlpArgs; use crate::mongo_stream::{ - MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV, - MAX_MONGO_BATCH_SIZE, + redact_embedded_mongo_uris, MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, + DEFAULT_MONGO_URI_ENV, MAX_MONGO_BATCH_SIZE, }; use crate::run_curate_adj::CurateAdjFactorsArgs; use crate::run_curate_bars::{ @@ -73,8 +73,10 @@ use crate::run_curate_posts::{ use crate::run_curate_qm_bars_1m::{CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE}; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; use crate::run_mongo::{ - CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, - CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, + CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateBars1mMongoArgs, + CurateCorporateActionsMongoArgs, CurateEventsMongoArgs, CurateFundamentalsMongoArgs, + CurateFx1dMongoArgs, CurateFx1mMongoArgs, CurateMacroMongoArgs, CuratePostsMongoArgs, + CurateQmBars1mMongoArgs, CurateShortsMongoArgs, }; /// Parsed CLI command to execute. @@ -96,11 +98,17 @@ pub enum CliAction { CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), CurateBars1m(CurateBars1mArgs), + CurateBars1mMongo(CurateBars1mMongoArgs), CurateQmBars1m(CurateQmBars1mArgs), + CurateQmBars1mMongo(CurateQmBars1mMongoArgs), CurateFx1m(CurateFx1mArgs), + CurateFx1mMongo(CurateFx1mMongoArgs), CuratePosts(CuratePostsArgs), + CuratePostsMongo(CuratePostsMongoArgs), CurateFundamentals(CurateFundamentalsArgs), + CurateFundamentalsMongo(CurateFundamentalsMongoArgs), CurateMacro(CurateMacroArgs), + CurateMacroMongo(CurateMacroMongoArgs), SendIlp(SendIlpArgs), BenchSplit(usize), BenchAdj(usize), @@ -163,18 +171,24 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ - {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ - {name} curate-qm-bars-1m --qm-intraday --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - Curate raw 1-minute bars from qmIntraday BSON + provider_mapping TSV into bars_1m_qm.shard-.ilp (file mode only; default --mapping-source: {DEFAULT_QM_BARS_1M_MAPPING_SOURCE})\n\ + {name} curate-bars-1m --eod-intraday --qm-splits (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-bars-1m --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON or read-only MongoDB + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ + {name} curate-qm-bars-1m --qm-intraday (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-qm-bars-1m --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + Curate raw 1-minute QuoteMedia bars from qmIntraday BSON or read-only MongoDB + provider_mapping TSV into bars_1m_qm.shard-.ilp (default --mapping-source: {DEFAULT_QM_BARS_1M_MAPPING_SOURCE})\n\ {name} curate-fx-1m --eod-intraday --out --shards \n\ - Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-.ilp\n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ - Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ - {name} curate-fundamentals --qm-financials --qm-filings --provider-mapping --listing-venues --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ - Curate point-in-time fundamentals from qmFinancials + qmFilings BSON + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (file mode only; defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\ + {name} curate-fx-1m --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --out --shards \n\ + Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON or read-only MongoDB into fx_1m.shard-.ilp\n\ + {name} curate-posts --ceo-posts (--curate-inputs | --provider-mapping ) --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + {name} curate-posts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] (--curate-inputs | --provider-mapping ) --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + Curate ceoPosts from BSON or read-only MongoDB + provider_mapping TSV into /events/year=YYYY/part-posts.parquet (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ + {name} curate-fundamentals --qm-financials [--qm-financials-old ] --qm-filings (--curate-inputs | --provider-mapping --listing-venues ) --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + {name} curate-fundamentals --from-mongo [--mongo-uri-env | --mongo-uri ] [--with-qm-financials-old] [--batch-size ] [--limit ] (--curate-inputs | --provider-mapping --listing-venues ) --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + Curate point-in-time fundamentals from qmFinancials (+ optional qmFinancials-old) + qmFilings BSON or read-only MongoDB + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\ {name} curate-macro --te-data --series-map --out \n\ - Curate macro regime series from a teData BSON dump + series-map TSV into /macro/part.parquet (file mode only)\n\ + {name} curate-macro --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --series-map --out \n\ + Curate macroeconomic series from teData BSON or read-only MongoDB + caller-owned series_map TSV into /macro/part.parquet\n\ {name} send-ilp --dir --prefix --addr \n\ Stream published ILP v2 shard files to an explicit QuestDB TCP endpoint (no default address; success means bytes were accepted by local sockets, not rows committed — verify row counts via PGWire; ILP v2 binary doubles over TCP on QuestDB 10.2.0 are unverified until the manual quant load check)\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ @@ -225,11 +239,11 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ - {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - {name} curate-qm-bars-1m --qm-intraday --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-bars-1m --eod-intraday --qm-splits (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-qm-bars-1m --qm-intraday (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ {name} curate-fx-1m --eod-intraday --out --shards \n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ - {name} curate-fundamentals --qm-financials --qm-filings --provider-mapping --listing-venues --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts (--curate-inputs | --provider-mapping ) --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + {name} curate-fundamentals --qm-financials [--qm-financials-old ] --qm-filings (--curate-inputs | --provider-mapping --listing-venues ) --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ {name} curate-macro --te-data --series-map --out \n\ {name} send-ilp --dir --prefix --addr \n\ {name} bench-split [rows]\n\ @@ -1204,8 +1218,51 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { Ok(CliAction::CurateShorts(parsed)) } +fn resolve_provider_mapping_input( + curate_inputs: Option, + provider_mapping: Option, +) -> Result { + if let Some(inputs_dir) = curate_inputs { + if provider_mapping.is_some() { + return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string()); + } + let pinned = pin_curate_inputs_dir(&inputs_dir)?; + Ok(pinned.join("provider_mapping.tsv")) + } else { + provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string()) + } +} + +fn resolve_fundamentals_tsv_inputs( + curate_inputs: Option, + provider_mapping: Option, + listing_venues: Option, +) -> Result<(PathBuf, PathBuf), String> { + if let Some(inputs_dir) = curate_inputs { + if provider_mapping.is_some() { + return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string()); + } + if listing_venues.is_some() { + return Err("cannot combine '--curate-inputs' with '--listing-venues'".to_string()); + } + let pinned = pin_curate_inputs_dir(&inputs_dir)?; + Ok(( + pinned.join("provider_mapping.tsv"), + pinned.join("listing_venues.tsv"), + )) + } else { + let pm = provider_mapping + .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let lv = listing_venues + .ok_or_else(|| "missing required flag '--listing-venues'".to_string())?; + Ok((pm, lv)) + } +} + fn parse_curate_posts_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); let mut ceo_posts: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping: Option = None; let mut out_dir: Option = None; let mut timestamp_unit: Option = None; @@ -1227,23 +1284,13 @@ fn parse_curate_posts_args(args: &[&str]) -> Result { )); } - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if !matches!( - flag_name, - "--ceo-posts" - | "--provider-mapping" - | "--out" - | "--timestamp-unit" - | "--key-field" - | "--spiel-id-field" - | "--timestamp-field" - | "--edited-field" - | "--bot-field" - | "--user-id-field" - | "--text-field" - | "--mapping-source" - ) { - return Err(format!("unknown flag '{flag_name}' for curate-posts")); + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; } let (flag, value) = if let Some((k, v)) = token.split_once('=') { @@ -1260,8 +1307,13 @@ fn parse_curate_posts_args(args: &[&str]) -> Result { (token, v) }; + if mongo.try_parse_value_flag(flag, value, false)? { + continue; + } + match flag { "--ceo-posts" => set_path(&mut ceo_posts, "--ceo-posts", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, "--out" => set_path(&mut out_dir, "--out", value)?, "--timestamp-unit" => { @@ -1290,9 +1342,66 @@ fn parse_curate_posts_args(args: &[&str]) -> Result { } } + if mongo.from_mongo { + if ceo_posts.is_some() { + return Err("cannot combine '--from-mongo' with '--ceo-posts'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let provider_mapping = resolve_provider_mapping_input(curate_inputs, provider_mapping)?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let timestamp_unit = + timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; + let key_field = key_field.unwrap_or_else(|| DEFAULT_POSTS_KEY_FIELD.to_string()); + let spiel_id_field = + spiel_id_field.unwrap_or_else(|| DEFAULT_POSTS_SPIEL_ID_FIELD.to_string()); + let timestamp_field = + timestamp_field.unwrap_or_else(|| DEFAULT_POSTS_TIMESTAMP_FIELD.to_string()); + let edited_field = edited_field.unwrap_or_else(|| DEFAULT_POSTS_EDITED_FIELD.to_string()); + let bot_field = bot_field.unwrap_or_else(|| DEFAULT_POSTS_BOT_FIELD.to_string()); + let user_id_field = + user_id_field.unwrap_or_else(|| DEFAULT_POSTS_USER_ID_FIELD.to_string()); + let text_field = text_field.unwrap_or_else(|| DEFAULT_POSTS_TEXT_FIELD.to_string()); + let mapping_source = + mapping_source.unwrap_or_else(|| DEFAULT_POSTS_MAPPING_SOURCE.to_string()); + + let check = CuratePostsArgs { + ceo_posts: PathBuf::from("mongodb://ceoPosts"), + provider_mapping: provider_mapping.clone(), + out_dir: out_dir.clone(), + timestamp_unit, + key_field: key_field.clone(), + spiel_id_field: spiel_id_field.clone(), + timestamp_field: timestamp_field.clone(), + edited_field: edited_field.clone(), + bot_field: bot_field.clone(), + user_id_field: user_id_field.clone(), + text_field: text_field.clone(), + mapping_source: mapping_source.clone(), + }; + check.field_names().validate().map_err(|e| e.to_string())?; + + return Ok(CliAction::CuratePostsMongo(CuratePostsMongoArgs { + mongo: mongo_opts, + provider_mapping, + out_dir, + timestamp_unit, + key_field, + spiel_id_field, + timestamp_field, + edited_field, + bot_field, + user_id_field, + text_field, + mapping_source, + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let ceo_posts = ceo_posts.ok_or_else(|| "missing required flag '--ceo-posts'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let provider_mapping = resolve_provider_mapping_input(curate_inputs, provider_mapping)?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; let timestamp_unit = timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; @@ -1341,8 +1450,12 @@ fn parse_curate_fundamentals_args(args: &[&str]) -> Result { } fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); + let mut with_qm_financials_old = false; let mut qm_financials: Option = None; + let mut qm_financials_old: Option = None; let mut qm_filings: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping: Option = None; let mut listing_venues: Option = None; let mut out_dir: Option = None; @@ -1377,11 +1490,34 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result Result set_path(&mut qm_financials, "--qm-financials", value)?, + "--qm-financials-old" => { + set_path(&mut qm_financials_old, "--qm-financials-old", value)?; + } "--qm-filings" => set_path(&mut qm_filings, "--qm-filings", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, "--listing-venues" => set_path(&mut listing_venues, "--listing-venues", value)?, "--out" => set_path(&mut out_dir, "--out", value)?, @@ -1533,14 +1677,110 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result { + return Err( + "cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'" + .to_string(), + ); + } + (Some(fixed), None, None) => CurateFundamentalsFiscalPeriod::Fixed(fixed), + (None, Some(quarterly), Some(annual)) => { + CurateFundamentalsFiscalPeriod::ByTokens { quarterly, annual } + } + (None, Some(quarterly), None) => CurateFundamentalsFiscalPeriod::ByTokens { + quarterly, + annual: Vec::new(), + }, + (None, None, Some(annual)) => CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: Vec::new(), + annual, + }, + (None, None, None) => { + return Err( + "missing required fiscal-period mode: pass either '--fiscal-period ' or '--quarterly-tokens' / '--annual-tokens'" + .to_string(), + ); + } + }; + + let parsed = CurateFundamentalsMongoArgs { + mongo: mongo_opts, + with_qm_financials_old, + provider_mapping, + listing_venues, + out_dir, + financials_key_field: financials_key_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string()), + financials_period_end_field: period_end_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string()), + financials_report_date_field: report_date_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string()), + financials_report_period_field: report_period_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string()), + financials_currency_field: currency_field, + financials_revenue_field: revenue_field, + financials_net_income_field: net_income_field, + financials_operating_cash_flow_field: operating_cash_flow_field, + financials_total_assets_field: total_assets_field, + financials_total_equity_field: total_equity_field, + financials_shares_outstanding_field: shares_outstanding_field, + fiscal_period, + filings_key_field: filings_key_field + .unwrap_or_else(|| DEFAULT_FILINGS_KEY_FIELD.to_string()), + filings_timefiled_field: filings_timefiled_field + .unwrap_or_else(|| DEFAULT_FILINGS_TIMEFILED_FIELD.to_string()), + filings_form_type_field, + filings_filing_id_field, + filings_url_field, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string()), + k, + }; + let check = parsed.to_file_args(); + check + .financials_field_names() + .validate() + .map_err(|e| e.to_string())?; + check + .filings_field_names() + .validate() + .map_err(|e| e.to_string())?; + check + .fiscal_period + .with_borrowed(|period| period.validate()) + .map_err(|e| e.to_string())?; + + return Ok(CliAction::CurateFundamentalsMongo(parsed)); + } + + if mongo.has_any_mongo_option() || with_qm_financials_old { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let qm_financials = qm_financials.ok_or_else(|| "missing required flag '--qm-financials'".to_string())?; let qm_filings = qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let listing_venues = - listing_venues.ok_or_else(|| "missing required flag '--listing-venues'".to_string())?; + let (provider_mapping, listing_venues) = + resolve_fundamentals_tsv_inputs(curate_inputs, provider_mapping, listing_venues)?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; let currency_field = currency_field.ok_or_else(|| "missing required flag '--currency-field'".to_string())?; @@ -1592,6 +1832,7 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result Result Result { - parse_curate_macro_args_inner(args).map_err(|e| sanitize_single_line(&e)) -} - -fn parse_curate_macro_args_inner(args: &[&str]) -> Result { - let mut te_data: Option = None; - let mut series_map: Option = None; - let mut out_dir: Option = None; - - let mut i = 0usize; - while i < args.len() { - let token = args[i]; - if !token.starts_with("--") { - return Err(format!( - "unexpected positional argument '{token}' for curate-macro" - )); - } - - let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag); - if !matches!(flag_name, "--te-data" | "--series-map" | "--out") { - return Err(format!("unknown flag '{flag_name}' for curate-macro")); - } - - let (flag, value) = if let Some((flag, v)) = token.split_once('=') { - i += 1; - (flag, v) - } else { - let Some(&v) = args.get(i + 1) else { - return Err(format!("missing value for flag '{token}'")); - }; - if v.starts_with("--") { - return Err(format!("missing value for flag '{token}'")); - } - i += 2; - (token, v) - }; - - match flag { - "--te-data" => set_path(&mut te_data, "--te-data", value)?, - "--series-map" => set_path(&mut series_map, "--series-map", value)?, - "--out" => set_path(&mut out_dir, "--out", value)?, - other => return Err(format!("unknown flag '{other}' for curate-macro")), - } - } - - let te_data = te_data.ok_or_else(|| "missing required flag '--te-data'".to_string())?; - let series_map = - series_map.ok_or_else(|| "missing required flag '--series-map'".to_string())?; - let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; - - Ok(CliAction::CurateMacro(CurateMacroArgs { - te_data, - series_map, - out_dir, - })) -} - fn parse_curate_events_args(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut qm_filings: Option = None; @@ -1967,8 +2151,10 @@ fn parse_curate_events_args(args: &[&str]) -> Result { } fn parse_curate_bars_1m_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); let mut intraday_path: Option = None; let mut splits_path: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping_path: Option = None; let mut out_dir: Option = None; let mut shard_count: Option = None; @@ -1984,21 +2170,13 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { )); } - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-bars-1m (file mode only)" - )); + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; } let (flag, value) = if let Some((k, v)) = token.split_once('=') { @@ -2015,31 +2193,14 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { (token, v) }; - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; + if mongo.try_parse_value_flag(flag, value, true)? { + continue; + } match flag { "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, "--qm-splits" => set_path(&mut splits_path, "--qm-splits", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => { set_path(&mut provider_mapping_path, "--provider-mapping", value)?; } @@ -2095,12 +2256,43 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { } } + if mongo.from_mongo { + if intraday_path.is_some() || splits_path.is_some() { + return Err( + "cannot combine '--from-mongo' with '--eod-intraday' or '--qm-splits'".to_string(), + ); + } + let mongo_opts = mongo.build_options()?; + let provider_mapping_path = + resolve_provider_mapping_input(curate_inputs, provider_mapping_path)?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + let known_at_micros = known_at_micros + .ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; + return Ok(CliAction::CurateBars1mMongo(CurateBars1mMongoArgs { + mongo: mongo_opts, + provider_mapping_path, + out_dir, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_BARS_1M_MAPPING_SOURCE.to_string()), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let intraday_path = intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; let splits_path = splits_path.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; - let provider_mapping_path = provider_mapping_path - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let provider_mapping_path = + resolve_provider_mapping_input(curate_inputs, provider_mapping_path)?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; let shard_count = shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; @@ -2126,7 +2318,9 @@ fn parse_curate_qm_bars_1m_args(args: &[&str]) -> Result { } fn parse_curate_qm_bars_1m_args_inner(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); let mut intraday_path: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping_path: Option = None; let mut out_dir: Option = None; let mut shard_count: Option = None; @@ -2142,26 +2336,26 @@ fn parse_curate_qm_bars_1m_args_inner(args: &[&str]) -> Result Result, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; + if mongo.try_parse_value_flag(flag, value, true)? { + continue; + } match flag { "--qm-intraday" => set_path(&mut intraday_path, "--qm-intraday", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => { set_path(&mut provider_mapping_path, "--provider-mapping", value)?; } @@ -2264,10 +2441,39 @@ fn parse_curate_qm_bars_1m_args_inner(args: &[&str]) -> Result Result Result { + let mut mongo = MongoFlagState::default(); let mut intraday_path: Option = None; let mut out_dir: Option = None; let mut shard_count: Option = None; @@ -2301,21 +2508,13 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { )); } - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-fx-1m (file mode only)" - )); + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; } let (flag, value) = if let Some((k, v)) = token.split_once('=') { @@ -2332,16 +2531,9 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { (token, v) }; - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; + if mongo.try_parse_value_flag(flag, value, true)? { + continue; + } match flag { "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, @@ -2372,6 +2564,27 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { } } + if mongo.from_mongo { + if intraday_path.is_some() { + return Err("cannot combine '--from-mongo' with '--eod-intraday'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + return Ok(CliAction::CurateFx1mMongo(CurateFx1mMongoArgs { + mongo: mongo_opts, + out_dir, + shard_count, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let intraday_path = intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; @@ -2387,6 +2600,105 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { })) } +fn parse_curate_macro_args(args: &[&str]) -> Result { + parse_curate_macro_args_inner(args).map_err(|e| sanitize_single_line(&e)) +} + +fn parse_curate_macro_args_inner(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); + let mut te_data: Option = None; + let mut series_map: Option = None; + let mut out_dir: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-macro" + )); + } + + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; + } + + let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag); + if !matches!( + flag_name, + "--mongo-uri" + | "--mongo-uri-env" + | "--batch-size" + | "--limit" + | "--te-data" + | "--series-map" + | "--out" + ) { + return Err(format!("unknown flag '{flag_name}' for curate-macro")); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + if mongo.try_parse_value_flag(flag, value, false)? { + continue; + } + + match flag { + "--te-data" => set_path(&mut te_data, "--te-data", value)?, + "--series-map" => set_path(&mut series_map, "--series-map", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + other => return Err(format!("unknown flag '{other}' for curate-macro")), + } + } + + if mongo.from_mongo { + if te_data.is_some() { + return Err("cannot combine '--from-mongo' with '--te-data'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let series_map = + series_map.ok_or_else(|| "missing required flag '--series-map'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + return Ok(CliAction::CurateMacroMongo(CurateMacroMongoArgs { + mongo: mongo_opts, + series_map, + out_dir, + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + + let te_data = te_data.ok_or_else(|| "missing required flag '--te-data'".to_string())?; + let series_map = + series_map.ok_or_else(|| "missing required flag '--series-map'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + + Ok(CliAction::CurateMacro(CurateMacroArgs { + te_data, + series_map, + out_dir, + })) +} + const ALLOWED_SEND_ILP_PREFIXES: [&str; 3] = ["bars_1m", "bars_1m_qm", "fx_1m"]; fn parse_send_ilp_args(args: &[&str]) -> Result { @@ -2461,8 +2773,16 @@ fn parse_send_ilp_args(args: &[&str]) -> Result { Ok(CliAction::SendIlp(SendIlpArgs { dir, prefix, addr })) } +fn redact_cli_error_secrets(msg: String) -> String { + redact_embedded_mongo_uris(&msg) +} + /// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. pub fn parse_args(args: &[String]) -> Result { + parse_args_inner(args).map_err(redact_cli_error_secrets) +} + +fn parse_args_inner(args: &[String]) -> Result { let slices: Vec<&str> = args.iter().map(String::as_str).collect(); match slices.as_slice() { [] | ["--help"] | ["-h"] => Ok(CliAction::Help), @@ -4795,50 +5115,77 @@ mod tests { } #[test] - fn parse_curate_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - + fn parse_curate_bars_1m_mongo_flags_and_mixing_rules_hide_secrets() { let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-bars-1m", flag])).unwrap_err(); - assert!( - err_bare.contains(flag) && err_bare.contains("file mode only"), - "bare {flag} should fail with file-mode error, got: {err_bare}" - ); - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-bars-1m", flag, secret])).unwrap_err(); - assert!( - err_sep.contains(flag) && err_sep.contains("file mode only"), - "separated {flag} should fail with file-mode error, got: {err_sep}" - ); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); + // Mongo options without --from-mongo fail with clear message and no secret leak. + let err = parse_args(&to_args(&[ + "curate-bars-1m", + "--eod-intraday", + "i.bson", + "--qm-splits", + "s.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + &format!("--mongo-uri={secret}"), + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t_pw")); - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-bars-1m", &eq_token])).unwrap_err(); - assert!( - err_eq.contains(flag) && err_eq.contains("file mode only"), - "equals {flag} should fail with file-mode error, got: {err_eq}" - ); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } + // Combining --from-mongo with file-mode BSON flags fails closed. + let err = parse_args(&to_args(&[ + "curate-bars-1m", + "--from-mongo", + "--eod-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + ])) + .unwrap_err(); + assert_eq!( + err, + "cannot combine '--from-mongo' with '--eod-intraday' or '--qm-splits'" + ); + + // Valid --from-mongo invocation with date bounds. + let parsed = parse_args(&to_args(&[ + "curate-bars-1m", + "--from-mongo", + "--date-gte", + "2024-01-01", + "--date-lt", + "2024-01-02", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("valid curate-bars-1m --from-mongo"); + assert!(matches!( + parsed, + CliAction::CurateBars1mMongo(CurateBars1mMongoArgs { + shard_count: 4, + known_at_micros: 1_735_689_600_000_000, + .. + }) + )); } #[test] @@ -5142,54 +5489,76 @@ mod tests { } #[test] - fn parse_curate_qm_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - + fn parse_curate_qm_bars_1m_mongo_flags_and_mixing_rules_hide_secrets() { let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-qm-bars-1m", flag])).unwrap_err(); - assert!( - err_bare.contains(flag) && err_bare.contains("file mode only"), - "bare {flag} should fail with file-mode error, got: {err_bare}" - ); - assert!( - !err_bare.contains('\r') && !err_bare.contains('\n'), - "bare {flag} error must be single-line: {err_bare:?}" - ); - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-qm-bars-1m", flag, secret])).unwrap_err(); - assert!( - err_sep.contains(flag) && err_sep.contains("file mode only"), - "separated {flag} should fail with file-mode error, got: {err_sep}" - ); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); + // Mongo options without --from-mongo fail with clear message and no secret leak. + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + &format!("--mongo-uri={secret}"), + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t_pw")); - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-qm-bars-1m", &eq_token])).unwrap_err(); - assert!( - err_eq.contains(flag) && err_eq.contains("file mode only"), - "equals {flag} should fail with file-mode error, got: {err_eq}" - ); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } + let err_sep = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + "--mongo-uri", + secret, + ])) + .unwrap_err(); + assert_eq!(err_sep, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err_sep.contains("s3cr3t_pw")); + + // --with-qm-prices is not a curate-qm-bars-1m flag and must not echo values. + let err_qm = parse_args(&to_args(&[ + "curate-qm-bars-1m", + &format!("--with-qm-prices={secret}"), + ])) + .unwrap_err(); + assert_eq!( + err_qm, + "unknown flag '--with-qm-prices' for curate-qm-bars-1m" + ); + assert!(!err_qm.contains("s3cr3t_pw")); + + // Combining --from-mongo with --qm-intraday fails closed. + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--from-mongo", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--qm-intraday'"); } #[test] @@ -5386,45 +5755,56 @@ mod tests { } #[test] - fn parse_curate_fx_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - + fn parse_curate_fx_1m_mongo_flags_and_mixing_rules_hide_secrets() { let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - let expected = format!( - "MongoDB streaming flag '{flag}' is not supported by curate-fx-1m (file mode only)" - ); - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-fx-1m", flag])).unwrap_err(); - assert_eq!(err_bare, expected, "bare {flag} error mismatch"); + let err = parse_args(&to_args(&[ + "curate-fx-1m", + "--eod-intraday", + "i.bson", + "--out", + "o", + "--shards", + "2", + &format!("--mongo-uri={secret}"), + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t_pw")); - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-fx-1m", flag, secret])).unwrap_err(); - assert_eq!(err_sep, expected, "separated {flag} error mismatch"); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); + let err = parse_args(&to_args(&[ + "curate-fx-1m", + "--from-mongo", + "--eod-intraday", + "i.bson", + "--out", + "o", + "--shards", + "2", + ])) + .unwrap_err(); + assert_eq!( + err, + "cannot combine '--from-mongo' with '--eod-intraday'" + ); - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-fx-1m", &eq_token])).unwrap_err(); - assert_eq!(err_eq, expected, "equals {flag} error mismatch"); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } + let parsed = parse_args(&to_args(&[ + "curate-fx-1m", + "--from-mongo", + "--date-gte", + "2024-01-01", + "--date-lt", + "2024-01-02", + "--out", + "o", + "--shards", + "4", + ])) + .expect("valid curate-fx-1m --from-mongo"); + assert!(matches!( + parsed, + CliAction::CurateFx1mMongo(CurateFx1mMongoArgs { shard_count: 4, .. }) + )); } #[test] @@ -5694,23 +6074,51 @@ mod tests { .unwrap_err(); assert_eq!(err, "unknown flag '--bogus' for curate-posts"); - for from_mongo_args in [ - &["curate-posts", "--from-mongo"][..], - &[ - "curate-posts", - "--from-mongo", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ][..], - &["curate-posts", "--from-mongo=true"][..], - ] { - let err = parse_args(&to_args(from_mongo_args)).unwrap_err(); - assert_eq!(err, "unknown flag '--from-mongo' for curate-posts"); - } + // Valid --from-mongo and flag-mixing rejections for curate-posts + let parsed_mongo = parse_args(&to_args(&[ + "curate-posts", + "--from-mongo", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .expect("valid curate-posts --from-mongo"); + assert!(matches!(parsed_mongo, CliAction::CuratePostsMongo(_))); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--from-mongo", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--ceo-posts'"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--mongo-uri", + "mongodb://u:secret_pw@localhost:27017/stock", + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("secret_pw")); // Positional argument rejected let err = parse_args(&to_args(&[ @@ -5849,6 +6257,7 @@ mod tests { ])), Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs { qm_financials: PathBuf::from("fin.bson"), + qm_financials_old: None, qm_filings: PathBuf::from("fil.bson"), provider_mapping: PathBuf::from("map.tsv"), listing_venues: PathBuf::from("venues.tsv"), @@ -5943,6 +6352,7 @@ mod tests { ])), Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs { qm_financials: PathBuf::from("fin2.bson"), + qm_financials_old: None, qm_filings: PathBuf::from("fil2.bson"), provider_mapping: PathBuf::from("map2.tsv"), listing_venues: PathBuf::from("venues2.tsv"), @@ -6219,33 +6629,120 @@ mod tests { let err = parse_args(&to_args(&dup_tok)).unwrap_err(); assert!(err.contains("duplicate flag '--quarterly-tokens'"), "{err}"); - // Unknown flags including --from-mongo and --mongo-uri (rejected before consuming a value) - for (args, expected_flag) in [ - (&["curate-fundamentals", "--bogus", "1"][..], "--bogus"), - (&["curate-fundamentals", "--from-mongo"][..], "--from-mongo"), - ( - &["curate-fundamentals", "--from-mongo", "--out", "o"][..], - "--from-mongo", - ), - ( - &["curate-fundamentals", "--from-mongo=true"][..], - "--from-mongo", - ), - ( - &["curate-fundamentals", "--mongo-uri", "mongodb://host"][..], - "--mongo-uri", - ), - ( - &["curate-fundamentals", "--mongo-uri-env=MONGODB_READ_URI"][..], - "--mongo-uri-env", - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!( - err, - format!("unknown flag '{expected_flag}' for curate-fundamentals") - ); - } + // Unknown flags and MongoDB / --qm-financials-old flag-mixing rules + let err = parse_args(&to_args(&["curate-fundamentals", "--bogus", "1"])).unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-fundamentals"); + + let err = parse_args(&to_args(&[ + "curate-fundamentals", + "--from-mongo", + "--qm-financials", + "fin.bson", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ])) + .unwrap_err(); + assert_eq!( + err, + "cannot combine '--from-mongo' with '--qm-financials', '--qm-financials-old', or '--qm-filings'" + ); + + let err = parse_args(&to_args(&[ + "curate-fundamentals", + "--qm-financials", + "fin.bson", + "--qm-filings", + "fil.bson", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + "--with-qm-financials-old", + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + + let parsed_with_old = parse_args(&to_args(&[ + "curate-fundamentals", + "--qm-financials", + "fin.bson", + "--qm-financials-old", + "fin-old.bson", + "--qm-filings", + "fil.bson", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ])) + .expect("file mode with --qm-financials-old"); + assert!(matches!( + parsed_with_old, + CliAction::CurateFundamentals(CurateFundamentalsArgs { + qm_financials_old: Some(ref p), + .. + }) if p == Path::new("fin-old.bson") + )); + + let parsed_mongo = parse_args(&to_args(&[ + "curate-fundamentals", + "--from-mongo", + "--with-qm-financials-old", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ])) + .expect("mongo mode with --with-qm-financials-old"); + assert!(matches!( + parsed_mongo, + CliAction::CurateFundamentalsMongo(CurateFundamentalsMongoArgs { + with_qm_financials_old: true, + .. + }) + )); // Positional argument rejected let err = parse_args(&to_args(&["curate-fundamentals", "extra"])).unwrap_err(); @@ -6284,7 +6781,7 @@ mod tests { ); } assert!(usage.contains("/macro/part.parquet"), "{usage}"); - assert!(usage.contains("file mode only"), "{usage}"); + assert!(usage.contains("curate-macro --from-mongo"), "{usage}"); let expected = CliAction::CurateMacro(CurateMacroArgs { te_data: PathBuf::from("teData.bson"), @@ -6444,30 +6941,40 @@ mod tests { assert_eq!(err, format!("duplicate flag '{dup_flag}'")); } - // Unknown flags including --mongo-uri and --from-mongo (rejected before consuming a value) - for (args, expected_flag) in [ - (&["curate-macro", "--bogus", "1"][..], "--bogus"), - (&["curate-macro", "--from-mongo"][..], "--from-mongo"), - ( - &["curate-macro", "--from-mongo", "--out", "o"][..], - "--from-mongo", - ), - (&["curate-macro", "--from-mongo=true"][..], "--from-mongo"), - ( - &["curate-macro", "--mongo-uri", "mongodb://host"][..], - "--mongo-uri", - ), - ( - &["curate-macro", "--mongo-uri-env=MONGODB_READ_URI"][..], - "--mongo-uri-env", - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!( - err, - format!("unknown flag '{expected_flag}' for curate-macro") - ); - } + // Unknown flags and MongoDB flag-mixing rules (with secret redaction) + let err = parse_args(&to_args(&["curate-macro", "--bogus", "1"])).unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-macro"); + + let err = parse_args(&to_args(&["curate-macro", "--from-mongo=true"])).unwrap_err(); + assert_eq!(err, "unknown flag '--from-mongo' for curate-macro"); + + let err = parse_args(&to_args(&[ + "curate-macro", + "--from-mongo", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "o", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--te-data'"); + + let err = parse_args(&to_args(&[ + "curate-macro", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "o", + "--mongo-uri", + "mongodb://user:s3cr3t@host:27017/stock", + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t")); // Unexpected positional arguments rejected (including single-dash token) for pos in ["extra", "-x"] { @@ -6776,4 +7283,109 @@ mod tests { .expect("space dir with equals and IPv6 equals addr"); assert_eq!(parsed_space, expected); } + + #[test] + fn parse_curate_macro_and_qm_bars_1m_file_and_mongo_modes() { + let macro_file = parse_args(&to_args(&[ + "curate-macro", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "out_macro", + ])) + .expect("curate-macro file mode"); + assert_eq!( + macro_file, + CliAction::CurateMacro(CurateMacroArgs { + te_data: PathBuf::from("te.bson"), + series_map: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("out_macro"), + }) + ); + + let macro_mongo = parse_args(&to_args(&[ + "curate-macro", + "--from-mongo", + "--series-map", + "map.tsv", + "--out", + "out_macro", + ])) + .expect("curate-macro --from-mongo"); + assert!(matches!(macro_mongo, CliAction::CurateMacroMongo(_))); + + let err = parse_args(&to_args(&[ + "curate-macro", + "--from-mongo", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "out_macro", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--te-data'"); + + let qm_file = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "qm.bson", + "--provider-mapping", + "pm.tsv", + "--out", + "out_qm", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("curate-qm-bars-1m file mode"); + assert!(matches!( + qm_file, + CliAction::CurateQmBars1m(CurateQmBars1mArgs { + shard_count: 4, + known_at_micros: 1_735_689_600_000_000, + .. + }) + )); + + let qm_mongo = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--from-mongo", + "--date-gte", + "2024-01-01", + "--date-lt", + "2024-01-02", + "--provider-mapping", + "pm.tsv", + "--out", + "out_qm", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("curate-qm-bars-1m --from-mongo"); + assert!(matches!(qm_mongo, CliAction::CurateQmBars1mMongo(_))); + + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--from-mongo", + "--qm-intraday", + "qm.bson", + "--provider-mapping", + "pm.tsv", + "--out", + "out_qm", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--qm-intraday'"); + } } diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs index f8c7689f..f02f2765 100644 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ b/tools/curate-etl/src/curate_bars_1m.rs @@ -492,6 +492,7 @@ where /// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022 /// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation /// invariants and cross-`source_id` collision handling. +#[cfg(test)] pub(crate) fn curate_and_write_bars_1m_by_listing( bars: B, listing_splits: &SplitTable, diff --git a/tools/curate-etl/src/curate_fundamentals.rs b/tools/curate-etl/src/curate_fundamentals.rs index 02092a68..3fffc104 100644 --- a/tools/curate-etl/src/curate_fundamentals.rs +++ b/tools/curate-etl/src/curate_fundamentals.rs @@ -32,8 +32,8 @@ use std::path::Path; use crate::events::{parse_filing_timefiled, QmFiling}; use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FundamentalsError, - FundamentalsStats, StatutoryLagVenue, + build_fundamentals_rows_with_legacy, build_fundamentals_snapshots, FinancialObservation, + FundamentalsError, FundamentalsStats, StatutoryLagVenue, }; use crate::parquet_fundamentals::{ write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions, @@ -172,6 +172,39 @@ where K: AsRef, IO: IntoIterator>, IF: IntoIterator>, +{ + curate_fundamentals_with_legacy( + observations, + std::iter::empty::>(), + filings, + mapping_source, + mapping, + venues, + k, + ) +} + +/// Pure `fundamentals_pit` curation stage merging primary (`qmFinancials`) and legacy +/// (`qmFinancials-old`) observations via [`build_fundamentals_rows_with_legacy`]. +/// +/// Rejects blank `mapping_source` with [`CurateFundamentalsError::EmptyMappingSource`] and `k == 0` +/// with [`CurateFundamentalsError::Fundamentals`] (`FundamentalsError::InvalidPeriodLimit`) before +/// consuming input iterators. +#[allow(clippy::too_many_arguments)] +pub fn curate_fundamentals_with_legacy( + primary_observations: IO, + legacy_observations: ILO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, +) -> Result +where + K: AsRef, + IO: IntoIterator>, + ILO: IntoIterator>, + IF: IntoIterator>, { if mapping_source.trim().is_empty() { return Err(CurateFundamentalsError::EmptyMappingSource); @@ -180,22 +213,42 @@ where return Err(FundamentalsError::InvalidPeriodLimit { k }.into()); } - let obs_iter = observations.into_iter(); + let primary_iter = primary_observations.into_iter(); + let legacy_iter = legacy_observations.into_iter(); let filings_iter = filings.into_iter(); let mut stats = CurateFundamentalsStats::default(); - let mut mapped_observations: Vec> = - Vec::with_capacity(obs_iter.size_hint().0); + let mut mapped_primary: Vec> = + Vec::with_capacity(primary_iter.size_hint().0); + let mut mapped_legacy: Vec> = + Vec::with_capacity(legacy_iter.size_hint().0); let mut mapped_filings: Vec> = Vec::with_capacity(filings_iter.size_hint().0); - for obs in obs_iter { + for obs in primary_iter { stats.observations_in += 1; let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end) else { stats.observations_dropped_unmapped += 1; continue; }; - mapped_observations.push(FinancialObservation { + mapped_primary.push(FinancialObservation { + key: listing_id, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + }); + } + + for obs in legacy_iter { + stats.observations_in += 1; + let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end) + else { + stats.observations_dropped_unmapped += 1; + continue; + }; + mapped_legacy.push(FinancialObservation { key: listing_id, period_end: obs.period_end, fiscal_period: obs.fiscal_period, @@ -226,7 +279,8 @@ where }); } - let built = build_fundamentals_rows(mapped_observations, mapped_filings, venues); + let built = + build_fundamentals_rows_with_legacy(mapped_primary, mapped_legacy, mapped_filings, venues); stats.build = built.stats; let snapshots = build_fundamentals_snapshots(&built.rows, k)?; @@ -269,7 +323,50 @@ where IO: IntoIterator>, IF: IntoIterator>, { - let curated = curate_fundamentals(observations, filings, mapping_source, mapping, venues, k)?; + curate_and_write_fundamentals_with_legacy( + out_dir, + observations, + std::iter::empty::>(), + filings, + mapping_source, + mapping, + venues, + k, + options, + ) +} + +/// Thin end-to-end wrapper running [`curate_fundamentals_with_legacy`] and publishing the +/// resulting contract rows via [`write_fundamentals_pit_dataset`] to +/// `/fundamentals_pit/year=YYYY/part.parquet`. +#[allow(clippy::too_many_arguments)] +pub fn curate_and_write_fundamentals_with_legacy( + out_dir: P, + primary_observations: IO, + legacy_observations: ILO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + K: AsRef, + IO: IntoIterator>, + ILO: IntoIterator>, + IF: IntoIterator>, +{ + let curated = curate_fundamentals_with_legacy( + primary_observations, + legacy_observations, + filings, + mapping_source, + mapping, + venues, + k, + )?; let write_stats = write_fundamentals_pit_dataset(out_dir, &curated.rows, options)?; Ok(CurateFundamentalsWriteReport { curate_stats: curated.stats, diff --git a/tools/curate-etl/src/curate_posts.rs b/tools/curate-etl/src/curate_posts.rs index 752ae9c9..c26c88f3 100644 --- a/tools/curate-etl/src/curate_posts.rs +++ b/tools/curate-etl/src/curate_posts.rs @@ -1,6 +1,6 @@ //! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`], //! [`crate::provider_mapping::ProviderMappingTable`], [`crate::parquet_posts`], and -//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s. +//! [`crate::parquet_events::write_posts_events_dataset`] into contract [`EventsParquetRow`]s. //! //! # Contract & Point-in-Time Rules //! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication, @@ -32,7 +32,7 @@ use std::fmt; use std::path::Path; use crate::parquet_events::{ - write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, + write_posts_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, }; use crate::parquet_posts::{POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL}; @@ -271,9 +271,9 @@ where } /// Thin end-to-end wrapper running [`curate_posts`] and publishing the resulting contract rows -/// via [`write_events_dataset`] to `/events/year=YYYY/part.parquet`. +/// via [`write_posts_events_dataset`] to `/events/year=YYYY/part-posts.parquet`. /// -/// Any [`CuratePostsError`] returns before [`write_events_dataset`] is invoked, leaving +/// Any [`CuratePostsError`] returns before [`write_posts_events_dataset`] is invoked, leaving /// `out_dir` untouched. pub fn curate_and_write_posts( out_dir: P, @@ -288,7 +288,7 @@ where I: IntoIterator>, { let curated = curate_posts(posts, mapping_source, mapping)?; - let write_stats = write_events_dataset(out_dir, &curated.rows, options)?; + let write_stats = write_posts_events_dataset(out_dir, &curated.rows, options)?; Ok(CuratePostsWriteReport { curate_stats: curated.stats, write_stats, diff --git a/tools/curate-etl/src/curate_posts_tests.rs b/tools/curate-etl/src/curate_posts_tests.rs index b58de460..73d9c5be 100644 --- a/tools/curate-etl/src/curate_posts_tests.rs +++ b/tools/curate-etl/src/curate_posts_tests.rs @@ -924,8 +924,8 @@ fn curate_and_write_posts_round_trips_zstd_parquet_field_for_field() { assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&2)); assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&1)); - let path_2024 = dir.path().join("events/year=2024/part.parquet"); - let path_2025 = dir.path().join("events/year=2025/part.parquet"); + let path_2024 = dir.path().join("events/year=2024/part-posts.parquet"); + let path_2025 = dir.path().join("events/year=2025/part-posts.parquet"); assert!(path_2024.exists()); assert!(path_2025.exists()); @@ -1304,7 +1304,7 @@ fn parquet_writer_error_is_wrapped_and_curate_stats_not_returned() { )); assert!(err.source().is_some()); assert!(err.to_string().contains("posts Parquet write failed")); - assert!(!dir.path().join("events/year=2024/part.parquet").exists()); + assert!(!dir.path().join("events/year=2024/part-posts.parquet").exists()); } #[test] @@ -1376,8 +1376,9 @@ fn same_listing_same_timestamp_tie_breaks_on_subtype_then_payload_and_round_trip .expect("write"); assert_eq!(report.curate_stats, pure.stats); assert_eq!(report.write_stats.rows_written, 4); - let read = - read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet")); + let read = read_events_parquet_and_verify_zstd( + &dir.path().join("events/year=2024/part-posts.parquet"), + ); assert_eq!(read, pure.rows); assert_strictly_ascending_by_tuple(&read); } diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs index 7ac7cae6..7753850a 100644 --- a/tools/curate-etl/src/fundamentals.rs +++ b/tools/curate-etl/src/fundamentals.rs @@ -75,7 +75,7 @@ use std::borrow::Borrow; use std::cmp::Ordering; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::error::Error; use std::fmt; @@ -408,6 +408,7 @@ struct EligibleObservation { report_date: Option, venue: StatutoryLagVenue, fields: FundamentalsFields, + is_legacy: bool, } #[derive(Debug, Clone, Copy)] @@ -428,6 +429,7 @@ struct ParsedPeriodicFiling { struct CandidateRow { row: FundamentalsRow, report_date: Option, + is_legacy: bool, } /// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic @@ -444,12 +446,65 @@ where IO: IntoIterator>, IF: IntoIterator>, { - let obs_iter = observations.into_iter(); - let mut stats = FundamentalsStats::default(); - let mut eligible_obs: Vec> = Vec::with_capacity(obs_iter.size_hint().0); - let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new(); + build_fundamentals_rows_with_legacy( + observations, + std::iter::empty::>(), + filings, + venues, + ) +} - for obs in obs_iter { +/// Builds sorted, unique bitemporal fundamentals rows by merging primary (`qmFinancials`) and +/// legacy (`qmFinancials-old`) financial observations alongside periodic filings and venue +/// statutory-lag classes. +/// +/// Merge precedence rules: +/// - Both primary and legacy observations feed `stats.observations_in` and filing-link earliest +/// period bounds so historical `qmFilings` can anchor `qmFinancials-old` periods. +/// - Distinct `known_at_utc_micros` vintages across both sources are preserved as separate +/// bitemporal versions (historical snapshots and restatements). +/// - Undated (`report_date: None`) legacy (`qmFinancials-old`) observations have no evidence +/// linking their values to an inferred periodic filing: they are never labeled +/// `filing_timestamp`, and any undated legacy observation overlapping a primary or dated vintage +/// for the same `(key, period_end, fiscal_period)` is withheld as an unanchored vintage +/// (`observations_dropped_unanchored_vintage`) so an overwritten legacy snapshot cannot leak +/// revised values before an amendment. +/// - Within a `(key, period_end, fiscal_period)` stream, an undated (`report_date: None`) legacy +/// `statutory_lag_estimate` candidate arriving after an already-accepted earlier row for the +/// same `fiscal_period` is dropped as a stale estimate (`observations_dropped_stale_estimate`). +/// - Within the same `(key, period_end, known_at_utc_micros)` group, primary (`qmFinancials`) +/// survivors supersede legacy (`qmFinancials-old`) survivors for the same `fiscal_period` +/// (`duplicate_collapsed`), while intra-collection conflicts remain dropped via +/// `duplicate_conflict_dropped`. +pub fn build_fundamentals_rows_with_legacy( + primary_observations: IO, + legacy_observations: ILO, + filings: IF, + venues: &BTreeMap, +) -> FundamentalsBuild +where + K: Ord + Clone, + IO: IntoIterator>, + ILO: IntoIterator>, + IF: IntoIterator>, +{ + let primary_iter = primary_observations.into_iter(); + let legacy_iter = legacy_observations.into_iter(); + let mut stats = FundamentalsStats::default(); + let mut eligible_obs: Vec> = Vec::with_capacity( + primary_iter + .size_hint() + .0 + .saturating_add(legacy_iter.size_hint().0), + ); + let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new(); + let mut anchored_or_primary_periods: BTreeSet<(K, i32, FiscalPeriod)> = BTreeSet::new(); + + let tagged_obs = primary_iter + .map(|obs| (obs, false)) + .chain(legacy_iter.map(|obs| (obs, true))); + + for (obs, is_legacy) in tagged_obs { stats.observations_in += 1; let Some(&venue) = venues.get(&obs.key) else { @@ -483,6 +538,14 @@ where }) .or_insert(obs.period_end); + if !is_legacy || obs.report_date.is_some() { + anchored_or_primary_periods.insert(( + obs.key.clone(), + obs.period_end, + obs.fiscal_period, + )); + } + eligible_obs.push(EligibleObservation { key: obs.key, period_end: obs.period_end, @@ -491,6 +554,7 @@ where report_date: obs.report_date, venue, fields: obs.fields.normalize_zeros(), + is_legacy, }); } @@ -559,31 +623,85 @@ where let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); for obs in eligible_obs { - let linked_micros = filing_index - .get(&(obs.key.clone(), obs.fiscal_period)) - .and_then(|bucket| match obs.report_date { - Some(rd) => { - // Earliest matching periodic filing (amended or unamended) on Eastern day `rd`. - // `rd > obs.period_end` is guaranteed by validation above. - let pos = bucket.partition_point(|f| f.et_date < rd); - bucket - .get(pos) - .filter(|f| f.et_date == rd) - .map(|f| f.utc_micros) - } - None => { - // Earliest matching non-amended periodic filing strictly after `period_end` - // and within the inclusive calendar-day inference window. + // An undated legacy (`qmFinancials-old`) observation carries no `report_date` proving + // which filing produced its values. If any primary or dated vintage exists for the same + // `(key, period_end, fiscal_period)`, withhold the undated legacy row rather than risking + // publishing an overwritten revision before an amendment. + if obs.is_legacy + && obs.report_date.is_none() + && anchored_or_primary_periods.contains(&( + obs.key.clone(), + obs.period_end, + obs.fiscal_period, + )) + { + stats.observations_dropped_unanchored_vintage += 1; + continue; + } + + let (linked_micros, legacy_filing_lower_bound_micros) = if obs.is_legacy + && obs.report_date.is_none() + { + // Never treat an undated legacy observation as filing-backed without a `report_date` + // linking it to the inferred filing, but still use any later plausible periodic filing + // (or in-window amendment) as a conservative lower bound on `known_at_utc_micros` so a + // late release is never exposed early at the statutory deadline. + let lower_bound = filing_index + .get(&(obs.key.clone(), obs.fiscal_period)) + .and_then(|bucket| { let window_end = i64::from(obs.period_end) + i64::from(obs.fiscal_period.undated_link_window_days()); let pos = bucket.partition_point(|f| f.et_date <= obs.period_end); - bucket[pos..] + let mut earliest_unamended: Option = None; + let mut latest_amendment: Option = None; + for f in bucket[pos..] .iter() .take_while(|f| i64::from(f.et_date) <= window_end) - .find(|f| !f.is_amendment) - .map(|f| f.utc_micros) - } - }); + { + if f.is_amendment { + latest_amendment = Some( + latest_amendment.map_or(f.utc_micros, |m| m.max(f.utc_micros)), + ); + } else if earliest_unamended.is_none() { + earliest_unamended = Some(f.utc_micros); + } + } + match (earliest_unamended, latest_amendment) { + (Some(u), Some(a)) => Some(u.max(a)), + (Some(u), None) => Some(u), + (None, Some(a)) => Some(a), + (None, None) => None, + } + }); + (None, lower_bound) + } else { + let linked = filing_index + .get(&(obs.key.clone(), obs.fiscal_period)) + .and_then(|bucket| match obs.report_date { + Some(rd) => { + // Earliest matching periodic filing (amended or unamended) on Eastern day + // `rd`. `rd > obs.period_end` is guaranteed by validation above. + let pos = bucket.partition_point(|f| f.et_date < rd); + bucket + .get(pos) + .filter(|f| f.et_date == rd) + .map(|f| f.utc_micros) + } + None => { + // Earliest matching non-amended periodic filing strictly after `period_end` + // and within the inclusive calendar-day inference window. + let window_end = i64::from(obs.period_end) + + i64::from(obs.fiscal_period.undated_link_window_days()); + let pos = bucket.partition_point(|f| f.et_date <= obs.period_end); + bucket[pos..] + .iter() + .take_while(|f| i64::from(f.et_date) <= window_end) + .find(|f| !f.is_amendment) + .map(|f| f.utc_micros) + } + }); + (linked, None) + }; let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros { (micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP) @@ -602,7 +720,7 @@ where stats.observations_dropped_date_out_of_range += 1; continue; }; - let Ok(micros) = et_to_utc_micros( + let Ok(lag_micros) = et_to_utc_micros( lag_date, FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, @@ -611,6 +729,10 @@ where stats.observations_dropped_date_out_of_range += 1; continue; }; + let micros = match legacy_filing_lower_bound_micros { + Some(lb) => lag_micros.max(lb), + None => lag_micros, + }; (micros, KNOWN_AT_SOURCE_STATUTORY_LAG) }; @@ -625,6 +747,7 @@ where fields: obs.fields, }, report_date: obs.report_date, + is_legacy: obs.is_legacy, }); } @@ -650,11 +773,13 @@ where pe_end += 1; } - // Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for - // each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag - // estimate. + // Track the newest accepted `report_date` (and whether any row was already accepted) at + // an earlier `known_at_utc_micros` for each `FiscalPeriod` so only accepted earlier + // versions can suppress a stale statutory-lag estimate. let mut max_accepted_rd_q: Option = None; let mut max_accepted_rd_fy: Option = None; + let mut has_accepted_q = false; + let mut has_accepted_fy = false; let mut g_start = pe_start; while g_start < pe_end { @@ -664,21 +789,26 @@ where g_end += 1; } - // Filter out stale dated statutory-lag candidates before duplicate/conflict checks - // so a superseded estimate cannot cause an eligible estimate at the same fallback + // Filter out stale statutory-lag candidates before duplicate/conflict checks so a + // superseded estimate cannot cause an eligible estimate at the same fallback // timestamp to be rejected as conflicting. survivors.clear(); for idx in g_start..g_end { let cand = &candidates[idx]; - let prior_max_rd = match cand.row.fiscal_period { - FiscalPeriod::Quarterly => max_accepted_rd_q, - FiscalPeriod::Annual => max_accepted_rd_fy, + let (prior_max_rd, prior_has_accepted) = match cand.row.fiscal_period { + FiscalPeriod::Quarterly => (max_accepted_rd_q, has_accepted_q), + FiscalPeriod::Annual => (max_accepted_rd_fy, has_accepted_fy), }; - let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - && cand - .report_date - .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); - if is_stale_estimate { + let is_stale_dated_estimate = + cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand + .report_date + .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); + let is_stale_undated_legacy_estimate = cand.is_legacy + && cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand.report_date.is_none() + && prior_has_accepted; + if is_stale_dated_estimate || is_stale_undated_legacy_estimate { stats.observations_dropped_stale_estimate += 1; } else { survivors.push(idx); @@ -690,6 +820,32 @@ where continue; } + // Within the same `(key, period_end, known_at_utc_micros)` group, primary + // (`qmFinancials`) survivors supersede legacy (`qmFinancials-old`) survivors for the + // same `FiscalPeriod` rather than triggering a cross-collection conflict drop. + let has_primary_q = survivors.iter().any(|&idx| { + !candidates[idx].is_legacy + && candidates[idx].row.fiscal_period == FiscalPeriod::Quarterly + }); + let has_primary_fy = survivors.iter().any(|&idx| { + !candidates[idx].is_legacy + && candidates[idx].row.fiscal_period == FiscalPeriod::Annual + }); + if has_primary_q || has_primary_fy { + let before = survivors.len(); + survivors.retain(|&idx| { + let cand = &candidates[idx]; + if !cand.is_legacy { + return true; + } + match cand.row.fiscal_period { + FiscalPeriod::Quarterly => !has_primary_q, + FiscalPeriod::Annual => !has_primary_fy, + } + }); + stats.duplicate_collapsed += before - survivors.len(); + } + let first = &candidates[survivors[0]].row; let all_identical = survivors[1..].iter().all(|&idx| { let other = &candidates[idx].row; @@ -711,12 +867,19 @@ where group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); } } - if let Some(rd) = group_max_rd { - let slot = match first.fiscal_period { - FiscalPeriod::Quarterly => &mut max_accepted_rd_q, - FiscalPeriod::Annual => &mut max_accepted_rd_fy, - }; - *slot = Some(slot.map_or(rd, |m| m.max(rd))); + match first.fiscal_period { + FiscalPeriod::Quarterly => { + has_accepted_q = true; + if let Some(rd) = group_max_rd { + max_accepted_rd_q = Some(max_accepted_rd_q.map_or(rd, |m| m.max(rd))); + } + } + FiscalPeriod::Annual => { + has_accepted_fy = true; + if let Some(rd) = group_max_rd { + max_accepted_rd_fy = Some(max_accepted_rd_fy.map_or(rd, |m| m.max(rd))); + } + } } stats.duplicate_collapsed += survivors.len() - 1; diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs index a3919caf..0a31fd29 100644 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -1067,3 +1067,678 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { assert!(fy_snap.has_estimated_lag); assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); } + +#[test] +fn legacy_merge_primary_supersedes_legacy_at_same_known_at_while_intra_primary_conflicts_still_drop() +{ + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + let filings = vec![filing("ACME", "2024-05-02T16:30:00 EDT", "10-Q")]; + + // Primary and legacy collide at identical known_at with differing revenue: primary wins. + let primary = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(120.0), + )]; + let legacy = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(100.0), + )]; + + let built = build_fundamentals_rows_with_legacy(primary, legacy, filings.clone(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 2); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.duplicate_collapsed, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); + assert_eq!(built.rows[0].fields.revenue, Some(120.0)); + + // Two conflicting primary observations + one legacy observation: legacy collapses, primary pair drops. + let conflicting_primary = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(120.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(125.0), + ), + ]; + let legacy_dup = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(100.0), + )]; + let built_conflict = + build_fundamentals_rows_with_legacy(conflicting_primary, legacy_dup, filings, &venues); + assert_reconciliation(&built_conflict); + assert_eq!(built_conflict.stats.observations_in, 3); + assert_eq!(built_conflict.stats.rows_out, 0); + assert_eq!(built_conflict.stats.duplicate_collapsed, 1); + assert_eq!(built_conflict.stats.duplicate_conflict_dropped, 2); +} + +#[test] +fn legacy_merge_undated_legacy_statutory_lag_does_not_overwrite_earlier_filing_timestamp() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + // Dated 10-Q/A on May 10 anchors primary observation; undated legacy observation only links + // non-amended filings, so it falls back to statutory_lag_estimate on May 15 (45d after Q1). + let filings = vec![filing("ACME", "2024-05-10T16:30:00 EDT", "10-Q/A")]; + + let primary = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(210.0), + )]; + let legacy = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(190.0), + )]; + + let built = build_fundamentals_rows_with_legacy(primary, legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 2); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 1); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + assert_eq!(built.stats.observations_dropped_unanchored_vintage, 1); + assert_eq!(built.stats.observations_dropped_stale_estimate, 0); + assert_eq!(built.rows[0].fields.revenue, Some(210.0)); + assert_eq!( + built.rows[0].known_at_source, + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); +} + +#[test] +fn legacy_merge_withholds_undated_legacy_overlapping_later_amendment_and_never_labels_undated_legacy_filing_backed() +{ + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q2_23 = day(2023, 6, 30); + let q3_23 = day(2023, 9, 30); + let q4_23 = day(2023, 12, 31); + let q1_24 = day(2024, 3, 31); + + let filings = vec![ + filing("ACME", "2023-08-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2023-11-05T16:30:00 EST", "10-Q"), + filing("ACME", "2024-02-20T16:30:00 EST", "10-Q"), + filing("ACME", "2024-05-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-07-10T16:30:00 EDT", "10-Q/A"), + ]; + + // Case 1: Legacy holds revised Q1 with no report_date; primary holds dated July amendment. + // Both May original 10-Q and July 10-Q/A exist in qmFilings. The undated legacy Q1 must be + // withheld so a June decision never sees revised Q1 values or an early TTM. + let legacy_no_orig = vec![ + obs( + "ACME", + q2_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 5)), + fields_rev(90.0), + ), + obs( + "ACME", + q3_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 5)), + fields_rev(100.0), + ), + obs( + "ACME", + q4_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 20)), + fields_rev(110.0), + ), + obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(125.0), + ), + ]; + let primary_amend = vec![obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 7, 10)), + fields_rev(125.0), + )]; + + let built_no_orig = build_fundamentals_rows_with_legacy( + primary_amend.clone(), + legacy_no_orig, + filings.clone(), + &venues, + ); + assert_reconciliation(&built_no_orig); + assert_eq!(built_no_orig.stats.observations_in, 5); + assert_eq!(built_no_orig.stats.rows_out, 4); + assert_eq!(built_no_orig.stats.rows_linked_to_filing, 4); + assert_eq!(built_no_orig.stats.rows_statutory_lag_estimate, 0); + assert_eq!(built_no_orig.stats.observations_dropped_unanchored_vintage, 1); + + let snaps_no_orig = build_fundamentals_snapshots(&built_no_orig.rows, 4).unwrap(); + let ts_june = utc_micros(2024, 6, 15, 16, 0, 0); + let ts_july = utc_micros(2024, 7, 15, 16, 0, 0); + + let at_june = as_of(&snaps_no_orig, "ACME", ts_june).expect("June snapshot"); + assert_eq!(at_june.periods[0].period_end, q4_23); + assert!(at_june.periods.iter().all(|p| p.period_end != q1_24)); + assert_eq!(at_june.ttm, None); + + let at_july = as_of(&snaps_no_orig, "ACME", ts_july).expect("July snapshot"); + assert_eq!(at_july.periods[0].period_end, q1_24); + assert_eq!(at_july.periods[0].fields.revenue, Some(125.0)); + assert_eq!( + at_july.periods[0].known_at_source, + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + assert_eq!(at_july.ttm.as_ref().unwrap().flows.revenue, Some(425.0)); + + // Case 2: Dated May original Q1 + undated revised legacy Q1 + dated July amendment. + // June sees original Q1 (120) and original TTM (420); July sees amended Q1 (125) and TTM (425). + let legacy_with_orig = vec![ + obs( + "ACME", + q2_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 5)), + fields_rev(90.0), + ), + obs( + "ACME", + q3_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 5)), + fields_rev(100.0), + ), + obs( + "ACME", + q4_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 20)), + fields_rev(110.0), + ), + obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 5)), + fields_rev(120.0), + ), + obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(125.0), + ), + ]; + let built_with_orig = build_fundamentals_rows_with_legacy( + primary_amend, + legacy_with_orig, + filings.clone(), + &venues, + ); + assert_reconciliation(&built_with_orig); + assert_eq!(built_with_orig.stats.observations_dropped_unanchored_vintage, 1); + let snaps_with_orig = build_fundamentals_snapshots(&built_with_orig.rows, 4).unwrap(); + + let june_orig = as_of(&snaps_with_orig, "ACME", ts_june).expect("June snapshot with original Q1"); + assert_eq!(june_orig.periods[0].period_end, q1_24); + assert_eq!(june_orig.periods[0].fields.revenue, Some(120.0)); + assert_eq!(june_orig.ttm.as_ref().unwrap().flows.revenue, Some(420.0)); + + let july_amended = as_of(&snaps_with_orig, "ACME", ts_july).expect("July snapshot after amendment"); + assert_eq!(july_amended.periods[0].period_end, q1_24); + assert_eq!(july_amended.periods[0].fields.revenue, Some(125.0)); + assert_eq!(july_amended.ttm.as_ref().unwrap().flows.revenue, Some(425.0)); + + // Case 3: Sole non-overlapping undated legacy statement with an unamended filing in window + // must NOT be labeled filing_timestamp; it falls back to statutory_lag_estimate. + let sole_legacy = vec![obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(120.0), + )]; + let built_sole = + build_fundamentals_rows_with_legacy(Vec::new(), sole_legacy, filings, &venues); + assert_reconciliation(&built_sole); + assert_eq!(built_sole.stats.rows_out, 1); + assert_eq!(built_sole.stats.rows_linked_to_filing, 0); + assert_eq!(built_sole.stats.rows_statutory_lag_estimate, 1); + assert_eq!( + built_sole.rows[0].known_at_source, + KNOWN_AT_SOURCE_STATUTORY_LAG + ); +} + +#[test] +fn legacy_merge_restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q3 = day(2023, 9, 30); + let q4 = day(2023, 12, 31); + let q1 = day(2024, 3, 31); + let q2 = day(2024, 6, 30); + + let filings = vec![ + filing("ACME", "2023-11-05T16:30:00 EST", "10-Q"), + filing("ACME", "2024-02-20T16:30:00 EST", "10-Q"), + filing("ACME", "2024-05-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-08-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-09-10T16:30:00 EDT", "10-Q/A"), + ]; + + // Historical quarters (Q3, Q4, original Q1) live in qmFinancials-old; Q2 + restated Q1 live + // in primary qmFinancials. + let legacy = vec![ + obs( + "ACME", + q3, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 5)), + fields_rev(100.0), + ), + obs( + "ACME", + q4, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 20)), + fields_rev(110.0), + ), + obs( + "ACME", + q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 5)), + fields_rev(120.0), + ), + ]; + let primary = vec![ + obs( + "ACME", + q2, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 5)), + fields_rev(130.0), + ), + obs( + "ACME", + q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 10)), + fields_rev(125.0), + ), + ]; + + let built = build_fundamentals_rows_with_legacy(primary, legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 5); + assert_eq!(built.stats.rows_out, 5); + assert_eq!(built.stats.rows_linked_to_filing, 5); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + let ts_q2 = utc_micros(2024, 8, 5, 20, 30, 0); + let ts_q1_restated = utc_micros(2024, 9, 10, 20, 30, 0); + + let at_q2 = as_of(&snaps, "ACME", ts_q2).expect("snapshot after Q2 filing"); + assert_eq!(at_q2.periods[0].period_end, q2); + assert_eq!(at_q2.periods[0].fields.revenue, Some(130.0)); + assert_eq!(at_q2.periods[1].period_end, q1); + assert_eq!(at_q2.periods[1].fields.revenue, Some(120.0)); + assert_eq!(at_q2.ttm.as_ref().unwrap().flows.revenue, Some(460.0)); + + let at_restated = as_of(&snaps, "ACME", ts_q1_restated).expect("snapshot after Q1 restatement"); + assert_eq!(at_restated.periods[0].period_end, q2); + assert_eq!(at_restated.periods[0].fields.revenue, Some(130.0)); + assert_eq!(at_restated.periods[1].period_end, q1); + assert_eq!(at_restated.periods[1].fields.revenue, Some(125.0)); + assert_eq!(at_restated.ttm.as_ref().unwrap().flows.revenue, Some(465.0)); +} + +#[test] +fn undated_legacy_only_late_filing_bounds_availability_without_claiming_filing_backed() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q2_23 = day(2023, 6, 30); + let q3_23 = day(2023, 9, 30); + let q4_23 = day(2023, 12, 31); + let q1_24 = day(2024, 3, 31); + + // US/TSX quarterly statutory deadline for 2024-03-31 is 2024-05-15 (+45d), + // but the first matching 10-Q was filed late on 2024-05-29 (within the 75-day window). + let filings = vec![ + filing("ACME", "2023-08-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2023-11-05T16:30:00 EST", "10-Q"), + filing("ACME", "2024-02-20T16:30:00 EST", "10-Q"), + filing("ACME", "2024-05-29T16:30:00 EDT", "10-Q"), + ]; + + let legacy = vec![ + obs( + "ACME", + q2_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 5)), + fields_rev(90.0), + ), + obs( + "ACME", + q3_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 5)), + fields_rev(100.0), + ), + obs( + "ACME", + q4_23, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 20)), + fields_rev(110.0), + ), + obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(120.0), + ), + ]; + + let built = build_fundamentals_rows_with_legacy(Vec::new(), legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 4); + assert_eq!(built.stats.rows_out, 4); + assert_eq!(built.stats.rows_linked_to_filing, 3); + assert_eq!(built.stats.rows_statutory_lag_estimate, 1); + + let q1_row = built + .rows + .iter() + .find(|r| r.period_end == q1_24) + .expect("Q1 row present"); + let expected_late_filing_ts = utc_micros(2024, 5, 29, 20, 30, 0); + assert_eq!(q1_row.known_at_utc_micros, expected_late_filing_ts); + assert_eq!(q1_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + + // On May 20 (after the May 15 statutory deadline, before the May 29 late filing), + // Q1 must NOT be visible and 4-quarter TTM must not yet include Q1. + let at_may_20 = as_of(&snaps, "ACME", utc_micros(2024, 5, 20, 16, 0, 0)) + .expect("May 20 snapshot exists from prior quarters"); + assert_eq!(at_may_20.periods[0].period_end, q4_23); + assert!(at_may_20.periods.iter().all(|p| p.period_end != q1_24)); + assert_eq!(at_may_20.ttm, None); + + // At/after the May 29 late filing, Q1 and TTM become visible but remain marked estimated. + let at_may_30 = as_of(&snaps, "ACME", utc_micros(2024, 5, 30, 16, 0, 0)) + .expect("May 30 snapshot"); + assert_eq!(at_may_30.periods[0].period_end, q1_24); + assert_eq!(at_may_30.periods[0].fields.revenue, Some(120.0)); + assert_eq!( + at_may_30.periods[0].known_at_source, + KNOWN_AT_SOURCE_STATUTORY_LAG + ); + assert!(at_may_30.periods[0].has_estimated_lag); + let ttm = at_may_30.ttm.as_ref().expect("4-quarter TTM after late filing"); + assert_eq!(ttm.flows.revenue, Some(420.0)); + assert!(ttm.has_estimated_lag); +} + +/// Deterministic Fisher-Yates shuffle driven by a fixed-seed 64-bit LCG (no external crates). +fn seeded_shuffle(items: &mut [T], seed: u64) { + let mut state = seed; + for i in (1..items.len()).rev() { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + let j = ((state >> 33) % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +#[test] +fn undated_legacy_only_with_in_window_amendment_is_not_visible_until_the_amendment_timestamp() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_24 = day(2024, 3, 31); + // Original 10-Q on May 5 and a 10-Q/A on June 10 (inside the 75-day window ending June 14). + // The undated legacy values cannot be tied to either release, so availability must be + // bounded by the later of the two (June 10 16:30 EDT = 20:30 UTC), not the May 15 deadline. + let filings = vec![ + filing("ACME", "2024-05-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-06-10T16:30:00 EDT", "10-Q/A"), + ]; + let legacy = vec![obs( + "ACME", + q1_24, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(120.0), + )]; + + let built = build_fundamentals_rows_with_legacy(Vec::new(), legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 0); + assert_eq!(built.stats.rows_statutory_lag_estimate, 1); + let amendment_ts = utc_micros(2024, 6, 10, 20, 30, 0); + assert_eq!(built.rows[0].known_at_utc_micros, amendment_ts); + assert_eq!(built.rows[0].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + + // Inclusive cutoff boundary: one microsecond earlier sees nothing; the amendment instant sees Q1. + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + assert!(as_of(&snaps, "ACME", amendment_ts - 1).is_none()); + assert!(as_of(&snaps, "ACME", utc_micros(2024, 5, 20, 16, 0, 0)).is_none()); + let at = as_of(&snaps, "ACME", amendment_ts).expect("visible at amendment instant"); + assert_eq!(at.periods[0].fields.revenue, Some(120.0)); + assert!(at.has_estimated_lag); +} + +#[test] +fn legacy_merge_intra_legacy_conflicts_drop_identical_legacy_duplicates_collapse() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1 = day(2024, 3, 31); + let q2 = day(2024, 6, 30); + let filings = vec![ + filing("ACME", "2024-05-02T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-08-02T16:30:00 EDT", "10-Q"), + ]; + + // Q1: two dated legacy observations disagree with no primary to arbitrate -> both dropped. + // Q2: two bit-identical dated legacy observations -> collapse to one filing-backed row. + let legacy = vec![ + obs("ACME", q1, FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 2)), fields_rev(100.0)), + obs("ACME", q1, FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 2)), fields_rev(101.0)), + obs("ACME", q2, FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 2)), fields_rev(130.0)), + obs("ACME", q2, FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 2)), fields_rev(130.0)), + ]; + + let built = build_fundamentals_rows_with_legacy(Vec::new(), legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 4); + assert_eq!(built.stats.duplicate_conflict_dropped, 2); + assert_eq!(built.stats.duplicate_collapsed, 1); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.rows[0].period_end, q2); + assert_eq!(built.rows[0].fields.revenue, Some(130.0)); + assert_eq!(built.rows[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(built.rows[0].known_at_utc_micros, utc_micros(2024, 8, 2, 20, 30, 0)); +} + +#[test] +fn legacy_merge_dated_legacy_withholds_undated_legacy_of_same_kind_but_not_other_fiscal_kind() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let fy_end = day(2023, 12, 31); + // Only a quarterly 10-Q for the Dec 31 period-end exists; no 10-K. + let filings = vec![filing("ACME", "2024-02-20T16:30:00 EST", "10-Q")]; + + let legacy = vec![ + // Dated Q4 anchors (ACME, 2023-12-31, Q). + obs("ACME", fy_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 20)), fields_rev(110.0)), + // Undated Q4 for the same kind must be withheld (unverified overlapping vintage). + obs("ACME", fy_end, FiscalPeriod::Quarterly, "USD", None, fields_rev(111.0)), + // Undated FY for the same period_end is a different fiscal kind and must survive at the + // US/TSX +90d statutory deadline (2024-03-30 16:05 EDT = 20:05 UTC). + obs("ACME", fy_end, FiscalPeriod::Annual, "USD", None, fields_rev(440.0)), + ]; + + let built = build_fundamentals_rows_with_legacy(Vec::new(), legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 3); + assert_eq!(built.stats.observations_dropped_unanchored_vintage, 1); + assert_eq!(built.stats.rows_out, 2); + assert_eq!(built.stats.rows_linked_to_filing, 1); + assert_eq!(built.stats.rows_statutory_lag_estimate, 1); + + let q_row = built + .rows + .iter() + .find(|r| r.fiscal_period == FiscalPeriod::Quarterly) + .expect("dated Q4 row"); + assert_eq!(q_row.fields.revenue, Some(110.0)); + assert_eq!(q_row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + + let fy_row = built + .rows + .iter() + .find(|r| r.fiscal_period == FiscalPeriod::Annual) + .expect("undated FY row"); + assert_eq!(fy_row.fields.revenue, Some(440.0)); + assert_eq!(fy_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(fy_row.known_at_utc_micros, utc_micros(2024, 3, 30, 20, 5, 0)); +} + +#[test] +fn legacy_merge_output_is_identical_under_seeded_permutations_of_primary_legacy_and_filings() { + let venues = venues_map(&[ + ("ACME", StatutoryLagVenue::UsTsx), + ("VENT", StatutoryLagVenue::TsxvCse), + ]); + let q3 = day(2023, 9, 30); + let q4 = day(2023, 12, 31); + let q1 = day(2024, 3, 31); + let q2 = day(2024, 6, 30); + + let filings = vec![ + filing("ACME", "2023-11-05T16:30:00 EST", "10-Q"), + filing("ACME", "2024-02-20T16:30:00 EST", "10-Q"), + filing("ACME", "2024-05-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-08-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-09-10T16:30:00 EDT", "10-Q/A"), + filing("VENT", "2024-05-25T16:30:00 EDT", "10-Q"), + filing("UNKNOWN", "2024-05-25T16:30:00 EDT", "10-Q"), + ]; + let primary = vec![ + obs("ACME", q2, FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 5)), fields_rev(130.0)), + obs("ACME", q1, FiscalPeriod::Quarterly, "USD", Some(day(2024, 9, 10)), fields_rev(125.0)), + // Collides with the legacy original Q1 at the same known_at: primary must win. + obs("ACME", q1, FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 5)), fields_rev(121.0)), + obs("UNKNOWN", q1, FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), + ]; + let legacy = vec![ + obs("ACME", q3, FiscalPeriod::Quarterly, "USD", Some(day(2023, 11, 5)), fields_rev(100.0)), + obs("ACME", q4, FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 20)), fields_rev(110.0)), + obs("ACME", q1, FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 5)), fields_rev(120.0)), + // Undated overlapping vintage: withheld. + obs("ACME", q1, FiscalPeriod::Quarterly, "USD", None, fields_rev(126.0)), + // Undated legacy-only TSXV quarter bounded by its May 25 filing. + obs("VENT", q1, FiscalPeriod::Quarterly, "CAD", None, fields_rev(7.0)), + obs("VENT", q1, FiscalPeriod::Quarterly, "CAD", None, fields_rev(7.0)), + ]; + + let reference = + build_fundamentals_rows_with_legacy(primary.clone(), legacy.clone(), filings.clone(), &venues); + assert_reconciliation(&reference); + assert_eq!(reference.stats.observations_in, 10); + assert_eq!(reference.stats.observations_dropped_unknown_key, 1); + assert_eq!(reference.stats.observations_dropped_unanchored_vintage, 1); + assert_eq!(reference.stats.duplicate_collapsed, 2); + assert_eq!(reference.stats.duplicate_conflict_dropped, 0); + assert_eq!(reference.stats.rows_out, 6); + let acme_q1_may = reference + .rows + .iter() + .find(|r| r.key == "ACME" && r.period_end == q1 && r.known_at_utc_micros == utc_micros(2024, 5, 5, 20, 30, 0)) + .expect("ACME original Q1 vintage"); + assert_eq!(acme_q1_may.fields.revenue, Some(121.0), "primary wins same-known_at collision"); + let vent = reference.rows.iter().find(|r| r.key == "VENT").expect("VENT row"); + assert_eq!(vent.known_at_utc_micros, utc_micros(2024, 5, 30, 20, 5, 0).max(utc_micros(2024, 5, 25, 20, 30, 0))); + assert_eq!(vent.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + + for seed in 1..=16u64 { + let mut p = primary.clone(); + let mut l = legacy.clone(); + let mut f = filings.clone(); + seeded_shuffle(&mut p, seed); + seeded_shuffle(&mut l, seed.wrapping_mul(31)); + seeded_shuffle(&mut f, seed.wrapping_mul(97)); + let built = build_fundamentals_rows_with_legacy(p, l, f, &venues); + assert_eq!(built, reference, "seed {seed} changed merged output"); + } + + // Empty legacy input must reproduce the primary-only builder exactly. + assert_eq!( + build_fundamentals_rows_with_legacy( + primary.clone(), + std::iter::empty::>(), + filings.clone(), + &venues, + ), + build_fundamentals_rows(primary, filings, &venues), + ); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a16d00be..20a6573e 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -3,6 +3,7 @@ pub mod adj; pub mod bars; pub mod bars_1m; +pub(crate) mod bars_1m_sort; pub mod bench; pub mod bson_ceo_posts; pub mod bson_ceo_shorts; @@ -137,11 +138,11 @@ pub use events::{ KNOWN_AT_SOURCE_STATUTORY_LAG, }; pub use fundamentals::{ - as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_snapshots, - FinancialObservation, FiscalPeriod, FundamentalsBuild, FundamentalsError, FundamentalsFields, - FundamentalsPeriodSlot, FundamentalsRow, FundamentalsSnapshot, FundamentalsStats, - FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, ANNUAL_FILING_LINK_WINDOW_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, + as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_rows_with_legacy, + build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, FundamentalsBuild, + FundamentalsError, FundamentalsFields, FundamentalsPeriodSlot, FundamentalsRow, + FundamentalsSnapshot, FundamentalsStats, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, + ANNUAL_FILING_LINK_WINDOW_DAYS, FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, QUARTERLY_FILING_LINK_WINDOW_DAYS, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, TTM_CONSECUTIVE_QUARTER_MAX_DAYS, @@ -272,9 +273,9 @@ pub use curate_posts::{ pub mod curate_fundamentals; pub use curate_fundamentals::{ - curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError, - CurateFundamentalsOutput, CurateFundamentalsStats, CurateFundamentalsWriteError, - CurateFundamentalsWriteReport, + curate_and_write_fundamentals, curate_and_write_fundamentals_with_legacy, curate_fundamentals, + curate_fundamentals_with_legacy, CurateFundamentalsError, CurateFundamentalsOutput, + CurateFundamentalsStats, CurateFundamentalsWriteError, CurateFundamentalsWriteReport, }; pub mod curate_macro; @@ -336,20 +337,21 @@ pub use run_curate_bars::{ pub mod run_curate_bars_1m; pub use run_curate_bars_1m::{ - format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_with_readers, - CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError, - DEFAULT_BARS_1M_MAPPING_SOURCE, + format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_from_readers_to_dir, + run_curate_bars_1m_with_readers, CurateBars1mArgs, CurateBars1mRunReport, + RunCurateBars1mError, DEFAULT_BARS_1M_MAPPING_SOURCE, }; pub mod run_curate_fx_1m; pub use run_curate_fx_1m::{ - format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs, - CurateFx1mRunReport, RunCurateFx1mError, + format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_from_reader_to_dir, + run_curate_fx_1m_with_readers, CurateFx1mArgs, CurateFx1mRunReport, RunCurateFx1mError, }; pub mod run_curate_qm_bars_1m; pub use run_curate_qm_bars_1m::{ - format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers, + format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, + run_curate_qm_bars_1m_from_reader_to_dir, run_curate_qm_bars_1m_with_readers, CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, }; @@ -384,15 +386,16 @@ pub use run_curate_posts::{ pub mod run_curate_fundamentals; pub use run_curate_fundamentals::{ format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, - run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, - CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, + run_curate_fundamentals_with_optional_old_readers, run_curate_fundamentals_with_readers, + CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, + RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, }; pub mod run_curate_macro; pub use run_curate_macro::{ format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro, - run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap, - RunCurateMacroError, MACRO_SERIES_MAP_HEADER, + run_curate_macro_from_reader, run_curate_macro_with_readers, CurateMacroArgs, + CurateMacroRunReport, MacroSeriesMap, RunCurateMacroError, MACRO_SERIES_MAP_HEADER, }; pub mod run_curate_shorts; @@ -409,10 +412,14 @@ pub use run_curate_events::{ pub mod run_mongo; pub use run_mongo::{ - run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, - run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo, - CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, - CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, + run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_bars_1m_mongo, + run_curate_corporate_actions_mongo, run_curate_events_mongo, run_curate_fundamentals_mongo, + run_curate_fx_1d_mongo, run_curate_fx_1m_mongo, run_curate_macro_mongo, run_curate_posts_mongo, + run_curate_qm_bars_1m_mongo, run_curate_shorts_mongo, CurateAdjFactorsMongoArgs, + CurateBars1dMongoArgs, CurateBars1mMongoArgs, CurateCorporateActionsMongoArgs, + CurateEventsMongoArgs, CurateFundamentalsMongoArgs, CurateFx1dMongoArgs, CurateFx1mMongoArgs, + CurateMacroMongoArgs, CuratePostsMongoArgs, CurateQmBars1mMongoArgs, CurateShortsMongoArgs, + RunMongoCurateError, }; #[cfg(test)] diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index e01d58a2..55fdab41 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -39,8 +39,10 @@ use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts} use curate_etl::run_curate_qm_bars_1m::{format_curate_qm_bars_1m_report, run_curate_qm_bars_1m}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; use curate_etl::run_mongo::{ - run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, - run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo, + run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_bars_1m_mongo, + run_curate_corporate_actions_mongo, run_curate_events_mongo, run_curate_fundamentals_mongo, + run_curate_fx_1d_mongo, run_curate_fx_1m_mongo, run_curate_macro_mongo, run_curate_posts_mongo, + run_curate_qm_bars_1m_mongo, run_curate_shorts_mongo, }; const NAME: &str = env!("CARGO_PKG_NAME"); @@ -216,6 +218,18 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateBars1mMongo(curate_args)) => { + match run_curate_bars_1m_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_bars_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CurateQmBars1m(curate_args)) => match run_curate_qm_bars_1m(&curate_args) { Ok(report) => { println!("{}", format_curate_qm_bars_1m_report(&report)); @@ -227,6 +241,19 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateQmBars1mMongo(curate_args)) => { + match run_curate_qm_bars_1m_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_qm_bars_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + let msg = err.to_string().replace('\r', "\\r").replace('\n', "\\n"); + eprintln!("error: {msg}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) { Ok(report) => { println!("{}", format_curate_fx_1m_report(&report)); @@ -237,6 +264,18 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateFx1mMongo(curate_args)) => { + match run_curate_fx_1m_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_fx_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { Ok(report) => { println!("{}", format_curate_posts_report(&report)); @@ -247,6 +286,18 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CuratePostsMongo(curate_args)) => { + match run_curate_posts_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_posts_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CurateFundamentals(curate_args)) => { match run_curate_fundamentals(&curate_args) { Ok(report) => { @@ -259,6 +310,18 @@ fn main() -> ExitCode { } } } + Ok(CliAction::CurateFundamentalsMongo(curate_args)) => { + match run_curate_fundamentals_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_fundamentals_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CurateMacro(curate_args)) => match run_curate_macro(&curate_args) { Ok(report) => { println!("{}", format_curate_macro_report(&report)); @@ -269,6 +332,18 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateMacroMongo(curate_args)) => { + match run_curate_macro_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_macro_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) { Ok(report) => { println!("{}", format_ilp_send_report(&report)); diff --git a/tools/curate-etl/src/mongo_stream.rs b/tools/curate-etl/src/mongo_stream.rs index 35564c58..fbfec4b5 100644 --- a/tools/curate-etl/src/mongo_stream.rs +++ b/tools/curate-etl/src/mongo_stream.rs @@ -9,7 +9,7 @@ //! backed by `mongodb::sync`. //! //! # Safety & Sealing Guarantees -//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in +//! - Closed [`SourceCollection`] allowlist matching all 14 M1+M2 collections in //! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API //! accepts a free-form collection name string. //! - Sealed read-only driver surface: [`ReadOnlyMongoClient`] requires a @@ -45,7 +45,7 @@ pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096; /// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`). pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000; -/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`. +/// Closed allowlist of the 14 M1+M2 MongoDB source collections consumed by `curate-etl`. /// /// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in /// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. @@ -59,11 +59,17 @@ pub enum SourceCollection { CeoShorts, QmFilings, QmEarnings, + QmFinancials, + QmFinancialsOld, + CeoPosts, + TeData, + EodIntraday1M, + QmIntraday, } impl SourceCollection { - /// All 8 allowlisted M1 source collections in canonical order. - pub const ALL: [SourceCollection; 8] = [ + /// All 14 allowlisted M1+M2 source collections in canonical order. + pub const ALL: [SourceCollection; 14] = [ Self::EodPrices, Self::QmSplits, Self::QmDividends, @@ -72,6 +78,12 @@ impl SourceCollection { Self::CeoShorts, Self::QmFilings, Self::QmEarnings, + Self::QmFinancials, + Self::QmFinancialsOld, + Self::CeoPosts, + Self::TeData, + Self::EodIntraday1M, + Self::QmIntraday, ]; /// Exact MongoDB collection name. @@ -85,6 +97,12 @@ impl SourceCollection { Self::CeoShorts => "ceoShorts", Self::QmFilings => "qmFilings", Self::QmEarnings => "qmEarnings", + Self::QmFinancials => "qmFinancials", + Self::QmFinancialsOld => "qmFinancials-old", + Self::CeoPosts => "ceoPosts", + Self::TeData => "teData", + Self::EodIntraday1M => "eodIntraday1M", + Self::QmIntraday => "qmIntraday", } } @@ -99,11 +117,18 @@ impl SourceCollection { Self::CeoShorts => "symbol", Self::QmFilings => "symbol", Self::QmEarnings => "qmSearchCode", + Self::QmFinancials => "qmSearchCode", + Self::QmFinancialsOld => "qmSearchCode", + Self::CeoPosts => "ceoId", + Self::TeData => "teSymbol", + Self::EodIntraday1M => "eodSearchCode", + Self::QmIntraday => "qmSearchCode", } } /// Date/timestamp field used for range filters (`date_range`), or `None` - /// for document-per-symbol collections (`teMarketData`). + /// for document-per-symbol / non-range-filtered collections (`teMarketData`, + /// `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`). pub const fn date_field(self) -> Option<&'static str> { match self { Self::EodPrices => Some("date"), @@ -114,18 +139,31 @@ impl SourceCollection { Self::CeoShorts => Some("timestamp"), Self::QmFilings => Some("timefiled"), Self::QmEarnings => Some("reportDate"), + Self::QmFinancials => None, + Self::QmFinancialsOld => None, + Self::CeoPosts => None, + Self::TeData => None, + Self::EodIntraday1M => Some("timestamp"), + Self::QmIntraday => Some("timestamp"), } } /// Returns `true` when the collection's [`Self::date_field`] is stored as a - /// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string. + /// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string or epoch seconds. /// - /// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md`): - /// `qmEarnings.reportDate` (100% BSON `DateTime`) and `ceoShorts.timestamp` - /// (BSON `DateTime`), while `eodPrices.date`, `qmPrices.date`, `qmSplits.date`, + /// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md` / + /// `design/DATA-CONTRACTS.md` §1): `qmEarnings.reportDate`, `ceoShorts.timestamp`, + /// and `qmIntraday.timestamp` are BSON `DateTime`s, while `eodIntraday1M.timestamp` + /// is UTC epoch seconds and `eodPrices.date`, `qmPrices.date`, `qmSplits.date`, /// `qmDividends.date`, and `qmFilings.timefiled` are UTF-8 strings. pub const fn date_field_is_bson_datetime(self) -> bool { - matches!(self, Self::QmEarnings | Self::CeoShorts) + matches!(self, Self::QmEarnings | Self::CeoShorts | Self::QmIntraday) + } + + /// Returns `true` when the collection's [`Self::date_field`] is stored as + /// UTC Unix epoch seconds (`Int32`/`Int64`), as in `eodIntraday1M.timestamp`. + pub const fn date_field_is_epoch_seconds(self) -> bool { + matches!(self, Self::EodIntraday1M) } } @@ -142,6 +180,8 @@ pub enum FilterDateValue { IsoString(String), /// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch. BsonDateTimeMillis(i64), + /// UTC Unix timestamp expressed as integer seconds (`Bson::Int64`), used by `eodIntraday1M`. + EpochSeconds(i64), } impl FilterDateValue { @@ -149,6 +189,7 @@ impl FilterDateValue { match self { Self::IsoString(s) => Bson::String(s.clone()), Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)), + Self::EpochSeconds(secs) => Bson::Int64(*secs), } } } @@ -259,20 +300,49 @@ impl MongoReadSpec { } Ok(()) } - Some(FilterDateValue::BsonDateTimeMillis(_)) => { - Err(MongoStreamError::InvalidDateRange { - collection, - detail: "qmFilings.timefiled is stored as an Eastern Time string; \ - only Eastern calendar-day boundaries (YYYY-MM-DD) are \ - supported for server-side ranges" - .to_owned(), - }) - } + Some( + FilterDateValue::BsonDateTimeMillis(_) + | FilterDateValue::EpochSeconds(_), + ) => Err(MongoStreamError::InvalidDateRange { + collection, + detail: "qmFilings.timefiled is stored as an Eastern Time string; \ + only Eastern calendar-day boundaries (YYYY-MM-DD) are \ + supported for server-side ranges" + .to_owned(), + }), None => Ok(()), }; validate_et_calendar_day(range.gte.as_ref(), "gte")?; validate_et_calendar_day(range.lt.as_ref(), "lt")?; } + if collection.date_field_is_epoch_seconds() { + for (label, bound) in [("gte", &range.gte), ("lt", &range.lt)] { + if let Some(val) = bound { + if !matches!(val, FilterDateValue::EpochSeconds(_)) { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!( + "{collection}.timestamp {label} must use EpochSeconds (UTC Unix seconds)" + ), + }); + } + } + } + } + if collection == SourceCollection::QmIntraday { + for (label, bound) in [("gte", &range.gte), ("lt", &range.lt)] { + if let Some(val) = bound { + if !matches!(val, FilterDateValue::BsonDateTimeMillis(_)) { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!( + "{collection}.timestamp {label} must use BsonDateTimeMillis (BSON DateTime)" + ), + }); + } + } + } + } if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) { match (gte, lt) { (FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => { @@ -294,6 +364,14 @@ impl MongoReadSpec { }); } } + (FilterDateValue::EpochSeconds(a), FilterDateValue::EpochSeconds(b)) => { + if a >= b { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!("gte ({a}) must be strictly less than lt ({b})"), + }); + } + } _ => { return Err(MongoStreamError::InvalidDateRange { collection, @@ -749,7 +827,7 @@ fn find_next_mongo_scheme(lower_slice: &str) -> Option<(usize, usize)> { } } -fn redact_embedded_mongo_uris(text: &str) -> String { +pub(crate) fn redact_embedded_mongo_uris(text: &str) -> String { let mut result = String::with_capacity(text.len()); let mut cursor = 0usize; let lower = text.to_ascii_lowercase(); @@ -1198,8 +1276,9 @@ impl MongoCliOptions { } /// Builds a [`MongoReadSpec`] using the collection's native BSON date representation: - /// `BsonDateTimeMillis` (UTC midnight) for BSON `DateTime` collections (`qmEarnings`, - /// `ceoShorts`) and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`, + /// `EpochSeconds` (UTC midnight seconds) for `eodIntraday1M`, `BsonDateTimeMillis` + /// (UTC midnight millis) for BSON `DateTime` collections (`qmEarnings`, `ceoShorts`, + /// `qmIntraday`), and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`, /// `qmSplits`, `qmDividends`, `qmFilings`). pub fn to_read_spec_for_collection( &self, @@ -1210,25 +1289,45 @@ impl MongoCliOptions { if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) { return self.to_read_spec(key_eq, false); } - if !collection.date_field_is_bson_datetime() { - return self.to_read_spec(key_eq, true); + if collection.date_field_is_epoch_seconds() { + let to_secs = |raw: &String| -> FilterDateValue { + match parse_ymd_strict_days(raw) { + Some(days) => FilterDateValue::EpochSeconds(i64::from(days) * 86_400), + None => FilterDateValue::IsoString(raw.clone()), + } + }; + return MongoReadSpec { + key_eq, + date_range: Some(MongoDateRange { + gte: self.date_gte.as_ref().map(to_secs), + lt: self.date_lt.as_ref().map(to_secs), + }), + batch_size: self.batch_size, + limit: self.limit, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; } - let to_dt = |raw: &String| -> FilterDateValue { - match parse_ymd_strict_days(raw) { - Some(days) => FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY), - None => FilterDateValue::IsoString(raw.clone()), - } - }; - MongoReadSpec { - key_eq, - date_range: Some(MongoDateRange { - gte: self.date_gte.as_ref().map(to_dt), - lt: self.date_lt.as_ref().map(to_dt), - }), - batch_size: self.batch_size, - limit: self.limit, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + if collection.date_field_is_bson_datetime() { + let to_dt = |raw: &String| -> FilterDateValue { + match parse_ymd_strict_days(raw) { + Some(days) => { + FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY) + } + None => FilterDateValue::IsoString(raw.clone()), + } + }; + return MongoReadSpec { + key_eq, + date_range: Some(MongoDateRange { + gte: self.date_gte.as_ref().map(to_dt), + lt: self.date_lt.as_ref().map(to_dt), + }), + batch_size: self.batch_size, + limit: self.limit, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; } + self.to_read_spec(key_eq, true) } } diff --git a/tools/curate-etl/src/mongo_stream_tests.rs b/tools/curate-etl/src/mongo_stream_tests.rs index 41fa6da4..ed4d8423 100644 --- a/tools/curate-etl/src/mongo_stream_tests.rs +++ b/tools/curate-etl/src/mongo_stream_tests.rs @@ -5,11 +5,16 @@ use std::path::PathBuf; use bson::raw::{cstr, RawDocumentBuf}; use bson::{Bson, DateTime}; +use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit}; use crate::bson_qm_events::QmFilingsFieldNames; +use crate::bson_qm_financials::{QmFinancialsFieldNames, QmFinancialsFiscalPeriod}; use crate::bson_stream::{ - decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream, - decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES, + decode_ceo_posts_stream, decode_eod_intraday_stream, decode_eod_price_stream, + decode_qm_dividend_stream, decode_qm_filings_stream, decode_qm_financials_stream, + decode_qm_intraday_stream, decode_qm_split_stream, decode_te_data_stream, BsonStreamError, + BsonStreamOptions, MIN_BSON_DOC_BYTES, }; +use crate::fundamentals::FiscalPeriod; use crate::mongo_safety::{ assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri, }; @@ -213,7 +218,8 @@ fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { .collect(); let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).collect(); - let expected = vec![ + let ts_name_refs: Vec<&str> = ts_names.iter().map(String::as_str).collect(); + let expected_ts = vec![ "eodPrices", "qmSplits", "qmDividends", @@ -222,18 +228,23 @@ fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { "ceoShorts", "qmFilings", "qmEarnings", + "qmFinancials", + "qmFinancials-old", + "ceoPosts", + "teData", + "eodIntraday1M", + "qmIntraday", ]; - assert_eq!(rust_names, expected); assert_eq!( - ts_names, - rust_names - .iter() - .map(|s| (*s).to_owned()) - .collect::>(), + ts_name_refs, expected_ts, + "RAW_BSON_EXPORT_COLLECTIONS must match the 14 M1+M2 collections in exact names and order" + ); + assert_eq!( + rust_names, ts_name_refs, "SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order" ); - assert_eq!(SourceCollection::ALL.len(), 8); + assert_eq!(SourceCollection::ALL.len(), 14); } // --------------------------------------------------------------------------- @@ -1774,66 +1785,134 @@ fn qm_filings_rejects_invalid_eastern_calendar_day_bounds() { #[test] fn source_collection_exhaustive_key_date_and_display_mappings() { - let expected: [(SourceCollection, &str, &str, Option<&str>); 8] = [ + let expected: [(SourceCollection, &str, &str, Option<&str>, bool, bool); 14] = [ ( SourceCollection::EodPrices, "eodPrices", "eodSearchCode", Some("date"), + false, + false, ), ( SourceCollection::QmSplits, "qmSplits", "qmSearchCode", Some("date"), + false, + false, ), ( SourceCollection::QmDividends, "qmDividends", "qmSearchCode", Some("date"), + false, + false, ), ( SourceCollection::QmPrices, "qmPrices", "qmSearchCode", Some("date"), + false, + false, ), ( SourceCollection::TeMarketData, "teMarketData", "teSymbol", None, + false, + false, ), ( SourceCollection::CeoShorts, "ceoShorts", "symbol", Some("timestamp"), + true, + false, ), ( SourceCollection::QmFilings, "qmFilings", "symbol", Some("timefiled"), + false, + false, ), ( SourceCollection::QmEarnings, "qmEarnings", "qmSearchCode", Some("reportDate"), + true, + false, + ), + ( + SourceCollection::QmFinancials, + "qmFinancials", + "qmSearchCode", + None, + false, + false, + ), + ( + SourceCollection::QmFinancialsOld, + "qmFinancials-old", + "qmSearchCode", + None, + false, + false, + ), + ( + SourceCollection::CeoPosts, + "ceoPosts", + "ceoId", + None, + false, + false, + ), + ( + SourceCollection::TeData, + "teData", + "teSymbol", + None, + false, + false, + ), + ( + SourceCollection::EodIntraday1M, + "eodIntraday1M", + "eodSearchCode", + Some("timestamp"), + false, + true, + ), + ( + SourceCollection::QmIntraday, + "qmIntraday", + "qmSearchCode", + Some("timestamp"), + true, + false, ), ]; assert_eq!(SourceCollection::ALL.len(), expected.len()); - for (actual, (exp_variant, exp_name, exp_key, exp_date)) in - SourceCollection::ALL.into_iter().zip(expected) + for ( + actual, + (exp_variant, exp_name, exp_key, exp_date, exp_is_dt, exp_is_secs), + ) in SourceCollection::ALL.into_iter().zip(expected) { assert_eq!(actual, exp_variant); assert_eq!(actual.as_str(), exp_name); assert_eq!(format!("{actual}"), exp_name); assert_eq!(actual.key_field(), exp_key); assert_eq!(actual.date_field(), exp_date); + assert_eq!(actual.date_field_is_bson_datetime(), exp_is_dt); + assert_eq!(actual.date_field_is_epoch_seconds(), exp_is_secs); } } @@ -1939,3 +2018,397 @@ fn cli_to_read_spec_for_collection_uses_bson_datetime_for_qm_earnings_and_iso_st Some(&Bson::DateTime(DateTime::from_millis(1_739_404_800_000))) ); } + +#[test] +fn m2_collections_date_range_typing_and_validation() { + let opts = super::MongoCliOptions { + date_gte: Some("2024-01-01".to_owned()), + date_lt: Some("2024-01-02".to_owned()), + ..super::MongoCliOptions::default() + }; + + // eodIntraday1M -> Bson::Int64 UTC epoch seconds + let eod_spec = opts.to_read_spec_for_collection( + SourceCollection::EodIntraday1M, + Some("CAD.FOREX".to_owned()), + true, + ); + let eod_doc = build_filter_document(SourceCollection::EodIntraday1M, &eod_spec) + .expect("eodIntraday1M EpochSeconds filter must succeed"); + assert_eq!( + eod_doc.get("eodSearchCode"), + Some(&Bson::String("CAD.FOREX".to_owned())) + ); + let eod_ts = eod_doc + .get_document("timestamp") + .expect("timestamp subdocument"); + assert_eq!(eod_ts.get("$gte"), Some(&Bson::Int64(1_704_067_200))); + assert_eq!(eod_ts.get("$lt"), Some(&Bson::Int64(1_704_153_600))); + + // qmIntraday -> Bson::DateTime UTC epoch millis + let qm_spec = opts.to_read_spec_for_collection(SourceCollection::QmIntraday, None, true); + let qm_doc = build_filter_document(SourceCollection::QmIntraday, &qm_spec) + .expect("qmIntraday BsonDateTimeMillis filter must succeed"); + let qm_ts = qm_doc + .get_document("timestamp") + .expect("timestamp subdocument"); + assert_eq!( + qm_ts.get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + assert_eq!( + qm_ts.get("$lt"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_153_600_000))) + ); + + // Collections without date_field reject date_range with DateRangeNotSupported. + for coll in [ + SourceCollection::QmFinancials, + SourceCollection::QmFinancialsOld, + SourceCollection::CeoPosts, + SourceCollection::TeData, + ] { + let spec = opts.to_read_spec_for_collection(coll, None, true); + assert!( + matches!( + build_filter_document(coll, &spec), + Err(MongoStreamError::DateRangeNotSupported { collection }) if collection == coll + ), + "expected DateRangeNotSupported for {coll}" + ); + } + + // Wrong FilterDateValue variants are rejected for EodIntraday1M and QmIntraday. + for bad_val in [ + FilterDateValue::IsoString("2024-01-01".to_owned()), + FilterDateValue::BsonDateTimeMillis(1_704_067_200_000), + ] { + assert!(matches!( + build_filter_document( + SourceCollection::EodIntraday1M, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(bad_val), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodIntraday1M, + .. + }) + )); + } + for bad_val in [ + FilterDateValue::IsoString("2024-01-01".to_owned()), + FilterDateValue::EpochSeconds(1_704_067_200), + ] { + assert!(matches!( + build_filter_document( + SourceCollection::QmIntraday, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(bad_val), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmIntraday, + .. + }) + )); + } + // Unparsable date strings in MongoCliOptions stay IsoString and fail validation. + let bad_opts = super::MongoCliOptions { + date_gte: Some("not-a-date".to_owned()), + ..super::MongoCliOptions::default() + }; + assert!(matches!( + bad_opts + .to_read_spec_for_collection(SourceCollection::EodIntraday1M, None, true) + .validate(SourceCollection::EodIntraday1M), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodIntraday1M, + .. + }) + )); + assert!(matches!( + bad_opts + .to_read_spec_for_collection(SourceCollection::QmIntraday, None, true) + .validate(SourceCollection::QmIntraday), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmIntraday, + .. + }) + )); + // EpochSeconds gte >= lt fails validation. + assert!(matches!( + build_filter_document( + SourceCollection::EodIntraday1M, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::EpochSeconds(1_704_067_200)), + lt: Some(FilterDateValue::EpochSeconds(1_704_067_200)), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodIntraday1M, + .. + }) + )); +} + +#[test] +fn parity_m2_decoders_across_default_and_odd_buffers() { + // 1. qmFinancials + let fin_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("qmSearchCode"), "AAPL:US"); + d1.append(cstr!("periodEndDate"), "2024-03-31"); + d1.append(cstr!("reportDate"), "2024-05-02"); + d1.append(cstr!("reportPeriod"), "Q1"); + d1.append(cstr!("currency"), "USD"); + d1.append(cstr!("revenue"), 90_000.0); + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("qmSearchCode"), "BAD:US"); + d2.append(cstr!("periodEndDate"), "bad-date"); + d2.append(cstr!("reportPeriod"), "Q1"); + d2.append(cstr!("currency"), "USD"); + vec![d1.into_bytes(), d2.into_bytes()] + }; + let fin_concat = concat_docs(&fin_docs); + let fin_fields = QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("revenue"), + None, + None, + None, + None, + None, + ); + let fin_fp = QmFinancialsFiscalPeriod::Fixed(FiscalPeriod::Quarterly); + let mut exp_fin = Vec::new(); + let exp_fin_stats = decode_qm_financials_stream( + Cursor::new(&fin_concat), + BsonStreamOptions::default(), + &fin_fields, + fin_fp, + |o| exp_fin.push((o.key.to_owned(), o.period_end, o.fields.revenue.map(f64::to_bits))), + ) + .expect("baseline qmFinancials decode"); + assert_eq!(exp_fin.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let slices: Vec<&[u8]> = fin_docs.iter().map(Vec::as_slice).collect(); + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&slices)); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_financials_stream(&mut reader, BsonStreamOptions::default(), &fin_fields, fin_fp, |o| { + got.push((o.key.to_owned(), o.period_end, o.fields.revenue.map(f64::to_bits))); + }) + .expect("qmFinancials stream decode") + } else { + decode_qm_financials_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + &fin_fields, + fin_fp, + |o| got.push((o.key.to_owned(), o.period_end, o.fields.revenue.map(f64::to_bits))), + ) + .expect("qmFinancials capped decode") + }; + assert_eq!(stats, exp_fin_stats); + assert_eq!(got, exp_fin); + } + + // 2. ceoPosts + let post_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "5001"); + d1.append(cstr!("spielId"), "sp-1"); + d1.append(cstr!("timestamp"), 1_710_000_000_i64); + d1.append(cstr!("edited"), false); + d1.append(cstr!("bot"), "0"); + d1.append(cstr!("userId"), "u1"); + d1.append(cstr!("spiel"), "hello world"); + vec![d1.into_bytes()] + }; + let post_concat = concat_docs(&post_docs); + let post_fields = CeoPostsFieldNames::default(); + let mut exp_posts = Vec::new(); + let exp_post_stats = decode_ceo_posts_stream( + Cursor::new(&post_concat), + BsonStreamOptions::default(), + &post_fields, + CeoPostsTimestampUnit::Seconds, + |p| exp_posts.push((p.key.to_owned(), p.spiel_id, p.timestamp_ms, p.text)), + ) + .expect("baseline ceoPosts decode"); + assert_eq!(exp_posts.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(post_docs.clone())); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_ceo_posts_stream(&mut reader, BsonStreamOptions::default(), &post_fields, CeoPostsTimestampUnit::Seconds, |p| { + got.push((p.key.to_owned(), p.spiel_id, p.timestamp_ms, p.text)); + }) + .expect("ceoPosts stream decode") + } else { + decode_ceo_posts_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + &post_fields, + CeoPostsTimestampUnit::Seconds, + |p| got.push((p.key.to_owned(), p.spiel_id, p.timestamp_ms, p.text)), + ) + .expect("ceoPosts capped decode") + }; + assert_eq!(stats, exp_post_stats); + assert_eq!(got, exp_posts); + } + + // 3. teData + let te_docs = { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-01-31"); + pt.append(cstr!("v"), 3.1_f64); + let mut arr = bson::raw::RawArrayBuf::new(); + arr.push(pt); + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("teSymbol"), "US_CPI"); + d1.append(cstr!("country"), "United States"); + d1.append(cstr!("category"), "Inflation Rate"); + d1.append(cstr!("data"), arr); + vec![d1.into_bytes()] + }; + let te_concat = concat_docs(&te_docs); + let mut exp_te = Vec::new(); + let exp_te_stats = decode_te_data_stream( + Cursor::new(&te_concat), + BsonStreamOptions::default(), + |pt| exp_te.push((pt.te_symbol.to_owned(), pt.period_date, pt.value.to_bits())), + |_off, _err| {}, + ) + .expect("baseline teData decode"); + assert_eq!(exp_te.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(te_docs.clone())); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_te_data_stream( + &mut reader, + BsonStreamOptions::default(), + |pt| got.push((pt.te_symbol.to_owned(), pt.period_date, pt.value.to_bits())), + |_off, _err| {}, + ) + .expect("teData stream decode") + } else { + decode_te_data_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + |pt| got.push((pt.te_symbol.to_owned(), pt.period_date, pt.value.to_bits())), + |_off, _err| {}, + ) + .expect("teData capped decode") + }; + assert_eq!(stats, exp_te_stats); + assert_eq!(got, exp_te); + } + + // 4. eodIntraday1M + let eod_1m_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("eodSearchCode"), "NVDA.US"); + d1.append(cstr!("timestamp"), 1_718_026_200_i64); + d1.append(cstr!("open"), 120.0_f64); + d1.append(cstr!("high"), 121.0_f64); + d1.append(cstr!("low"), 119.5_f64); + d1.append(cstr!("close"), 120.5_f64); + d1.append(cstr!("volume"), 5000.0_f64); + vec![d1.into_bytes()] + }; + let eod_1m_concat = concat_docs(&eod_1m_docs); + let mut exp_eod_1m = Vec::new(); + let exp_eod_1m_stats = decode_eod_intraday_stream( + Cursor::new(&eod_1m_concat), + BsonStreamOptions::default(), + |b| exp_eod_1m.push((b.eod_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("baseline eodIntraday1M decode"); + assert_eq!(exp_eod_1m.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs.clone())); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_eod_intraday_stream( + &mut reader, + BsonStreamOptions::default(), + |b| got.push((b.eod_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("eodIntraday1M stream decode") + } else { + decode_eod_intraday_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + |b| got.push((b.eod_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("eodIntraday1M capped decode") + }; + assert_eq!(stats, exp_eod_1m_stats); + assert_eq!(got, exp_eod_1m); + } + + // 5. qmIntraday + let qm_1m_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("qmSearchCode"), "NVDA:US"); + d1.append(cstr!("timestamp"), DateTime::from_millis(1_718_026_200_000)); + d1.append(cstr!("open"), 120.0_f64); + d1.append(cstr!("high"), 121.0_f64); + d1.append(cstr!("low"), 119.5_f64); + d1.append(cstr!("close"), 120.5_f64); + d1.append(cstr!("sharevolume"), 5000.0_f64); + vec![d1.into_bytes()] + }; + let qm_1m_concat = concat_docs(&qm_1m_docs); + let mut exp_qm_1m = Vec::new(); + let exp_qm_1m_stats = decode_qm_intraday_stream( + Cursor::new(&qm_1m_concat), + BsonStreamOptions::default(), + |b| exp_qm_1m.push((b.qm_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("baseline qmIntraday decode"); + assert_eq!(exp_qm_1m.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let slices: Vec<&[u8]> = qm_1m_docs.iter().map(Vec::as_slice).collect(); + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&slices)); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_intraday_stream( + &mut reader, + BsonStreamOptions::default(), + |b| got.push((b.qm_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("qmIntraday stream decode") + } else { + decode_qm_intraday_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + |b| got.push((b.qm_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("qmIntraday capped decode") + }; + assert_eq!(stats, exp_qm_1m_stats); + assert_eq!(got, exp_qm_1m); + } +} diff --git a/tools/curate-etl/src/parquet_events.rs b/tools/curate-etl/src/parquet_events.rs index 64c07c5c..203e23e8 100644 --- a/tools/curate-etl/src/parquet_events.rs +++ b/tools/curate-etl/src/parquet_events.rs @@ -1,6 +1,8 @@ //! Streaming, atomic, year-partitioned Zstd Parquet writer for `events`. //! -//! Writes `/events/year=YYYY/part.parquet` files matching the 7-column contract schema in +//! Writes `/events/year=YYYY/part.parquet` (filings & earnings via +//! [`write_events_dataset`]) or `/events/year=YYYY/part-posts.parquet` +//! (`ceoPosts` via [`write_posts_events_dataset`]) matching the 7-column contract schema in //! `design/DATA-CONTRACTS.md` (§3A): //! //! 1. `listing_id` (`INT32`, `REQUIRED`) @@ -41,6 +43,12 @@ use crate::parquet_publish::{ }; pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; +/// Target Parquet file name under `/events/year=YYYY/` for filings & earnings. +pub const EVENTS_PART_FILE_NAME: &str = "part.parquet"; + +/// Target Parquet file name under `/events/year=YYYY/` for curated `ceoPosts` events. +pub const POSTS_PART_FILE_NAME: &str = "part-posts.parquet"; + /// Single `events` row matching the `design/DATA-CONTRACTS.md` Parquet schema. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EventsParquetRow { @@ -494,6 +502,7 @@ impl YearWriter { fn open( events_dir: &Path, year: i32, + part_file_name: &str, run_id: &str, schema: &TypePtr, props: &WriterPropertiesPtr, @@ -507,7 +516,7 @@ impl YearWriter { let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); - let final_path = year_dir.join("part.parquet"); + let final_path = year_dir.join(part_file_name); let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( @@ -690,6 +699,35 @@ where ) } +/// Streams strictly ascending `ceoPosts` event rows into year-partitioned Zstd Parquet files at +/// `/events/year=YYYY/part-posts.parquet`. +/// +/// Shares `/events` locking (`dataset_mutex` + `.write.lock`), validation, `.tmp` +/// staging, `sync_all`, live-preserving `.bak` backup, atomic `rename`, and per-run rollback with +/// [`write_events_dataset`], while scoping publication and rollback strictly to +/// [`POSTS_PART_FILE_NAME`] so `part.parquet` (filings/earnings) and `part-posts.parquet` +/// (`ceoPosts`) coexist and remain independently re-runnable without clobbering each other. +pub fn write_posts_events_dataset( + out_dir: P, + rows: I, + options: EventsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_events_dataset_with_lock_and_backup_hooks( + out_dir, + POSTS_PART_FILE_NAME, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + || {}, + |_, _, _| {}, + ) +} + fn write_events_dataset_with_hooks( out_dir: P, rows: I, @@ -705,6 +743,7 @@ where { write_events_dataset_with_lock_and_backup_hooks( out_dir, + EVENTS_PART_FILE_NAME, rows, options, lock_timeout, @@ -715,6 +754,7 @@ where fn write_events_dataset_with_lock_and_backup_hooks( out_dir: P, + part_file_name: &str, rows: I, options: EventsWriteOptions, lock_timeout: Duration, @@ -812,6 +852,7 @@ where let opened = YearWriter::open( &events_dir, year, + part_file_name, &run_id, &schema, &props, diff --git a/tools/curate-etl/src/parquet_events_tests.rs b/tools/curate-etl/src/parquet_events_tests.rs index bd12232f..5531f431 100644 --- a/tools/curate-etl/src/parquet_events_tests.rs +++ b/tools/curate-etl/src/parquet_events_tests.rs @@ -16,8 +16,9 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use super::tests::{assert_no_transient_files, make_event_row, read_parquet_rows, utc_micros, TempDirGuard}; use super::{ write_events_dataset, write_events_dataset_with_hooks, - write_events_dataset_with_lock_and_backup_hooks, EventsParquetRow, EventsWriteOptions, - EventsWriteStats, ParquetEventsError, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + write_events_dataset_with_lock_and_backup_hooks, write_posts_events_dataset, EventsParquetRow, + EventsWriteOptions, EventsWriteStats, ParquetEventsError, DEFAULT_ZSTD_LEVEL, + EVENTS_PART_FILE_NAME, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, POSTS_PART_FILE_NAME, }; use crate::events::{ build_events, partition_year_utc, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, @@ -774,6 +775,7 @@ fn concurrent_writers_serialize_without_mixed_generations() { }; write_events_dataset_with_lock_and_backup_hooks( &out_2, + EVENTS_PART_FILE_NAME, iter, EventsWriteOptions::default(), DEFAULT_LOCK_TIMEOUT, @@ -1213,3 +1215,160 @@ fn large_build_events_round_trip_preserves_order_and_fields_across_years() { assert_eq!(total_read, rows.len()); assert_no_transient_files(&tmp.path().join("events")); } + +#[test] +fn write_posts_events_dataset_copublishes_with_part_parquet_and_preserves_siblings() { + let tmp = TempDirGuard::new("copublish-posts"); + + let events_v1 = vec![ + base_row(1, 2023, 3, 15), + base_row(1, 2024, 6, 10), + ]; + let posts_v1 = vec![ + make_event_row( + 1, + utc_micros(2023, 4, 1, 14, 0, 0, 0), + utc_micros(2023, 4, 1, 14, 0, 0, 0), + "post_timestamp", + "ceo_post", + "retail", + r#"{"spiel_id":"p23-1","user_id":"u1","is_edited":false,"source":"ceo_posts","text":"v1"}"#, + ), + make_event_row( + 1, + utc_micros(2024, 6, 10, 15, 0, 0, 0), + utc_micros(2024, 6, 10, 21, 0, 0, 0), + "post_edited", + "ceo_post", + "retail", + r#"{"spiel_id":"p24-1","user_id":"u1","is_edited":true,"source":"ceo_posts","text":"v1 edited"}"#, + ), + ]; + + write_events_dataset(tmp.path(), &events_v1, EventsWriteOptions::default()).unwrap(); + let events_2023_path = tmp.path().join("events/year=2023").join(EVENTS_PART_FILE_NAME); + let events_2024_path = tmp.path().join("events/year=2024").join(EVENTS_PART_FILE_NAME); + let events_2023_bytes_v1 = fs::read(&events_2023_path).unwrap(); + let events_2024_bytes_v1 = fs::read(&events_2024_path).unwrap(); + + let posts_stats = write_posts_events_dataset( + tmp.path(), + &posts_v1, + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(posts_stats.rows_written, 2); + assert_eq!(posts_stats.files_written, 2); + + let posts_2023_path = tmp.path().join("events/year=2023").join(POSTS_PART_FILE_NAME); + let posts_2024_path = tmp.path().join("events/year=2024").join(POSTS_PART_FILE_NAME); + assert_eq!(read_parquet_rows(&posts_2023_path), vec![posts_v1[0].clone()]); + assert_eq!(read_parquet_rows(&posts_2024_path), vec![posts_v1[1].clone()]); + assert_eq!(fs::read(&events_2023_path).unwrap(), events_2023_bytes_v1); + assert_eq!(fs::read(&events_2024_path).unwrap(), events_2024_bytes_v1); + + // Re-running write_posts_events_dataset replaces only part-posts.parquet; part.parquet stays byte-identical. + let posts_v2 = vec![ + make_event_row( + 1, + utc_micros(2024, 6, 10, 15, 0, 0, 0), + utc_micros(2024, 6, 10, 22, 0, 0, 0), + "post_edited", + "ceo_post", + "newswire", + r#"{"spiel_id":"p24-2","user_id":null,"is_edited":true,"source":"ceo_posts","text":"v2"}"#, + ), + ]; + write_posts_events_dataset(tmp.path(), &posts_v2, EventsWriteOptions::default()).unwrap(); + let posts_2024_bytes_v2 = fs::read(&posts_2024_path).unwrap(); + assert_eq!(read_parquet_rows(&posts_2024_path), posts_v2); + assert_eq!(fs::read(&events_2023_path).unwrap(), events_2023_bytes_v1); + assert_eq!(fs::read(&events_2024_path).unwrap(), events_2024_bytes_v1); + + // Re-running write_events_dataset replaces only part.parquet; part-posts.parquet stays byte-identical. + let events_v2 = vec![base_row(2, 2024, 7, 1)]; + write_events_dataset(tmp.path(), &events_v2, EventsWriteOptions::default()).unwrap(); + assert_eq!(read_parquet_rows(&events_2024_path), events_v2); + assert_eq!(fs::read(&posts_2024_path).unwrap(), posts_2024_bytes_v2); + assert_no_transient_files(&tmp.path().join("events")); +} + +#[test] +fn write_posts_events_dataset_rollback_leaves_sibling_part_parquet_byte_identical() { + let tmp = TempDirGuard::new("copublish-rollback"); + + let events_seed = vec![base_row(1, 2023, 5, 10), base_row(1, 2024, 5, 10)]; + write_events_dataset(tmp.path(), &events_seed, EventsWriteOptions::default()).unwrap(); + let events_2023 = tmp.path().join("events/year=2023").join(EVENTS_PART_FILE_NAME); + let events_2024 = tmp.path().join("events/year=2024").join(EVENTS_PART_FILE_NAME); + let events_2023_bytes = fs::read(&events_2023).unwrap(); + let events_2024_bytes = fs::read(&events_2024).unwrap(); + + let posts_2023_seed = vec![make_event_row( + 1, + utc_micros(2023, 5, 10, 14, 0, 0, 0), + utc_micros(2023, 5, 10, 14, 0, 0, 0), + "post_timestamp", + "ceo_post", + "retail", + r#"{"spiel_id":"seed-23","user_id":"u1","is_edited":false,"source":"ceo_posts","text":"seed"}"#, + )]; + write_posts_events_dataset(tmp.path(), &posts_2023_seed, EventsWriteOptions::default()).unwrap(); + let posts_2023 = tmp.path().join("events/year=2023").join(POSTS_PART_FILE_NAME); + let posts_2023_bytes = fs::read(&posts_2023).unwrap(); + + // Place a blocker directory at year=2024/part-posts.parquet so multi-year publish fails on 2024. + let blocker_2024 = tmp.path().join("events/year=2024").join(POSTS_PART_FILE_NAME); + fs::create_dir_all(&blocker_2024).unwrap(); + + let failing_posts = vec![ + make_event_row( + 1, + utc_micros(2022, 6, 1, 14, 0, 0, 0), + utc_micros(2022, 6, 1, 14, 0, 0, 0), + "post_timestamp", + "ceo_post", + "retail", + r#"{"spiel_id":"new-22","user_id":"u1","is_edited":false,"source":"ceo_posts","text":"new"}"#, + ), + make_event_row( + 1, + utc_micros(2023, 6, 1, 14, 0, 0, 0), + utc_micros(2023, 6, 1, 14, 0, 0, 0), + "post_timestamp", + "ceo_post", + "retail", + r#"{"spiel_id":"upd-23","user_id":"u1","is_edited":false,"source":"ceo_posts","text":"upd"}"#, + ), + make_event_row( + 1, + utc_micros(2024, 6, 1, 14, 0, 0, 0), + utc_micros(2024, 6, 1, 14, 0, 0, 0), + "post_timestamp", + "ceo_post", + "retail", + r#"{"spiel_id":"fail-24","user_id":"u1","is_edited":false,"source":"ceo_posts","text":"fail"}"#, + ), + ]; + + let err = write_posts_events_dataset( + tmp.path(), + &failing_posts, + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetEventsError::Io { ref path, .. } if path == &blocker_2024), + "expected Io error at {}, got {err:?}", + blocker_2024.display() + ); + + // Rollback removes newly published 2022/part-posts.parquet and restores 2023/part-posts.parquet. + assert!(!tmp.path().join("events/year=2022").join(POSTS_PART_FILE_NAME).exists()); + assert_eq!(fs::read(&posts_2023).unwrap(), posts_2023_bytes); + // Sibling part.parquet files remain completely untouched. + assert_eq!(fs::read(&events_2023).unwrap(), events_2023_bytes); + assert_eq!(fs::read(&events_2024).unwrap(), events_2024_bytes); + assert!(blocker_2024.is_dir()); + assert_no_transient_files(&tmp.path().join("events")); +} diff --git a/tools/curate-etl/src/parquet_posts.rs b/tools/curate-etl/src/parquet_posts.rs index 07500644..ce718be0 100644 --- a/tools/curate-etl/src/parquet_posts.rs +++ b/tools/curate-etl/src/parquet_posts.rs @@ -1,8 +1,8 @@ //! Adapter mapping curated `ceoPosts` rows ([`PostRow`] / [`PostsBuild`]) into the -//! 7-column `events` Parquet contract ([`EventsParquetRow`], `events/year=YYYY/part.parquet`). +//! 7-column `events` Parquet contract ([`EventsParquetRow`], `events/year=YYYY/part-posts.parquet`). //! //! Aligned with `design/DATA-CONTRACTS.md` §1 & §3A and `design/PLATFORM-PLAN.md`: -//! - `kind` is always [`EVENT_KIND_POST`] (`"post"`). +//! - `kind` is always [`EVENT_KIND_POST`] (`"ceo_post"`). //! - `subtype` is [`POST_SUBTYPE_NEWSWIRE`] (`"newswire"`) when `is_bot` is `true`, and //! [`POST_SUBTYPE_RETAIL`] (`"retail"`) otherwise, so wire releases are never pooled with crowd //! chat. @@ -19,7 +19,7 @@ use crate::parquet_events::EventsParquetRow; use crate::posts::{PostRow, PostsBuild}; /// Canonical `events.kind` label for curated `ceoPosts` rows. -pub const EVENT_KIND_POST: &str = "post"; +pub const EVENT_KIND_POST: &str = "ceo_post"; /// Canonical `events.subtype` label for `bot == "1"` newswire posts. pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire"; @@ -89,7 +89,7 @@ impl From> for EventsParquetRow { /// Converts both `newswire` and `retail` streams of a [`PostsBuild`] into /// [`EventsParquetRow`] records sorted in the exact order required by -/// [`crate::parquet_events::write_events_dataset`]: +/// [`crate::parquet_events::write_posts_events_dataset`]: /// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. pub fn posts_to_event_rows(build: &PostsBuild) -> Vec { let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len()); diff --git a/tools/curate-etl/src/parquet_posts_tests.rs b/tools/curate-etl/src/parquet_posts_tests.rs index 69812e00..98d252d0 100644 --- a/tools/curate-etl/src/parquet_posts_tests.rs +++ b/tools/curate-etl/src/parquet_posts_tests.rs @@ -265,7 +265,9 @@ fn maps_retail_unedited_edited_newswire_and_clamped_edit_for_borrowed_and_owned( } let mapped = posts_to_event_rows(&build); + assert_eq!(EVENT_KIND_POST, "ceo_post"); assert_eq!(mapped.len(), 4); + assert!(mapped.iter().all(|row| row.kind.as_ref() == "ceo_post")); // 101: retail unedited assert_eq!( @@ -814,3 +816,39 @@ fn post_2200_timestamp_is_preserved_by_adapter_and_rejected_by_writer() { ); assert!(!dir.path().join("events/year=2201").exists()); } + +/// Regression for T-209: the curated `ceoPosts` kind must be one of the `EventKind` values the +/// downstream TypeScript and Python readers accept. With the old `"post"` label every curated post +/// was unreachable through `store.events` / MCP `event_study` because `validateEventKinds` rejects +/// unknown kinds and no reader can request `"post"`. +#[test] +fn event_kind_post_is_accepted_by_ts_and_python_event_kind_contracts() { + const TS_READER: &str = include_str!("../../../libs/research/src/market-data-store-duckdb.ts"); + const TS_CONTRACT: &str = include_str!("../../../libs/research/src/market-data-store.ts"); + const PY_READER: &str = include_str!("../../../python/stockbot/data.py"); + + let ts_kinds_line = TS_READER + .lines() + .find(|l| l.starts_with("export const EVENT_KINDS")) + .expect("EVENT_KINDS declaration in market-data-store-duckdb.ts"); + let ts_type_line = TS_CONTRACT + .lines() + .find(|l| l.starts_with("export type EventKind")) + .expect("EventKind type in market-data-store.ts"); + let py_line = PY_READER + .lines() + .find(|l| l.starts_with("EventKind = Literal[")) + .expect("EventKind Literal in python/stockbot/data.py"); + + let quoted_single = format!("'{EVENT_KIND_POST}'"); + let quoted_double = format!("\"{EVENT_KIND_POST}\""); + assert!(ts_kinds_line.contains("ed_single), "TS EVENT_KINDS lacks {quoted_single}: {ts_kinds_line}"); + assert!(ts_type_line.contains("ed_single), "TS EventKind lacks {quoted_single}: {ts_type_line}"); + assert!(py_line.contains("ed_double), "Python EventKind lacks {quoted_double}: {py_line}"); + + // Both readers must glob every `.parquet` sibling in a year partition so the posts file + // (`part-posts.parquet`) is read alongside filings/earnings (`part.parquet`). + assert!(TS_READER.contains("'events/year=*/*.parquet'")); + assert!(PY_READER.contains("/events/year=*/*.parquet")); + assert!(!PY_READER.contains("/events/year=*/part.parquet")); +} diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs index 86c6c8e5..f5731824 100644 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -48,23 +48,22 @@ //! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors //! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`]. -use std::collections::{HashMap, HashSet}; use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; -use std::sync::Arc; use std::time::Instant; -use crate::bars_1m::{Bars1mStats, EodIntradayBar}; +use crate::bars_1m::BARS_1M_SOURCE_EOD; +use crate::bars_1m_sort::{ + Bars1mExternalSortError, Bars1mExternalSorter, Bars1mSortConfig, ExternalSortMetrics, +}; use crate::bson_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecodeStats}; use crate::bson_qm_actions::BsonQmActionDecodeStats; use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; -use crate::curate_bars_1m::{ - curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError, -}; +use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError}; use crate::ilp::{ IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M, }; @@ -241,7 +240,6 @@ impl Error for RunCurateBars1mError { struct LoadedReferenceInputs { mapping: ProviderMappingTable, - eod_keys: HashSet>, splits: SplitTable, splits_docs_framed: u64, splits_bytes_read: u64, @@ -378,9 +376,7 @@ fn load_reference_inputs( let mapping_rows = load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?; let EodMappingIndex { - eod_keys, - eod_by_listing, - .. + eod_by_listing, .. } = build_eod_mapping_index(&mapping_rows, false); let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { @@ -416,7 +412,6 @@ fn load_reference_inputs( Ok(LoadedReferenceInputs { mapping, - eod_keys, splits, splits_docs_framed, splits_bytes_read, @@ -425,47 +420,28 @@ fn load_reference_inputs( }) } -#[inline] -fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) { - total.bars_in += chunk.bars_in; - total.rows_out += chunk.rows_out; - total.keys_out += chunk.keys_out; - total.pre_rows_out += chunk.pre_rows_out; - total.rth_rows_out += chunk.rth_rows_out; - total.post_rows_out += chunk.post_rows_out; - total.dropped_invalid_ohlc += chunk.dropped_invalid_ohlc; - total.dropped_inconsistent_ohlc += chunk.dropped_inconsistent_ohlc; - total.dropped_invalid_volume += chunk.dropped_invalid_volume; - total.dropped_ts_out_of_range += chunk.dropped_ts_out_of_range; - total.duplicate_collapsed += chunk.duplicate_collapsed; - total.duplicate_conflict_dropped += chunk.duplicate_conflict_dropped; -} - -#[inline] -pub(crate) fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) { - add_bars_1m_stats(&mut total.builder, &chunk.builder); - total.rows_in += chunk.rows_in; - total.rows_out += chunk.rows_out; - total.listings_out += chunk.listings_out; - total.pre_rows_out += chunk.pre_rows_out; - total.rth_rows_out += chunk.rth_rows_out; - total.post_rows_out += chunk.post_rows_out; - total.dropped_unmapped += chunk.dropped_unmapped; - total.listing_collision_collapsed += chunk.listing_collision_collapsed; - total.listing_collision_dropped += chunk.listing_collision_dropped; +fn map_sort_error(err: Bars1mExternalSortError) -> RunCurateBars1mError { + match err { + Bars1mExternalSortError::Io { path, source } => RunCurateBars1mError::Io { path, source }, + Bars1mExternalSortError::Ilp(err) => { + RunCurateBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(err)) + } + } } fn stream_intraday_chunks_to_writer( args: &CurateBars1mArgs, reference: LoadedReferenceInputs, intraday: RI, - mut writer: IlpShardedWriter, + writer: IlpShardedWriter, + sort_config: Bars1mSortConfig, start: Instant, -) -> Result +) -> Result<(CurateBars1mRunReport, ExternalSortMetrics), RunCurateBars1mError> where RI: io::Read, W: Write + Send, { + let mut writer = writer; let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err( |source| RunCurateBars1mError::BsonStream { label: "eod-intraday", @@ -475,14 +451,13 @@ where )?; let mut intraday_decode = BsonEodIntradayDecodeStats::default(); - let mut curate_stats = CurateBars1mStats::default(); let mut chunks: usize = 0; let mut max_rows_per_chunk: usize = 0; - let mut rows_written: usize = 0; - // Reusable per-chunk buffers; cleared before each chunk so peak RAM stays bounded by chunk size. - let mut chunk_bars: Vec>> = Vec::new(); - let mut unknown_keys: HashMap> = HashMap::new(); + // Bounded-memory external sort/merge resolves same-key duplicates and cross-source listing + // collisions globally across BSON chunks without retaining all rows in RAM. + let mut sorter = + Bars1mExternalSorter::new(&reference.mapping, &args.mapping_source, sort_config); while let Some(chunk) = reader @@ -493,67 +468,75 @@ where source, })? { - chunk_bars.clear(); - unknown_keys.clear(); + let mut chunk_rows = 0usize; + let mut spill_err: Option = None; let chunk_decode = decode_eod_intraday_buffer( chunk.bytes, |raw| { - let key = if let Some(existing) = reference.eod_keys.get(raw.eod_search_code) { - Arc::clone(existing) - } else if let Some(existing) = unknown_keys.get(raw.eod_search_code) { - Arc::clone(existing) - } else { - let arc: Arc = Arc::from(raw.eod_search_code); - unknown_keys.insert(raw.eod_search_code.to_owned(), Arc::clone(&arc)); - arc - }; - chunk_bars.push(raw.into_eod_intraday_bar(|_, _| key)); + if spill_err.is_some() { + return; + } + chunk_rows += 1; + if let Err(err) = sorter.push_raw( + raw.eod_search_code, + raw.ts, + raw.open, + raw.high, + raw.low, + raw.close, + raw.volume, + ) { + spill_err = Some(err); + } }, |_local_offset, _err| {}, ); + if let Some(err) = spill_err { + return Err(map_sort_error(err)); + } intraday_decode += chunk_decode; chunks += 1; - let chunk_len = chunk_bars.len(); - if chunk_len > max_rows_per_chunk { - max_rows_per_chunk = chunk_len; + if chunk_rows > max_rows_per_chunk { + max_rows_per_chunk = chunk_rows; } - - let write_report = curate_and_write_bars_1m_by_listing( - chunk_bars.drain(..), - &reference.splits, - &reference.mapping, - &args.mapping_source, - &mut writer, - args.known_at_micros, - ) - .map_err(RunCurateBars1mError::CurateWrite)?; - - add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); - rows_written += write_report.rows_written; } let intraday_docs_framed = reader.docs_framed(); let intraday_bytes_read = reader.bytes_read(); + drop(reader); + + let outcome = sorter + .finish_and_write( + Some(&reference.splits), + BARS_1M_SOURCE_EOD, + &mut writer, + args.known_at_micros, + ) + .map_err(map_sort_error)?; + let write_report = outcome.write_report; let ilp_stats = writer.finish().map_err(RunCurateBars1mError::Ilp)?; - Ok(CurateBars1mRunReport { - intraday_docs_framed, - intraday_bytes_read, - intraday_decode, - splits_docs_framed: reference.splits_docs_framed, - splits_bytes_read: reference.splits_bytes_read, - splits_decode: reference.splits_decode, - split_rekey: reference.split_rekey, - chunks, - max_rows_per_chunk, - curate_stats, - rows_written, - ilp_stats, - shard_count: args.shard_count, - elapsed_secs: start.elapsed().as_secs_f64(), - }) + Ok(( + CurateBars1mRunReport { + intraday_docs_framed, + intraday_bytes_read, + intraday_decode, + splits_docs_framed: reference.splits_docs_framed, + splits_bytes_read: reference.splits_bytes_read, + splits_decode: reference.splits_decode, + split_rekey: reference.split_rekey, + chunks, + max_rows_per_chunk, + curate_stats: write_report.curate_stats, + rows_written: write_report.rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }, + outcome.metrics, + )) } /// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary [`io::Read`] streams into a @@ -561,8 +544,8 @@ where /// /// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits` /// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] + -/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits, -/// and calls [`IlpShardedWriter::finish`] exactly once after EOF. +/// [`decode_eod_intraday_buffer`] into the bounded-memory external sorter/merger with listing-keyed +/// splits, and calls [`IlpShardedWriter::finish`] exactly once after EOF. pub fn run_curate_bars_1m_with_readers( args: &CurateBars1mArgs, intraday: RI, @@ -584,7 +567,10 @@ where } let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?; - stream_intraday_chunks_to_writer(args, reference, intraday, writer, start) + let sort_config = Bars1mSortConfig::new(None, TABLE_BARS_1M); + let (report, _metrics) = + stream_intraday_chunks_to_writer(args, reference, intraday, writer, sort_config, start)?; + Ok(report) } /// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once @@ -755,12 +741,85 @@ where } let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?; - let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?; + let sort_config = Bars1mSortConfig::new(Some(args.out_dir.clone()), TABLE_BARS_1M); + let (report, _metrics) = + stream_intraday_chunks_to_writer(args, reference, intraday, writer, sort_config, start)?; publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?; Ok(report) } +#[cfg(test)] +pub(crate) fn run_curate_bars_1m_from_readers_to_dir_with_sort_config( + args: &CurateBars1mArgs, + intraday: RI, + splits: RS, + sort_config: Bars1mSortConfig, +) -> Result<(CurateBars1mRunReport, ExternalSortMetrics), RunCurateBars1mError> +where + RI: io::Read, + RS: io::Read, +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateBars1mError::Io { + path: args.out_dir.clone(), + source, + })?; + + let run_id = next_run_id(); + let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); + let mut sinks: Vec = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + TABLE_BARS_1M, + shard_idx, + &run_id, + )?; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(SyncedBufFile::new(file)); + } + + let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?; + let (report, metrics) = + stream_intraday_chunks_to_writer(args, reference, intraday, writer, sort_config, start)?; + + publish_staged_shards_for_table( + &args.out_dir, + TABLE_BARS_1M, + &mut staged, + |_shard_idx, _final_path| {}, + )?; + Ok((report, metrics)) +} + +/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary raw-BSON [`io::Read`] +/// streams (such as read-only MongoDB cursors), running full directory preflight, exclusive `.tmp` +/// staging, atomic `hard_link` publication to `/bars_1m.shard-.ilp`, and rollback +/// cleanup on failure with zero intermediate `.bson` scratch files. +pub fn run_curate_bars_1m_from_readers_to_dir( + args: &CurateBars1mArgs, + intraday: RI, + splits: RS, +) -> Result +where + RI: io::Read, + RS: io::Read, +{ + run_curate_bars_1m_to_dir_with_hooks( + args, + intraday, + splits, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + /// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly /// `args.shard_count` QuestDB ILP v2 files (`/bars_1m.shard-.ilp`). pub fn run_curate_bars_1m( @@ -783,13 +842,7 @@ pub fn run_curate_bars_1m( } })?; - run_curate_bars_1m_to_dir_with_hooks( - args, - intraday_file, - splits_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) + run_curate_bars_1m_from_readers_to_dir(args, intraday_file, splits_file) } /// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary. diff --git a/tools/curate-etl/src/run_curate_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_bars_1m_tests.rs index 6cf6c065..f1420c9b 100644 --- a/tools/curate-etl/src/run_curate_bars_1m_tests.rs +++ b/tools/curate-etl/src/run_curate_bars_1m_tests.rs @@ -4,13 +4,14 @@ use std::fs; use std::io::{self, Cursor, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; use bson::raw::{cstr, RawDocumentBuf}; use super::*; use crate::bars::Bar1dRow; use crate::bars_1m::{ - Bar1mRow, IntradaySession, SessionCloseCutoffPolicy, BARS_1M_SOURCE_EOD, + Bar1mRow, EodIntradayBar, IntradaySession, SessionCloseCutoffPolicy, BARS_1M_SOURCE_EOD, }; use crate::curate_bars_1m::check_curated_session_closes; use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; @@ -955,22 +956,21 @@ fn cross_chunk_duplicate_is_emitted_twice_and_reported() { assert_report_conservation(&report); assert_eq!(report.chunks, 2); assert_eq!(report.max_rows_per_chunk, 1); - assert_eq!(report.curate_stats.builder.duplicate_collapsed, 0); + assert_eq!(report.curate_stats.builder.duplicate_collapsed, 1); assert_eq!(report.curate_stats.listing_collision_collapsed, 0); - assert_eq!(report.curate_stats.listings_out, 2); - assert_eq!(report.curate_stats.builder.keys_out, 2); - assert_eq!(report.rows_written, 2); + assert_eq!(report.curate_stats.listings_out, 1); + assert_eq!(report.curate_stats.builder.keys_out, 1); + assert_eq!(report.rows_written, 1); let rows = decode_ilp_bars_1m(&sink); - assert_eq!(rows.len(), 2); - assert_eq!(rows[0], rows[1]); + assert_eq!(rows.len(), 1); assert_eq!(rows[0].listing_id, 505); assert_eq!(rows[0].ts, ts * 1_000_000); let formatted = format_curate_bars_1m_report(&report); - assert!(formatted.contains("cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)")); - assert!(formatted.contains("listings_out_per_chunk_sum=2")); - assert!(formatted.contains("keys_out_per_chunk_sum=2")); + assert!(formatted.contains("dup_collapsed=1")); + assert!(formatted.contains("listings_out_per_chunk_sum=1")); + assert!(formatted.contains("keys_out_per_chunk_sum=1")); } #[test] @@ -1996,3 +1996,365 @@ fn qa_listing_split_applies_to_all_eod_aliases_of_the_listing() { let oth = get(88, et_ts_sec(2025, 5, 20, 10, 0)); assert_eq!((oth.close, oth.volume), (20.5, 50.0)); } + +#[test] +fn external_sort_multi_run_matches_single_run_byte_for_byte_across_reordered_collisions_and_splits() +{ + let dir = TempDirGuard::new("bars1m-ext-sort-parity"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tA1.US\t2020-01-01\t\t10", + "eod\tA2.US\t2020-01-01\t\t10", + "qm\tAQ\t2020-01-01\t\t10", + "eod\tB.US\t2020-01-01\t\t20", + ], + ); + let splits_bytes = concat_docs(&[make_split_doc("AQ", "2024-06-10", 1.0, 2.0)]); + + let t1 = et_ts_sec(2024, 6, 7, 9, 30); + let t2 = et_ts_sec(2024, 6, 7, 9, 31); + let t3 = et_ts_sec(2024, 6, 7, 9, 32); + let t4 = et_ts_sec(2024, 6, 7, 9, 33); + + let docs = vec![ + // Same-key identical duplicate (A1.US @ t1) + make_intraday_doc("A1.US", t1, 50.0, 51.0, 49.0, 50.5, 200.0), + make_intraday_doc("A1.US", t1, 50.0, 51.0, 49.0, 50.5, 200.0), + // Cross-source identical collision on listing 10 @ t1 (A2.US matches A1.US) + make_intraday_doc("A2.US", t1, 50.0, 51.0, 49.0, 50.5, 200.0), + // Cross-source conflicting collision on listing 10 @ t2 (both dropped) + make_intraday_doc("A1.US", t2, 51.0, 52.0, 50.0, 51.5, 100.0), + make_intraday_doc("A2.US", t2, 51.0, 52.0, 50.0, 51.75, 100.0), + // Same-key conflicting duplicate on B.US @ t3 (both dropped) + make_intraday_doc("B.US", t3, 20.0, 21.0, 19.0, 20.5, 50.0), + make_intraday_doc("B.US", t3, 20.0, 21.0, 19.0, 20.6, 50.0), + // Clean bar on B.US @ t4 + unmapped bar + make_intraday_doc("B.US", t4, 21.0, 22.0, 20.0, 21.5, 75.0), + make_intraday_doc("UNMAPPED.US", t1, 5.0, 6.0, 4.0, 5.5, 10.0), + make_intraday_doc("UNMAPPED.US", t1, 5.0, 6.0, 4.0, 5.5, 10.0), + ]; + + let canonical_bytes = concat_docs(&docs); + let mut reversed_docs = docs.clone(); + reversed_docs.reverse(); + let reordered_bytes = concat_docs(&reversed_docs); + + let out_ref = dir.path().join("out-ref"); + let out_bounded = dir.path().join("out-bounded"); + let ref_args = make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + out_ref.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let (ref_report, ref_metrics) = run_curate_bars_1m_from_readers_to_dir_with_sort_config( + &ref_args, + Cursor::new(&canonical_bytes), + Cursor::new(&splits_bytes), + Bars1mSortConfig { + spill_dir: Some(out_ref.clone()), + spill_prefix: TABLE_BARS_1M, + max_run_rows: 10_000, + max_merge_fan_in: 64, + }, + ) + .expect("single-run reference"); + assert_report_conservation(&ref_report); + assert_eq!(ref_metrics.runs_spilled, 0); + + let bounded_args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + out_bounded.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: 1024 * 1024, + }, + ); + let (bounded_report, bounded_metrics) = + run_curate_bars_1m_from_readers_to_dir_with_sort_config( + &bounded_args, + Cursor::new(&reordered_bytes), + Cursor::new(&splits_bytes), + Bars1mSortConfig { + spill_dir: Some(out_bounded.clone()), + spill_prefix: TABLE_BARS_1M, + max_run_rows: 2, + max_merge_fan_in: 2, + }, + ) + .expect("bounded multi-run external sort"); + assert_report_conservation(&bounded_report); + assert!(bounded_metrics.peak_buffer_rows <= 2); + assert!(bounded_metrics.runs_spilled >= 4); + assert!(bounded_metrics.merge_passes >= 2); + + assert_eq!(bounded_report.curate_stats, ref_report.curate_stats); + assert_eq!(bounded_report.rows_written, ref_report.rows_written); + assert_eq!(bounded_report.ilp_stats, ref_report.ilp_stats); + assert_eq!(bounded_report.rows_written, 2); + assert_eq!(bounded_report.curate_stats.builder.duplicate_collapsed, 2); + assert_eq!( + bounded_report.curate_stats.builder.duplicate_conflict_dropped, + 2 + ); + assert_eq!(bounded_report.curate_stats.listing_collision_collapsed, 1); + assert_eq!(bounded_report.curate_stats.listing_collision_dropped, 2); + assert_eq!(bounded_report.curate_stats.dropped_unmapped, 1); + + let expected_names = vec![ + "bars_1m.shard-00.ilp".to_string(), + "bars_1m.shard-01.ilp".to_string(), + ]; + assert_eq!(list_dir_names(&out_ref), expected_names); + assert_eq!(list_dir_names(&out_bounded), expected_names); + for name in &expected_names { + assert_eq!( + fs::read(out_bounded.join(name)).unwrap(), + fs::read(out_ref.join(name)).unwrap(), + "shard {name} must match byte-for-byte across external sort runs" + ); + } +} + +#[test] +fn external_sort_bounded_memory_on_representative_multi_symbol_backfill() { + let dir = TempDirGuard::new("bars1m-ext-sort-backfill"); + let mut map_lines = Vec::new(); + for sym in 0..10 { + map_lines.push(format!("eod\tSYM{sym}.US\t2020-01-01\t\t{}", 100 + sym)); + } + let map_refs: Vec<&str> = map_lines.iter().map(String::as_str).collect(); + let mapping_path = write_mapping_tsv(dir.path(), &map_refs); + + let base_ts = et_ts_sec(2024, 6, 7, 9, 30); + let mut docs = Vec::with_capacity(4_000); + for minute in (0..400i64).rev() { + for sym in 0..10 { + let price = 10.0 + sym as f64 + (minute % 20) as f64 * 0.05; + docs.push(make_intraday_doc( + &format!("SYM{sym}.US"), + base_ts + minute * 60, + price, + price + 0.5, + price - 0.5, + price + 0.1, + 100.0 + sym as f64, + )); + } + } + let intraday_bytes = concat_docs(&docs); + let splits_bytes: Vec = Vec::new(); + + let out_ref = dir.path().join("out-ref"); + let out_bounded = dir.path().join("out-bounded"); + let (ref_report, _) = run_curate_bars_1m_from_readers_to_dir_with_sort_config( + &make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + out_ref.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ), + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + Bars1mSortConfig { + spill_dir: Some(out_ref.clone()), + spill_prefix: TABLE_BARS_1M, + max_run_rows: 100_000, + max_merge_fan_in: 64, + }, + ) + .expect("reference backfill"); + + let (bounded_report, metrics) = run_curate_bars_1m_from_readers_to_dir_with_sort_config( + &make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + out_bounded.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ), + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + Bars1mSortConfig { + spill_dir: Some(out_bounded.clone()), + spill_prefix: TABLE_BARS_1M, + max_run_rows: 250, + max_merge_fan_in: 4, + }, + ) + .expect("bounded backfill"); + + assert_report_conservation(&bounded_report); + assert_eq!(bounded_report.rows_written, 4_000); + assert!(metrics.peak_buffer_rows <= 250); + assert_eq!(metrics.runs_spilled, 16); + assert!(metrics.merge_passes >= 2); + assert_eq!(bounded_report.curate_stats, ref_report.curate_stats); + assert_eq!(bounded_report.ilp_stats, ref_report.ilp_stats); + for shard in 0..2 { + let name = format!("bars_1m.shard-{shard:02}.ilp"); + assert_eq!( + fs::read(out_bounded.join(&name)).unwrap(), + fs::read(out_ref.join(&name)).unwrap(), + ); + } + assert_eq!(list_dir_names(&out_bounded).len(), 2); +} + +/// Deterministic Fisher-Yates shuffle driven by a fixed-seed 64-bit LCG (no external crates). +fn seeded_shuffle(items: &mut [T], seed: u64) { + let mut state = seed; + for i in (1..items.len()).rev() { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + let j = ((state >> 33) % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +#[test] +fn external_sort_duplicate_heavy_groups_spanning_many_runs_are_order_and_run_size_invariant() { + let dir = TempDirGuard::new("bars1m-ext-sort-dup-heavy"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tA1.US\t2020-01-01\t\t10", + "eod\tA2.US\t2020-01-01\t\t10", + "eod\tA3.US\t2020-01-01\t\t10", + "eod\tB.US\t2020-01-01\t\t20", + ], + ); + let splits_bytes: Vec = Vec::new(); + + let t1 = et_ts_sec(2024, 6, 7, 9, 30); + let t2 = et_ts_sec(2024, 6, 7, 9, 31); + let t3 = et_ts_sec(2024, 6, 7, 9, 32); + + let mut docs = Vec::new(); + // t1: 6x A1 + 5x A2 + 4x A3, all bit-identical -> 12 same-key collapses, 2 listing collapses. + for (code, copies) in [("A1.US", 6), ("A2.US", 5), ("A3.US", 4)] { + for _ in 0..copies { + docs.push(make_intraday_doc(code, t1, 50.0, 51.0, 49.0, 50.5, 200.0)); + } + } + // t2: 6x identical A1 plus one conflicting A1 -> all 7 dropped; lone A2 survives. + for _ in 0..6 { + docs.push(make_intraday_doc("A1.US", t2, 51.0, 52.0, 50.0, 51.5, 100.0)); + } + docs.push(make_intraday_doc("A1.US", t2, 51.0, 52.0, 50.0, 51.6, 100.0)); + docs.push(make_intraday_doc("A2.US", t2, 51.0, 52.0, 50.0, 51.5, 100.0)); + // t3: cross-source conflict on listing 10 -> both dropped. + docs.push(make_intraday_doc("A1.US", t3, 52.0, 53.0, 51.0, 52.5, 90.0)); + docs.push(make_intraday_doc("A2.US", t3, 52.0, 53.0, 51.0, 52.4, 90.0)); + // Clean B.US bars on listing 20. + for ts in [t1, t2, t3] { + docs.push(make_intraday_doc("B.US", ts, 20.0, 21.0, 19.0, 20.5, 50.0)); + } + + let out_ref = dir.path().join("out-ref"); + let (ref_report, ref_metrics) = run_curate_bars_1m_from_readers_to_dir_with_sort_config( + &make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + out_ref.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ), + Cursor::new(concat_docs(&docs)), + Cursor::new(&splits_bytes), + Bars1mSortConfig { + spill_dir: Some(out_ref.clone()), + spill_prefix: TABLE_BARS_1M, + max_run_rows: 10_000, + max_merge_fan_in: 64, + }, + ) + .expect("in-memory reference run"); + assert_report_conservation(&ref_report); + assert_eq!(ref_metrics.runs_spilled, 0); + assert_eq!(ref_report.rows_written, 5); + assert_eq!(ref_report.curate_stats.builder.duplicate_collapsed, 12); + assert_eq!(ref_report.curate_stats.builder.duplicate_conflict_dropped, 7); + assert_eq!(ref_report.curate_stats.listing_collision_collapsed, 2); + assert_eq!(ref_report.curate_stats.listing_collision_dropped, 2); + + let expected_names = vec![ + "bars_1m.shard-00.ilp".to_string(), + "bars_1m.shard-01.ilp".to_string(), + ]; + assert_eq!(list_dir_names(&out_ref), expected_names); + let ref_shards: Vec> = expected_names + .iter() + .map(|name| fs::read(out_ref.join(name)).unwrap()) + .collect(); + + let mut case = 0usize; + for seed in 1..=4u64 { + let mut permuted = docs.clone(); + seeded_shuffle(&mut permuted, seed); + let permuted_bytes = concat_docs(&permuted); + for max_run_rows in [1usize, 2, 3, 5, 7] { + for max_merge_fan_in in [2usize, 3] { + case += 1; + let out = dir.path().join(format!("out-{case}")); + let (report, metrics) = run_curate_bars_1m_from_readers_to_dir_with_sort_config( + &make_args( + mapping_path.clone(), + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + out.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: 1024 * 1024, + }, + ), + Cursor::new(&permuted_bytes), + Cursor::new(&splits_bytes), + Bars1mSortConfig { + spill_dir: Some(out.clone()), + spill_prefix: TABLE_BARS_1M, + max_run_rows, + max_merge_fan_in, + }, + ) + .unwrap_or_else(|e| { + panic!("seed={seed} run={max_run_rows} fan_in={max_merge_fan_in}: {e:?}") + }); + let ctx = format!("seed={seed} run={max_run_rows} fan_in={max_merge_fan_in}"); + assert_report_conservation(&report); + assert!(metrics.peak_buffer_rows <= max_run_rows, "{ctx}"); + assert!(metrics.runs_spilled >= docs.len() / max_run_rows, "{ctx}"); + assert_eq!(report.curate_stats, ref_report.curate_stats, "{ctx}"); + assert_eq!(report.rows_written, ref_report.rows_written, "{ctx}"); + assert_eq!(report.ilp_stats, ref_report.ilp_stats, "{ctx}"); + // Only the published shards remain: every spilled sort-run file was removed. + assert_eq!(list_dir_names(&out), expected_names, "{ctx}"); + for (name, expected) in expected_names.iter().zip(&ref_shards) { + assert_eq!( + &fs::read(out.join(name)).unwrap(), + expected, + "{ctx}: shard {name} bytes differ" + ); + } + } + } + } +} diff --git a/tools/curate-etl/src/run_curate_fundamentals.rs b/tools/curate-etl/src/run_curate_fundamentals.rs index f62c9e70..fe5fce66 100644 --- a/tools/curate-etl/src/run_curate_fundamentals.rs +++ b/tools/curate-etl/src/run_curate_fundamentals.rs @@ -63,7 +63,8 @@ use crate::bson_stream::{ BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, }; use crate::curate_fundamentals::{ - curate_and_write_fundamentals, CurateFundamentalsStats, CurateFundamentalsWriteError, + curate_and_write_fundamentals_with_legacy, CurateFundamentalsStats, + CurateFundamentalsWriteError, }; use crate::events::QmFiling; use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue}; @@ -112,6 +113,7 @@ impl CurateFundamentalsFiscalPeriod { #[derive(Debug, Clone, PartialEq, Eq)] pub struct CurateFundamentalsArgs { pub qm_financials: PathBuf, + pub qm_financials_old: Option, pub qm_filings: PathBuf, pub provider_mapping: PathBuf, pub listing_venues: PathBuf, @@ -165,6 +167,7 @@ impl CurateFundamentalsArgs { ) -> Self { Self { qm_financials, + qm_financials_old: None, qm_filings, provider_mapping, listing_venues, @@ -618,7 +621,7 @@ fn validate_out_dir_and_inputs( let resolved_out = resolve_normalized_path(&args.out_dir); let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir); - let resolved_inputs = [ + let mut resolved_inputs = vec![ ( "qm-financials", &args.qm_financials, @@ -640,6 +643,13 @@ fn validate_out_dir_and_inputs( resolve_normalized_path(&args.listing_venues), ), ]; + if let Some(old_path) = &args.qm_financials_old { + resolved_inputs.push(( + "qm-financials-old", + old_path, + resolve_normalized_path(old_path), + )); + } for (label, input_path, resolved_in) in &resolved_inputs { if *resolved_in == resolved_out @@ -774,12 +784,13 @@ fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 { } fn map_financials_stream_error( + label: &'static str, path: &Path, err: BsonQmFinancialsStreamError, ) -> RunCurateFundamentalsError { match err { BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { - label: "qm-financials", + label, path: path.to_path_buf(), source, }, @@ -847,6 +858,7 @@ struct DecodedFundamentalsInputs { mapping: ProviderMappingTable, venues: BTreeMap, observations: Vec>>, + legacy_observations: Vec>>, filings: Vec>>, financials_docs_framed: u64, financials_bytes_read: u64, @@ -858,14 +870,17 @@ struct DecodedFundamentalsInputs { filings_decode: BsonQmFilingsDecodeStats, } -fn decode_inputs_from_openers( +fn decode_inputs_from_openers( args: &CurateFundamentalsArgs, open_financials: FF, + open_financials_old: Option<(&Path, FO)>, open_filings: FL, ) -> Result where RF: io::Read, FF: FnOnce() -> Result, + RO: io::Read, + FO: FnOnce() -> Result, RL: io::Read, FL: FnOnce() -> Result, { @@ -916,10 +931,10 @@ where // Stream and decode qmFinancials, releasing the chunk reader immediately afterward. let ( observations, - financials_docs_framed, - financials_bytes_read, - financials_peak_chunk_bytes, - financials_decode, + mut financials_docs_framed, + mut financials_bytes_read, + mut financials_peak_chunk_bytes, + mut financials_decode, ) = { let financials_stream = open_financials()?; let mut financials_reader = @@ -944,7 +959,7 @@ where }); }) }) - .map_err(|err| map_financials_stream_error(&args.qm_financials, err))?; + .map_err(|err| map_financials_stream_error("qm-financials", &args.qm_financials, err))?; ( observations, @@ -955,6 +970,42 @@ where ) }; + // Optionally stream and decode legacy qmFinancials-old, accumulating framing & decode stats. + let mut legacy_observations: Vec>> = Vec::new(); + if let Some((old_path, open_old)) = open_financials_old { + let old_stream = open_old()?; + let mut old_reader = + RawBsonChunkReader::with_options(old_stream, BsonStreamOptions::default()).map_err( + |source| RunCurateFundamentalsError::BsonStream { + label: "qm-financials-old", + path: old_path.to_path_buf(), + source, + }, + )?; + + let old_decode = args + .fiscal_period + .with_borrowed(|fp| { + decode_qm_financials_chunks(&mut old_reader, &financials_fields, fp, |obs| { + let key = intern_key(&mut key_interner, obs.key); + legacy_observations.push(FinancialObservation { + key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + }); + }) + }) + .map_err(|err| map_financials_stream_error("qm-financials-old", old_path, err))?; + + financials_docs_framed += old_reader.docs_framed(); + financials_bytes_read += old_reader.bytes_read(); + financials_peak_chunk_bytes = financials_peak_chunk_bytes.max(old_reader.buffer_capacity()); + financials_decode.merge(&old_decode); + } + // Stream and decode qmFilings, reusing the same key interner and releasing the chunk reader. let (filings, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = { let filings_stream = open_filings()?; @@ -986,6 +1037,7 @@ where mapping, venues, observations, + legacy_observations, filings, financials_docs_framed, financials_bytes_read, @@ -998,25 +1050,29 @@ where }) } -fn run_curate_fundamentals_from_openers( +fn run_curate_fundamentals_from_openers( args: &CurateFundamentalsArgs, open_financials: FF, + open_financials_old: Option<(&Path, FO)>, open_filings: FL, ) -> Result where RF: io::Read, FF: FnOnce() -> Result, + RO: io::Read, + FO: FnOnce() -> Result, RL: io::Read, FL: FnOnce() -> Result, { let start = Instant::now(); validate_out_dir_and_inputs(args)?; - let decoded = decode_inputs_from_openers(args, open_financials, open_filings)?; + let decoded = decode_inputs_from_openers(args, open_financials, open_financials_old, open_filings)?; - let write_report = curate_and_write_fundamentals( + let write_report = curate_and_write_fundamentals_with_legacy( &args.out_dir, decoded.observations, + decoded.legacy_observations, decoded.filings, &args.mapping_source, &decoded.mapping, @@ -1045,7 +1101,7 @@ where } /// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via -/// [`curate_and_write_fundamentals`]. +/// [`curate_and_write_fundamentals_with_legacy`]. /// /// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error /// returns before touching `args.out_dir`, leaving any pre-existing @@ -1053,6 +1109,17 @@ where pub fn run_curate_fundamentals( args: &CurateFundamentalsArgs, ) -> Result { + let open_old = args.qm_financials_old.as_deref().map(|old_path| { + let opener = move || { + File::open(old_path).map_err(|source| RunCurateFundamentalsError::OpenInput { + label: "qm-financials-old", + path: old_path.to_path_buf(), + source, + }) + }; + (old_path, opener) + }); + run_curate_fundamentals_from_openers( args, || { @@ -1064,6 +1131,7 @@ pub fn run_curate_fundamentals( } }) }, + open_old, || { File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput { label: "qm-filings", @@ -1082,7 +1150,35 @@ pub fn run_curate_fundamentals_with_readers( financials_reader: RF, filings_reader: RL, ) -> Result { - run_curate_fundamentals_from_openers(args, || Ok(financials_reader), || Ok(filings_reader)) + run_curate_fundamentals_with_optional_old_readers( + args, + financials_reader, + None::, + filings_reader, + ) +} + +/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams with an optional +/// legacy `qmFinancials-old` stream, running full preflight validation and loading +/// `provider_mapping.tsv` / `listing_venues.tsv` from disk. +pub fn run_curate_fundamentals_with_optional_old_readers( + args: &CurateFundamentalsArgs, + financials_reader: RF, + financials_old_reader: Option, + filings_reader: RL, +) -> Result { + let fallback_old_path = Path::new("qmFinancials-old"); + let old_path = args + .qm_financials_old + .as_deref() + .unwrap_or(fallback_old_path); + let open_old = financials_old_reader.map(|r| (old_path, move || Ok(r))); + run_curate_fundamentals_from_openers( + args, + || Ok(financials_reader), + open_old, + || Ok(filings_reader), + ) } /// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value` diff --git a/tools/curate-etl/src/run_curate_fundamentals_tests.rs b/tools/curate-etl/src/run_curate_fundamentals_tests.rs index 37afd1bf..72fe0c47 100644 --- a/tools/curate-etl/src/run_curate_fundamentals_tests.rs +++ b/tools/curate-etl/src/run_curate_fundamentals_tests.rs @@ -15,8 +15,9 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use super::{ format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, - run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, - CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, + run_curate_fundamentals_with_optional_old_readers, run_curate_fundamentals_with_readers, + CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, + RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, }; use crate::bson_qm_events::decode_qm_filing_buffer; use crate::bson_qm_financials::decode_qm_financials_buffer; @@ -2757,3 +2758,141 @@ fn listing_venues_missing_file_reports_open_error_with_path() { assert!(matches!(err, RunCurateFundamentalsError::OpenInput { ref path, .. } if path.ends_with("nope.tsv"))); assert!(err.to_string().contains(&path.display().to_string())); } + +#[test] +fn qm_financials_old_merges_with_conservation_and_reader_parity() { + let tmp = TempDirGuard::new("qm-financials-old-merge"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let old_path = tmp.path().join("qmFinancials-old.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let ven_path = tmp.path().join("listing_venues.tsv"); + let out_file = tmp.path().join("out_file"); + let out_reader = tmp.path().join("out_reader"); + + fs::write(&map_path, "qm\tACME:US\t2020-01-01\t\t101\n").unwrap(); + fs::write(&ven_path, "101\tus_tsx\n").unwrap(); + + let fields = |rev: f64| FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev * 0.1), + operating_cash_flow: Some(rev * 0.15), + total_assets: Some(rev * 5.0), + total_equity: Some(rev * 2.0), + shares_outstanding: Some(1_000.0), + }; + + // Primary has Q2 + restated Q1 + a collision with old Q1 at same filing timestamp. + let mut fin_bytes = Vec::new(); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-06-30", + Some("2024-08-05"), + "Q2", + "USD", + fields(130.0), + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-03-31", + Some("2024-09-10"), + "Q1", + "USD", + fields(125.0), + )); + fs::write(&fin_path, &fin_bytes).unwrap(); + + // Legacy has historical Q3, Q4, original Q1 (and an older duplicate Q2 at same known_at that primary supersedes). + let mut old_bytes = Vec::new(); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2023-09-30", + Some("2023-11-05"), + "Q3", + "USD", + fields(100.0), + )); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2023-12-31", + Some("2024-02-20"), + "Q4", + "USD", + fields(110.0), + )); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-03-31", + Some("2024-05-05"), + "Q1", + "USD", + fields(120.0), + )); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-06-30", + Some("2024-08-05"), + "Q2", + "USD", + fields(99.0), + )); + fs::write(&old_path, &old_bytes).unwrap(); + + let mut fil_bytes = Vec::new(); + for (ts, form) in [ + ("2023-11-05T16:30:00 EST", "10-Q"), + ("2024-02-20T16:30:00 EST", "10-Q"), + ("2024-05-05T16:30:00 EDT", "10-Q"), + ("2024-08-05T16:30:00 EDT", "10-Q"), + ("2024-09-10T16:30:00 EDT", "10-Q/A"), + ] { + fil_bytes.extend_from_slice(&make_filing_doc(Some("ACME:US"), ts, form, None, None)); + } + fs::write(&fil_path, &fil_bytes).unwrap(); + + let mut file_args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + ven_path.clone(), + out_file.clone(), + ); + file_args.qm_financials_old = Some(old_path.clone()); + + let file_report = run_curate_fundamentals(&file_args).expect("file-mode merge must succeed"); + assert_eq!(file_report.financials_docs_framed, 6); + assert_eq!(file_report.financials_decode.docs_in, 6); + assert_eq!(file_report.financials_decode.rows_out, 6); + assert_eq!(file_report.curate_stats.observations_in, 6); + assert_eq!(file_report.curate_stats.build.duplicate_collapsed, 1); + assert_eq!(file_report.curate_stats.build.duplicate_conflict_dropped, 0); + assert_eq!(file_report.curate_stats.rows_out, 5); + assert_eq!(file_report.write_stats.rows_written, 5); + + let mut reader_args = file_args.clone(); + reader_args.out_dir = out_reader.clone(); + let reader_report = run_curate_fundamentals_with_optional_old_readers( + &reader_args, + Cursor::new(&fin_bytes), + Some(Cursor::new(&old_bytes)), + Cursor::new(&fil_bytes), + ) + .expect("reader-mode merge must succeed"); + + assert_eq!( + reader_report.financials_docs_framed, + file_report.financials_docs_framed + ); + assert_eq!(reader_report.curate_stats, file_report.curate_stats); + assert_eq!(reader_report.write_stats, file_report.write_stats); + assert_eq!(snapshot_tree(&out_file), snapshot_tree(&out_reader)); + + // Path overlap guard catches qm-financials-old inside out_dir/fundamentals_pit. + let mut bad_args = file_args; + bad_args.qm_financials_old = Some(out_file.join("fundamentals_pit").join("year=2024")); + let err = run_curate_fundamentals(&bad_args).expect_err("overlapping qm-financials-old must fail"); + assert!( + err.to_string().contains("qm-financials-old"), + "expected qm-financials-old in overlap error, got: {err}" + ); +} diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs index 7c938c0b..1eb1cece 100644 --- a/tools/curate-etl/src/run_curate_fx_1m.rs +++ b/tools/curate-etl/src/run_curate_fx_1m.rs @@ -476,6 +476,25 @@ where ) } +/// Runs the `fx_1m` curation pipeline from an arbitrary raw-BSON [`io::Read`] stream (such as a +/// read-only MongoDB cursor), running full directory preflight, exclusive `.tmp` staging, atomic +/// `hard_link` publication to `/fx_1m.shard-.ilp`, and rollback cleanup on failure +/// with zero intermediate `.bson` scratch files. +pub fn run_curate_fx_1m_from_reader_to_dir( + args: &CurateFx1mArgs, + intraday: R, +) -> Result +where + R: io::Read, +{ + run_curate_fx_1m_to_dir_with_hooks( + args, + intraday, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + /// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB /// ILP v2 files (`/fx_1m.shard-.ilp`). pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result { @@ -489,12 +508,7 @@ pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result Self { + pub(crate) fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self { match self { Self::ReadInput { role, @@ -521,19 +521,11 @@ pub fn load_macro_series_map_tsv( Ok(map) } -/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and -/// the series-map TSV, publishing `/macro/part.parquet` via [`curate_and_write_macro`]. -/// -/// The series map is validated in full before `te_data` is decoded or `out_dir` is touched. Any -/// map, I/O, structural BSON, or curation error returns before publishing and leaves `out_dir` and -/// any pre-existing `/macro/part.parquet` untouched. -pub fn run_curate_macro_with_readers( +fn run_curate_macro_with_map( mut te_data: RT, - series_map: RM, + map: &MacroSeriesMap, out_dir: &Path, ) -> Result { - let map = load_macro_series_map_tsv(series_map)?; - let mut te_data_buf = Vec::new(); te_data .read_to_end(&mut te_data_buf) @@ -577,6 +569,57 @@ pub fn run_curate_macro_with_readers( }) } +pub(crate) fn load_macro_series_map_file( + series_map_path: &Path, +) -> Result { + let series_map_file = + File::open(series_map_path).map_err(|source| RunCurateMacroError::OpenInput { + role: ROLE_SERIES_MAP, + path: series_map_path.to_path_buf(), + source, + })?; + load_macro_series_map_tsv(series_map_file) + .map_err(|err| err.with_input_paths(Path::new(""), series_map_path)) +} + +pub(crate) fn run_curate_macro_with_parsed_map( + te_data_path: &Path, + te_data: RT, + map: &MacroSeriesMap, + out_dir: &Path, +) -> Result { + run_curate_macro_with_map(te_data, map, out_dir) + .map_err(|err| err.with_input_paths(te_data_path, Path::new(""))) +} + +/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and +/// the series-map TSV, publishing `/macro/part.parquet` via [`curate_and_write_macro`]. +/// +/// The series map is validated in full before `te_data` is decoded or `out_dir` is touched. Any +/// map, I/O, structural BSON, or curation error returns before publishing and leaves `out_dir` and +/// any pre-existing `/macro/part.parquet` untouched. +pub fn run_curate_macro_with_readers( + te_data: RT, + series_map: RM, + out_dir: &Path, +) -> Result { + let map = load_macro_series_map_tsv(series_map)?; + run_curate_macro_with_map(te_data, &map, out_dir) +} + +/// Runs `curate-macro` from an arbitrary raw-BSON `teData` [`io::Read`] stream (such as a +/// read-only MongoDB cursor) and a `series_map_path` TSV on disk, validating `series_map_path` +/// before reading `te_data` and attaching `te_data_path` / `series_map_path` to any error. +pub fn run_curate_macro_from_reader( + te_data_path: &Path, + te_data: RT, + series_map_path: &Path, + out_dir: &Path, +) -> Result { + let map = load_macro_series_map_file(series_map_path)?; + run_curate_macro_with_parsed_map(te_data_path, te_data, &map, out_dir) +} + /// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating /// to [`run_curate_macro_with_readers`]. /// diff --git a/tools/curate-etl/src/run_curate_posts.rs b/tools/curate-etl/src/run_curate_posts.rs index 9f7e6c2e..b5fb757d 100644 --- a/tools/curate-etl/src/run_curate_posts.rs +++ b/tools/curate-etl/src/run_curate_posts.rs @@ -1,16 +1,14 @@ -//! File-to-file `curate-posts` runner (`M2.2i`). +//! File-to-file `curate-posts` runner (`M2.2i` / `M2.2u`). //! //! Streams a concatenated raw BSON `ceoPosts` dump file alongside `provider_mapping.tsv` into an -//! atomically published `/events/year=YYYY/part.parquet` dataset via -//! [`curate_and_write_posts`]. +//! atomically published `/events/year=YYYY/part-posts.parquet` dataset via +//! [`curate_posts`] and [`write_posts_events_dataset`]. //! -//! # Dedicated Output Directory & Clobber Guard -//! `write_events_dataset` replaces whole `/events/year=YYYY/part.parquet` files, and -//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `/events` -//! directory. To prevent silently clobbering another stage's partitions, this runner **requires a -//! dedicated output directory** and fails closed with [`RunCuratePostsError::EventsDatasetExists`] -//! before any write whenever `/events` already contains any `year=*` entry. Combining -//! filings, earnings, and posts into one `events` dataset is a separate follow-up. +//! # Co-Publication with `curate-events` +//! [`crate::run_curate_events`] (filings + earnings) writes `/events/year=YYYY/part.parquet` +//! and this runner writes `/events/year=YYYY/part-posts.parquet` (`kind = "ceo_post"`). +//! Both share `/events/.write.lock` and remain independently re-runnable in the same +//! `curatedRoot` without clobbering each other's partition files. //! //! # Contract & Point-in-Time Rules //! - Field names are supplied via [`CuratePostsArgs`] (validated via @@ -30,10 +28,10 @@ //! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires. //! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and //! `files_written == 0` without creating `/events`. -//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `/events/year=*` entries, -//! invalid field names, blank `mapping_source`, unreadable inputs, malformed/overlapping -//! `provider_mapping.tsv`, truncated/corrupt BSON framing or element bytes, and curation -//! timestamp overflow errors return a typed [`RunCuratePostsError`] before touching `out_dir`. +//! - **Fail-closed safety:** invalid `out_dir`, input-output path overlap, invalid field names, +//! blank `mapping_source`, unreadable inputs, malformed/overlapping `provider_mapping.tsv`, +//! truncated/corrupt BSON framing or element bytes, and curation timestamp overflow errors return +//! a typed [`RunCuratePostsError`] before touching `out_dir`. //! //! # Counter Conservation Invariants //! Every successful [`CuratePostsRunReport`] satisfies: @@ -43,7 +41,7 @@ //! - `curate_stats.rows_in == curate_stats.builder.newswire + curate_stats.builder.retail == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unsupported_date + curate_stats.listing_duplicate_collapsed` //! - `write_stats.rows_written == curate_stats.rows_out` -use std::collections::HashSet; +use std::collections::{BTreeSet, HashSet}; use std::error::Error; use std::fmt::{self, Write as _}; use std::fs::{self, File}; @@ -59,8 +57,12 @@ use crate::bson_stream::{ decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, }; -use crate::curate_posts::{curate_and_write_posts, CuratePostsStats, CuratePostsWriteError}; -use crate::parquet_events::{EventsWriteOptions, EventsWriteStats}; +use crate::curate_posts::{curate_posts, CuratePostsStats, CuratePostsWriteError}; +use crate::events::partition_year_utc; +use crate::parquet_events::{ + write_posts_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, + POSTS_PART_FILE_NAME, +}; use crate::posts::CeoPost; use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; @@ -130,9 +132,6 @@ pub enum RunCuratePostsError { path: PathBuf, source: io::Error, }, - EventsDatasetExists { - path: PathBuf, - }, InvalidFieldNames { source: BsonCeoPostsError, }, @@ -212,11 +211,6 @@ impl fmt::Display for RunCuratePostsError { path.display() ) } - Self::EventsDatasetExists { path } => write!( - w, - "refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts", - path.display() - ), Self::InvalidFieldNames { source } => write!(w, "{source}"), Self::EmptyMappingSource => { write!(w, "invalid --mapping-source: must not be empty or blank") @@ -266,15 +260,66 @@ impl Error for RunCuratePostsError { Self::BsonStream { source, .. } => Some(source), Self::CorruptBson { source, .. } => Some(source), Self::CurateWrite { source, .. } => Some(source), - Self::InvalidOutDir { .. } - | Self::EventsDatasetExists { .. } - | Self::EmptyMappingSource - | Self::TsvParse { .. } => None, + Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None, } } } -fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePostsError> { +/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..` +/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked +/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically +/// normalizing `..` within any non-existent suffix. +fn resolve_normalized_path(path: &Path) -> PathBuf { + if let Ok(canon) = path.canonicalize() { + return canon; + } + + let abs = if path.is_absolute() { + path.to_path_buf() + } else if let Ok(cwd) = std::env::current_dir() { + cwd.join(path) + } else { + path.to_path_buf() + }; + + if let Ok(canon) = abs.canonicalize() { + return canon; + } + + let mut resolved = PathBuf::new(); + for comp in abs.components() { + match comp { + Component::Prefix(prefix) => resolved.push(prefix.as_os_str()), + Component::RootDir => resolved.push(Component::RootDir.as_os_str()), + Component::CurDir => {} + Component::Normal(seg) => { + resolved.push(seg); + if let Ok(canon) = resolved.canonicalize() { + resolved = canon; + } + } + Component::ParentDir => { + resolved.push(Component::ParentDir.as_os_str()); + if let Ok(canon) = resolved.canonicalize() { + resolved = canon; + } else { + resolved.pop(); + if matches!(resolved.components().next_back(), Some(Component::Normal(_))) { + resolved.pop(); + } + } + } + } + } + + resolved +} + +fn validate_out_dir_and_inputs( + out_dir: &Path, + ceo_posts_path: &Path, + provider_mapping_path: &Path, +) -> Result<(), RunCuratePostsError> { if out_dir.as_os_str().is_empty() { return Err(RunCuratePostsError::InvalidOutDir { path: out_dir.to_path_buf(), @@ -283,8 +328,7 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost } // Reject `..` after a missing path component: `fs::metadata` reports `NotFound` for the - // unresolved path, but `create_dir_all` would create the missing component and then traverse - // `..` into an existing directory, bypassing the events clobber guard. + // unresolved path, while `create_dir_all` would create the missing component and traverse `..`. let mut prefix = PathBuf::new(); let mut saw_missing = false; for component in out_dir.components() { @@ -327,6 +371,7 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost } } + let events_dir = out_dir.join("events"); match fs::metadata(out_dir) { Ok(meta) if !meta.is_dir() => { return Err(RunCuratePostsError::InvalidOutDir { @@ -334,8 +379,23 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost detail: "path exists and is not a directory".to_string(), }); } - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Ok(_) => match fs::metadata(&events_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCuratePostsError::InvalidOutDir { + path: events_dir, + detail: "events output path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(source) => { + return Err(RunCuratePostsError::InspectOutDir { + path: events_dir, + source, + }); + } + }, + Err(err) if err.kind() == io::ErrorKind::NotFound => {} Err(source) => { return Err(RunCuratePostsError::InspectOutDir { path: out_dir.to_path_buf(), @@ -344,51 +404,89 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost } } - let events_dir = out_dir.join("events"); - match fs::metadata(&events_dir) { - Ok(meta) if !meta.is_dir() => { + let resolved_out = resolve_normalized_path(out_dir); + let resolved_events = resolve_normalized_path(&events_dir); + + for (label, input_path) in [ + ("ceo-posts", ceo_posts_path), + ("provider-mapping", provider_mapping_path), + ] { + let resolved_in = resolve_normalized_path(input_path); + if resolved_in == resolved_out + || resolved_in == resolved_events + || resolved_in.starts_with(&resolved_events) + { return Err(RunCuratePostsError::InvalidOutDir { - path: events_dir, - detail: "events output path exists and is not a directory".to_string(), - }); - } - Ok(_) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(source) => { - return Err(RunCuratePostsError::InspectOutDir { - path: events_dir, - source, + path: out_dir.to_path_buf(), + detail: format!( + "output directory would overlap {label} input '{}'", + input_path.display() + ), }); } } - let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir { - path: events_dir.clone(), - source, - })?; + Ok(()) +} - let mut existing_year_entry: Option = None; - for entry_res in entries { - let entry = entry_res.map_err(|source| RunCuratePostsError::InspectOutDir { - path: events_dir.clone(), - source, - })?; - let name = entry.file_name(); - if name.to_string_lossy().starts_with("year=") { - let candidate = entry.path(); - if existing_year_entry - .as_ref() - .is_none_or(|current| candidate < *current) +/// Checks each destination `year=YYYY` partition directory and its `part-posts.parquet` path +/// against all resolved input paths before publishing. +/// +/// Catches symlinked year directories (e.g. `/events/year=2024 -> /external/dir`) whose +/// resolved target lies outside `/events` and would otherwise let +/// `write_posts_events_dataset` overwrite an input located at `/external/dir/part-posts.parquet`. +fn validate_partition_outputs_and_inputs( + out_dir: &Path, + ceo_posts_path: &Path, + provider_mapping_path: &Path, + rows: &[EventsParquetRow], +) -> Result<(), RunCuratePostsError> { + if rows.is_empty() { + return Ok(()); + } + + let mut years = BTreeSet::new(); + for row in rows { + years.insert(partition_year_utc(row.ts_micros)); + } + + let resolved_inputs = [ + ( + "ceo-posts", + ceo_posts_path, + resolve_normalized_path(ceo_posts_path), + ), + ( + "provider-mapping", + provider_mapping_path, + resolve_normalized_path(provider_mapping_path), + ), + ]; + + let events_dir = out_dir.join("events"); + for year in years { + let year_dir = events_dir.join(format!("year={year:04}")); + let resolved_year_dir = resolve_normalized_path(&year_dir); + let resolved_part_via_dir = resolved_year_dir.join(POSTS_PART_FILE_NAME); + let resolved_part = resolve_normalized_path(&year_dir.join(POSTS_PART_FILE_NAME)); + + for (label, input_path, resolved_in) in &resolved_inputs { + if *resolved_in == resolved_year_dir + || *resolved_in == resolved_part_via_dir + || *resolved_in == resolved_part { - existing_year_entry = Some(candidate); + return Err(RunCuratePostsError::InvalidOutDir { + path: year_dir, + detail: format!( + "partition output '{}' would overlap {label} input '{}'", + resolved_part_via_dir.display(), + input_path.display() + ), + }); } } } - if let Some(path) = existing_year_entry { - return Err(RunCuratePostsError::EventsDatasetExists { path }); - } - Ok(()) } @@ -545,7 +643,7 @@ where F: FnOnce() -> Result, { let start = Instant::now(); - validate_out_dir_and_events_guard(out_dir)?; + validate_out_dir_and_inputs(out_dir, ceo_posts_path, provider_mapping_path)?; let decoded = decode_inputs_from_opener( provider_mapping_path, @@ -556,28 +654,37 @@ where open_posts, )?; - // Re-check output directory and clobber guard immediately before curating/writing. - validate_out_dir_and_events_guard(out_dir)?; - - let write_report = curate_and_write_posts( - out_dir, - decoded.posts, - mapping_source, - &decoded.mapping, - EventsWriteOptions::default(), - ) - .map_err(|source| RunCuratePostsError::CurateWrite { - out_dir: out_dir.to_path_buf(), - source, + let curated = curate_posts(decoded.posts, mapping_source, &decoded.mapping).map_err(|err| { + RunCuratePostsError::CurateWrite { + out_dir: out_dir.to_path_buf(), + source: CuratePostsWriteError::Curate(err), + } })?; + // Re-check output directory and per-year partition overlap immediately before writing. + validate_out_dir_and_inputs(out_dir, ceo_posts_path, provider_mapping_path)?; + validate_partition_outputs_and_inputs( + out_dir, + ceo_posts_path, + provider_mapping_path, + &curated.rows, + )?; + + let write_stats = + write_posts_events_dataset(out_dir, &curated.rows, EventsWriteOptions::default()).map_err( + |err| RunCuratePostsError::CurateWrite { + out_dir: out_dir.to_path_buf(), + source: CuratePostsWriteError::Parquet(err), + }, + )?; + Ok(CuratePostsRunReport { docs_framed: decoded.docs_framed, bytes_read: decoded.bytes_read, peak_chunk_bytes: decoded.peak_chunk_bytes, decode: decoded.decode, - curate_stats: write_report.curate_stats, - write_stats: write_report.write_stats, + curate_stats: curated.stats, + write_stats, elapsed_secs: start.elapsed().as_secs_f64(), }) } diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs index 7456672b..f08047cf 100644 --- a/tools/curate-etl/src/run_curate_posts_tests.rs +++ b/tools/curate-etl/src/run_curate_posts_tests.rs @@ -15,13 +15,16 @@ use crate::bson_ceo_posts::{ DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, }; use crate::curate_posts::{curate_posts, CuratePostsError, CuratePostsWriteError}; -use crate::parquet_events::EventsParquetRow; +use crate::parquet_events::{EventsParquetRow, EVENTS_PART_FILE_NAME, POSTS_PART_FILE_NAME}; use crate::parquet_posts::{ EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, }; use crate::posts::PostsError; use crate::provider_mapping::ProviderMappingRow; +use crate::run_curate_events::{ + run_curate_events, CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE, +}; use crate::split::ymd_to_epoch_days; static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); @@ -270,7 +273,7 @@ fn read_all_event_partitions(out_dir: &Path) -> Vec { let mut all = Vec::new(); for yd in year_dirs { all.extend(read_events_parquet_and_verify_zstd( - &yd.join("part.parquet"), + &yd.join(POSTS_PART_FILE_NAME), )); } all.sort_by(|a, b| { @@ -568,11 +571,13 @@ fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { assert_eq!(report_a.write_stats, report_b.write_stats); for year in ["year=2024", "year=2025"] { - let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a"); - let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b"); + let a = fs::read(out_a.join("events").join(year).join(POSTS_PART_FILE_NAME)) + .expect("read a"); + let b = fs::read(out_b.join("events").join(year).join(POSTS_PART_FILE_NAME)) + .expect("read b"); assert_eq!( a, b, - "reversed input must produce byte-identical {year}/part.parquet" + "reversed input must produce byte-identical {year}/{POSTS_PART_FILE_NAME}" ); } @@ -659,74 +664,171 @@ fn seconds_vs_millis_and_custom_fields_with_reader_work_end_to_end() { assert_eq!(rows_sec[0].known_at_micros, ed_sec * 1_000_000); } +fn make_filing_doc(key: &str, timefiled: &str, form_type: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), key); + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formType"), form_type); + doc.into_bytes() +} + +fn make_earning_doc(key: &str, report_date: &str, announce_time: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), key); + doc.append(cstr!("reportDate"), report_date); + doc.append(cstr!("announceTime"), announce_time); + doc.into_bytes() +} + +fn default_events_args( + qm_filings: PathBuf, + qm_earnings: PathBuf, + provider_mapping: PathBuf, + out_dir: PathBuf, +) -> CurateEventsArgs { + CurateEventsArgs { + qm_filings, + qm_earnings, + provider_mapping, + out_dir, + filings_key_field: "symbol".to_string(), + filings_timefiled_field: "timefiled".to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + earnings_key_field: "qmSearchCode".to_string(), + earnings_report_date_field: "reportDate".to_string(), + earnings_announce_time_field: "announceTime".to_string(), + earnings_fiscal_period_end_field: None, + earnings_actual_eps_field: None, + earnings_revenue_field: None, + mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), + } +} + #[test] -fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { - let dir = TempDirGuard::new("clobber"); +fn copublishes_with_curate_events_in_both_orders_and_preserves_sibling_bytes_on_rerun() { + let dir = TempDirGuard::new("copublish-both-orders"); let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + write_bytes( + &map_path, + b"ceo\tCEO_RY\t2020-01-01\t\t101\nqm\tRY:CA\t2020-01-01\t\t101\n", + ); let fields = CeoPostsFieldNames::default(); - let bson_path = dir.path().join("posts.bson"); + let posts_v1 = dir.path().join("posts_v1.bson"); write_bytes( - &bson_path, + &posts_v1, &make_post_doc( &fields, "CEO_RY", "sp-1", utc_ms(2024, 6, 15, 14, 0, 0), + Some(utc_ms(2024, 6, 15, 21, 0, 0)), None, + Some("u1"), + "v1 text", + ), + ); + let posts_v2 = dir.path().join("posts_v2.bson"); + write_bytes( + &posts_v2, + &make_post_doc( + &fields, + "CEO_RY", + "sp-2", + utc_ms(2024, 6, 16, 14, 0, 0), None, + Some("1"), None, - "hi", + "v2 wire", ), ); - // 1. Pre-existing events/year=2024/part.parquet with sentinel bytes - let out_a = dir.path().join("out_existing_parquet"); - let year_2024 = out_a.join("events/year=2024"); - fs::create_dir_all(&year_2024).unwrap(); - let sentinel_path = year_2024.join("part.parquet"); - let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-EVENTS-PARQUET".to_vec(); - write_bytes(&sentinel_path, &sentinel_bytes); + let filings_path = dir.path().join("filings.bson"); + write_bytes( + &filings_path, + &make_filing_doc("RY:CA", "2024-06-10T16:15:00 EDT", "8-K"), + ); + let earnings_path = dir.path().join("earnings.bson"); + write_bytes( + &earnings_path, + &make_earning_doc("RY:CA", "2024-06-12", "AMC"), + ); - let args_a = default_args( - bson_path.clone(), + // Order 1: curate-events first, then curate-posts, then re-run curate-posts. + let out_ef_first = dir.path().join("out_events_first"); + let ev_report = run_curate_events(&default_events_args( + filings_path.clone(), + earnings_path.clone(), map_path.clone(), - out_a.clone(), - CeoPostsTimestampUnit::Millis, - ); - let err = run_curate_posts(&args_a).unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::EventsDatasetExists { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("year=2024"), "expected year=2024 in {msg}"); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); - let entries: Vec<_> = fs::read_dir(out_a.join("events")) - .unwrap() - .map(|e| e.unwrap().file_name()) - .collect(); - assert_eq!(entries.len(), 1); + out_ef_first.clone(), + )) + .expect("run_curate_events"); + assert_eq!(ev_report.write_stats.rows_written, 2); - // 2. Pre-existing year=* directory without a Parquet file must also fail closed - let out_b = dir.path().join("out_empty_year_dir"); - let year_2025 = out_b.join("events/year=2025"); - fs::create_dir_all(&year_2025).unwrap(); - let args_b = default_args( - bson_path, - map_path, - out_b.clone(), + let events_part = out_ef_first + .join("events/year=2024") + .join(EVENTS_PART_FILE_NAME); + let posts_part = out_ef_first + .join("events/year=2024") + .join(POSTS_PART_FILE_NAME); + let events_bytes = fs::read(&events_part).unwrap(); + + let p1_report = run_curate_posts(&default_args( + posts_v1.clone(), + map_path.clone(), + out_ef_first.clone(), CeoPostsTimestampUnit::Millis, - ); - let err = run_curate_posts(&args_b).unwrap_err(); - assert!(matches!( - err, - RunCuratePostsError::EventsDatasetExists { .. } - )); - let msg = assert_single_line_err(&err); - assert!(msg.contains("year=2025"), "expected year=2025 in {msg}"); - assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); + )) + .expect("run_curate_posts alongside events"); + assert_report_invariants(&p1_report); + assert_eq!(p1_report.write_stats.rows_written, 1); + assert_eq!(fs::read(&events_part).unwrap(), events_bytes); + let post_rows_v1 = read_events_parquet_and_verify_zstd(&posts_part); + assert_eq!(post_rows_v1.len(), 1); + assert_eq!(post_rows_v1[0].kind.as_ref(), "ceo_post"); + + // Re-running curate-posts replaces part-posts.parquet and keeps part.parquet byte-identical. + let p2_report = run_curate_posts(&default_args( + posts_v2.clone(), + map_path.clone(), + out_ef_first.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("re-run curate_posts"); + assert_report_invariants(&p2_report); + assert_eq!(fs::read(&events_part).unwrap(), events_bytes); + let post_rows_v2 = read_events_parquet_and_verify_zstd(&posts_part); + assert_eq!(post_rows_v2.len(), 1); + assert_eq!(post_rows_v2[0].subtype, POST_SUBTYPE_NEWSWIRE); + + // Order 2: curate-posts first, then curate-events, verifying part-posts.parquet is untouched. + let out_posts_first = dir.path().join("out_posts_first"); + run_curate_posts(&default_args( + posts_v1, + map_path.clone(), + out_posts_first.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("run_curate_posts first"); + let pf_posts_part = out_posts_first + .join("events/year=2024") + .join(POSTS_PART_FILE_NAME); + let pf_events_part = out_posts_first + .join("events/year=2024") + .join(EVENTS_PART_FILE_NAME); + let pf_posts_bytes = fs::read(&pf_posts_part).unwrap(); + + run_curate_events(&default_events_args( + filings_path, + earnings_path, + map_path, + out_posts_first.clone(), + )) + .expect("run_curate_events after posts"); + assert_eq!(fs::read(&pf_posts_part).unwrap(), pf_posts_bytes); + assert_eq!(fs::read(&pf_events_part).unwrap(), events_bytes); } #[test] @@ -1161,29 +1263,6 @@ fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir() assert!(!out_unmapped.join("events").exists()); } -/// Reader that serves `bytes` and, on the first EOF, runs `on_eof` once (used to simulate another -/// publisher creating an `events/year=*` partition while the dump is still being decoded). -struct EofHookReader { - bytes: Vec, - pos: usize, - on_eof: Option, -} - -impl Read for EofHookReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.pos < self.bytes.len() { - let n = (self.bytes.len() - self.pos).min(buf.len()); - buf[..n].copy_from_slice(&self.bytes[self.pos..self.pos + n]); - self.pos += n; - return Ok(n); - } - if let Some(mut hook) = self.on_eof.take() { - hook(); - } - Ok(0) - } -} - fn sorted_names(p: &Path) -> Vec { let mut names: Vec = fs::read_dir(p) .expect("read dir") @@ -1194,12 +1273,10 @@ fn sorted_names(p: &Path) -> Vec { } #[test] -fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes() { - let dir = TempDirGuard::new("guard-recheck"); - let map_path = dir.path().join("mapping.tsv"); - write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); +fn input_path_overlap_with_out_dir_events_or_partition_target_fails_closed() { + let dir = TempDirGuard::new("input-overlap"); let fields = CeoPostsFieldNames::default(); - let doc = make_post_doc( + let valid_doc = make_post_doc( &fields, "CEO_RY", "sp-1", @@ -1210,46 +1287,80 @@ fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes "hi", ); - let out_dir = dir.path().join("out"); - let partition = out_dir.join("events").join("year=2024"); - let sentinel_path = partition.join("part.parquet"); - let sentinel = b"SENTINEL-CONCURRENT-FILINGS".to_vec(); - assert!( - !out_dir.exists(), - "first guard must see a fresh output root" - ); + // 1. ceo_posts inside /events/ + let out_a = dir.path().join("out_a"); + let events_a = out_a.join("events"); + fs::create_dir_all(&events_a).unwrap(); + let posts_inside_events = events_a.join("ceoPosts.bson"); + write_bytes(&posts_inside_events, &valid_doc); + let map_a = dir.path().join("map_a.tsv"); + write_bytes(&map_a, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); - let hook_partition = partition.clone(); - let hook_sentinel_path = sentinel_path.clone(); - let hook_sentinel = sentinel.clone(); - let err = run_curate_posts_with_reader( - &map_path, - DEFAULT_MAPPING_SOURCE, - &fields, + let err = run_curate_posts(&default_args( + posts_inside_events.clone(), + map_a.clone(), + out_a.clone(), CeoPostsTimestampUnit::Millis, - ( - Path::new("hooked.bson"), - EofHookReader { - bytes: doc, - pos: 0, - on_eof: Some(move || { - fs::create_dir_all(&hook_partition).expect("create concurrent partition"); - write_bytes(&hook_sentinel_path, &hook_sentinel); - }), - }, - ), - &out_dir, - ) + )) .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("ceo-posts"), "expected ceo-posts in {msg}"); + assert_eq!(fs::read(&posts_inside_events).unwrap(), valid_doc); + // 2. provider_mapping inside /events/year=2024/ + let out_b = dir.path().join("out_b"); + let year_b = out_b.join("events/year=2024"); + fs::create_dir_all(&year_b).unwrap(); + let map_inside_year = year_b.join("provider_mapping.tsv"); + write_bytes(&map_inside_year, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + let posts_b = dir.path().join("posts_b.bson"); + write_bytes(&posts_b, &valid_doc); + + let err = run_curate_posts(&default_args( + posts_b, + map_inside_year.clone(), + out_b, + CeoPostsTimestampUnit::Millis, + )) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + let msg = assert_single_line_err(&err); assert!( - matches!(&err, RunCuratePostsError::EventsDatasetExists { path } if path == &partition), - "expected EventsDatasetExists for {partition:?}, got {err:?}" + msg.contains("provider-mapping"), + "expected provider-mapping in {msg}" ); - assert_single_line_err(&err); - assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); - assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]); - assert_eq!(sorted_names(&partition), vec!["part.parquet"]); + assert_eq!( + fs::read(&map_inside_year).unwrap(), + b"ceo\tCEO_RY\t2020-01-01\t\t101\n" + ); + + // 3. Symlinked events/year=2024 pointing to an external directory containing ceo_posts named part-posts.parquet + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + + let ext_dir = dir.path().join("external"); + fs::create_dir_all(&ext_dir).unwrap(); + let ext_posts = ext_dir.join(POSTS_PART_FILE_NAME); + write_bytes(&ext_posts, &valid_doc); + + let out_c = dir.path().join("out_c"); + fs::create_dir_all(out_c.join("events")).unwrap(); + symlink(&ext_dir, out_c.join("events/year=2024")).unwrap(); + + let err = run_curate_posts(&default_args( + ext_posts.clone(), + map_a, + out_c, + CeoPostsTimestampUnit::Millis, + )) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("overlap"), "expected overlap detail in {msg}"); + assert_eq!(fs::read(&ext_posts).unwrap(), valid_doc); + } } #[test] @@ -1285,16 +1396,20 @@ fn events_dir_with_only_non_year_entries_is_published_and_non_year_entries_prese out_dir.clone(), CeoPostsTimestampUnit::Millis, )) - .expect("non-year entries must not trip the clobber guard"); + .expect("non-year entries must be preserved"); assert_report_invariants(&report); assert_eq!(report.write_stats.rows_written, 1); assert_eq!(fs::read(&readme).unwrap(), b"not a partition"); assert_eq!(sorted_names(&events_dir), vec!["README.txt", "year=2024"]); + assert_eq!( + sorted_names(&events_dir.join("year=2024")), + vec![POSTS_PART_FILE_NAME] + ); } #[test] -fn parent_dir_through_existing_components_still_hits_events_guard() { +fn parent_dir_through_existing_components_copublishes_alongside_part_parquet() { let dir = TempDirGuard::new("parent-existing"); let map_path = dir.path().join("mapping.tsv"); write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); @@ -1318,26 +1433,25 @@ fn parent_dir_through_existing_components_still_hits_events_guard() { let shared_partition = exports.join("shared/events/year=2024"); fs::create_dir_all(&shared_partition).unwrap(); fs::create_dir_all(exports.join("scratch")).unwrap(); - let sentinel_path = shared_partition.join("part.parquet"); + let sentinel_path = shared_partition.join(EVENTS_PART_FILE_NAME); write_bytes(&sentinel_path, b"SENTINEL"); - // `scratch` exists, so `..` resolves consistently and the guard must inspect `shared`. + // `scratch` exists, so `..` resolves cleanly into `shared` and co-publishes part-posts.parquet. let out = exports.join("scratch").join("..").join("shared"); - let err = run_curate_posts(&default_args( + let report = run_curate_posts(&default_args( bson_path, map_path, out, CeoPostsTimestampUnit::Millis, )) - .unwrap_err(); - assert!( - matches!(err, RunCuratePostsError::EventsDatasetExists { .. }), - "got {err:?}" - ); - assert_single_line_err(&err); + .expect("copublish through existing parent component"); + assert_report_invariants(&report); + assert_eq!(report.write_stats.rows_written, 1); assert_eq!(fs::read(&sentinel_path).unwrap(), b"SENTINEL"); - assert_eq!(sorted_names(&exports), vec!["scratch", "shared"]); - assert!(sorted_names(&exports.join("scratch")).is_empty()); + assert_eq!( + sorted_names(&shared_partition), + vec![POSTS_PART_FILE_NAME, EVENTS_PART_FILE_NAME] + ); } #[test] diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m.rs b/tools/curate-etl/src/run_curate_qm_bars_1m.rs index 0d6ec861..ca0c3d80 100644 --- a/tools/curate-etl/src/run_curate_qm_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_qm_bars_1m.rs @@ -59,18 +59,20 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::time::Instant; -use crate::bars_1m::EodIntradayBar; +use crate::bars_1m::BARS_1M_SOURCE_QM; +use crate::bars_1m_sort::{ + Bars1mExternalSortError, Bars1mExternalSorter, Bars1mSortConfig, ExternalSortMetrics, +}; use crate::bson_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats}; use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError}; -use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m; use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions}; use crate::parquet_bars::RollbackFailure; use crate::parquet_publish::{next_run_id, StagingFileGuard}; use crate::provider_mapping::ProviderMappingTable; use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; use crate::run_curate_bars_1m::{ - add_curate_bars_1m_stats, create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, + create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, }; use crate::run_curate_fx_1m::cleanup_armed_staged_shards; @@ -286,13 +288,23 @@ fn load_provider_mapping_table( }) } +fn map_sort_error(err: Bars1mExternalSortError) -> RunCurateQmBars1mError { + match err { + Bars1mExternalSortError::Io { path, source } => RunCurateQmBars1mError::Io { path, source }, + Bars1mExternalSortError::Ilp(err) => { + RunCurateQmBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(err)) + } + } +} + fn stream_qm_intraday_chunks_to_writer( args: &CurateQmBars1mArgs, mapping: &ProviderMappingTable, intraday: R, mut writer: IlpShardedWriter, + sort_config: Bars1mSortConfig, start: Instant, -) -> Result +) -> Result<(CurateQmBars1mRunReport, ExternalSortMetrics), RunCurateQmBars1mError> where R: io::Read, W: Write + Send, @@ -306,10 +318,12 @@ where )?; let mut intraday_decode = BsonQmIntradayDecodeStats::default(); - let mut curate_stats = CurateBars1mStats::default(); let mut chunks: usize = 0; let mut max_rows_per_chunk: usize = 0; - let mut rows_written: usize = 0; + + // Bounded-memory external sort/merge resolves same-key duplicates and cross-source listing + // collisions globally across BSON chunks without retaining all rows in RAM. + let mut sorter = Bars1mExternalSorter::new(mapping, &args.mapping_source, sort_config); while let Some(chunk) = reader @@ -320,51 +334,66 @@ where source, })? { - let mut chunk_bars: Vec> = Vec::new(); + let mut chunk_rows = 0usize; + let mut spill_err: Option = None; + let chunk_decode = decode_qm_intraday_buffer( chunk.bytes, |raw| { - chunk_bars.push(raw.into_eod_intraday_bar(|key, _| key)); + if spill_err.is_some() { + return; + } + chunk_rows += 1; + if let Err(err) = sorter.push_raw( + raw.qm_search_code, + raw.ts, + raw.open, + raw.high, + raw.low, + raw.close, + raw.volume, + ) { + spill_err = Some(err); + } }, |_local_offset, _err| {}, ); + if let Some(err) = spill_err { + return Err(map_sort_error(err)); + } intraday_decode.merge(&chunk_decode); chunks += 1; - let chunk_len = chunk_bars.len(); - if chunk_len > max_rows_per_chunk { - max_rows_per_chunk = chunk_len; + if chunk_rows > max_rows_per_chunk { + max_rows_per_chunk = chunk_rows; } - - let write_report = curate_and_write_qm_bars_1m( - chunk_bars, - mapping, - &args.mapping_source, - &mut writer, - args.known_at_micros, - ) - .map_err(RunCurateQmBars1mError::CurateWrite)?; - - add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); - rows_written += write_report.rows_written; } let intraday_docs_framed = reader.docs_framed(); let intraday_bytes_read = reader.bytes_read(); + drop(reader); + + let outcome = sorter + .finish_and_write(None, BARS_1M_SOURCE_QM, &mut writer, args.known_at_micros) + .map_err(map_sort_error)?; + let write_report = outcome.write_report; let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?; - Ok(CurateQmBars1mRunReport { - intraday_docs_framed, - intraday_bytes_read, - intraday_decode, - chunks, - max_rows_per_chunk, - curate_stats, - rows_written, - ilp_stats, - shard_count: args.shard_count, - elapsed_secs: start.elapsed().as_secs_f64(), - }) + Ok(( + CurateQmBars1mRunReport { + intraday_docs_framed, + intraday_bytes_read, + intraday_decode, + chunks, + max_rows_per_chunk, + curate_stats: write_report.curate_stats, + rows_written: write_report.rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }, + outcome.metrics, + )) } /// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary @@ -373,9 +402,9 @@ where /// Validates `args` (rejecting blank `mapping_source` first, then `shard_count`, stream options, /// and ILP options) and loads `provider_mapping.tsv` from `args.provider_mapping_path` before /// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through -/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once -/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once -/// after clean EOF. +/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`] into the bounded-memory +/// external sorter/merger without split un-adjustment, and calls [`IlpShardedWriter::finish`] +/// exactly once after clean EOF. pub fn run_curate_qm_bars_1m_with_readers( args: &CurateQmBars1mArgs, intraday: R, @@ -398,7 +427,10 @@ where let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?; - stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) + let sort_config = Bars1mSortConfig::new(None, QM_BARS_1M_SHARD_PREFIX); + let (report, _metrics) = + stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, sort_config, start)?; + Ok(report) } fn fail_with_staging_cleanup( @@ -493,9 +525,16 @@ where )); } }; - let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) - { - Ok(report) => report, + let sort_config = Bars1mSortConfig::new(Some(args.out_dir.clone()), QM_BARS_1M_SHARD_PREFIX); + let (report, _metrics) = match stream_qm_intraday_chunks_to_writer( + args, + &mapping, + intraday, + writer, + sort_config, + start, + ) { + Ok(pair) => pair, Err(err) => { return Err(fail_with_staging_cleanup( err, @@ -544,6 +583,112 @@ where ) } +/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary raw-BSON +/// [`io::Read`] stream (such as a read-only MongoDB cursor), running full directory preflight, +/// exclusive `.tmp` staging, atomic `hard_link` publication to `/bars_1m_qm.shard-.ilp`, +/// and rollback cleanup on failure with zero intermediate `.bson` scratch files. +pub fn run_curate_qm_bars_1m_from_reader_to_dir( + args: &CurateQmBars1mArgs, + intraday: R, +) -> Result +where + R: io::Read, +{ + run_curate_qm_bars_1m_to_dir_with_hooks( + args, + intraday, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + +#[cfg(test)] +pub(crate) fn run_curate_qm_bars_1m_from_reader_to_dir_with_sort_config( + args: &CurateQmBars1mArgs, + intraday: R, + sort_config: Bars1mSortConfig, +) -> Result<(CurateQmBars1mRunReport, ExternalSortMetrics), RunCurateQmBars1mError> +where + R: io::Read, +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateQmBars1mError::Io { + path: args.out_dir.clone(), + source, + })?; + + let run_id = next_run_id(); + let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); + let mut sinks: Vec = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + QM_BARS_1M_SHARD_PREFIX, + shard_idx, + &run_id, + ) { + Ok(pair) => pair, + Err(err) => { + drop(sinks); + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut |path| fs::remove_file(path), + )); + } + }; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(SyncedBufFile::new(file)); + } + + let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { + Ok(writer) => writer, + Err(err) => { + return Err(fail_with_staging_cleanup( + RunCurateQmBars1mError::Ilp(err), + &mut staged, + &mut |path| fs::remove_file(path), + )); + } + }; + let (report, metrics) = match stream_qm_intraday_chunks_to_writer( + args, + &mapping, + intraday, + writer, + sort_config, + start, + ) { + Ok(pair) => pair, + Err(err) => { + return Err(fail_with_staging_cleanup( + err, + &mut staged, + &mut |path| fs::remove_file(path), + )); + } + }; + + if let Err(err) = publish_staged_shards_for_table( + &args.out_dir, + QM_BARS_1M_SHARD_PREFIX, + &mut staged, + |_shard_idx, _final_path| {}, + ) { + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut |path| fs::remove_file(path), + )); + } + Ok((report, metrics)) +} + /// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing /// exactly `args.shard_count` QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`). pub fn run_curate_qm_bars_1m( @@ -558,12 +703,7 @@ pub fn run_curate_qm_bars_1m( source, })?; - run_curate_qm_bars_1m_to_dir_with_hooks( - args, - intraday_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) + run_curate_qm_bars_1m_from_reader_to_dir(args, intraday_file) } /// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary. diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs index 39245692..ea125100 100644 --- a/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs +++ b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs @@ -11,6 +11,7 @@ use bson::DateTime as BsonDateTime; use super::*; use crate::bars_1m::{IntradaySession, BARS_1M_SOURCE_QM}; use crate::bson_stream::MIN_BSON_DOC_BYTES; +use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m; use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; use crate::run_curate_bars_1m::tests::TempDirGuard; use crate::shorts::et_to_utc_micros; @@ -800,8 +801,8 @@ fn conservation_counts_unmapped_semantic_decode_errors_collisions_and_cross_chun assert_eq!(report.curate_stats.post_rows_out, 1); assert_eq!(report.rows_written, 3); - // Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks emits both - // rows (relying on QuestDB DEDUP UPSERT KEYS(ts, listing_id)) and sums listings_out/keys_out. + // Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks collapses + // globally before ILP publication so output is invariant to chunk boundaries. let dup_doc = make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0); let doc_len = dup_doc.as_bytes().len(); let cross_chunk_bytes = concat_docs(&[dup_doc.clone(), dup_doc]); @@ -827,12 +828,13 @@ fn conservation_counts_unmapped_semantic_decode_errors_collisions_and_cross_chun .expect("cross-chunk duplicate run should succeed"); assert_report_conservation(&cross_report); assert_eq!(cross_report.chunks, 2); - assert_eq!(cross_report.rows_written, 2); - assert_eq!(cross_report.curate_stats.listings_out, 2); - assert_eq!(cross_report.curate_stats.builder.keys_out, 2); + assert_eq!(cross_report.rows_written, 1); + assert_eq!(cross_report.curate_stats.builder.duplicate_collapsed, 1); + assert_eq!(cross_report.curate_stats.listings_out, 1); + assert_eq!(cross_report.curate_stats.builder.keys_out, 1); let emitted = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); - assert_eq!(emitted.len(), 2); - assert_eq!(emitted[0], emitted[1]); + assert_eq!(emitted.len(), 1); + assert_eq!(emitted[0].listing_id, 500); } #[test] @@ -1537,7 +1539,7 @@ fn file_mode_single_chunk_shards_match_pure_stage_byte_for_byte() { } #[test] -fn file_mode_multi_chunk_shards_match_pure_stage_applied_per_document_chunk() { +fn file_mode_multi_chunk_shards_match_global_pure_stage_byte_for_byte() { let dir = TempDirGuard::new("qm-bars1m-qa-chunk-bytes"); let mapping_path = write_mapping_tsv( dir.path(), @@ -1584,14 +1586,17 @@ fn file_mode_multi_chunk_shards_match_pure_stage_applied_per_document_chunk() { assert_eq!(report.chunks, 6); assert_eq!(report.max_rows_per_chunk, 1); assert_eq!( - report.curate_stats.listings_out, 6, - "per-chunk sum, not distinct" + report.curate_stats.listings_out, 2, + "global distinct listings across chunks" + ); + assert_eq!( + report.curate_stats.builder.keys_out, 2, + "global distinct keys across chunks" ); let mapping = load_provider_mapping_table(&mapping_path).unwrap(); - let chunks: Vec<&[u8]> = bytes.chunks(doc_len).collect(); let expected = pure_stage_shard_bytes( - &chunks, + &[bytes.as_slice()], &mapping, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, 2, @@ -1744,3 +1749,109 @@ fn doc_larger_than_chunk_capacity_succeeds_and_doc_over_max_doc_bytes_fails_clea ); assert!(list_dir_names(&out_bad).is_empty()); } + +#[test] +fn qm_external_sort_multi_run_matches_single_run_byte_for_byte_across_reordered_collisions() { + let dir = TempDirGuard::new("qmbars1m-ext-sort-parity"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tA1:US\t2020-01-01\t\t10", + "qm\tA2:US\t2020-01-01\t\t10", + "qm\tB:US\t2020-01-01\t\t20", + ], + ); + + let t1 = et_ts_millis(2024, 6, 7, 9, 30); + let t2 = et_ts_millis(2024, 6, 7, 9, 31); + let t3 = et_ts_millis(2024, 6, 7, 9, 32); + let t4 = et_ts_millis(2024, 6, 7, 9, 33); + + let docs = vec![ + make_qm_intraday_doc("A1:US", t1, 50.0, 51.0, 49.0, 50.5, 200.0), + make_qm_intraday_doc("A1:US", t1, 50.0, 51.0, 49.0, 50.5, 200.0), + make_qm_intraday_doc("A2:US", t1, 50.0, 51.0, 49.0, 50.5, 200.0), + make_qm_intraday_doc("A1:US", t2, 51.0, 52.0, 50.0, 51.5, 100.0), + make_qm_intraday_doc("A2:US", t2, 51.0, 52.0, 50.0, 51.75, 100.0), + make_qm_intraday_doc("B:US", t3, 20.0, 21.0, 19.0, 20.5, 50.0), + make_qm_intraday_doc("B:US", t3, 20.0, 21.0, 19.0, 20.6, 50.0), + make_qm_intraday_doc("B:US", t4, 21.0, 22.0, 20.0, 21.5, 75.0), + make_qm_intraday_doc("UNMAPPED:US", t1, 5.0, 6.0, 4.0, 5.5, 10.0), + ]; + + let canonical_bytes = concat_docs(&docs); + let mut reversed_docs = docs.clone(); + reversed_docs.reverse(); + let reordered_bytes = concat_docs(&reversed_docs); + + let out_ref = dir.path().join("out-ref"); + let out_bounded = dir.path().join("out-bounded"); + let (ref_report, ref_metrics) = run_curate_qm_bars_1m_from_reader_to_dir_with_sort_config( + &make_args( + dir.path().join("qmIntraday.bson"), + mapping_path.clone(), + out_ref.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ), + Cursor::new(&canonical_bytes), + Bars1mSortConfig { + spill_dir: Some(out_ref.clone()), + spill_prefix: QM_BARS_1M_SHARD_PREFIX, + max_run_rows: 10_000, + max_merge_fan_in: 64, + }, + ) + .expect("single-run QM reference"); + assert_report_conservation(&ref_report); + assert_eq!(ref_metrics.runs_spilled, 0); + + let (bounded_report, bounded_metrics) = + run_curate_qm_bars_1m_from_reader_to_dir_with_sort_config( + &make_args( + dir.path().join("qmIntraday.bson"), + mapping_path, + out_bounded.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + 1_750_000_000_000_000, + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: 1024 * 1024, + }, + ), + Cursor::new(&reordered_bytes), + Bars1mSortConfig { + spill_dir: Some(out_bounded.clone()), + spill_prefix: QM_BARS_1M_SHARD_PREFIX, + max_run_rows: 2, + max_merge_fan_in: 2, + }, + ) + .expect("bounded multi-run QM external sort"); + assert_report_conservation(&bounded_report); + assert!(bounded_metrics.peak_buffer_rows <= 2); + assert!(bounded_metrics.runs_spilled >= 4); + assert!(bounded_metrics.merge_passes >= 2); + + assert_eq!(bounded_report.curate_stats, ref_report.curate_stats); + assert_eq!(bounded_report.rows_written, ref_report.rows_written); + assert_eq!(bounded_report.ilp_stats, ref_report.ilp_stats); + assert_eq!(bounded_report.rows_written, 2); + + let expected_names = vec![ + "bars_1m_qm.shard-00.ilp".to_string(), + "bars_1m_qm.shard-01.ilp".to_string(), + ]; + assert_eq!(list_dir_names(&out_ref), expected_names); + assert_eq!(list_dir_names(&out_bounded), expected_names); + for name in &expected_names { + assert_eq!( + fs::read(out_bounded.join(name)).unwrap(), + fs::read(out_ref.join(name)).unwrap(), + "QM shard {name} must match byte-for-byte across external sort runs" + ); + } +} diff --git a/tools/curate-etl/src/run_mongo.rs b/tools/curate-etl/src/run_mongo.rs index b36af63e..1af14f9c 100644 --- a/tools/curate-etl/src/run_mongo.rs +++ b/tools/curate-etl/src/run_mongo.rs @@ -1,18 +1,22 @@ -//! Direct read-only MongoDB streaming runners for all six M1 `curate-*` CLI commands. +//! Direct read-only MongoDB streaming runners for all M1 and M2 `curate-*` CLI commands. //! //! Uses [`ReadOnlyMongoClient`] (constructed strictly from [`crate::ValidatedReadOnlyMongoUri`]) //! to open zero-copy raw-BSON cursors over allowlisted [`SourceCollection`]s and feeds them -//! directly into the shared `run_curate_*_with_readers` pipelines with zero intermediate `.bson` +//! directly into the shared `run_curate_*` reader pipelines with zero intermediate `.bson` //! scratch files. use std::collections::BTreeSet; use std::error::Error; use std::fmt; +use std::io; use std::path::{Path, PathBuf}; +use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit}; use crate::bson_ceo_shorts::CeoShortsFieldNames; use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames}; +use crate::bson_stream::BsonStreamOptions; use crate::curate_adj::AdjPointInTimeFence; +use crate::ilp::IlpWriterOptions; use crate::mongo_stream::{ MongoCliOptions, MongoReadSpec, MongoStreamError, ReadOnlyMongoClient, SourceCollection, }; @@ -23,6 +27,10 @@ use crate::run_curate_bars::{ load_provider_mapping_tsv, run_curate_bars_1d_with_readers, CurateBars1dRunReport, RunCurateBarsError, }; +use crate::run_curate_bars_1m::{ + run_curate_bars_1m_from_readers_to_dir, CurateBars1mArgs, CurateBars1mRunReport, + RunCurateBars1mError, +}; use crate::run_curate_corporate_actions::{ run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport, RunCurateCorporateActionsError, @@ -30,9 +38,27 @@ use crate::run_curate_corporate_actions::{ use crate::run_curate_events::{ run_curate_events_with_readers, CurateEventsRunReport, RunCurateEventsError, }; +use crate::run_curate_fundamentals::{ + run_curate_fundamentals_with_optional_old_readers, CurateFundamentalsArgs, + CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, RunCurateFundamentalsError, +}; use crate::run_curate_fx::{ run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE, }; +use crate::run_curate_fx_1m::{ + run_curate_fx_1m_from_reader_to_dir, CurateFx1mArgs, CurateFx1mRunReport, RunCurateFx1mError, +}; +use crate::run_curate_macro::{ + load_macro_series_map_file, run_curate_macro_from_reader, run_curate_macro_with_parsed_map, + CurateMacroRunReport, RunCurateMacroError, +}; +use crate::run_curate_posts::{ + run_curate_posts_with_reader, CuratePostsRunReport, RunCuratePostsError, +}; +use crate::run_curate_qm_bars_1m::{ + run_curate_qm_bars_1m_from_reader_to_dir, CurateQmBars1mArgs, CurateQmBars1mRunReport, + RunCurateQmBars1mError, +}; use crate::run_curate_shorts::{ run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError, }; @@ -47,6 +73,12 @@ pub enum RunMongoCurateError { Fx(RunCurateFxError), Shorts(RunCurateShortsError), Events(RunCurateEventsError), + Fundamentals(RunCurateFundamentalsError), + Posts(RunCuratePostsError), + Macro(RunCurateMacroError), + Bars1m(RunCurateBars1mError), + QmBars1m(RunCurateQmBars1mError), + Fx1m(RunCurateFx1mError), } impl fmt::Display for RunMongoCurateError { @@ -59,6 +91,12 @@ impl fmt::Display for RunMongoCurateError { Self::Fx(e) => write!(f, "{e}"), Self::Shorts(e) => write!(f, "{e}"), Self::Events(e) => write!(f, "{e}"), + Self::Fundamentals(e) => write!(f, "{e}"), + Self::Posts(e) => write!(f, "{e}"), + Self::Macro(e) => write!(f, "{e}"), + Self::Bars1m(e) => write!(f, "{e}"), + Self::QmBars1m(e) => write!(f, "{e}"), + Self::Fx1m(e) => write!(f, "{e}"), } } } @@ -73,6 +111,12 @@ impl Error for RunMongoCurateError { Self::Fx(e) => Some(e), Self::Shorts(e) => Some(e), Self::Events(e) => Some(e), + Self::Fundamentals(e) => Some(e), + Self::Posts(e) => Some(e), + Self::Macro(e) => Some(e), + Self::Bars1m(e) => Some(e), + Self::QmBars1m(e) => Some(e), + Self::Fx1m(e) => Some(e), } } } @@ -150,6 +194,175 @@ pub struct CurateEventsMongoArgs { pub mapping_source: String, } +/// Parsed arguments for `curate-fundamentals --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFundamentalsMongoArgs { + pub mongo: MongoCliOptions, + pub with_qm_financials_old: bool, + pub provider_mapping: PathBuf, + pub listing_venues: PathBuf, + pub out_dir: PathBuf, + pub financials_key_field: String, + pub financials_period_end_field: String, + pub financials_report_date_field: String, + pub financials_report_period_field: String, + pub financials_currency_field: String, + pub financials_revenue_field: Option, + pub financials_net_income_field: Option, + pub financials_operating_cash_flow_field: Option, + pub financials_total_assets_field: Option, + pub financials_total_equity_field: Option, + pub financials_shares_outstanding_field: Option, + pub fiscal_period: CurateFundamentalsFiscalPeriod, + pub filings_key_field: String, + pub filings_timefiled_field: String, + pub filings_form_type_field: String, + pub filings_filing_id_field: Option, + pub filings_url_field: Option, + pub mapping_source: String, + pub k: usize, +} + +impl CurateFundamentalsMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateFundamentalsArgs { + CurateFundamentalsArgs { + qm_financials: mongo_virtual_path(SourceCollection::QmFinancials), + qm_financials_old: self + .with_qm_financials_old + .then(|| mongo_virtual_path(SourceCollection::QmFinancialsOld)), + qm_filings: mongo_virtual_path(SourceCollection::QmFilings), + provider_mapping: self.provider_mapping.clone(), + listing_venues: self.listing_venues.clone(), + out_dir: self.out_dir.clone(), + financials_key_field: self.financials_key_field.clone(), + financials_period_end_field: self.financials_period_end_field.clone(), + financials_report_date_field: self.financials_report_date_field.clone(), + financials_report_period_field: self.financials_report_period_field.clone(), + financials_currency_field: self.financials_currency_field.clone(), + financials_revenue_field: self.financials_revenue_field.clone(), + financials_net_income_field: self.financials_net_income_field.clone(), + financials_operating_cash_flow_field: self + .financials_operating_cash_flow_field + .clone(), + financials_total_assets_field: self.financials_total_assets_field.clone(), + financials_total_equity_field: self.financials_total_equity_field.clone(), + financials_shares_outstanding_field: self.financials_shares_outstanding_field.clone(), + fiscal_period: self.fiscal_period.clone(), + filings_key_field: self.filings_key_field.clone(), + filings_timefiled_field: self.filings_timefiled_field.clone(), + filings_form_type_field: self.filings_form_type_field.clone(), + filings_filing_id_field: self.filings_filing_id_field.clone(), + filings_url_field: self.filings_url_field.clone(), + mapping_source: self.mapping_source.clone(), + k: self.k, + } + } +} + +/// Parsed arguments for `curate-posts --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsMongoArgs { + pub mongo: MongoCliOptions, + pub provider_mapping: PathBuf, + pub out_dir: PathBuf, + pub timestamp_unit: CeoPostsTimestampUnit, + pub key_field: String, + pub spiel_id_field: String, + pub timestamp_field: String, + pub edited_field: String, + pub bot_field: String, + pub user_id_field: String, + pub text_field: String, + pub mapping_source: String, +} + +/// Parsed arguments for `curate-macro --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateMacroMongoArgs { + pub mongo: MongoCliOptions, + pub series_map: PathBuf, + pub out_dir: PathBuf, +} + +/// Parsed arguments for `curate-bars-1m --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateBars1mMongoArgs { + pub mongo: MongoCliOptions, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +impl CurateBars1mMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateBars1mArgs { + CurateBars1mArgs { + intraday_path: mongo_virtual_path(SourceCollection::EodIntraday1M), + splits_path: mongo_virtual_path(SourceCollection::QmSplits), + provider_mapping_path: self.provider_mapping_path.clone(), + out_dir: self.out_dir.clone(), + mapping_source: self.mapping_source.clone(), + shard_count: self.shard_count, + known_at_micros: self.known_at_micros, + stream_options: self.stream_options, + ilp_options: self.ilp_options, + } + } +} + +/// Parsed arguments for `curate-qm-bars-1m --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateQmBars1mMongoArgs { + pub mongo: MongoCliOptions, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +impl CurateQmBars1mMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateQmBars1mArgs { + CurateQmBars1mArgs { + intraday_path: mongo_virtual_path(SourceCollection::QmIntraday), + provider_mapping_path: self.provider_mapping_path.clone(), + out_dir: self.out_dir.clone(), + mapping_source: self.mapping_source.clone(), + shard_count: self.shard_count, + known_at_micros: self.known_at_micros, + stream_options: self.stream_options, + ilp_options: self.ilp_options, + } + } +} + +/// Parsed arguments for `curate-fx-1m --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFx1mMongoArgs { + pub mongo: MongoCliOptions, + pub out_dir: PathBuf, + pub shard_count: usize, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +impl CurateFx1mMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateFx1mArgs { + CurateFx1mArgs { + intraday_path: mongo_virtual_path(SourceCollection::EodIntraday1M), + out_dir: self.out_dir.clone(), + shard_count: self.shard_count, + stream_options: self.stream_options, + ilp_options: self.ilp_options, + } + } +} + fn mongo_virtual_path(collection: SourceCollection) -> PathBuf { PathBuf::from(format!("mongodb://{}", collection.as_str())) } @@ -165,6 +378,20 @@ fn connect_and_validate_specs( mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo) } +fn with_mongo_client( + mongo: &MongoCliOptions, + checks: &[(SourceCollection, MongoReadSpec)], + f: F, +) -> Result +where + F: FnOnce(&ReadOnlyMongoClient) -> Result, +{ + let client = connect_and_validate_specs(mongo, checks)?; + let result = f(&client); + client.shutdown(); + result +} + fn unique_mapping_keys_for_source( provider_mapping_path: &Path, source: &str, @@ -496,8 +723,326 @@ pub fn run_curate_events_mongo( result } +pub(crate) fn fundamentals_read_specs( + args: &CurateFundamentalsMongoArgs, +) -> (MongoReadSpec, Option, MongoReadSpec) { + let fin_spec = args + .mongo + .to_read_spec_for_collection(SourceCollection::QmFinancials, None, true); + let fin_old_spec = args.with_qm_financials_old.then(|| { + args.mongo + .to_read_spec_for_collection(SourceCollection::QmFinancialsOld, None, true) + }); + let filings_spec = MongoReadSpec { + batch_size: args.mongo.batch_size, + ..MongoReadSpec::default() + }; + (fin_spec, fin_old_spec, filings_spec) +} + +pub(crate) fn run_curate_fundamentals_mongo_with_readers( + args: &CurateFundamentalsMongoArgs, + financials_reader: RF, + financials_old_reader: Option, + filings_reader: RL, +) -> Result { + let file_args = args.to_file_args(); + run_curate_fundamentals_with_optional_old_readers( + &file_args, + financials_reader, + financials_old_reader, + filings_reader, + ) + .map_err(RunMongoCurateError::Fundamentals) +} + +/// Streams `qmFinancials`, optional `qmFinancials-old`, and `qmFilings` directly from read-only +/// MongoDB into `fundamentals_pit/year=YYYY/part.parquet`. +/// +/// `qmFilings` is always read without date-range or `--limit` caps so retained financial +/// observations (including restatements) never lose their matching filing timestamps when +/// `--limit` samples `qmFinancials` / `qmFinancials-old`. +pub fn run_curate_fundamentals_mongo( + args: &CurateFundamentalsMongoArgs, +) -> Result { + let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(args); + let mut checks = vec![ + (SourceCollection::QmFinancials, fin_spec.clone()), + (SourceCollection::QmFilings, filings_spec.clone()), + ]; + if let Some(old_spec) = &fin_old_spec { + checks.push((SourceCollection::QmFinancialsOld, old_spec.clone())); + } + with_mongo_client(&args.mongo, &checks, |client| { + let fin_reader = client + .open_raw_cursor(SourceCollection::QmFinancials, &fin_spec) + .map_err(RunMongoCurateError::Mongo)?; + let fin_old_reader = if let Some(old_spec) = &fin_old_spec { + Some( + client + .open_raw_cursor(SourceCollection::QmFinancialsOld, old_spec) + .map_err(RunMongoCurateError::Mongo)?, + ) + } else { + None + }; + let filings_reader = client + .open_raw_cursor(SourceCollection::QmFilings, &filings_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_fundamentals_mongo_with_readers(args, fin_reader, fin_old_reader, filings_reader) + }) +} + +pub(crate) fn posts_read_spec(args: &CuratePostsMongoArgs) -> MongoReadSpec { + args.mongo + .to_read_spec_for_collection(SourceCollection::CeoPosts, None, true) +} + +pub(crate) fn run_curate_posts_mongo_with_reader( + args: &CuratePostsMongoArgs, + posts_reader: R, +) -> Result { + let fields = CeoPostsFieldNames { + key: args.key_field.as_str(), + spiel_id: args.spiel_id_field.as_str(), + timestamp: args.timestamp_field.as_str(), + edited: args.edited_field.as_str(), + bot: args.bot_field.as_str(), + user_id: args.user_id_field.as_str(), + text: args.text_field.as_str(), + }; + let posts_path = mongo_virtual_path(SourceCollection::CeoPosts); + run_curate_posts_with_reader( + &args.provider_mapping, + &args.mapping_source, + &fields, + args.timestamp_unit, + (&posts_path, posts_reader), + &args.out_dir, + ) + .map_err(RunMongoCurateError::Posts) +} + +/// Streams `ceoPosts` directly from read-only MongoDB into `events/year=YYYY/part-posts.parquet`. +pub fn run_curate_posts_mongo( + args: &CuratePostsMongoArgs, +) -> Result { + let posts_spec = posts_read_spec(args); + with_mongo_client( + &args.mongo, + &[(SourceCollection::CeoPosts, posts_spec.clone())], + |client| { + let posts_reader = client + .open_raw_cursor(SourceCollection::CeoPosts, &posts_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_posts_mongo_with_reader(args, posts_reader) + }, + ) +} + +pub(crate) fn macro_read_spec(args: &CurateMacroMongoArgs) -> MongoReadSpec { + args.mongo + .to_read_spec_for_collection(SourceCollection::TeData, None, true) +} + +pub(crate) fn run_curate_macro_mongo_with_reader( + args: &CurateMacroMongoArgs, + te_data_reader: R, +) -> Result { + let te_path = mongo_virtual_path(SourceCollection::TeData); + run_curate_macro_from_reader(&te_path, te_data_reader, &args.series_map, &args.out_dir) + .map_err(RunMongoCurateError::Macro) +} + +/// Streams `teData` directly from read-only MongoDB alongside caller-owned `series_map.tsv` +/// into `macro/part.parquet`. +pub fn run_curate_macro_mongo( + args: &CurateMacroMongoArgs, +) -> Result { + let te_spec = macro_read_spec(args); + with_mongo_client( + &args.mongo, + &[(SourceCollection::TeData, te_spec.clone())], + |client| { + let map = load_macro_series_map_file(&args.series_map) + .map_err(RunMongoCurateError::Macro)?; + let te_reader = client + .open_raw_cursor(SourceCollection::TeData, &te_spec) + .map_err(RunMongoCurateError::Mongo)?; + let te_path = mongo_virtual_path(SourceCollection::TeData); + run_curate_macro_with_parsed_map(&te_path, te_reader, &map, &args.out_dir) + .map_err(RunMongoCurateError::Macro) + }, + ) +} + +pub(crate) fn bars_1m_read_specs(args: &CurateBars1mMongoArgs) -> (MongoReadSpec, MongoReadSpec) { + let splits_spec = MongoReadSpec { + batch_size: args.mongo.batch_size, + ..MongoReadSpec::default() + }; + let intraday_spec = + args.mongo + .to_read_spec_for_collection(SourceCollection::EodIntraday1M, None, true); + (splits_spec, intraday_spec) +} + +pub(crate) fn run_curate_bars_1m_mongo_with_readers( + args: &CurateBars1mMongoArgs, + intraday_reader: RI, + splits_reader: RS, +) -> Result { + let file_args = args.to_file_args(); + run_curate_bars_1m_from_readers_to_dir(&file_args, intraday_reader, splits_reader) + .map_err(RunMongoCurateError::Bars1m) +} + +/// Streams `qmSplits` and `eodIntraday1M` directly from read-only MongoDB into +/// `/bars_1m.shard-.ilp`. +/// +/// `qmSplits` is always read without a date-range filter so post-bar cumulative split factors +/// remain exact. When `--limit` is not set, `eodIntraday1M` is streamed in indexed `$in` key +/// chunks (`250` keys/chunk) derived from `provider_mapping.tsv`. +pub fn run_curate_bars_1m_mongo( + args: &CurateBars1mMongoArgs, +) -> Result { + let (splits_spec, intraday_spec) = bars_1m_read_specs(args); + with_mongo_client( + &args.mongo, + &[ + (SourceCollection::QmSplits, splits_spec.clone()), + (SourceCollection::EodIntraday1M, intraday_spec.clone()), + ], + |client| { + let use_key_chunks = args.mongo.limit.is_none(); + let eod_keys = if use_key_chunks { + unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source) + .map_err(|e| RunMongoCurateError::Bars1m(RunCurateBars1mError::LoadReference(e)))? + } else { + Vec::new() + }; + + let splits_reader = client + .open_raw_cursor(SourceCollection::QmSplits, &splits_spec) + .map_err(RunMongoCurateError::Mongo)?; + if use_key_chunks { + let intraday_reader = client + .open_raw_cursor_for_keys( + SourceCollection::EodIntraday1M, + &intraday_spec, + &eod_keys, + 250, + ) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader) + } else { + let intraday_reader = client + .open_raw_cursor(SourceCollection::EodIntraday1M, &intraday_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader) + } + }, + ) +} + +pub(crate) fn qm_bars_1m_read_spec(args: &CurateQmBars1mMongoArgs) -> MongoReadSpec { + args.mongo + .to_read_spec_for_collection(SourceCollection::QmIntraday, None, true) +} + +pub(crate) fn run_curate_qm_bars_1m_mongo_with_reader( + args: &CurateQmBars1mMongoArgs, + intraday_reader: R, +) -> Result { + let file_args = args.to_file_args(); + run_curate_qm_bars_1m_from_reader_to_dir(&file_args, intraday_reader) + .map_err(RunMongoCurateError::QmBars1m) +} + +/// Streams `qmIntraday` directly from read-only MongoDB into +/// `/bars_1m_qm.shard-.ilp`. +/// +/// When `--limit` is not set, `qmIntraday` is streamed in indexed `$in` key chunks (`250` +/// keys/chunk) derived from `provider_mapping.tsv`. +pub fn run_curate_qm_bars_1m_mongo( + args: &CurateQmBars1mMongoArgs, +) -> Result { + let intraday_spec = qm_bars_1m_read_spec(args); + with_mongo_client( + &args.mongo, + &[(SourceCollection::QmIntraday, intraday_spec.clone())], + |client| { + let use_key_chunks = args.mongo.limit.is_none(); + let qm_keys = if use_key_chunks { + unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source) + .map_err(|e| { + RunMongoCurateError::QmBars1m(RunCurateQmBars1mError::LoadReference(e)) + })? + } else { + Vec::new() + }; + + if use_key_chunks { + let intraday_reader = client + .open_raw_cursor_for_keys( + SourceCollection::QmIntraday, + &intraday_spec, + &qm_keys, + 250, + ) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader) + } else { + let intraday_reader = client + .open_raw_cursor(SourceCollection::QmIntraday, &intraday_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader) + } + }, + ) +} + +pub(crate) fn fx_1m_read_spec(args: &CurateFx1mMongoArgs) -> MongoReadSpec { + args.mongo.to_read_spec_for_collection( + SourceCollection::EodIntraday1M, + Some(EOD_CAD_FOREX_CODE.to_owned()), + true, + ) +} + +pub(crate) fn run_curate_fx_1m_mongo_with_reader( + args: &CurateFx1mMongoArgs, + intraday_reader: R, +) -> Result { + let file_args = args.to_file_args(); + run_curate_fx_1m_from_reader_to_dir(&file_args, intraday_reader) + .map_err(RunMongoCurateError::Fx1m) +} + +/// Streams `eodIntraday1M` (`eodSearchCode == "CAD.FOREX"`) directly from read-only MongoDB into +/// `/fx_1m.shard-.ilp`. +pub fn run_curate_fx_1m_mongo( + args: &CurateFx1mMongoArgs, +) -> Result { + let fx_spec = fx_1m_read_spec(args); + with_mongo_client( + &args.mongo, + &[(SourceCollection::EodIntraday1M, fx_spec.clone())], + |client| { + let intraday_reader = client + .open_raw_cursor(SourceCollection::EodIntraday1M, &fx_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_fx_1m_mongo_with_reader(args, intraday_reader) + }, + ) +} + /// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly). #[allow(dead_code)] fn _assert_path_ref(path: &Path) -> &Path { path } + +#[cfg(test)] +#[path = "run_mongo_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_mongo_tests.rs b/tools/curate-etl/src/run_mongo_tests.rs new file mode 100644 index 00000000..f7251e52 --- /dev/null +++ b/tools/curate-etl/src/run_mongo_tests.rs @@ -0,0 +1,1823 @@ +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; +use bson::{Bson, DateTime}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + bars_1m_read_specs, fundamentals_read_specs, fx_1m_read_spec, macro_read_spec, posts_read_spec, + qm_bars_1m_read_spec, run_curate_bars_1m_mongo, run_curate_bars_1m_mongo_with_readers, + run_curate_fundamentals_mongo, run_curate_fundamentals_mongo_with_readers, + run_curate_fx_1m_mongo, run_curate_fx_1m_mongo_with_reader, run_curate_macro_mongo, + run_curate_macro_mongo_with_reader, run_curate_posts_mongo, + run_curate_posts_mongo_with_reader, run_curate_qm_bars_1m_mongo, + run_curate_qm_bars_1m_mongo_with_reader, unique_mapping_keys_for_source, CurateBars1mMongoArgs, + CurateFundamentalsMongoArgs, CurateFx1mMongoArgs, CurateMacroMongoArgs, CuratePostsMongoArgs, + CurateQmBars1mMongoArgs, RunMongoCurateError, +}; +use crate::bson_ceo_posts::{ + CeoPostsTimestampUnit, DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD, + DEFAULT_SPIEL_ID_FIELD, DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, +}; +use crate::bson_qm_events::{DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD}; +use crate::bson_qm_financials::{ + DEFAULT_QM_FINANCIALS_KEY_FIELD, DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, + DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, +}; +use crate::bson_stream::BsonStreamOptions; +use crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP; +use crate::fundamentals::FiscalPeriod; +use crate::ilp::{IlpWriterOptions, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M}; +use crate::mongo_stream::{ + build_filter_document, MongoCliOptions, MongoStreamError, MongoUriSource, RawBsonCursorReader, + SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, +}; +use crate::run_curate_bars_1m::{ + run_curate_bars_1m, CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE, +}; +use crate::run_curate_fundamentals::{ + run_curate_fundamentals, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, + DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, +}; +use crate::run_curate_fx_1m::{run_curate_fx_1m, CurateFx1mArgs}; +use crate::run_curate_macro::{run_curate_macro, CurateMacroArgs, MACRO_SERIES_MAP_HEADER}; +use crate::run_curate_posts::{ + run_curate_posts, CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, +}; +use crate::run_curate_qm_bars_1m::{ + run_curate_qm_bars_1m, CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, +}; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-run-mongo-test-{label}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp test dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +struct CappedRead { + inner: R, + max_step: usize, +} + +impl CappedRead { + fn new(inner: R, max_step: usize) -> Self { + Self { inner, max_step } + } +} + +impl Read for CappedRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let cap = buf.len().min(self.max_step); + self.inner.read(&mut buf[..cap]) + } +} + +fn concat_docs(docs: &[Vec]) -> Vec { + let mut out = Vec::new(); + for d in docs { + out.extend_from_slice(d); + } + out +} + +fn snapshot_files(root: &Path) -> BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read_dir") { + let entry = entry.expect("dir entry"); + let path = entry.path(); + if path.is_dir() { + walk(base, &path, out); + } else { + let rel = path.strip_prefix(base).expect("strip_prefix").to_path_buf(); + out.insert(rel, fs::read(&path).expect("read file")); + } + } + } + let mut out = BTreeMap::new(); + walk(root, root, &mut out); + out +} + +fn make_fin_doc( + key: &str, + period_end: &str, + report_date: &str, + report_period: &str, + rev: f64, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), key); + doc.append(cstr!("periodEndDate"), period_end); + doc.append(cstr!("reportDate"), report_date); + doc.append(cstr!("reportPeriod"), report_period); + doc.append(cstr!("currency"), "USD"); + doc.append(cstr!("revenue"), rev); + doc.into_bytes() +} + +fn make_filing_doc(key: &str, timefiled: &str, form_type: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), key); + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formType"), form_type); + doc.into_bytes() +} + +#[test] +fn parity_curate_fundamentals_mongo_cursor_matches_file_mode_with_and_without_old() { + let tmp = TempDirGuard::new("parity-fundamentals"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let ven_path = tmp.path().join("listing_venues.tsv"); + fs::write(&map_path, "qm\tACME:US\t2020-01-01\t\t101\n").unwrap(); + fs::write(&ven_path, "101\tus_tsx\n").unwrap(); + + let fin_docs = vec![ + make_fin_doc("ACME:US", "2024-06-30", "2024-08-05", "Q2", 130.0), + make_fin_doc("ACME:US", "2024-03-31", "2024-09-10", "Q1", 125.0), + ]; + let old_docs = vec![ + make_fin_doc("ACME:US", "2023-09-30", "2023-11-05", "Q3", 100.0), + make_fin_doc("ACME:US", "2023-12-31", "2024-02-20", "Q4", 110.0), + make_fin_doc("ACME:US", "2024-03-31", "2024-05-05", "Q1", 120.0), + ]; + let fil_docs = vec![ + make_filing_doc("ACME:US", "2023-11-05T16:30:00 EST", "10-Q"), + make_filing_doc("ACME:US", "2024-02-20T16:30:00 EST", "10-Q"), + make_filing_doc("ACME:US", "2024-05-05T16:30:00 EDT", "10-Q"), + make_filing_doc("ACME:US", "2024-08-05T16:30:00 EDT", "10-Q"), + make_filing_doc("ACME:US", "2024-09-10T16:30:00 EDT", "10-Q/A"), + ]; + + let fin_path = tmp.path().join("qmFinancials.bson"); + let old_path = tmp.path().join("qmFinancials-old.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + fs::write(&fin_path, concat_docs(&fin_docs)).unwrap(); + fs::write(&old_path, concat_docs(&old_docs)).unwrap(); + fs::write(&fil_path, concat_docs(&fil_docs)).unwrap(); + + for with_old in [false, true] { + let out_file = tmp.path().join(format!("out_file_{with_old}")); + let out_mongo = tmp.path().join(format!("out_mongo_{with_old}")); + + let mut file_args = CurateFundamentalsArgs::with_verified_defaults( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + ven_path.clone(), + out_file.clone(), + "currency", + Some("revenue".to_string()), + None, + None, + None, + None, + None, + CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + "formType", + 4, + ); + if with_old { + file_args.qm_financials_old = Some(old_path.clone()); + } + let file_rep = run_curate_fundamentals(&file_args).expect("file-mode fundamentals"); + + let mongo_args = CurateFundamentalsMongoArgs { + mongo: MongoCliOptions::default(), + with_qm_financials_old: with_old, + provider_mapping: map_path.clone(), + listing_venues: ven_path.clone(), + out_dir: out_mongo.clone(), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: Some("revenue".to_string()), + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }; + + let fin_slices: Vec<&[u8]> = fin_docs.iter().map(Vec::as_slice).collect(); + let fin_reader = CappedRead::new( + RawBsonCursorReader::new(SliceRawDocumentSource::new(&fin_slices)), + 7, + ); + let old_reader = with_old.then(|| { + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(old_docs.clone())), + 13, + ) + }); + let fil_reader = CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(fil_docs.clone())), + 11, + ); + + let mongo_rep = run_curate_fundamentals_mongo_with_readers( + &mongo_args, + fin_reader, + old_reader, + fil_reader, + ) + .expect("mongo-cursor fundamentals"); + + assert_eq!(mongo_rep.curate_stats, file_rep.curate_stats); + assert_eq!(mongo_rep.write_stats, file_rep.write_stats); + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); + } +} + +#[test] +fn parity_curate_posts_mongo_cursor_matches_file_mode_byte_for_byte() { + let tmp = TempDirGuard::new("parity-posts"); + let map_path = tmp.path().join("provider_mapping.tsv"); + fs::write(&map_path, "ceo\t5001\t2020-01-01\t\t202\n").unwrap(); + + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "5001"); + d1.append(cstr!("spielId"), "p1"); + d1.append(cstr!("timestamp"), 1_710_000_000_i64); + d1.append(cstr!("edited"), 1_710_003_600_i64); + d1.append(cstr!("bot"), "0"); + d1.append(cstr!("userId"), "u1"); + d1.append(cstr!("spiel"), "edited post body"); + + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "5001"); + d2.append(cstr!("spielId"), "p2"); + d2.append(cstr!("timestamp"), 1_710_010_000_i64); + d2.append(cstr!("edited"), false); + d2.append(cstr!("bot"), "1"); + d2.append(cstr!("userId"), "bot"); + d2.append(cstr!("spiel"), "newswire release"); + + let docs = vec![d1.into_bytes(), d2.into_bytes()]; + let bson_path = tmp.path().join("ceoPosts.bson"); + fs::write(&bson_path, concat_docs(&docs)).unwrap(); + + let out_file = tmp.path().join("out_file"); + let out_mongo = tmp.path().join("out_mongo"); + + let file_rep = run_curate_posts(&CuratePostsArgs { + ceo_posts: bson_path, + provider_mapping: map_path.clone(), + out_dir: out_file.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }) + .expect("file-mode posts"); + + let mongo_args = CuratePostsMongoArgs { + mongo: MongoCliOptions::default(), + provider_mapping: map_path, + out_dir: out_mongo.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }; + let reader = CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(docs)), + 5, + ); + let mongo_rep = run_curate_posts_mongo_with_reader(&mongo_args, reader).expect("mongo posts"); + + assert_eq!(mongo_rep.curate_stats, file_rep.curate_stats); + assert_eq!(mongo_rep.write_stats, file_rep.write_stats); + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); +} + +#[test] +fn parity_curate_macro_mongo_cursor_matches_file_mode_byte_for_byte() { + let tmp = TempDirGuard::new("parity-macro"); + let map_path = tmp.path().join("series_map.tsv"); + fs::write( + &map_path, + format!( + "{MACRO_SERIES_MAP_HEADER}\nUS_CPI\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n" + ), + ) + .unwrap(); + + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-01-31"); + pt.append(cstr!("v"), 3.1_f64); + let mut data_arr = RawArrayBuf::new(); + data_arr.push(pt); + let mut fpt = RawDocumentBuf::new(); + fpt.append(cstr!("d"), "2025-01-31"); + fpt.append(cstr!("v"), 9.9_f64); + let mut forecast_arr = RawArrayBuf::new(); + forecast_arr.push(fpt); + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("teSymbol"), "US_CPI"); + doc.append(cstr!("country"), "United States"); + doc.append(cstr!("category"), "Inflation Rate"); + doc.append(cstr!("data"), data_arr); + doc.append(cstr!("forecast"), forecast_arr); + + let docs = vec![doc.into_bytes()]; + let bson_path = tmp.path().join("teData.bson"); + fs::write(&bson_path, concat_docs(&docs)).unwrap(); + + let out_file = tmp.path().join("out_file"); + let out_mongo = tmp.path().join("out_mongo"); + + let file_rep = run_curate_macro(&CurateMacroArgs { + te_data: bson_path, + series_map: map_path.clone(), + out_dir: out_file.clone(), + }) + .expect("file-mode macro"); + + let mongo_args = CurateMacroMongoArgs { + mongo: MongoCliOptions::default(), + series_map: map_path, + out_dir: out_mongo.clone(), + }; + let reader = CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(docs)), + 7, + ); + let mongo_rep = run_curate_macro_mongo_with_reader(&mongo_args, reader).expect("mongo macro"); + + assert_eq!(mongo_rep, file_rep); + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); +} + +#[test] +fn parity_curate_1m_ilp_mongo_cursors_match_file_mode_byte_for_byte() { + let tmp = TempDirGuard::new("parity-1m-ilp"); + let map_path = tmp.path().join("provider_mapping.tsv"); + fs::write( + &map_path, + "eod\tNVDA.US\t2020-01-01\t\t301\nqm\tNVDA:US\t2020-01-01\t\t301\n", + ) + .unwrap(); + + // qmSplits: 10:1 forward split on 2024-06-10 (QuoteMedia stores splitratio = old / new = 0.1) + let mut sp = RawDocumentBuf::new(); + sp.append(cstr!("qmSearchCode"), "NVDA:US"); + sp.append(cstr!("date"), "2024-06-10"); + sp.append(cstr!("forfactor"), 1.0_f64); + sp.append(cstr!("tofactor"), 10.0_f64); + sp.append(cstr!("splitratio"), 0.1_f64); + let split_docs = vec![sp.into_bytes()]; + + // eodIntraday1M: equity bar + CAD.FOREX bar + let mut b_eq = RawDocumentBuf::new(); + b_eq.append(cstr!("eodSearchCode"), "NVDA.US"); + b_eq.append(cstr!("timestamp"), 1_717_767_000_i64); // 2024-06-07 13:30:00Z (09:30 ET) + b_eq.append(cstr!("open"), 120.0_f64); + b_eq.append(cstr!("high"), 121.0_f64); + b_eq.append(cstr!("low"), 119.0_f64); + b_eq.append(cstr!("close"), 120.5_f64); + b_eq.append(cstr!("volume"), 1000.0_f64); + + let mut b_fx = RawDocumentBuf::new(); + b_fx.append(cstr!("eodSearchCode"), "CAD.FOREX"); + b_fx.append(cstr!("timestamp"), 1_717_767_000_i64); + b_fx.append(cstr!("open"), 1.3700_f64); + b_fx.append(cstr!("high"), 1.3710_f64); + b_fx.append(cstr!("low"), 1.3690_f64); + b_fx.append(cstr!("close"), 1.3705_f64); + b_fx.append(cstr!("volume"), 0.0_f64); + + let eod_1m_docs = vec![b_eq.into_bytes(), b_fx.into_bytes()]; + + // qmIntraday: raw bar + let mut b_qm = RawDocumentBuf::new(); + b_qm.append(cstr!("qmSearchCode"), "NVDA:US"); + b_qm.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + b_qm.append(cstr!("open"), 1200.0_f64); + b_qm.append(cstr!("high"), 1210.0_f64); + b_qm.append(cstr!("low"), 1190.0_f64); + b_qm.append(cstr!("close"), 1205.0_f64); + b_qm.append(cstr!("sharevolume"), 100.0_f64); + let qm_1m_docs = vec![b_qm.into_bytes()]; + + let splits_path = tmp.path().join("qmSplits.bson"); + let eod_path = tmp.path().join("eodIntraday1M.bson"); + let qm_path = tmp.path().join("qmIntraday.bson"); + fs::write(&splits_path, concat_docs(&split_docs)).unwrap(); + fs::write(&eod_path, concat_docs(&eod_1m_docs)).unwrap(); + fs::write(&qm_path, concat_docs(&qm_1m_docs)).unwrap(); + + // Shared output dirs prove bars_1m, bars_1m_qm, and fx_1m co-exist in one --out dir. + let out_file = tmp.path().join("out_file"); + let out_mongo = tmp.path().join("out_mongo"); + let known_at = 1_750_000_000_000_000_i64; + + // 1. curate-bars-1m + let file_b1m = run_curate_bars_1m(&CurateBars1mArgs { + intraday_path: eod_path.clone(), + splits_path, + provider_mapping_path: map_path.clone(), + out_dir: out_file.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect("file bars_1m"); + let mongo_b1m = run_curate_bars_1m_mongo_with_readers( + &CurateBars1mMongoArgs { + mongo: MongoCliOptions::default(), + provider_mapping_path: map_path.clone(), + out_dir: out_mongo.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs.clone())), + 9, + ), + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs)), + 5, + ), + ) + .expect("mongo bars_1m"); + assert_eq!(mongo_b1m.curate_stats, file_b1m.curate_stats); + assert_eq!(mongo_b1m.ilp_stats, file_b1m.ilp_stats); + + // 2. curate-qm-bars-1m in the same --out dir + let file_qm1m = run_curate_qm_bars_1m(&CurateQmBars1mArgs { + intraday_path: qm_path, + provider_mapping_path: map_path.clone(), + out_dir: out_file.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect("file qm_bars_1m"); + let qm_slices: Vec<&[u8]> = qm_1m_docs.iter().map(Vec::as_slice).collect(); + let mongo_qm1m = run_curate_qm_bars_1m_mongo_with_reader( + &CurateQmBars1mMongoArgs { + mongo: MongoCliOptions::default(), + provider_mapping_path: map_path, + out_dir: out_mongo.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }, + CappedRead::new( + RawBsonCursorReader::new(SliceRawDocumentSource::new(&qm_slices)), + 7, + ), + ) + .expect("mongo qm_bars_1m"); + assert_eq!(mongo_qm1m.curate_stats, file_qm1m.curate_stats); + assert_eq!(mongo_qm1m.ilp_stats, file_qm1m.ilp_stats); + + // 3. curate-fx-1m in the same --out dir + let file_fx1m = run_curate_fx_1m(&CurateFx1mArgs { + intraday_path: eod_path, + out_dir: out_file.clone(), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect("file fx_1m"); + let mongo_fx1m = run_curate_fx_1m_mongo_with_reader( + &CurateFx1mMongoArgs { + mongo: MongoCliOptions::default(), + out_dir: out_mongo.clone(), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs)), + 11, + ), + ) + .expect("mongo fx_1m"); + assert_eq!(mongo_fx1m.curate_stats, file_fx1m.curate_stats); + assert_eq!(mongo_fx1m.ilp_stats, file_fx1m.ilp_stats); + + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); +} + +#[test] +fn m2_mongo_read_specs_enforce_filter_types_and_key_scoping() { + let opts = MongoCliOptions { + date_gte: Some("2024-01-01".to_owned()), + date_lt: Some("2024-01-02".to_owned()), + ..MongoCliOptions::default() + }; + + // curate-fx-1m scopes to eodSearchCode == "CAD.FOREX" + Int64 epoch seconds. + let fx_args = CurateFx1mMongoArgs { + mongo: opts.clone(), + out_dir: PathBuf::from("out"), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let fx_spec = fx_1m_read_spec(&fx_args); + let fx_doc = build_filter_document(SourceCollection::EodIntraday1M, &fx_spec).unwrap(); + assert_eq!( + fx_doc.get("eodSearchCode"), + Some(&Bson::String("CAD.FOREX".to_owned())) + ); + let fx_ts = fx_doc.get_document("timestamp").unwrap(); + assert_eq!(fx_ts.get("$gte"), Some(&Bson::Int64(1_704_067_200))); + assert_eq!(fx_ts.get("$lt"), Some(&Bson::Int64(1_704_153_600))); + + // curate-bars-1m keeps qmSplits unfiltered on dates, eodIntraday1M as Int64 epoch seconds. + let b1m_args = CurateBars1mMongoArgs { + mongo: opts.clone(), + provider_mapping_path: PathBuf::from("pm.tsv"), + out_dir: PathBuf::from("out"), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let (splits_spec, intraday_spec) = bars_1m_read_specs(&b1m_args); + assert!(splits_spec.date_range.is_none()); + let b1m_doc = build_filter_document(SourceCollection::EodIntraday1M, &intraday_spec).unwrap(); + assert_eq!( + b1m_doc.get_document("timestamp").unwrap().get("$gte"), + Some(&Bson::Int64(1_704_067_200)) + ); + + // curate-qm-bars-1m uses Bson::DateTime millis. + let qm_args = CurateQmBars1mMongoArgs { + mongo: opts.clone(), + provider_mapping_path: PathBuf::from("pm.tsv"), + out_dir: PathBuf::from("out"), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let qm_spec = qm_bars_1m_read_spec(&qm_args); + let qm_doc = build_filter_document(SourceCollection::QmIntraday, &qm_spec).unwrap(); + assert_eq!( + qm_doc.get_document("timestamp").unwrap().get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + + // Non-date-ranged M2 collections fail closed with DateRangeNotSupported. + let fin_args = CurateFundamentalsMongoArgs { + mongo: opts.clone(), + with_qm_financials_old: true, + provider_mapping: PathBuf::from("pm.tsv"), + listing_venues: PathBuf::from("lv.tsv"), + out_dir: PathBuf::from("out"), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: None, + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }; + let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(&fin_args); + assert!(matches!( + fin_spec.validate(SourceCollection::QmFinancials), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::QmFinancials + }) + )); + assert!(matches!( + fin_old_spec + .unwrap() + .validate(SourceCollection::QmFinancialsOld), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::QmFinancialsOld + }) + )); + assert!(filings_spec.date_range.is_none()); + + let posts_spec = posts_read_spec(&CuratePostsMongoArgs { + mongo: opts.clone(), + provider_mapping: PathBuf::from("pm.tsv"), + out_dir: PathBuf::from("out"), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }); + assert!(matches!( + posts_spec.validate(SourceCollection::CeoPosts), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::CeoPosts + }) + )); + + let macro_spec = macro_read_spec(&CurateMacroMongoArgs { + mongo: opts, + series_map: PathBuf::from("sm.tsv"), + out_dir: PathBuf::from("out"), + }); + assert!(matches!( + macro_spec.validate(SourceCollection::TeData), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::TeData + }) + )); +} + +#[test] +fn m2_mongo_runners_fail_closed_on_trading_admin_and_unauthenticated_qa_uris() { + let tmp = TempDirGuard::new("mongo-safety-m2"); + let secret = "S3CR3T_ADMIN_PASS_999"; + let bad_uris = [ + format!("mongodb://trading_admin:{secret}@localhost:27017/stock?authSource=admin"), + "mongodb://localhost:27017/stock".to_string(), + ]; + + for (idx, uri) in bad_uris.iter().enumerate() { + let mongo = MongoCliOptions { + uri_source: MongoUriSource::Literal(uri.clone()), + ..MongoCliOptions::default() + }; + + let out_fin = tmp.path().join(format!("fin_{idx}")); + let err = run_curate_fundamentals_mongo(&CurateFundamentalsMongoArgs { + mongo: mongo.clone(), + with_qm_financials_old: true, + provider_mapping: tmp.path().join("pm.tsv"), + listing_venues: tmp.path().join("lv.tsv"), + out_dir: out_fin.clone(), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: None, + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_fin.exists()); + + let out_posts = tmp.path().join(format!("posts_{idx}")); + let err = run_curate_posts_mongo(&CuratePostsMongoArgs { + mongo: mongo.clone(), + provider_mapping: tmp.path().join("pm.tsv"), + out_dir: out_posts.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_posts.exists()); + + let out_macro = tmp.path().join(format!("macro_{idx}")); + let err = run_curate_macro_mongo(&CurateMacroMongoArgs { + mongo: mongo.clone(), + series_map: tmp.path().join("sm.tsv"), + out_dir: out_macro.clone(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_macro.exists()); + + let out_b1m = tmp.path().join(format!("b1m_{idx}")); + let err = run_curate_bars_1m_mongo(&CurateBars1mMongoArgs { + mongo: mongo.clone(), + provider_mapping_path: tmp.path().join("pm.tsv"), + out_dir: out_b1m.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_b1m.exists()); + + let out_qm1m = tmp.path().join(format!("qm1m_{idx}")); + let err = run_curate_qm_bars_1m_mongo(&CurateQmBars1mMongoArgs { + mongo: mongo.clone(), + provider_mapping_path: tmp.path().join("pm.tsv"), + out_dir: out_qm1m.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_qm1m.exists()); + + let out_fx1m = tmp.path().join(format!("fx1m_{idx}")); + let err = run_curate_fx_1m_mongo(&CurateFx1mMongoArgs { + mongo, + out_dir: out_fx1m.clone(), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_fx1m.exists()); + } +} + +#[derive(Debug, Clone, PartialEq)] +struct FundamentalsPitSummaryRow { + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + ttm_revenue: Option, +} + +fn read_fundamentals_pit_summary_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open fundamentals parquet"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let schema_descr = meta.file_metadata().schema_descr(); + let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); + for (idx, col) in schema_descr.columns().iter().enumerate() { + col_idx_by_name.insert(col.name(), idx); + } + let col_idx = |name: &str| -> usize { + *col_idx_by_name + .get(name) + .unwrap_or_else(|| panic!("missing Parquet column '{name}'")) + }; + + let mut out = Vec::new(); + for rg_idx in 0..meta.num_row_groups() { + let rg_rows = meta.row_group(rg_idx).num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let mut known_at = Vec::with_capacity(rg_rows); + match rg_reader + .get_column_reader(col_idx("effective_known_at")) + .unwrap() + { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut known_at) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 for effective_known_at"), + } + + let mut sources = Vec::with_capacity(rg_rows); + match rg_reader + .get_column_reader(col_idx("known_at_source")) + .unwrap() + { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut sources) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for known_at_source"), + } + + let mut estimated = Vec::with_capacity(rg_rows); + match rg_reader + .get_column_reader(col_idx("has_estimated_lag")) + .unwrap() + { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut estimated) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for has_estimated_lag"), + } + + let mut ttm_vals = Vec::with_capacity(rg_rows); + let mut ttm_defs = Vec::with_capacity(rg_rows); + match rg_reader + .get_column_reader(col_idx("ttm_revenue")) + .unwrap() + { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut ttm_defs), None, &mut ttm_vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE for ttm_revenue"), + } + let mut vi = 0usize; + let ttm_revenues: Vec> = ttm_defs + .into_iter() + .map(|d| { + if d == 1 { + let v = ttm_vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect(); + + for i in 0..rg_rows { + out.push(FundamentalsPitSummaryRow { + effective_known_at: known_at[i], + known_at_source: String::from_utf8(sources[i].data().to_vec()).unwrap(), + has_estimated_lag: estimated[i], + ttm_revenue: ttm_revenues[i], + }); + } + } + out +} + +fn apply_doc_limit(docs: &[Vec], limit: Option) -> Vec> { + match limit { + Some(n) => docs.iter().take(n as usize).cloned().collect(), + None => docs.to_vec(), + } +} + +#[test] +fn curate_fundamentals_mongo_limit_preserves_unbounded_filings_and_restated_ttm() { + let tmp = TempDirGuard::new("fundamentals-limit-unbounded-filings"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let ven_path = tmp.path().join("listing_venues.tsv"); + fs::write(&map_path, "qm\tACME:US\t2020-01-01\t\t101\n").unwrap(); + fs::write(&ven_path, "101\tus_tsx\n").unwrap(); + + let fin_docs = vec![ + make_fin_doc("ACME:US", "2024-06-30", "2024-08-05", "Q2", 130.0), + make_fin_doc("ACME:US", "2024-03-31", "2024-09-10", "Q1", 125.0), + ]; + let old_docs = vec![ + make_fin_doc("ACME:US", "2023-09-30", "2023-11-05", "Q3", 100.0), + make_fin_doc("ACME:US", "2023-12-31", "2024-02-20", "Q4", 110.0), + make_fin_doc("ACME:US", "2024-03-31", "2024-05-05", "Q1", 120.0), + ]; + + // Place 8 unrelated filings ahead of ACME's filings so any `--limit 5` cap on `qmFilings` + // would cut off ACME's filing evidence (including the 2024-09-10 Q1 amendment). + let mut fil_docs: Vec> = (0..8) + .map(|_| make_filing_doc("OTHER:US", "2023-01-15T16:30:00 EST", "10-Q")) + .collect(); + fil_docs.extend([ + make_filing_doc("ACME:US", "2023-11-05T16:30:00 EST", "10-Q"), + make_filing_doc("ACME:US", "2024-02-20T16:30:00 EST", "10-Q"), + make_filing_doc("ACME:US", "2024-05-05T16:30:00 EDT", "10-Q"), + make_filing_doc("ACME:US", "2024-08-05T16:30:00 EDT", "10-Q"), + make_filing_doc("ACME:US", "2024-09-10T16:30:00 EDT", "10-Q/A"), + ]); + + let out_unbounded_filings = tmp.path().join("out_unbounded_filings"); + let mongo_args = CurateFundamentalsMongoArgs { + mongo: MongoCliOptions { + limit: Some(5), + ..MongoCliOptions::default() + }, + with_qm_financials_old: true, + provider_mapping: map_path.clone(), + listing_venues: ven_path.clone(), + out_dir: out_unbounded_filings.clone(), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: Some("revenue".to_string()), + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }; + + let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(&mongo_args); + assert_eq!(fin_spec.limit, Some(5)); + assert_eq!(fin_old_spec.as_ref().unwrap().limit, Some(5)); + assert!( + filings_spec.limit.is_none(), + "qmFilings must stay uncapped under --limit" + ); + assert!(filings_spec.date_range.is_none()); + + let fin_cursor = RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit( + &fin_docs, + fin_spec.limit, + ))); + let old_cursor = RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit( + &old_docs, + fin_old_spec.unwrap().limit, + ))); + let fil_cursor = RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit( + &fil_docs, + filings_spec.limit, + ))); + + run_curate_fundamentals_mongo_with_readers(&mongo_args, fin_cursor, Some(old_cursor), fil_cursor) + .expect("fundamentals run under --limit"); + + let rows_2024 = read_fundamentals_pit_summary_rows( + &out_unbounded_filings + .join("fundamentals_pit") + .join("year=2024") + .join("part.parquet"), + ); + let expected_amendment_micros = + et_to_utc_micros(ymd_to_epoch_days(2024, 9, 10).unwrap(), 16, 30, 0).unwrap(); + let amendment_row = rows_2024 + .iter() + .find(|r| r.effective_known_at == expected_amendment_micros) + .expect("retained Q1 amendment must keep its 2024-09-10 filing timestamp under --limit"); + assert_eq!( + amendment_row.known_at_source, + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); + assert!(!amendment_row.has_estimated_lag); + assert_eq!(amendment_row.ttm_revenue, Some(465.0)); + + // Negative control: if `qmFilings` had been capped by `--limit 5`, the amendment would lose + // its filing and drop as unanchored, leaving TTM stale. + let out_capped_filings = tmp.path().join("out_capped_filings"); + let mut capped_args = mongo_args; + capped_args.out_dir = out_capped_filings.clone(); + run_curate_fundamentals_mongo_with_readers( + &capped_args, + RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit( + &fin_docs, + Some(5), + ))), + Some(RawBsonCursorReader::new(VecRawDocumentSource::new( + apply_doc_limit(&old_docs, Some(5)), + ))), + RawBsonCursorReader::new(VecRawDocumentSource::new(apply_doc_limit( + &fil_docs, + Some(5), + ))), + ) + .expect("negative-control run"); + let capped_rows = read_fundamentals_pit_summary_rows( + &out_capped_filings + .join("fundamentals_pit") + .join("year=2024") + .join("part.parquet"), + ); + assert!( + !capped_rows + .iter() + .any(|r| r.effective_known_at == expected_amendment_micros), + "capping qmFilings would drop the unanchored amendment" + ); + assert!(!capped_rows.iter().any(|r| r.ttm_revenue == Some(465.0))); +} + +fn make_eod_1m_doc( + code: &str, + ts_secs: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), ts_secs); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc.into_bytes() +} + +fn make_qm_1m_doc( + code: &str, + ts_secs: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(ts_secs * 1_000)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), volume); + doc.into_bytes() +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct EconomicBar1mRow { + listing_id: i32, + ts: i64, + source: String, + open_bits: u64, + high_bits: u64, + low_bits: u64, + close_bits: u64, + volume_bits: u64, + known_at: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct EconomicFx1mRow { + pair: String, + source: String, + ts: i64, + open_bits: u64, + high_bits: u64, + low_bits: u64, + close_bits: u64, +} + +fn read_ilp_bin_f64_bits(data: &[u8], pos: &mut usize, name: &str) -> u64 { + let prefix = format!("{name}=="); + assert!( + data[*pos..].starts_with(prefix.as_bytes()), + "expected ILP field '{prefix}' at offset {}", + *pos + ); + *pos += prefix.len(); + assert_eq!(data[*pos], ILP_V2_DOUBLE_TYPE); + *pos += 1; + let bytes: [u8; 8] = data[*pos..*pos + 8].try_into().expect("8-byte f64"); + *pos += 8; + f64::from_le_bytes(bytes).to_bits() +} + +fn collect_ilp_bars_1m_rows(out_dir: &Path, prefix: &str) -> BTreeSet { + let mut rows = BTreeSet::new(); + for entry in fs::read_dir(out_dir).expect("read ilp out_dir") { + let path = entry.expect("dir entry").path(); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if !(name.starts_with(prefix) && name.ends_with(".ilp")) { + continue; + } + let data = fs::read(&path).expect("read ilp shard"); + let mut i = 0usize; + while i < data.len() { + let tag_start = i; + while i < data.len() { + match data[i] { + b'\\' => i += 2, + b' ' => break, + _ => i += 1, + } + } + let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("utf8 tag set"); + i += 1; + let mut tags = tag_str.split(','); + assert_eq!(tags.next(), Some(TABLE_BARS_1M)); + let listing_id: i32 = tags + .next() + .unwrap() + .strip_prefix("listing_id=") + .unwrap() + .parse() + .unwrap(); + let _session = tags.next().unwrap(); + let source = tags + .next() + .unwrap() + .strip_prefix("source=") + .unwrap() + .to_owned(); + assert!(tags.next().is_none()); + + let open_bits = read_ilp_bin_f64_bits(&data, &mut i, "open"); + assert_eq!(data[i], b','); + i += 1; + let high_bits = read_ilp_bin_f64_bits(&data, &mut i, "high"); + assert_eq!(data[i], b','); + i += 1; + let low_bits = read_ilp_bin_f64_bits(&data, &mut i, "low"); + assert_eq!(data[i], b','); + i += 1; + let close_bits = read_ilp_bin_f64_bits(&data, &mut i, "close"); + assert_eq!(data[i], b','); + i += 1; + let volume_bits = read_ilp_bin_f64_bits(&data, &mut i, "volume"); + assert!(data[i..].starts_with(b",known_at=")); + i += b",known_at=".len(); + let ka_start = i; + while data[i] != b't' { + i += 1; + } + let known_at: i64 = std::str::from_utf8(&data[ka_start..i]) + .unwrap() + .parse() + .unwrap(); + assert!(data[i..].starts_with(b"t ")); + i += 2; + let ts_start = i; + while data[i] != b't' { + i += 1; + } + let ts: i64 = std::str::from_utf8(&data[ts_start..i]) + .unwrap() + .parse() + .unwrap(); + assert!(data[i..].starts_with(b"t\n")); + i += 2; + + rows.insert(EconomicBar1mRow { + listing_id, + ts, + source, + open_bits, + high_bits, + low_bits, + close_bits, + volume_bits, + known_at, + }); + } + } + rows +} + +fn collect_ilp_fx_1m_rows(out_dir: &Path, prefix: &str) -> BTreeSet { + let mut rows = BTreeSet::new(); + for entry in fs::read_dir(out_dir).expect("read ilp out_dir") { + let path = entry.expect("dir entry").path(); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if !(name.starts_with(prefix) && name.ends_with(".ilp")) { + continue; + } + let data = fs::read(&path).expect("read ilp shard"); + let mut i = 0usize; + while i < data.len() { + let tag_start = i; + while i < data.len() { + match data[i] { + b'\\' => i += 2, + b' ' => break, + _ => i += 1, + } + } + let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("utf8 tag set"); + i += 1; + let mut tags = tag_str.split(','); + assert_eq!(tags.next(), Some(TABLE_FX_1M)); + let pair = tags + .next() + .unwrap() + .strip_prefix("pair=") + .unwrap() + .to_owned(); + let source = tags + .next() + .unwrap() + .strip_prefix("source=") + .unwrap() + .to_owned(); + assert!(tags.next().is_none()); + + let open_bits = read_ilp_bin_f64_bits(&data, &mut i, "open"); + assert_eq!(data[i], b','); + i += 1; + let high_bits = read_ilp_bin_f64_bits(&data, &mut i, "high"); + assert_eq!(data[i], b','); + i += 1; + let low_bits = read_ilp_bin_f64_bits(&data, &mut i, "low"); + assert_eq!(data[i], b','); + i += 1; + let close_bits = read_ilp_bin_f64_bits(&data, &mut i, "close"); + assert_eq!(data[i], b' '); + i += 1; + let ts_start = i; + while data[i] != b't' { + i += 1; + } + let ts: i64 = std::str::from_utf8(&data[ts_start..i]) + .unwrap() + .parse() + .unwrap(); + assert!(data[i..].starts_with(b"t\n")); + i += 2; + + rows.insert(EconomicFx1mRow { + pair, + source, + ts, + open_bits, + high_bits, + low_bits, + close_bits, + }); + } + } + rows +} + +#[test] +fn parity_curate_1m_ilp_filtered_multi_key_cross_chunk_matches_economic_rows_and_pinned_bytes() { + let tmp = TempDirGuard::new("parity-1m-ilp-filtered-cross-chunk"); + let map_path = tmp.path().join("provider_mapping.tsv"); + fs::write( + &map_path, + "eod\tNVDA.US\t2020-01-01\t\t301\n\ + eod\tAAPL.US\t2020-01-01\t\t302\n\ + qm\tNVDA:US\t2020-01-01\t\t301\n\ + qm\tAAPL:US\t2020-01-01\t\t302\n", + ) + .unwrap(); + + // 10:1 forward split for NVDA (listing 301) on 2024-06-10 (QuoteMedia stores + // `splitratio = forfactor / tofactor = old_shares / new_shares = 0.1`); AAPL has no split. + let mut sp = RawDocumentBuf::new(); + sp.append(cstr!("qmSearchCode"), "NVDA:US"); + sp.append(cstr!("date"), "2024-06-10"); + sp.append(cstr!("forfactor"), 1.0_f64); + sp.append(cstr!("tofactor"), 10.0_f64); + sp.append(cstr!("splitratio"), 0.1_f64); + let split_docs = vec![sp.into_bytes()]; + let splits_path = tmp.path().join("qmSplits.bson"); + fs::write(&splits_path, concat_docs(&split_docs)).unwrap(); + + // Window: [2024-06-07, 2024-06-08) -> [1_717_718_400, 1_717_804_800) UTC seconds. + let ts_before = 1_717_680_600_i64; // 2024-06-06 13:30:00Z + let ts_1330 = 1_717_767_000_i64; // 2024-06-07 13:30:00Z + let ts_1331 = 1_717_767_060_i64; // 2024-06-07 13:31:00Z + let ts_after = 1_717_853_400_i64; // 2024-06-08 13:30:00Z + + let eod_corpus: Vec<(&str, i64, Vec)> = vec![ + // Out-of-window and unmapped rows excluded by production Mongo filters. + ( + "NVDA.US", + ts_before, + make_eod_1m_doc("NVDA.US", ts_before, 118.0, 119.0, 117.0, 118.5, 500.0), + ), + ( + "UNMAPPED.US", + ts_1330, + make_eod_1m_doc("UNMAPPED.US", ts_1330, 50.0, 51.0, 49.0, 50.5, 100.0), + ), + ( + "AAPL.US", + ts_after, + make_eod_1m_doc("AAPL.US", ts_after, 199.0, 200.0, 198.0, 199.5, 400.0), + ), + ( + "CAD.FOREX", + ts_before, + make_eod_1m_doc("CAD.FOREX", ts_before, 1.365, 1.366, 1.364, 1.3655, 0.0), + ), + // In-window multi-key equity rows + exact duplicate to exercise per-chunk dedup. + ( + "NVDA.US", + ts_1330, + make_eod_1m_doc("NVDA.US", ts_1330, 120.0, 121.0, 119.0, 120.5, 1000.0), + ), + ( + "AAPL.US", + ts_1330, + make_eod_1m_doc("AAPL.US", ts_1330, 195.0, 196.0, 194.0, 195.5, 800.0), + ), + ( + "NVDA.US", + ts_1330, + make_eod_1m_doc("NVDA.US", ts_1330, 120.0, 121.0, 119.0, 120.5, 1000.0), + ), + ( + "NVDA.US", + ts_1331, + make_eod_1m_doc("NVDA.US", ts_1331, 121.0, 122.0, 120.0, 121.5, 1100.0), + ), + ( + "AAPL.US", + ts_1331, + make_eod_1m_doc("AAPL.US", ts_1331, 196.0, 197.0, 195.0, 196.5, 900.0), + ), + // In-window CAD.FOREX rows (including a cross-chunk duplicate at ts_1330). + ( + "CAD.FOREX", + ts_1330, + make_eod_1m_doc("CAD.FOREX", ts_1330, 1.370, 1.371, 1.369, 1.3705, 0.0), + ), + ( + "CAD.FOREX", + ts_1331, + make_eod_1m_doc("CAD.FOREX", ts_1331, 1.371, 1.372, 1.370, 1.3715, 0.0), + ), + ( + "CAD.FOREX", + ts_1330, + make_eod_1m_doc("CAD.FOREX", ts_1330, 1.370, 1.371, 1.369, 1.3705, 0.0), + ), + ]; + + let qm_corpus: Vec<(&str, i64, Vec)> = vec![ + ( + "UNMAPPED:US", + ts_1330, + make_qm_1m_doc("UNMAPPED:US", ts_1330, 50.0, 51.0, 49.0, 50.5, 100.0), + ), + ( + "NVDA:US", + ts_before, + make_qm_1m_doc("NVDA:US", ts_before, 1180.0, 1190.0, 1170.0, 1185.0, 50.0), + ), + ( + "NVDA:US", + ts_1330, + make_qm_1m_doc("NVDA:US", ts_1330, 1200.0, 1210.0, 1190.0, 1205.0, 100.0), + ), + ( + "AAPL:US", + ts_1330, + make_qm_1m_doc("AAPL:US", ts_1330, 195.0, 196.0, 194.0, 195.5, 800.0), + ), + ( + "NVDA:US", + ts_1331, + make_qm_1m_doc("NVDA:US", ts_1331, 1210.0, 1220.0, 1200.0, 1215.0, 110.0), + ), + ( + "AAPL:US", + ts_1331, + make_qm_1m_doc("AAPL:US", ts_1331, 196.0, 197.0, 195.0, 196.5, 900.0), + ), + // Cross-chunk duplicate for NVDA:US at ts_1330. + ( + "NVDA:US", + ts_1330, + make_qm_1m_doc("NVDA:US", ts_1330, 1200.0, 1210.0, 1190.0, 1205.0, 100.0), + ), + ]; + + let date_opts = MongoCliOptions { + date_gte: Some("2024-06-07".to_owned()), + date_lt: Some("2024-06-08".to_owned()), + ..MongoCliOptions::default() + }; + // Small chunk capacity (~2 docs/chunk) forces multi-key streams across BSON chunk boundaries. + let small_chunks = BsonStreamOptions { + chunk_capacity_bytes: 280, + max_doc_bytes: 1024 * 1024, + }; + let known_at = 1_750_000_000_000_000_i64; + + // 1. bars_1m: apply production `$in` eod key filter + Int64 epoch-second date filter. + let b1m_mongo_args = CurateBars1mMongoArgs { + mongo: date_opts.clone(), + provider_mapping_path: map_path.clone(), + out_dir: tmp.path().join("b1m_mongo_pinned"), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: small_chunks, + ilp_options: IlpWriterOptions::default(), + }; + let (_splits_spec, b1m_spec) = bars_1m_read_specs(&b1m_mongo_args); + let b1m_filter = build_filter_document(SourceCollection::EodIntraday1M, &b1m_spec).unwrap(); + let b1m_gte = b1m_filter + .get_document("timestamp") + .unwrap() + .get_i64("$gte") + .unwrap(); + let b1m_lt = b1m_filter + .get_document("timestamp") + .unwrap() + .get_i64("$lt") + .unwrap(); + let eod_keys: BTreeSet = + unique_mapping_keys_for_source(&map_path, DEFAULT_BARS_1M_MAPPING_SOURCE) + .unwrap() + .into_iter() + .collect(); + + let b1m_filtered_pinned: Vec> = eod_corpus + .iter() + .filter(|(k, ts, _)| eod_keys.contains(*k) && *ts >= b1m_gte && *ts < b1m_lt) + .map(|(_, _, b)| b.clone()) + .collect(); + assert_eq!(b1m_filtered_pinned.len(), 5); + assert!( + concat_docs(&b1m_filtered_pinned).len() > small_chunks.chunk_capacity_bytes, + "filtered bars_1m fixture must cross a BSON chunk boundary" + ); + + let b1m_filtered_path = tmp.path().join("eodIntraday1M_filtered.bson"); + fs::write(&b1m_filtered_path, concat_docs(&b1m_filtered_pinned)).unwrap(); + let b1m_file_out = tmp.path().join("b1m_file_pinned"); + let b1m_file_rep = run_curate_bars_1m(&CurateBars1mArgs { + intraday_path: b1m_filtered_path, + splits_path, + provider_mapping_path: map_path.clone(), + out_dir: b1m_file_out.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: small_chunks, + ilp_options: IlpWriterOptions::default(), + }) + .expect("file bars_1m pinned"); + let b1m_pinned_rep = run_curate_bars_1m_mongo_with_readers( + &b1m_mongo_args, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(b1m_filtered_pinned.clone())), + 19, + ), + RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs.clone())), + ) + .expect("mongo bars_1m pinned"); + assert_eq!(b1m_pinned_rep.rows_written, 4); + assert_eq!(b1m_pinned_rep.curate_stats, b1m_file_rep.curate_stats); + assert_eq!(b1m_pinned_rep.ilp_stats, b1m_file_rep.ilp_stats); + assert_eq!( + snapshot_files(&b1m_mongo_args.out_dir), + snapshot_files(&b1m_file_out) + ); + + // Reordered `$in` key-grouped cursor order (all AAPL docs before NVDA docs, reversed ts) + // with duplicates straddling BSON chunk boundaries must produce byte-identical shards and + // identical row counts. + let mut b1m_reordered: Vec<(&str, i64, Vec)> = eod_corpus + .iter() + .filter(|(k, ts, _)| eod_keys.contains(*k) && *ts >= b1m_gte && *ts < b1m_lt) + .cloned() + .collect(); + b1m_reordered.sort_by(|a, b| a.0.cmp(b.0).then_with(|| b.1.cmp(&a.1))); + let b1m_reordered_docs: Vec> = b1m_reordered.into_iter().map(|(_, _, b)| b).collect(); + let mut b1m_reordered_args = b1m_mongo_args; + b1m_reordered_args.out_dir = tmp.path().join("b1m_mongo_reordered"); + let b1m_reordered_rep = run_curate_bars_1m_mongo_with_readers( + &b1m_reordered_args, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(b1m_reordered_docs)), + 17, + ), + RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs)), + ) + .expect("mongo bars_1m reordered"); + + assert!(b1m_reordered_rep.chunks > 1); + assert_eq!(b1m_reordered_rep.rows_written, b1m_file_rep.rows_written); + assert_eq!(b1m_reordered_rep.rows_written, 4); + assert_eq!(b1m_reordered_rep.curate_stats, b1m_file_rep.curate_stats); + assert_eq!(b1m_reordered_rep.ilp_stats, b1m_file_rep.ilp_stats); + assert_eq!( + snapshot_files(&b1m_reordered_args.out_dir), + snapshot_files(&b1m_file_out) + ); + + let b1m_file_rows = collect_ilp_bars_1m_rows(&b1m_file_out, "bars_1m.shard-"); + let b1m_reordered_rows = collect_ilp_bars_1m_rows(&b1m_reordered_args.out_dir, "bars_1m.shard-"); + assert_eq!(b1m_reordered_rows, b1m_file_rows); + assert_eq!(b1m_reordered_rows.len(), 4); + assert!(b1m_reordered_rows.iter().any(|r| { + r.listing_id == 301 + && r.ts == ts_1330 * 1_000_000 + && f64::from_bits(r.open_bits) == 1200.0 + && r.known_at == known_at + })); + assert!(b1m_reordered_rows.iter().any(|r| { + r.listing_id == 302 + && r.ts == ts_1330 * 1_000_000 + && f64::from_bits(r.open_bits) == 195.0 + && r.known_at == known_at + })); + + // 2. qm_bars_1m: apply production `$in` qm key filter + DateTime millisecond date filter. + let qm_mongo_args = CurateQmBars1mMongoArgs { + mongo: date_opts.clone(), + provider_mapping_path: map_path.clone(), + out_dir: tmp.path().join("qm_mongo_pinned"), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: small_chunks, + ilp_options: IlpWriterOptions::default(), + }; + let qm_spec = qm_bars_1m_read_spec(&qm_mongo_args); + let qm_filter = build_filter_document(SourceCollection::QmIntraday, &qm_spec).unwrap(); + let qm_gte_ms = qm_filter + .get_document("timestamp") + .unwrap() + .get_datetime("$gte") + .unwrap() + .timestamp_millis(); + let qm_lt_ms = qm_filter + .get_document("timestamp") + .unwrap() + .get_datetime("$lt") + .unwrap() + .timestamp_millis(); + let qm_keys: BTreeSet = + unique_mapping_keys_for_source(&map_path, DEFAULT_QM_BARS_1M_MAPPING_SOURCE) + .unwrap() + .into_iter() + .collect(); + + let qm_filtered_pinned: Vec> = qm_corpus + .iter() + .filter(|(k, ts, _)| { + qm_keys.contains(*k) && (*ts * 1_000) >= qm_gte_ms && (*ts * 1_000) < qm_lt_ms + }) + .map(|(_, _, b)| b.clone()) + .collect(); + assert_eq!(qm_filtered_pinned.len(), 5); + assert!( + concat_docs(&qm_filtered_pinned).len() > small_chunks.chunk_capacity_bytes, + "filtered qm_bars_1m fixture must cross a BSON chunk boundary" + ); + + let qm_filtered_path = tmp.path().join("qmIntraday_filtered.bson"); + fs::write(&qm_filtered_path, concat_docs(&qm_filtered_pinned)).unwrap(); + let qm_file_out = tmp.path().join("qm_file_pinned"); + let qm_file_rep = run_curate_qm_bars_1m(&CurateQmBars1mArgs { + intraday_path: qm_filtered_path, + provider_mapping_path: map_path, + out_dir: qm_file_out.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: small_chunks, + ilp_options: IlpWriterOptions::default(), + }) + .expect("file qm_bars_1m pinned"); + let qm_pinned_rep = run_curate_qm_bars_1m_mongo_with_reader( + &qm_mongo_args, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(qm_filtered_pinned)), + 13, + ), + ) + .expect("mongo qm_bars_1m pinned"); + assert_eq!(qm_pinned_rep.rows_written, 4); + assert_eq!(qm_pinned_rep.curate_stats, qm_file_rep.curate_stats); + assert_eq!(qm_pinned_rep.ilp_stats, qm_file_rep.ilp_stats); + assert_eq!( + snapshot_files(&qm_mongo_args.out_dir), + snapshot_files(&qm_file_out) + ); + + let mut qm_reordered: Vec<(&str, i64, Vec)> = qm_corpus + .iter() + .filter(|(k, ts, _)| { + qm_keys.contains(*k) && (*ts * 1_000) >= qm_gte_ms && (*ts * 1_000) < qm_lt_ms + }) + .cloned() + .collect(); + qm_reordered.sort_by(|a, b| a.0.cmp(b.0).then_with(|| b.1.cmp(&a.1))); + let mut qm_reordered_args = qm_mongo_args; + qm_reordered_args.out_dir = tmp.path().join("qm_mongo_reordered"); + let qm_reordered_rep = run_curate_qm_bars_1m_mongo_with_reader( + &qm_reordered_args, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new( + qm_reordered.into_iter().map(|(_, _, b)| b).collect(), + )), + 11, + ), + ) + .expect("mongo qm_bars_1m reordered"); + assert!(qm_reordered_rep.chunks > 1); + assert_eq!(qm_reordered_rep.rows_written, qm_file_rep.rows_written); + assert_eq!(qm_reordered_rep.rows_written, 4); + assert_eq!(qm_reordered_rep.curate_stats, qm_file_rep.curate_stats); + assert_eq!(qm_reordered_rep.ilp_stats, qm_file_rep.ilp_stats); + assert_eq!( + snapshot_files(&qm_reordered_args.out_dir), + snapshot_files(&qm_file_out) + ); + let qm_file_rows = collect_ilp_bars_1m_rows(&qm_file_out, "bars_1m_qm.shard-"); + let qm_reordered_rows = + collect_ilp_bars_1m_rows(&qm_reordered_args.out_dir, "bars_1m_qm.shard-"); + assert_eq!(qm_reordered_rows, qm_file_rows); + assert_eq!(qm_reordered_rows.len(), 4); + assert!(qm_reordered_rows + .iter() + .all(|r| r.source == "qm_raw" && r.known_at == known_at)); + + // 3. fx_1m: apply production `eodSearchCode == "CAD.FOREX"` + epoch-second date filter. + let fx_mongo_args = CurateFx1mMongoArgs { + mongo: date_opts, + out_dir: tmp.path().join("fx_mongo_pinned"), + shard_count: 2, + stream_options: BsonStreamOptions { + chunk_capacity_bytes: 160, + max_doc_bytes: 1024 * 1024, + }, + ilp_options: IlpWriterOptions::default(), + }; + let fx_spec = fx_1m_read_spec(&fx_mongo_args); + let fx_filter = build_filter_document(SourceCollection::EodIntraday1M, &fx_spec).unwrap(); + let fx_key = fx_filter.get_str("eodSearchCode").unwrap(); + let fx_gte = fx_filter + .get_document("timestamp") + .unwrap() + .get_i64("$gte") + .unwrap(); + let fx_lt = fx_filter + .get_document("timestamp") + .unwrap() + .get_i64("$lt") + .unwrap(); + + let fx_filtered_pinned: Vec> = eod_corpus + .iter() + .filter(|(k, ts, _)| *k == fx_key && *ts >= fx_gte && *ts < fx_lt) + .map(|(_, _, b)| b.clone()) + .collect(); + assert_eq!(fx_filtered_pinned.len(), 3); + assert!( + concat_docs(&fx_filtered_pinned).len() > fx_mongo_args.stream_options.chunk_capacity_bytes, + "filtered fx_1m fixture must cross a BSON chunk boundary" + ); + + let fx_filtered_path = tmp.path().join("fx_filtered.bson"); + fs::write(&fx_filtered_path, concat_docs(&fx_filtered_pinned)).unwrap(); + let fx_file_out = tmp.path().join("fx_file_pinned"); + let fx_file_rep = run_curate_fx_1m(&CurateFx1mArgs { + intraday_path: fx_filtered_path, + out_dir: fx_file_out.clone(), + shard_count: 2, + stream_options: fx_mongo_args.stream_options, + ilp_options: IlpWriterOptions::default(), + }) + .expect("file fx_1m pinned"); + let fx_pinned_rep = run_curate_fx_1m_mongo_with_reader( + &fx_mongo_args, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(fx_filtered_pinned.clone())), + 11, + ), + ) + .expect("mongo fx_1m pinned"); + assert_eq!(fx_pinned_rep.rows_written, 2); + assert_eq!(fx_pinned_rep.curate_stats, fx_file_rep.curate_stats); + assert_eq!(fx_pinned_rep.ilp_stats, fx_file_rep.ilp_stats); + assert_eq!( + snapshot_files(&fx_mongo_args.out_dir), + snapshot_files(&fx_file_out) + ); + + let mut fx_reversed = fx_filtered_pinned; + fx_reversed.reverse(); + let mut fx_reordered_args = fx_mongo_args; + fx_reordered_args.out_dir = tmp.path().join("fx_mongo_reordered"); + let fx_reordered_rep = run_curate_fx_1m_mongo_with_reader( + &fx_reordered_args, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(fx_reversed)), + 7, + ), + ) + .expect("mongo fx_1m reordered"); + assert_eq!(fx_reordered_rep.rows_written, fx_file_rep.rows_written); + assert_eq!(fx_reordered_rep.rows_written, 2); + assert_eq!(fx_reordered_rep.curate_stats, fx_file_rep.curate_stats); + assert_eq!(fx_reordered_rep.ilp_stats, fx_file_rep.ilp_stats); + assert_eq!( + snapshot_files(&fx_reordered_args.out_dir), + snapshot_files(&fx_file_out) + ); + let fx_file_rows = collect_ilp_fx_1m_rows(&fx_file_out, "fx_1m.shard-"); + let fx_reordered_rows = collect_ilp_fx_1m_rows(&fx_reordered_args.out_dir, "fx_1m.shard-"); + assert_eq!(fx_reordered_rows, fx_file_rows); + assert_eq!(fx_reordered_rows.len(), 2); + assert!(fx_reordered_rows + .iter() + .all(|r| r.pair == "USDCAD" && r.source == "eod")); +} diff --git a/tools/curate-etl/tests/curate_bars_1m.rs b/tools/curate-etl/tests/curate_bars_1m.rs index f1b43972..9ade034d 100644 --- a/tools/curate-etl/tests/curate_bars_1m.rs +++ b/tools/curate-etl/tests/curate_bars_1m.rs @@ -619,7 +619,10 @@ fn curate_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothin assert!(!output.status.success()); assert!(output.stdout.is_empty()); let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("file mode only"), "stderr: {stderr}"); + assert!( + stderr.contains("MongoDB streaming flags require '--from-mongo'"), + "stderr: {stderr}" + ); assert!(stderr.contains("curate-bars-1m --eod-intraday"), "usage expected: {stderr}"); assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}"); assert!(!out.exists(), "parse failure must not create --out"); diff --git a/tools/curate-etl/tests/curate_fundamentals.rs b/tools/curate-etl/tests/curate_fundamentals.rs index b5fef7b5..4660479f 100644 --- a/tools/curate-etl/tests/curate_fundamentals.rs +++ b/tools/curate-etl/tests/curate_fundamentals.rs @@ -493,7 +493,7 @@ fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() { let mut lines_mongo = stderr_mongo.lines(); assert_eq!( lines_mongo.next(), - Some("error: unknown flag '--from-mongo' for curate-fundamentals") + Some("error: cannot combine '--from-mongo' with '--qm-financials', '--qm-financials-old', or '--qm-filings'") ); assert_eq!(lines_mongo.next(), Some("Usage:")); assert!( @@ -690,7 +690,7 @@ fn cli_parse_time_config_errors_fail_closed_before_touching_out() { ), ( &["--fiscal-period", "quarterly", "--mongo-uri", "mongodb://localhost:27017/stock"], - "error: unknown flag '--mongo-uri' for curate-fundamentals", + "error: MongoDB streaming flags require '--from-mongo'", ), ( &["--fiscal-period", "quarterly", "--k", "0"], @@ -716,3 +716,97 @@ fn cli_parse_time_config_errors_fail_closed_before_touching_out() { ); } } + +#[test] +fn cli_supports_qm_financials_old_curate_inputs_and_blocks_unsafe_mongo_uri() { + let dir = TempDir::new("old-and-curate-inputs"); + write_restatement_fixture(&dir.0); + + // Create a committed curate-inputs/ + current symlink layout. + let inputs_root = dir.0.join("curate_inputs"); + let gen_dir = inputs_root.join("gen-1"); + std::fs::create_dir_all(&gen_dir).unwrap(); + std::fs::copy( + dir.0.join("provider_mapping.tsv"), + gen_dir.join("provider_mapping.tsv"), + ) + .unwrap(); + std::fs::copy( + dir.0.join("listing_venues.tsv"), + gen_dir.join("listing_venues.tsv"), + ) + .unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&gen_dir, inputs_root.join("current")).unwrap(); + + // Run with --qm-financials-old (empty BSON) + --curate-inputs. + let old_bson = dir.0.join("qmFinancials-old.bson"); + std::fs::write(&old_bson, b"").unwrap(); + let out_dir = dir.0.join("out_curate_inputs"); + let res = cli() + .current_dir(&dir.0) + .args([ + "--qm-financials", + "qmFinancials.bson", + "--qm-financials-old", + "qmFinancials-old.bson", + "--qm-filings", + "qmFilings.bson", + "--curate-inputs", + "curate_inputs", + "--out", + "out_curate_inputs", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--quarterly-tokens", + "Q1,Q2,Q3,Q4", + ]) + .output() + .expect("run curate-fundamentals with --qm-financials-old and --curate-inputs"); + assert!( + res.status.success(), + "stderr: {}", + String::from_utf8_lossy(&res.stderr) + ); + assert!(out_dir.join("fundamentals_pit").is_dir()); + + // Fail-closed mongo_safety check on trading_admin URI: redacts password and creates no --out. + let out_unsafe = dir.0.join("out_unsafe_mongo"); + let secret = "T212_ADMIN_SECRET_PW"; + let unsafe_uri = + format!("mongodb://trading_admin:{secret}@localhost:27017/stock?authSource=admin"); + let res_unsafe = cli() + .current_dir(&dir.0) + .args([ + "--from-mongo", + "--mongo-uri", + &unsafe_uri, + "--with-qm-financials-old", + "--curate-inputs", + "curate_inputs", + "--out", + "out_unsafe_mongo", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ]) + .output() + .expect("run curate-fundamentals --from-mongo with trading_admin"); + assert_eq!(res_unsafe.status.code(), Some(1)); + assert!(res_unsafe.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&res_unsafe.stderr); + assert!( + !stderr.contains(secret), + "secret leaked in stderr: {stderr}" + ); + assert!(!out_unsafe.exists(), "unsafe URI must not create --out"); +} diff --git a/tools/curate-etl/tests/curate_macro.rs b/tools/curate-etl/tests/curate_macro.rs index c35eefbf..e990f891 100644 --- a/tools/curate-etl/tests/curate_macro.rs +++ b/tools/curate-etl/tests/curate_macro.rs @@ -430,7 +430,7 @@ fn cli_invalid_flags_print_error_and_usage_without_touching_out() { "--out", "out_from_mongo", ], - "error: unknown flag '--from-mongo' for curate-macro", + "error: cannot combine '--from-mongo' with '--te-data'", ), ( &[ @@ -624,7 +624,7 @@ fn cli_help_lists_curate_macro_and_parse_errors_print_usage_without_writing() { let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0); let cli_out = dir.0.join("cli_out"); - // `--mongo-uri` is not a file-mode flag; it must be rejected before any run. + // `--mongo-uri` requires `--from-mongo`; mixing it into file mode fails before any run. let result = cli() .arg("--te-data") .arg(&te_data_path) @@ -640,7 +640,7 @@ fn cli_help_lists_curate_macro_and_parse_errors_print_usage_without_writing() { assert!(result.stdout.is_empty(), "{result:?}"); let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr"); assert!( - stderr.starts_with("error: unknown flag '--mongo-uri' for curate-macro\n"), + stderr.starts_with("error: MongoDB streaming flags require '--from-mongo'\n"), "{stderr:?}" ); assert!(stderr.contains("Usage:"), "{stderr:?}"); diff --git a/tools/curate-etl/tests/curate_posts.rs b/tools/curate-etl/tests/curate_posts.rs index c349ceec..c75d85d6 100644 --- a/tools/curate-etl/tests/curate_posts.rs +++ b/tools/curate-etl/tests/curate_posts.rs @@ -12,8 +12,9 @@ use parquet::record::RowAccessor; const POSTED: i64 = 1_718_460_000; const EDITED: i64 = POSTED + 3_600; -const PARTITION: &str = "events/year=2024/part.parquet"; -const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\n"; +const PARTITION: &str = "events/year=2024/part-posts.parquet"; +const EVENTS_PARTITION: &str = "events/year=2024/part.parquet"; +const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\nqm\tSYM_1\t2020-01-01\t\t555\n"; const CUSTOM_FLAGS: &[&str] = &[ "--key-field=channel", "--spiel-id-field=id", @@ -75,8 +76,42 @@ fn write_posts(path: &Path, scale: i64, edited_text: &str) { fs::write(path, bytes).expect("write concatenated BSON"); } +fn curate_events(dir: &Path, out: &str) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .arg("curate-events") + .current_dir(dir) + .args([ + "--qm-filings", + "filings.bson", + "--qm-earnings", + "earnings.bson", + "--provider-mapping=mapping.tsv", + "--out", + out, + "--filings-form-type-field", + "formType", + ]) + .output() + .expect("run curate-events") +} + +fn write_events_fixtures(dir: &Path) { + let filing = doc! { + "symbol": "SYM_1", + "timefiled": "2024-06-10T16:15:00 EDT", + "formType": "8-K", + }; + let earning = doc! { + "qmSearchCode": "SYM_1", + "reportDate": "2024-06-12", + "announceTime": "AMC", + }; + fs::write(dir.join("filings.bson"), filing.to_vec().unwrap()).expect("write filings.bson"); + fs::write(dir.join("earnings.bson"), earning.to_vec().unwrap()).expect("write earnings.bson"); +} + #[test] -fn cli_publishes_runner_equivalent_posts_and_preserves_an_existing_partition() { +fn cli_publishes_runner_equivalent_posts_and_copublishes_with_curate_events() { // Use the runner's fixed custom-field and edited-post fixture, plus a wire and an unmapped row. let path = std::env::temp_dir().join(format!("curate-posts-cli-{}", std::process::id())); fs::create_dir(&path).expect("create isolated test directory"); @@ -140,7 +175,7 @@ fn cli_publishes_runner_equivalent_posts_and_preserves_an_existing_partition() { assert_eq!(row.get_int(0).unwrap(), listing); assert_eq!(row.get_timestamp_micros(1).unwrap(), POSTED * 1_000_000); assert_eq!(row.get_timestamp_micros(2).unwrap(), known_at * 1_000_000); - assert_eq!(row.get_string(4).unwrap(), "post"); + assert_eq!(row.get_string(4).unwrap(), "ceo_post"); assert_eq!(row.get_string(5).unwrap(), subtype); } @@ -153,21 +188,45 @@ fn cli_publishes_runner_equivalent_posts_and_preserves_an_existing_partition() { assert!(!edited_text_visible(EDITED * 1_000_000 - 1)); assert!(edited_text_visible(EDITED * 1_000_000)); + // Co-publish curate-events into the same --out and verify part-posts.parquet stays intact. + write_events_fixtures(&dir.0); + let ev_res = curate_events(&dir.0, "millis"); + assert!(ev_res.status.success(), "curate-events: {:?}", ev_res); + assert!(ev_res.stderr.is_empty()); + let events_part = dir.0.join("millis").join(EVENTS_PARTITION); + let events_bytes = fs::read(&events_part).unwrap(); + assert_eq!(fs::read(&partition).unwrap(), baseline); + + // Re-running curate-posts updates part-posts.parquet with exit code 0 while preserving part.parquet. write_posts(&bson, 1_000, "replacement"); let retry = curate(&dir.0, "millis", "millis"); - assert_eq!(retry.status.code(), Some(1)); - assert!(retry.stdout.is_empty()); - assert!(String::from_utf8_lossy(&retry.stderr) - .starts_with("error: refusing to overwrite existing events partition")); - assert_eq!(fs::read(partition).unwrap(), baseline); + assert!(retry.status.success(), "curate-posts rerun: {:?}", retry); + assert!(retry.stderr.is_empty()); + assert_eq!(fs::read(&events_part).unwrap(), events_bytes); + let rerun_reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap(); + let rerun_rows: Vec<_> = rerun_reader + .get_row_iter(None) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!(rerun_rows.len(), 2); + assert_eq!(rerun_rows[0].get_string(4).unwrap(), "ceo_post"); + assert!(rerun_rows[0] + .get_string(6) + .unwrap() + .contains(r#""text":"replacement""#)); } #[test] fn cli_reports_usage_for_invalid_posts_flags() { for (args, error) in [ ( - &["--from-mongo"][..], - "unknown flag '--from-mongo' for curate-posts", + &["--from-mongo", "--ceo-posts", "p.bson"][..], + "cannot combine '--from-mongo' with '--ceo-posts'", + ), + ( + &["--mongo-uri", "mongodb://u:s3cr3t@localhost:27017/stock"][..], + "MongoDB streaming flags require '--from-mongo'", ), ( &["--timestamp-unit", "--out=x"][..], diff --git a/tools/curate-etl/tests/curate_qm_bars_1m.rs b/tools/curate-etl/tests/curate_qm_bars_1m.rs index 48eca37a..4d530a52 100644 --- a/tools/curate-etl/tests/curate_qm_bars_1m.rs +++ b/tools/curate-etl/tests/curate_qm_bars_1m.rs @@ -600,7 +600,10 @@ fn curate_qm_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_not assert!(!output.status.success()); assert!(output.stdout.is_empty()); let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("file mode only"), "stderr: {stderr}"); + assert!( + stderr.contains("MongoDB streaming flags require '--from-mongo'"), + "stderr: {stderr}" + ); assert!( stderr.contains("curate-qm-bars-1m --qm-intraday"), "usage expected: {stderr}"