T-212: M2.3t — Add --qm-financials-old merge and Option B --from-mongo streaming for M2 collections in curate-etl
This commit is contained in:
commit
88d447bdfd
80 changed files with 13900 additions and 1488 deletions
|
|
@ -33,6 +33,7 @@ interface BenchContinuityRow {
|
||||||
interface BenchListingRow {
|
interface BenchListingRow {
|
||||||
listing_id: number;
|
listing_id: number;
|
||||||
currency: string;
|
currency: string;
|
||||||
|
mic: string;
|
||||||
listed_to: string | null;
|
listed_to: string | null;
|
||||||
delist_reason: string | null;
|
delist_reason: string | null;
|
||||||
terminal_return: 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<BenchListingRow>(LISTING_COUNT);
|
const listings = new Array<BenchListingRow>(LISTING_COUNT);
|
||||||
for (let i = 0; i < LISTING_COUNT; i++) {
|
for (let i = 0; i < LISTING_COUNT; i++) {
|
||||||
const id = i + 1;
|
const id = i + 1;
|
||||||
const currency = id % 5 === 0 ? 'CAD' : 'USD';
|
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) {
|
if (id <= OTC_CONTINUITY_COUNT) {
|
||||||
listings[i] = {
|
listings[i] = {
|
||||||
listing_id: id,
|
listing_id: id,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: '2023-03-10',
|
listed_to: '2023-03-10',
|
||||||
delist_reason: 'moved_to_otc',
|
delist_reason: 'moved_to_otc',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -92,6 +100,7 @@ function buildSyntheticTables(): {
|
||||||
listings[i] = {
|
listings[i] = {
|
||||||
listing_id: id,
|
listing_id: id,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: '2024-11-07',
|
listed_to: '2024-11-07',
|
||||||
delist_reason: 'bankruptcy_cancelled',
|
delist_reason: 'bankruptcy_cancelled',
|
||||||
terminal_return: '-1.000000',
|
terminal_return: '-1.000000',
|
||||||
|
|
@ -100,6 +109,7 @@ function buildSyntheticTables(): {
|
||||||
listings[i] = {
|
listings[i] = {
|
||||||
listing_id: id,
|
listing_id: id,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: null,
|
listed_to: null,
|
||||||
delist_reason: 'active',
|
delist_reason: 'active',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -110,6 +120,7 @@ function buildSyntheticTables(): {
|
||||||
listings[i] = {
|
listings[i] = {
|
||||||
listing_id: id,
|
listing_id: id,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: missingDate ? null : '2023-06-15',
|
listed_to: missingDate ? null : '2023-06-15',
|
||||||
delist_reason: 'unknown_involuntary',
|
delist_reason: 'unknown_involuntary',
|
||||||
terminal_return: '-0.300000',
|
terminal_return: '-0.300000',
|
||||||
|
|
@ -118,6 +129,7 @@ function buildSyntheticTables(): {
|
||||||
listings[i] = {
|
listings[i] = {
|
||||||
listing_id: id,
|
listing_id: id,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: '2022-12-30',
|
listed_to: '2022-12-30',
|
||||||
delist_reason: null,
|
delist_reason: null,
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -126,6 +138,7 @@ function buildSyntheticTables(): {
|
||||||
listings[i] = {
|
listings[i] = {
|
||||||
listing_id: id,
|
listing_id: id,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: null,
|
listed_to: null,
|
||||||
delist_reason: 'active',
|
delist_reason: 'active',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -266,7 +279,10 @@ async function main(): Promise<void> {
|
||||||
}
|
}
|
||||||
|
|
||||||
const totalRowsExported =
|
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);
|
const rowsPerSec = totalRowsExported / (elapsedMs / 1000);
|
||||||
// process.resourceUsage().maxRSS is reported in KiB on Linux.
|
// process.resourceUsage().maxRSS is reported in KiB on Linux.
|
||||||
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
|
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
|
||||||
|
|
@ -276,7 +292,7 @@ async function main(): Promise<void> {
|
||||||
` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n`
|
` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n`
|
||||||
);
|
);
|
||||||
process.stdout.write(
|
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(
|
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`
|
` 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`
|
||||||
|
|
|
||||||
|
|
@ -20,9 +20,34 @@ import type { SecurityMasterQueryable } from './persist';
|
||||||
export const CURATE_INPUT_FILES = Object.freeze({
|
export const CURATE_INPUT_FILES = Object.freeze({
|
||||||
providerMapping: 'provider_mapping.tsv',
|
providerMapping: 'provider_mapping.tsv',
|
||||||
listingCurrencies: 'listing_currencies.tsv',
|
listingCurrencies: 'listing_currencies.tsv',
|
||||||
|
listingVenues: 'listing_venues.tsv',
|
||||||
delistings: 'delistings.tsv',
|
delistings: 'delistings.tsv',
|
||||||
} as const);
|
} 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<Record<string, ListingStatutoryLagVenue>> = 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_GENERATIONS_DIR = 'generations';
|
||||||
export const CURATE_INPUT_CURRENT_LINK = 'current';
|
export const CURATE_INPUT_CURRENT_LINK = 'current';
|
||||||
export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock';
|
export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock';
|
||||||
|
|
@ -50,6 +75,9 @@ export type CurateInputExportErrorCode =
|
||||||
| 'OVERLAPPING_PROVIDER_MAPPING'
|
| 'OVERLAPPING_PROVIDER_MAPPING'
|
||||||
| 'UNSORTED_PROVIDER_MAPPING_STREAM'
|
| 'UNSORTED_PROVIDER_MAPPING_STREAM'
|
||||||
| 'DUPLICATE_LISTING_CURRENCY'
|
| 'DUPLICATE_LISTING_CURRENCY'
|
||||||
|
| 'UNKNOWN_LISTING_MIC'
|
||||||
|
| 'INVALID_LISTING_VENUE'
|
||||||
|
| 'DUPLICATE_LISTING_VENUE'
|
||||||
| 'UNSORTED_LISTING_STREAM'
|
| 'UNSORTED_LISTING_STREAM'
|
||||||
| 'INVALID_TERMINAL_RETURN'
|
| 'INVALID_TERMINAL_RETURN'
|
||||||
| 'INVALID_DELISTING_OUTCOME'
|
| 'INVALID_DELISTING_OUTCOME'
|
||||||
|
|
@ -59,7 +87,8 @@ export type CurateInputExportErrorCode =
|
||||||
| 'DUPLICATE_OTC_CONTINUITY'
|
| 'DUPLICATE_OTC_CONTINUITY'
|
||||||
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
|
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
|
||||||
| 'PUBLISH_LOCK_TIMEOUT'
|
| 'PUBLISH_LOCK_TIMEOUT'
|
||||||
| 'PUBLISH_ROLLBACK_FAILED';
|
| 'PUBLISH_ROLLBACK_FAILED'
|
||||||
|
| 'INCOMPLETE_SNAPSHOT';
|
||||||
|
|
||||||
export interface CurateInputExportErrorOptions {
|
export interface CurateInputExportErrorOptions {
|
||||||
readonly code: CurateInputExportErrorCode;
|
readonly code: CurateInputExportErrorCode;
|
||||||
|
|
@ -105,6 +134,11 @@ export interface ListingCurrencyExportRow {
|
||||||
readonly currency: string;
|
readonly currency: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ListingVenueExportRow {
|
||||||
|
readonly listingId: number;
|
||||||
|
readonly venue: ListingStatutoryLagVenue;
|
||||||
|
}
|
||||||
|
|
||||||
export interface DelistingExportRow {
|
export interface DelistingExportRow {
|
||||||
readonly sourceId: string;
|
readonly sourceId: string;
|
||||||
readonly delistDate: string;
|
readonly delistDate: string;
|
||||||
|
|
@ -189,6 +223,7 @@ export interface PinnedCurateInputSnapshot {
|
||||||
readonly generationDir: string;
|
readonly generationDir: string;
|
||||||
readonly providerMapping: string;
|
readonly providerMapping: string;
|
||||||
readonly listingCurrencies: string;
|
readonly listingCurrencies: string;
|
||||||
|
readonly listingVenues: string;
|
||||||
readonly delistings: string;
|
readonly delistings: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -201,6 +236,7 @@ export interface ExportCurateInputsResult {
|
||||||
readonly delistingMappingSource: string;
|
readonly delistingMappingSource: string;
|
||||||
readonly providerMapping: ExportCurateInputsFileStats;
|
readonly providerMapping: ExportCurateInputsFileStats;
|
||||||
readonly listingCurrencies: ExportCurateInputsFileStats;
|
readonly listingCurrencies: ExportCurateInputsFileStats;
|
||||||
|
readonly listingVenues: ExportCurateInputsFileStats;
|
||||||
readonly delistings: ExportCurateInputsFileStats & {
|
readonly delistings: ExportCurateInputsFileStats & {
|
||||||
readonly stats: DelistingExportStats;
|
readonly stats: DelistingExportStats;
|
||||||
};
|
};
|
||||||
|
|
@ -232,6 +268,7 @@ interface DbContinuityRow {
|
||||||
|
|
||||||
interface DbListingRow {
|
interface DbListingRow {
|
||||||
listing_id: number;
|
listing_id: number;
|
||||||
|
mic: string | null;
|
||||||
currency: string | null;
|
currency: string | null;
|
||||||
listed_to: string | null;
|
listed_to: string | null;
|
||||||
delist_reason: string | null;
|
delist_reason: string | null;
|
||||||
|
|
@ -596,6 +633,95 @@ export function formatListingCurrenciesTsv(rows: readonly ListingCurrencyExportR
|
||||||
return joinLinesInChunks(lines);
|
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 {
|
function validateDelistingExportRow(row: DelistingExportRow, index: number): ValidatedDelistingRow {
|
||||||
const fallbackKey = `row#${index}`;
|
const fallbackKey = `row#${index}`;
|
||||||
const sourceId = assertNonBlankVerbatim(row.sourceId, 'delistings', fallbackKey, 'source_id');
|
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 `<outDir>/current`
|
* Resolves and pins the currently active immutable generation directory via `<outDir>/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 `<outDir>/current`.
|
* PostgreSQL snapshot and remain immutable even if a concurrent export refreshes `<outDir>/current`.
|
||||||
*/
|
*/
|
||||||
export async function pinCurateInputSnapshot(
|
export async function pinCurateInputSnapshot(
|
||||||
outDir: string,
|
outDir: string,
|
||||||
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath'>
|
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath' | 'access'>
|
||||||
): Promise<PinnedCurateInputSnapshot> {
|
): Promise<PinnedCurateInputSnapshot> {
|
||||||
if (typeof outDir !== 'string' || outDir.trim().length === 0) {
|
if (typeof outDir !== 'string' || outDir.trim().length === 0) {
|
||||||
throw new CurateInputExportError({
|
throw new CurateInputExportError({
|
||||||
|
|
@ -1207,16 +1333,41 @@ export async function pinCurateInputSnapshot(
|
||||||
}
|
}
|
||||||
const normalizedOutDir = outDir.trim();
|
const normalizedOutDir = outDir.trim();
|
||||||
const fsRealpath = fsHooks?.realpath ?? realpath;
|
const fsRealpath = fsHooks?.realpath ?? realpath;
|
||||||
|
const fsAccess = fsHooks?.access ?? access;
|
||||||
const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK);
|
const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK);
|
||||||
const generationDir = await fsRealpath(currentLink);
|
const generationDir = await fsRealpath(currentLink);
|
||||||
const generationId = basename(generationDir);
|
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 {
|
return {
|
||||||
outDir: normalizedOutDir,
|
outDir: normalizedOutDir,
|
||||||
generationId,
|
generationId,
|
||||||
generationDir,
|
generationDir,
|
||||||
providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping),
|
providerMapping,
|
||||||
listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies),
|
listingCurrencies,
|
||||||
delistings: join(generationDir, CURATE_INPUT_FILES.delistings),
|
listingVenues,
|
||||||
|
delistings,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1225,7 +1376,7 @@ export async function pinCurateInputSnapshot(
|
||||||
* transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable
|
* transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable
|
||||||
* generation directory under `<outDir>/generations/<generationId>`, and atomically commits
|
* generation directory under `<outDir>/generations/<generationId>`, and atomically commits
|
||||||
* `<outDir>/current` (plus top-level symlinks `provider_mapping.tsv`, `listing_currencies.tsv`,
|
* `<outDir>/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(
|
export async function exportCurateInputs(
|
||||||
queryable: SecurityMasterQueryable,
|
queryable: SecurityMasterQueryable,
|
||||||
|
|
@ -1299,31 +1450,37 @@ export async function exportCurateInputs(
|
||||||
const targets = {
|
const targets = {
|
||||||
providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping),
|
providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping),
|
||||||
listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies),
|
listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies),
|
||||||
|
listingVenues: join(outDir, CURATE_INPUT_FILES.listingVenues),
|
||||||
delistings: join(outDir, CURATE_INPUT_FILES.delistings),
|
delistings: join(outDir, CURATE_INPUT_FILES.delistings),
|
||||||
};
|
};
|
||||||
const stagedFiles = {
|
const stagedFiles = {
|
||||||
providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping),
|
providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping),
|
||||||
listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies),
|
listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies),
|
||||||
|
listingVenues: join(stagingDir, CURATE_INPUT_FILES.listingVenues),
|
||||||
delistings: join(stagingDir, CURATE_INPUT_FILES.delistings),
|
delistings: join(stagingDir, CURATE_INPUT_FILES.delistings),
|
||||||
};
|
};
|
||||||
const generationFiles = {
|
const generationFiles = {
|
||||||
providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping),
|
providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping),
|
||||||
listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies),
|
listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies),
|
||||||
|
listingVenues: join(generationDir, CURATE_INPUT_FILES.listingVenues),
|
||||||
delistings: join(generationDir, CURATE_INPUT_FILES.delistings),
|
delistings: join(generationDir, CURATE_INPUT_FILES.delistings),
|
||||||
};
|
};
|
||||||
const backups = {
|
const backups = {
|
||||||
providerMapping: `${targets.providerMapping}.${runTag}.bak`,
|
providerMapping: `${targets.providerMapping}.${runTag}.bak`,
|
||||||
listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`,
|
listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`,
|
||||||
|
listingVenues: `${targets.listingVenues}.${runTag}.bak`,
|
||||||
delistings: `${targets.delistings}.${runTag}.bak`,
|
delistings: `${targets.delistings}.${runTag}.bak`,
|
||||||
};
|
};
|
||||||
const linkTemps = {
|
const linkTemps = {
|
||||||
providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`,
|
providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`,
|
||||||
listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`,
|
listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`,
|
||||||
|
listingVenues: `${targets.listingVenues}.${runTag}.link.tmp`,
|
||||||
delistings: `${targets.delistings}.${runTag}.link.tmp`,
|
delistings: `${targets.delistings}.${runTag}.link.tmp`,
|
||||||
};
|
};
|
||||||
|
|
||||||
let providerMappingHandle: FileHandle | null = null;
|
let providerMappingHandle: FileHandle | null = null;
|
||||||
let listingCurrenciesHandle: FileHandle | null = null;
|
let listingCurrenciesHandle: FileHandle | null = null;
|
||||||
|
let listingVenuesHandle: FileHandle | null = null;
|
||||||
let delistingsHandle: FileHandle | null = null;
|
let delistingsHandle: FileHandle | null = null;
|
||||||
|
|
||||||
let providerMappingRowsIn = 0;
|
let providerMappingRowsIn = 0;
|
||||||
|
|
@ -1334,11 +1491,20 @@ export async function exportCurateInputs(
|
||||||
let listingCurrenciesRowsOut = 0;
|
let listingCurrenciesRowsOut = 0;
|
||||||
let listingCurrenciesBytes = 0;
|
let listingCurrenciesBytes = 0;
|
||||||
|
|
||||||
|
let listingVenuesRowsIn = 0;
|
||||||
|
let listingVenuesRowsOut = 0;
|
||||||
|
let listingVenuesBytes = 0;
|
||||||
|
|
||||||
let delistingsBytes = 0;
|
let delistingsBytes = 0;
|
||||||
let delistingsStats!: DelistingExportStats;
|
let delistingsStats!: DelistingExportStats;
|
||||||
|
|
||||||
type PublishKey = 'providerMapping' | 'listingCurrencies' | 'delistings';
|
type PublishKey = 'providerMapping' | 'listingCurrencies' | 'listingVenues' | 'delistings';
|
||||||
const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings'];
|
const publishOrder: PublishKey[] = [
|
||||||
|
'providerMapping',
|
||||||
|
'listingCurrencies',
|
||||||
|
'listingVenues',
|
||||||
|
'delistings',
|
||||||
|
];
|
||||||
|
|
||||||
let stagingCreated = false;
|
let stagingCreated = false;
|
||||||
let publishLockAcquired = false;
|
let publishLockAcquired = false;
|
||||||
|
|
@ -1353,6 +1519,7 @@ export async function exportCurateInputs(
|
||||||
|
|
||||||
providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx');
|
providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx');
|
||||||
listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx');
|
listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx');
|
||||||
|
listingVenuesHandle = await fsOpen(stagedFiles.listingVenues, 'wx');
|
||||||
delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx');
|
delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx');
|
||||||
|
|
||||||
const otcByFromListingId = new Map<number, ContinuityExportSourceRow>();
|
const otcByFromListingId = new Map<number, ContinuityExportSourceRow>();
|
||||||
|
|
@ -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;
|
let lastListingId: number | null = null;
|
||||||
for (;;) {
|
for (;;) {
|
||||||
const res =
|
const res =
|
||||||
|
|
@ -1489,6 +1656,7 @@ export async function exportCurateInputs(
|
||||||
? await queryable.query<DbListingRow>(
|
? await queryable.query<DbListingRow>(
|
||||||
`SELECT
|
`SELECT
|
||||||
listing_id,
|
listing_id,
|
||||||
|
mic,
|
||||||
btrim(currency) AS currency,
|
btrim(currency) AS currency,
|
||||||
to_char(listed_to, 'YYYY-MM-DD') AS listed_to,
|
to_char(listed_to, 'YYYY-MM-DD') AS listed_to,
|
||||||
delist_reason,
|
delist_reason,
|
||||||
|
|
@ -1501,6 +1669,7 @@ export async function exportCurateInputs(
|
||||||
: await queryable.query<DbListingRow>(
|
: await queryable.query<DbListingRow>(
|
||||||
`SELECT
|
`SELECT
|
||||||
listing_id,
|
listing_id,
|
||||||
|
mic,
|
||||||
btrim(currency) AS currency,
|
btrim(currency) AS currency,
|
||||||
to_char(listed_to, 'YYYY-MM-DD') AS listed_to,
|
to_char(listed_to, 'YYYY-MM-DD') AS listed_to,
|
||||||
delist_reason,
|
delist_reason,
|
||||||
|
|
@ -1517,6 +1686,7 @@ export async function exportCurateInputs(
|
||||||
}
|
}
|
||||||
|
|
||||||
const chunkLines: string[] = [];
|
const chunkLines: string[] = [];
|
||||||
|
const venueChunkLines: string[] = [];
|
||||||
for (const row of res.rows) {
|
for (const row of res.rows) {
|
||||||
const listingId = assertPositiveI32(
|
const listingId = assertPositiveI32(
|
||||||
row.listing_id,
|
row.listing_id,
|
||||||
|
|
@ -1548,9 +1718,13 @@ export async function exportCurateInputs(
|
||||||
}
|
}
|
||||||
|
|
||||||
const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency');
|
const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency');
|
||||||
|
const venue = resolveListingVenueForMic(row.mic, 'listing', listingKey);
|
||||||
chunkLines.push(`${listingId}\t${currency}`);
|
chunkLines.push(`${listingId}\t${currency}`);
|
||||||
|
venueChunkLines.push(`${listingId}\t${venue}`);
|
||||||
listingCurrenciesRowsIn += 1;
|
listingCurrenciesRowsIn += 1;
|
||||||
listingCurrenciesRowsOut += 1;
|
listingCurrenciesRowsOut += 1;
|
||||||
|
listingVenuesRowsIn += 1;
|
||||||
|
listingVenuesRowsOut += 1;
|
||||||
|
|
||||||
const otc = otcByFromListingId.get(listingId);
|
const otc = otcByFromListingId.get(listingId);
|
||||||
const hasTerminalReturn =
|
const hasTerminalReturn =
|
||||||
|
|
@ -1607,6 +1781,11 @@ export async function exportCurateInputs(
|
||||||
await writeAll(listingCurrenciesHandle, buf);
|
await writeAll(listingCurrenciesHandle, buf);
|
||||||
listingCurrenciesBytes += buf.byteLength;
|
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) {
|
if (res.rows.length < chunkSize) {
|
||||||
break;
|
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.sync();
|
||||||
await providerMappingHandle.close();
|
await providerMappingHandle.close();
|
||||||
providerMappingHandle = null;
|
providerMappingHandle = null;
|
||||||
|
|
@ -1851,6 +2030,10 @@ export async function exportCurateInputs(
|
||||||
await listingCurrenciesHandle.close();
|
await listingCurrenciesHandle.close();
|
||||||
listingCurrenciesHandle = null;
|
listingCurrenciesHandle = null;
|
||||||
|
|
||||||
|
await listingVenuesHandle.sync();
|
||||||
|
await listingVenuesHandle.close();
|
||||||
|
listingVenuesHandle = null;
|
||||||
|
|
||||||
await delistingsHandle.sync();
|
await delistingsHandle.sync();
|
||||||
await delistingsHandle.close();
|
await delistingsHandle.close();
|
||||||
delistingsHandle = null;
|
delistingsHandle = null;
|
||||||
|
|
@ -1915,7 +2098,12 @@ export async function exportCurateInputs(
|
||||||
currentTempCreated = false;
|
currentTempCreated = false;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Close any still-open staged file handles.
|
// 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) {
|
if (handle !== null) {
|
||||||
await handle.close().catch(() => {});
|
await handle.close().catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
@ -2027,6 +2215,12 @@ export async function exportCurateInputs(
|
||||||
rowsOut: listingCurrenciesRowsOut,
|
rowsOut: listingCurrenciesRowsOut,
|
||||||
bytesWritten: listingCurrenciesBytes,
|
bytesWritten: listingCurrenciesBytes,
|
||||||
},
|
},
|
||||||
|
listingVenues: {
|
||||||
|
path: generationFiles.listingVenues,
|
||||||
|
rowsIn: listingVenuesRowsIn,
|
||||||
|
rowsOut: listingVenuesRowsOut,
|
||||||
|
bytesWritten: listingVenuesBytes,
|
||||||
|
},
|
||||||
delistings: {
|
delistings: {
|
||||||
path: generationFiles.delistings,
|
path: generationFiles.delistings,
|
||||||
rowsIn: delistingsStats.rowsIn,
|
rowsIn: delistingsStats.rowsIn,
|
||||||
|
|
@ -2034,7 +2228,8 @@ export async function exportCurateInputs(
|
||||||
bytesWritten: delistingsBytes,
|
bytesWritten: delistingsBytes,
|
||||||
stats: delistingsStats,
|
stats: delistingsStats,
|
||||||
},
|
},
|
||||||
totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes,
|
totalBytesWritten:
|
||||||
|
providerMappingBytes + listingCurrenciesBytes + listingVenuesBytes + delistingsBytes,
|
||||||
cleanupWarnings,
|
cleanupWarnings,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,10 @@ import { join } from 'node:path';
|
||||||
import type { MongoDBClient } from '@stock-bot/mongodb';
|
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`,
|
* `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([
|
export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([
|
||||||
'eodPrices',
|
'eodPrices',
|
||||||
|
|
@ -17,6 +18,12 @@ export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([
|
||||||
'ceoShorts',
|
'ceoShorts',
|
||||||
'qmFilings',
|
'qmFilings',
|
||||||
'qmEarnings',
|
'qmEarnings',
|
||||||
|
'qmFinancials',
|
||||||
|
'qmFinancials-old',
|
||||||
|
'ceoPosts',
|
||||||
|
'teData',
|
||||||
|
'eodIntraday1M',
|
||||||
|
'qmIntraday',
|
||||||
] as const);
|
] as const);
|
||||||
|
|
||||||
export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number];
|
export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number];
|
||||||
|
|
@ -390,7 +397,7 @@ function validateExportOptions(options: ExportRawBsonCollectionOptions): Validat
|
||||||
throw new RawBsonExportError({
|
throw new RawBsonExportError({
|
||||||
code: 'DISALLOWED_COLLECTION',
|
code: 'DISALLOWED_COLLECTION',
|
||||||
collection: collectionName || '<empty>',
|
collection: collectionName || '<empty>',
|
||||||
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(', ')})`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -60,11 +60,15 @@ export {
|
||||||
exportCurateInputs,
|
exportCurateInputs,
|
||||||
formatDelistingsTsv,
|
formatDelistingsTsv,
|
||||||
formatListingCurrenciesTsv,
|
formatListingCurrenciesTsv,
|
||||||
|
formatListingVenuesTsv,
|
||||||
formatPlainDecimal,
|
formatPlainDecimal,
|
||||||
formatProviderMappingTsv,
|
formatProviderMappingTsv,
|
||||||
isValidStrictYmd,
|
isValidStrictYmd,
|
||||||
|
LISTING_STATUTORY_LAG_VENUES,
|
||||||
|
LISTING_VENUE_BY_MIC,
|
||||||
MAX_EXPORT_CHUNK_SIZE,
|
MAX_EXPORT_CHUNK_SIZE,
|
||||||
pinCurateInputSnapshot,
|
pinCurateInputSnapshot,
|
||||||
|
resolveListingVenueForMic,
|
||||||
type BuildDelistingExportRowsOptions,
|
type BuildDelistingExportRowsOptions,
|
||||||
type BuildDelistingExportRowsResult,
|
type BuildDelistingExportRowsResult,
|
||||||
type ContinuityExportSourceRow,
|
type ContinuityExportSourceRow,
|
||||||
|
|
@ -79,6 +83,8 @@ export {
|
||||||
type ExportCurateInputsResult,
|
type ExportCurateInputsResult,
|
||||||
type ListingCurrencyExportRow,
|
type ListingCurrencyExportRow,
|
||||||
type ListingDelistingSourceRow,
|
type ListingDelistingSourceRow,
|
||||||
|
type ListingStatutoryLagVenue,
|
||||||
|
type ListingVenueExportRow,
|
||||||
type PinnedCurateInputSnapshot,
|
type PinnedCurateInputSnapshot,
|
||||||
type ProviderMappingExportRow,
|
type ProviderMappingExportRow,
|
||||||
} from './export-curate-inputs';
|
} from './export-curate-inputs';
|
||||||
|
|
@ -128,6 +134,7 @@ export {
|
||||||
|
|
||||||
export {
|
export {
|
||||||
assertExportRawBsonSafety,
|
assertExportRawBsonSafety,
|
||||||
|
DEFAULT_RAW_BSON_EXPORT_COLLECTIONS,
|
||||||
EXPORT_RAW_BSON_USAGE,
|
EXPORT_RAW_BSON_USAGE,
|
||||||
formatExportRawBsonSummary,
|
formatExportRawBsonSummary,
|
||||||
parseExportRawBsonArgs,
|
parseExportRawBsonArgs,
|
||||||
|
|
@ -141,6 +148,11 @@ export {
|
||||||
type RunExportRawBsonOutput,
|
type RunExportRawBsonOutput,
|
||||||
} from './run-export-raw-bson';
|
} from './run-export-raw-bson';
|
||||||
|
|
||||||
|
export {
|
||||||
|
assertReadOnlyMongoDiagnosticSafety,
|
||||||
|
type ReadOnlyMongoDiagnosticSafetyOptions,
|
||||||
|
} from './read-only-mongo-safety';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
escapeSqlLiteral,
|
escapeSqlLiteral,
|
||||||
generateExchangeSeedSql,
|
generateExchangeSeedSql,
|
||||||
|
|
@ -360,11 +372,13 @@ export {
|
||||||
} from './security-type';
|
} from './security-type';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
assertProbeSourceFieldShapesSafety,
|
||||||
parseProbeSourceFieldShapesArgs,
|
parseProbeSourceFieldShapesArgs,
|
||||||
PROBE_SOURCE_FIELD_SHAPES_USAGE,
|
PROBE_SOURCE_FIELD_SHAPES_USAGE,
|
||||||
runCli as runProbeSourceFieldShapesCli,
|
runCli as runProbeSourceFieldShapesCli,
|
||||||
runSourceFieldShapesProbe,
|
runSourceFieldShapesProbe,
|
||||||
type ParsedProbeSourceFieldShapesArgs,
|
type ParsedProbeSourceFieldShapesArgs,
|
||||||
|
type RunProbeSourceFieldShapesCliOverrides,
|
||||||
type RunSourceFieldShapesProbeDeps,
|
type RunSourceFieldShapesProbeDeps,
|
||||||
type RunSourceFieldShapesProbeOptions,
|
type RunSourceFieldShapesProbeOptions,
|
||||||
type RunSourceFieldShapesProbeOutput,
|
type RunSourceFieldShapesProbeOutput,
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,9 @@ import { mkdir, writeFile } from 'node:fs/promises';
|
||||||
import { dirname } from 'node:path';
|
import { dirname } from 'node:path';
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
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 { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
|
||||||
|
import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety';
|
||||||
import {
|
import {
|
||||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||||
|
|
@ -45,6 +46,22 @@ export interface RunSourceFieldShapesProbeDeps {
|
||||||
readonly writeStdout?: (text: string) => void;
|
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> | void;
|
||||||
|
}>
|
||||||
|
| {
|
||||||
|
readonly client: ReadOnlyMongoCollectionClient;
|
||||||
|
readonly close: () => Promise<void> | void;
|
||||||
|
};
|
||||||
|
readonly writeFile?: (filePath: string, content: string) => Promise<void> | void;
|
||||||
|
readonly writeStdout?: (text: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
export interface RunSourceFieldShapesProbeOptions {
|
export interface RunSourceFieldShapesProbeOptions {
|
||||||
readonly outPath: string;
|
readonly outPath: string;
|
||||||
readonly limit?: number;
|
readonly limit?: number;
|
||||||
|
|
@ -256,23 +273,72 @@ export async function runSourceFieldShapesProbe(
|
||||||
return output;
|
return output;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise<void> {
|
export function assertProbeSourceFieldShapesSafety(
|
||||||
|
config: StockAppConfig,
|
||||||
|
env: Record<string, string | undefined> = 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<void> {
|
||||||
const parsed = parseProbeSourceFieldShapesArgs(argv);
|
const parsed = parseProbeSourceFieldShapesArgs(argv);
|
||||||
if (parsed.help) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const logger = getLogger('source-field-shapes-probe');
|
const logger = getLogger('source-field-shapes-probe');
|
||||||
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
const initConfig = overrides?.initializeConfig ?? initializeStockConfig;
|
||||||
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
|
const config = initConfig('dataPipeline', { mongoReadOnly: true });
|
||||||
const mongo = new MongoDBClient(mongoConfig, logger);
|
|
||||||
|
|
||||||
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<void> {
|
||||||
|
if (closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
closed = true;
|
||||||
|
await mongo.disconnect();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const mongoHandle = await createMongoClient();
|
||||||
await runSourceFieldShapesProbe(
|
await runSourceFieldShapesProbe(
|
||||||
{
|
{
|
||||||
mongoCollectionClient: mongo,
|
mongoCollectionClient: mongoHandle.client,
|
||||||
closeMongo: () => mongo.disconnect(),
|
closeMongo: mongoHandle.close,
|
||||||
|
writeFile: overrides?.writeFile,
|
||||||
|
writeStdout: overrides?.writeStdout,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
outPath: parsed.outPath,
|
outPath: parsed.outPath,
|
||||||
|
|
|
||||||
|
|
@ -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<string> = 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<string, string | undefined> = 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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 <dir> [--chunk-size <n>] [--help]',
|
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir <dir> [--chunk-size <n>] [--help]',
|
||||||
'',
|
'',
|
||||||
'Options:',
|
'Options:',
|
||||||
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`,
|
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, ${CURATE_INPUT_FILES.listingVenues}, and ${CURATE_INPUT_FILES.delistings}.`,
|
||||||
` --chunk-size <n> Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`,
|
` --chunk-size <n> Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`,
|
||||||
' --help Show this help message and exit.',
|
' --help Show this help message and exit.',
|
||||||
].join('\n');
|
].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-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.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.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}`,
|
` ${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}`,
|
` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`,
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,6 @@
|
||||||
import { getLogger } from '@stock-bot/logger';
|
import { getLogger } from '@stock-bot/logger';
|
||||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||||
import {
|
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
|
||||||
assertEnvironmentSafety,
|
|
||||||
initializeStockConfig,
|
|
||||||
type StockAppConfig,
|
|
||||||
} from '@stock-bot/stock-config';
|
|
||||||
import {
|
import {
|
||||||
createReadOnlyMongoRawBsonSource,
|
createReadOnlyMongoRawBsonSource,
|
||||||
DEFAULT_RAW_BSON_BATCH_SIZE,
|
DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||||
|
|
@ -19,13 +15,32 @@ import {
|
||||||
type ReadOnlyMongoRawBsonClient,
|
type ReadOnlyMongoRawBsonClient,
|
||||||
} from './export-raw-bson';
|
} from './export-raw-bson';
|
||||||
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
|
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 = [
|
export const EXPORT_RAW_BSON_USAGE = [
|
||||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
|
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
|
||||||
'',
|
'',
|
||||||
'Options:',
|
'Options:',
|
||||||
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
|
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
|
||||||
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`,
|
` --collections <c1,c2,...> 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 <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
|
' --eod-symbol <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
|
||||||
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
|
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
|
||||||
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
|
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
|
||||||
|
|
@ -121,7 +136,7 @@ function parseCollectionsList(raw: string): RawBsonExportCollection[] {
|
||||||
throw new RawBsonExportError({
|
throw new RawBsonExportError({
|
||||||
code: 'DISALLOWED_COLLECTION',
|
code: 'DISALLOWED_COLLECTION',
|
||||||
collection: trimmed,
|
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)) {
|
if (seen.has(trimmed)) {
|
||||||
|
|
@ -242,7 +257,7 @@ export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRaw
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedCollections: readonly RawBsonExportCollection[] =
|
const resolvedCollections: readonly RawBsonExportCollection[] =
|
||||||
collections ?? [...RAW_BSON_EXPORT_COLLECTIONS];
|
collections ?? [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS];
|
||||||
|
|
||||||
if (eodSymbol !== undefined) {
|
if (eodSymbol !== undefined) {
|
||||||
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
|
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
|
||||||
|
|
@ -275,28 +290,14 @@ export function assertExportRawBsonSafety(
|
||||||
config: StockAppConfig,
|
config: StockAppConfig,
|
||||||
env: Record<string, string | undefined> = process.env
|
env: Record<string, string | undefined> = process.env
|
||||||
): void {
|
): void {
|
||||||
const mongo = config.database.mongodb;
|
assertReadOnlyMongoDiagnosticSafety(
|
||||||
if (!mongo.enabled) {
|
config,
|
||||||
throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections');
|
{
|
||||||
}
|
operationLabel: 'export raw BSON collections',
|
||||||
if (mongo.readOnly !== true) {
|
diagnosticLabel: 'Raw BSON exporter',
|
||||||
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,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
};
|
env
|
||||||
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatExportRawBsonSummary(
|
export function formatExportRawBsonSummary(
|
||||||
|
|
@ -327,7 +328,7 @@ export async function runExportRawBson(
|
||||||
throw new RawBsonExportError({
|
throw new RawBsonExportError({
|
||||||
code: 'DISALLOWED_COLLECTION',
|
code: 'DISALLOWED_COLLECTION',
|
||||||
collection: String(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`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,12 @@ export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([
|
||||||
'qmPrices',
|
'qmPrices',
|
||||||
'eodPrices',
|
'eodPrices',
|
||||||
'teMarketData',
|
'teMarketData',
|
||||||
|
'qmFinancials',
|
||||||
|
'qmFinancials-old',
|
||||||
|
'ceoPosts',
|
||||||
|
'teData',
|
||||||
|
'eodIntraday1M',
|
||||||
|
'qmIntraday',
|
||||||
] as const);
|
] as const);
|
||||||
|
|
||||||
export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number];
|
export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number];
|
||||||
|
|
|
||||||
|
|
@ -446,12 +446,27 @@ describe('exportRawBsonCollection', () => {
|
||||||
};
|
};
|
||||||
const fsHooks: ExportRawBsonFsHooks = { open: openMock };
|
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(
|
await expect(
|
||||||
exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks })
|
exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks })
|
||||||
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed });
|
).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(
|
await expect(
|
||||||
exportRawBsonCollection(source, {
|
exportRawBsonCollection(source, {
|
||||||
collection: 'teMarketData',
|
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([
|
expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([
|
||||||
'eodPrices',
|
'eodPrices',
|
||||||
'qmSplits',
|
'qmSplits',
|
||||||
|
|
@ -660,6 +709,12 @@ describe('exportRawBsonCollection', () => {
|
||||||
'ceoShorts',
|
'ceoShorts',
|
||||||
'qmFilings',
|
'qmFilings',
|
||||||
'qmEarnings',
|
'qmEarnings',
|
||||||
|
'qmFinancials',
|
||||||
|
'qmFinancials-old',
|
||||||
|
'ceoPosts',
|
||||||
|
'teData',
|
||||||
|
'eodIntraday1M',
|
||||||
|
'qmIntraday',
|
||||||
]);
|
]);
|
||||||
const emptyBson = new Uint8Array([5, 0, 0, 0, 0]);
|
const emptyBson = new Uint8Array([5, 0, 0, 0, 0]);
|
||||||
expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson);
|
expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson);
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import {
|
||||||
} from '../src/security-master/export-raw-bson';
|
} from '../src/security-master/export-raw-bson';
|
||||||
import {
|
import {
|
||||||
assertExportRawBsonSafety,
|
assertExportRawBsonSafety,
|
||||||
|
DEFAULT_RAW_BSON_EXPORT_COLLECTIONS,
|
||||||
EXPORT_RAW_BSON_USAGE,
|
EXPORT_RAW_BSON_USAGE,
|
||||||
parseExportRawBsonArgs,
|
parseExportRawBsonArgs,
|
||||||
runCli,
|
runCli,
|
||||||
|
|
@ -99,9 +100,52 @@ describe('parseExportRawBsonArgs', () => {
|
||||||
expect(parsedDefault).toEqual({
|
expect(parsedDefault).toEqual({
|
||||||
help: false,
|
help: false,
|
||||||
outDir: './tmp/all',
|
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],
|
collections: [...RAW_BSON_EXPORT_COLLECTIONS],
|
||||||
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
|
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 });
|
expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true });
|
||||||
});
|
});
|
||||||
|
|
@ -149,12 +193,20 @@ describe('parseExportRawBsonArgs', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => {
|
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(() =>
|
expect(() =>
|
||||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M'])
|
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M', '--eod-symbol', 'AAPL.US'])
|
||||||
).toThrow(RawBsonExportError);
|
).toThrow(/--eod-symbol is only permitted/);
|
||||||
expect(() =>
|
|
||||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols'])
|
|
||||||
).toThrow(RawBsonExportError);
|
|
||||||
expect(() =>
|
expect(() =>
|
||||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX'])
|
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX'])
|
||||||
).toThrow(/--eod-symbol is only permitted/);
|
).toThrow(/--eod-symbol is only permitted/);
|
||||||
|
|
@ -193,9 +245,74 @@ describe('assertExportRawBsonSafety', () => {
|
||||||
readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin',
|
readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin',
|
||||||
readOnly: true,
|
readOnly: true,
|
||||||
}),
|
}),
|
||||||
{}
|
{ STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' }
|
||||||
)
|
)
|
||||||
).toThrow(/Safety guard/);
|
).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',
|
outDir: '/tmp/unused',
|
||||||
collections: ['eodIntraday1M' as never],
|
collections: ['eodFundamentalsOLD' as never],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' });
|
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' });
|
||||||
|
|
@ -396,4 +513,43 @@ describe('runExportRawBson & runCli', () => {
|
||||||
await rm(outDir, { recursive: true, force: true });
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -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 { readFileSync } from 'node:fs';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
|
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||||
import type { ParserOptions } from 'prettier';
|
import type { ParserOptions } from 'prettier';
|
||||||
import * as markdownPlugin from 'prettier/plugins/markdown';
|
import * as markdownPlugin from 'prettier/plugins/markdown';
|
||||||
import {
|
import {
|
||||||
|
assertProbeSourceFieldShapesSafety,
|
||||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||||
DEFAULT_MAX_EXAMPLE_LENGTH,
|
DEFAULT_MAX_EXAMPLE_LENGTH,
|
||||||
DEFAULT_MAX_EXAMPLES,
|
DEFAULT_MAX_EXAMPLES,
|
||||||
|
|
@ -13,8 +15,10 @@ import {
|
||||||
MAX_EXAMPLES_CAP,
|
MAX_EXAMPLES_CAP,
|
||||||
MAX_FIELD_SHAPE_LIMIT,
|
MAX_FIELD_SHAPE_LIMIT,
|
||||||
parseProbeSourceFieldShapesArgs,
|
parseProbeSourceFieldShapesArgs,
|
||||||
|
PROBE_SOURCE_FIELD_SHAPES_USAGE,
|
||||||
readFieldShapes,
|
readFieldShapes,
|
||||||
renderFieldShapesMarkdown,
|
renderFieldShapesMarkdown,
|
||||||
|
runProbeSourceFieldShapesCli,
|
||||||
runSourceFieldShapesProbe,
|
runSourceFieldShapesProbe,
|
||||||
STRING_PATTERN_CLASSES,
|
STRING_PATTERN_CLASSES,
|
||||||
summarizeFieldShapes,
|
summarizeFieldShapes,
|
||||||
|
|
@ -444,14 +448,31 @@ describe('readFieldShapes', () => {
|
||||||
expect(amountField.typeCounts.double).toBe(2);
|
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 { reader, calls } = createFakeReader({});
|
||||||
const result = await readFieldShapes(reader);
|
const result = await readFieldShapes(reader);
|
||||||
|
|
||||||
expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT);
|
expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT);
|
||||||
expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES);
|
expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES);
|
||||||
expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH);
|
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) {
|
for (const call of calls) {
|
||||||
expect(call.options).toEqual({
|
expect(call.options).toEqual({
|
||||||
limit: DEFAULT_FIELD_SHAPE_LIMIT,
|
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<string, Record<string, unknown>[]> = {
|
||||||
|
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 });
|
const nonRo = createFakeReader({}, { readOnly: false });
|
||||||
await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i);
|
await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i);
|
||||||
expect(nonRo.calls.length).toBe(0);
|
expect(nonRo.calls.length).toBe(0);
|
||||||
|
|
@ -476,16 +535,25 @@ describe('readFieldShapes', () => {
|
||||||
await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError);
|
await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError);
|
||||||
expect(badLimitZero.calls.length).toBe(0);
|
expect(badLimitZero.calls.length).toBe(0);
|
||||||
|
|
||||||
const unknownCol = createFakeReader({});
|
for (const disallowed of [
|
||||||
let caught: unknown;
|
'notACollection',
|
||||||
try {
|
'symbols',
|
||||||
await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] });
|
'eodSymbols',
|
||||||
} catch (err) {
|
'eodFundamentalsOLD',
|
||||||
caught = err;
|
'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 () => {
|
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(writtenFiles[0]!.content).toBe(output.markdown);
|
||||||
expect(stdoutChunks.join('')).toContain('Documents sampled: 1');
|
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['database']['mongodb']> = {}
|
||||||
|
): 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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
1
bun.lock
1
bun.lock
|
|
@ -360,6 +360,7 @@
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@duckdb/node-api": "^1.4.4-r.1",
|
"@duckdb/node-api": "^1.4.4-r.1",
|
||||||
|
"@stock-bot/questdb": "workspace:*",
|
||||||
"@stock-bot/research": "workspace:*",
|
"@stock-bot/research": "workspace:*",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@duckdb/node-api": "^1.4.4-r.1",
|
"@duckdb/node-api": "^1.4.4-r.1",
|
||||||
|
"@stock-bot/questdb": "workspace:*",
|
||||||
"@stock-bot/research": "workspace:*"
|
"@stock-bot/research": "workspace:*"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,23 @@
|
||||||
* (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`).
|
* (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`).
|
||||||
*
|
*
|
||||||
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared
|
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared
|
||||||
* between the host and the underlying DuckDB store, and hardcodes
|
* between the host, the underlying DuckDB store, and (when configured) the
|
||||||
* `vaultOperatorAuthorized: false` so every query remains strictly
|
* QuestDB intraday reader, hardcoding `vaultOperatorAuthorized: false` so
|
||||||
* `'vault_fenced'`.
|
* every query remains strictly `'vault_fenced'`.
|
||||||
* - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose
|
* - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose
|
||||||
* `close()` releases the underlying DuckDB connection and instance.
|
* `close()` idempotently releases all acquired DuckDB and QuestDB resources.
|
||||||
* - Any failure during open (native connection creation or store validation)
|
* - Any failure during open (native connection creation, store validation, or
|
||||||
* releases already-acquired DuckDB resources before rejecting.
|
* 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 {
|
import type {
|
||||||
ManagedMarketDataStore,
|
ManagedMarketDataStore,
|
||||||
ResearchCopilotHostConfig,
|
ResearchCopilotHostConfig,
|
||||||
|
|
@ -19,16 +27,23 @@ import type {
|
||||||
} from '@stock-bot/research/mcp';
|
} from '@stock-bot/research/mcp';
|
||||||
import { openDuckDbMarketDataStore } from './index';
|
import { openDuckDbMarketDataStore } from './index';
|
||||||
|
|
||||||
|
export type QuestDbExecutorOpener = (
|
||||||
|
config: QuestDbPgExecutorConfig
|
||||||
|
) => Promise<QuestDbPgExecutorHandle>;
|
||||||
|
|
||||||
export interface OpenResearchCopilotStoreOptions {
|
export interface OpenResearchCopilotStoreOptions {
|
||||||
/** Optional DuckDB database path; defaults to `':memory:'`. */
|
/** Optional DuckDB database path; defaults to `':memory:'`. */
|
||||||
readonly databasePath?: string;
|
readonly databasePath?: string;
|
||||||
/** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */
|
/** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */
|
||||||
readonly env?: Readonly<Record<string, string | undefined>>;
|
readonly env?: Readonly<Record<string, string | undefined>>;
|
||||||
|
/** Optional override for opening the QuestDB intraday executor (defaults to `openQuestDbPgExecutor`). */
|
||||||
|
readonly openQuestDbExecutor?: QuestDbExecutorOpener;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a
|
* Opens a Vault-fenced DuckDB-backed (and optionally QuestDB-routed for 1m
|
||||||
* validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`.
|
* intraday `bars` and `fx`) {@link ManagedMarketDataStore} from a validated
|
||||||
|
* {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`.
|
||||||
*/
|
*/
|
||||||
export const openResearchCopilotStore = (async (
|
export const openResearchCopilotStore = (async (
|
||||||
config: ResearchCopilotHostConfig,
|
config: ResearchCopilotHostConfig,
|
||||||
|
|
@ -42,8 +57,66 @@ export const openResearchCopilotStore = (async (
|
||||||
...(options?.env !== undefined ? { env: options.env } : {}),
|
...(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<void> | null = null;
|
||||||
|
const close = (): Promise<void> => {
|
||||||
|
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 {
|
return {
|
||||||
store: opened.store,
|
store: routedStore,
|
||||||
close: opened.close,
|
close,
|
||||||
};
|
};
|
||||||
}) satisfies ResearchCopilotStdioHostDeps['openStore'];
|
}) satisfies ResearchCopilotStdioHostDeps['openStore'];
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,19 @@
|
||||||
import { afterEach, describe, expect, test } from 'bun:test';
|
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 { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import {
|
import {
|
||||||
computeVaultCutoffTs,
|
computeVaultCutoffTs,
|
||||||
|
MarketDataStoreValidationError,
|
||||||
VaultHoldoutFenceError,
|
VaultHoldoutFenceError,
|
||||||
type BarRecord,
|
type BarRecord,
|
||||||
} from '@stock-bot/research/market-data-store';
|
} 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 {
|
import {
|
||||||
createNodeDuckDbExecutor,
|
createNodeDuckDbExecutor,
|
||||||
openDuckDbMarketDataStore,
|
openDuckDbMarketDataStore,
|
||||||
|
|
@ -929,3 +936,844 @@ describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-ap
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function createInMemoryTrialLedger(): TrialLedgerExecutor {
|
||||||
|
const rows: Array<Record<string, unknown>> = [];
|
||||||
|
let nextTrialId = 1;
|
||||||
|
return {
|
||||||
|
async query<Row = Record<string, unknown>>(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<EventStudyResultPayload> => {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -527,4 +527,158 @@ describe('openResearchCopilotStore (@duckdb/node-api)', () => {
|
||||||
expect(connCloseSpy).toHaveBeenCalledTimes(0);
|
expect(connCloseSpy).toHaveBeenCalledTimes(0);
|
||||||
expect(instCloseSpy).toHaveBeenCalledTimes(1);
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,9 @@
|
||||||
"references": [
|
"references": [
|
||||||
{
|
{
|
||||||
"path": "../../research"
|
"path": "../../research"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "../questdb"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,12 +27,27 @@ export {
|
||||||
type IlpV2EncodeErrorKind,
|
type IlpV2EncodeErrorKind,
|
||||||
} from './ilp-v2-writer';
|
} from './ilp-v2-writer';
|
||||||
export {
|
export {
|
||||||
|
applyM2IntradayDDL,
|
||||||
formatCreateTableSQL,
|
formatCreateTableSQL,
|
||||||
getM2IntradayDDL,
|
getM2IntradayDDL,
|
||||||
M2_INTRADAY_SCHEMAS,
|
M2_INTRADAY_SCHEMAS,
|
||||||
|
M2_INTRADAY_TABLE_NAMES,
|
||||||
QuestDBSchemaManager,
|
QuestDBSchemaManager,
|
||||||
|
type ApplyM2IntradayDDLOptions,
|
||||||
|
type ApplyM2IntradayDDLResult,
|
||||||
type M2IntradayTableName,
|
type M2IntradayTableName,
|
||||||
} from './schema';
|
} from './schema';
|
||||||
|
export {
|
||||||
|
assertNoConflictingQuestDbSsl,
|
||||||
|
hasConflictingQuestDbUrlSsl,
|
||||||
|
hasQuestDbUrlTlsOptions,
|
||||||
|
openQuestDbPgExecutor,
|
||||||
|
type OpenQuestDbPgExecutorOptions,
|
||||||
|
type QuestDbPgExecutorConfig,
|
||||||
|
type QuestDbPgExecutorHandle,
|
||||||
|
type QuestDbPgPoolLike,
|
||||||
|
type QuestDbPgQueryExecutor,
|
||||||
|
} from './pg-executor';
|
||||||
|
|
||||||
// Types
|
// Types
|
||||||
export type {
|
export type {
|
||||||
|
|
|
||||||
248
libs/data/questdb/src/pg-executor.ts
Normal file
248
libs/data/questdb/src/pg-executor.ts
Normal file
|
|
@ -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<string, unknown>[] }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QuestDbPgExecutorHandle {
|
||||||
|
readonly executor: QuestDbPgQueryExecutor;
|
||||||
|
close(): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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<string>, 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<string>();
|
||||||
|
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<QuestDbPgExecutorHandle> {
|
||||||
|
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<void> | null = null;
|
||||||
|
const close = (): Promise<void> => {
|
||||||
|
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<string, unknown>[],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return { executor, close };
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,14 @@ import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types';
|
||||||
|
|
||||||
export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions';
|
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<string> = new Set<string>(M2_INTRADAY_TABLE_NAMES);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B).
|
* Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B).
|
||||||
* Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`).
|
* Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`).
|
||||||
|
|
@ -144,6 +152,68 @@ export function getM2IntradayDDL(): Record<M2IntradayTableName, string> {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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<unknown> },
|
||||||
|
options?: ApplyM2IntradayDDLOptions
|
||||||
|
): Promise<ApplyM2IntradayDDLResult> {
|
||||||
|
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<M2IntradayTableName>();
|
||||||
|
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
|
* QuestDB Schema Manager
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,19 @@
|
||||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
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 { QuestDBHealthMonitor } from '../src/health';
|
||||||
import { QuestDBInfluxWriter } from '../src/influx-writer';
|
import { QuestDBInfluxWriter } from '../src/influx-writer';
|
||||||
|
import {
|
||||||
|
openQuestDbPgExecutor,
|
||||||
|
type QuestDbPgPoolLike,
|
||||||
|
} from '../src/pg-executor';
|
||||||
import { QuestDBQueryBuilder } from '../src/query-builder';
|
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';
|
import type { OHLCVData, QuestDBClientConfig, TradeData } from '../src/types';
|
||||||
|
|
||||||
// Simple in-memory QuestDB client for testing
|
// Simple in-memory QuestDB client for testing
|
||||||
|
|
@ -474,6 +485,41 @@ describe('QuestDB', () => {
|
||||||
expect(stats.min_timestamp).toBeDefined();
|
expect(stats.min_timestamp).toBeDefined();
|
||||||
expect(stats.max_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', () => {
|
describe('QuestDBHealthMonitor', () => {
|
||||||
|
|
@ -531,4 +577,189 @@ describe('QuestDB', () => {
|
||||||
monitor.stopMonitoring();
|
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<void> {
|
||||||
|
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<readonly [string, boolean]> = [
|
||||||
|
[`${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<typeof openQuestDbPgExecutor>[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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -61,10 +61,12 @@ export type FeatureKind = (typeof FEATURE_KINDS)[number];
|
||||||
export const FEATURE_INPUT_DATASETS = [
|
export const FEATURE_INPUT_DATASETS = [
|
||||||
'bars_1d',
|
'bars_1d',
|
||||||
'adj_factors',
|
'adj_factors',
|
||||||
|
'corporate_actions',
|
||||||
'events',
|
'events',
|
||||||
'shorts',
|
'shorts',
|
||||||
'fx_1d',
|
'fx_1d',
|
||||||
'fundamentals_pit',
|
'fundamentals_pit',
|
||||||
|
'macro',
|
||||||
] as const;
|
] as const;
|
||||||
export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number];
|
export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number];
|
||||||
|
|
||||||
|
|
@ -553,7 +555,7 @@ type SqlToken =
|
||||||
interface DatasetScanSpec {
|
interface DatasetScanSpec {
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
readonly hivePartitioning: boolean;
|
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<Record<FeatureInputDataset, DatasetScanSpec>> = {
|
const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>> = {
|
||||||
|
|
@ -567,6 +569,11 @@ const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>>
|
||||||
hivePartitioning: false,
|
hivePartitioning: false,
|
||||||
predicateKind: 'known_at',
|
predicateKind: 'known_at',
|
||||||
},
|
},
|
||||||
|
corporate_actions: {
|
||||||
|
relativePath: 'corporate_actions/part.parquet',
|
||||||
|
hivePartitioning: false,
|
||||||
|
predicateKind: 'known_at',
|
||||||
|
},
|
||||||
events: {
|
events: {
|
||||||
relativePath: 'events/year=*/part.parquet',
|
relativePath: 'events/year=*/part.parquet',
|
||||||
hivePartitioning: true,
|
hivePartitioning: true,
|
||||||
|
|
@ -587,6 +594,11 @@ const DATASET_SCAN_SPECS: Readonly<Record<FeatureInputDataset, DatasetScanSpec>>
|
||||||
hivePartitioning: true,
|
hivePartitioning: true,
|
||||||
predicateKind: 'effective_known_at',
|
predicateKind: 'effective_known_at',
|
||||||
},
|
},
|
||||||
|
macro: {
|
||||||
|
relativePath: 'macro/part.parquet',
|
||||||
|
hivePartitioning: false,
|
||||||
|
predicateKind: 'macro_known_at',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
|
@ -1959,6 +1971,11 @@ function expandSqlForYear(
|
||||||
} else if (spec.predicateKind === 'effective_known_at') {
|
} else if (spec.predicateKind === 'effective_known_at') {
|
||||||
parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`);
|
parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`);
|
||||||
scanParams.push(knownAtUpperIso);
|
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 {
|
} else {
|
||||||
parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`);
|
parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`);
|
||||||
scanParams.push(knownAtUpperIso);
|
scanParams.push(knownAtUpperIso);
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@
|
||||||
* - `<curatedRoot>/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`)
|
* - `<curatedRoot>/bars_1d/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||||
* - `<curatedRoot>/adj_factors/part.parquet` (point-in-time fenced snapshot with
|
* - `<curatedRoot>/adj_factors/part.parquet` (point-in-time fenced snapshot with
|
||||||
* `stock_bot.adj_factors.*` Parquet footer metadata)
|
* `stock_bot.adj_factors.*` Parquet footer metadata)
|
||||||
* - `<curatedRoot>/events/year=*\/part.parquet` (`hive_partitioning = true`)
|
* - `<curatedRoot>/events/year=*\/\*.parquet` (`hive_partitioning = true`)
|
||||||
* - `<curatedRoot>/shorts/part.parquet`
|
* - `<curatedRoot>/shorts/part.parquet`
|
||||||
* - `<curatedRoot>/fx_1d/part.parquet`
|
* - `<curatedRoot>/fx_1d/part.parquet`
|
||||||
* - `<curatedRoot>/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`)
|
* - `<curatedRoot>/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||||
|
|
@ -94,6 +94,8 @@ const STRICT_INT_RE = /^-?\d+$/;
|
||||||
const STRICT_UINT_RE = /^\d+$/;
|
const STRICT_UINT_RE = /^\d+$/;
|
||||||
const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/;
|
const SNAPSHOT_CHECKSUM_RE = /^0x[0-9a-f]{16}$/;
|
||||||
const FD_HANDLE_PATH_RE = /^\/(?:proc\/self|dev)\/fd\/[1-9]\d*$/;
|
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_FORMAT_VERSION = 1;
|
||||||
export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.';
|
export const ADJ_SNAPSHOT_KV_PREFIX = 'stock_bot.adj_factors.';
|
||||||
|
|
@ -157,6 +159,15 @@ export const FX_1D_COLUMNS = [
|
||||||
'known_at',
|
'known_at',
|
||||||
] as const;
|
] 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 = [
|
export const FUNDAMENTALS_PIT_VALUE_FIELDS = [
|
||||||
'revenue',
|
'revenue',
|
||||||
'net_income',
|
'net_income',
|
||||||
|
|
@ -219,6 +230,15 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [
|
||||||
{ name: 'known_at', kind: 'safe_int', nullable: false },
|
{ 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[] = [
|
const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [
|
||||||
{ name: 'listing_id', kind: 'int32', nullable: false },
|
{ name: 'listing_id', kind: 'int32', nullable: false },
|
||||||
{ name: 'effective_known_at', kind: 'safe_int', nullable: false },
|
{ name: 'effective_known_at', kind: 'safe_int', nullable: false },
|
||||||
|
|
@ -399,6 +419,8 @@ export type ShortsAsOfQuery = Parameters<MarketDataStore['shortsAsOf']>[0];
|
||||||
export type FxQuery = Parameters<MarketDataStore['fx']>[0];
|
export type FxQuery = Parameters<MarketDataStore['fx']>[0];
|
||||||
export type UniverseQuery = Parameters<MarketDataStore['universe']>[0];
|
export type UniverseQuery = Parameters<MarketDataStore['universe']>[0];
|
||||||
export type FundamentalsAsOfQuery = Parameters<MarketDataStore['fundamentalsAsOf']>[0];
|
export type FundamentalsAsOfQuery = Parameters<MarketDataStore['fundamentalsAsOf']>[0];
|
||||||
|
export type MacroAsOfQuery = Parameters<MarketDataStore['macroAsOf']>[0];
|
||||||
|
export type CrossSectionQuery = Parameters<MarketDataStore['crossSection']>[0];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Thrown when a `MarketDataStore` method or timeframe is outside the curated
|
* 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<string>();
|
||||||
|
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 ("<name>@v<version>") for "features".',
|
||||||
|
'features'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
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 "<name>@v<version>".`,
|
||||||
|
'features'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const match = CROSS_SECTION_FEATURE_REF_RE.exec(item);
|
||||||
|
if (match === null) {
|
||||||
|
throw new MarketDataStoreValidationError(
|
||||||
|
`Invalid feature ref "${item}" at features[${i}]. Expected "<name>@v<version>" 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 {
|
function validateUniverseLookbackDays(raw: unknown, vaultCutoffTs?: number): number {
|
||||||
const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw;
|
const days = raw === undefined ? DEFAULT_UNIVERSE_LOOKBACK_DAYS : raw;
|
||||||
if (typeof days !== 'number' || !Number.isSafeInteger(days) || days < 1) {
|
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 fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs);
|
||||||
const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs);
|
const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs);
|
||||||
const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs);
|
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 kindPlaceholders = buildPlaceholders(kinds.length);
|
||||||
const orderBy =
|
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';
|
'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;
|
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/<name>/v<version>/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<string, unknown>, key: string, rowIndex: number): number {
|
function readRequiredInt32(row: Record<string, unknown>, key: string, rowIndex: number): number {
|
||||||
const val = row[key];
|
const val = row[key];
|
||||||
if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) {
|
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[] {
|
function mapUniverseRows(rows: readonly TableRow[]): number[] {
|
||||||
if (!Array.isArray(rows)) {
|
if (!Array.isArray(rows)) {
|
||||||
throw new MarketDataStoreValidationError(
|
throw new MarketDataStoreValidationError(
|
||||||
|
|
@ -2281,7 +2612,10 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
||||||
},
|
},
|
||||||
|
|
||||||
async crossSection(q: CrossSectionQuery): Promise<Table> {
|
async crossSection(q: CrossSectionQuery): Promise<Table> {
|
||||||
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<Table> {
|
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
||||||
|
|
@ -2291,8 +2625,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
||||||
return mapTableRows(columns, schema, rawRows);
|
return mapTableRows(columns, schema, rawRows);
|
||||||
},
|
},
|
||||||
|
|
||||||
macroAsOf(): Promise<Table> {
|
async macroAsOf(q: MacroAsOfQuery): Promise<Table> {
|
||||||
return Promise.reject(new MarketDataStoreNotImplementedError('macroAsOf'));
|
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<number[]> {
|
async universe(q: UniverseQuery): Promise<number[]> {
|
||||||
|
|
@ -2303,246 +2640,3 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CrossSectionQuery = Parameters<MarketDataStore['crossSection']>[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 "<name>@v<version>" feature refs.',
|
|
||||||
field
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const seen = new Set<string>();
|
|
||||||
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 "<name>@v<version>".`,
|
|
||||||
field
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const item: unknown = raw[i];
|
|
||||||
if (typeof item !== 'string') {
|
|
||||||
throw new MarketDataStoreValidationError(
|
|
||||||
`Invalid feature ref at index ${i}. Expected canonical "<name>@v<version>".`,
|
|
||||||
field
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const match = CROSS_SECTION_FEATURE_REF_RE.exec(item);
|
|
||||||
if (match === null) {
|
|
||||||
throw new MarketDataStoreValidationError(
|
|
||||||
`Invalid feature ref "${item}". Expected canonical "<name>@v<version>".`,
|
|
||||||
field
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const name = match[1];
|
|
||||||
const versionStr = match[2];
|
|
||||||
if (name === undefined || versionStr === undefined) {
|
|
||||||
throw new MarketDataStoreValidationError(
|
|
||||||
`Invalid feature ref "${item}". Expected canonical "<name>@v<version>".`,
|
|
||||||
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/<name>/v<version>/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<void>,
|
|
||||||
typedExecutor: DuckDbExecutor
|
|
||||||
): Promise<Table> {
|
|
||||||
const { planned, columns, schema } = planCrossSectionInternal(q, planCtx);
|
|
||||||
await ensureBudgetInitialized();
|
|
||||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
|
||||||
return mapTableRows(columns, schema, rawRows);
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,8 @@ import {
|
||||||
type FencedTimeRange,
|
type FencedTimeRange,
|
||||||
type MarketDataStore,
|
type MarketDataStore,
|
||||||
MarketDataStoreValidationError,
|
MarketDataStoreValidationError,
|
||||||
|
type Table,
|
||||||
|
type TableRow,
|
||||||
type VaultFenceContext,
|
type VaultFenceContext,
|
||||||
applyVaultFence,
|
applyVaultFence,
|
||||||
} from './market-data-store';
|
} 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`. */
|
/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */
|
||||||
export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000;
|
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<string> = new Set(['USDCAD', 'USD.CAD']);
|
||||||
|
|
||||||
/** Input query type derived from `MarketDataStore['bars']`. */
|
/** Input query type derived from `MarketDataStore['bars']`. */
|
||||||
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
|
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
|
||||||
|
|
||||||
|
/** Input query type derived from `MarketDataStore['fx']`. */
|
||||||
|
export type QuestDbFx1mQuery = Parameters<MarketDataStore['fx']>[0];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Injected PGWire SQL executor port, structurally compatible with
|
* Injected PGWire SQL executor port, structurally compatible with
|
||||||
* `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`.
|
* `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`.
|
||||||
|
|
@ -63,6 +73,13 @@ export interface PlannedQuestDbBars1mQuery {
|
||||||
readonly fence: FencedTimeRange;
|
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}. */
|
/** Configuration for {@link createQuestDbIntradayBarsReader}. */
|
||||||
export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
|
export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
|
||||||
readonly executor: QuestDbQueryExecutor;
|
readonly executor: QuestDbQueryExecutor;
|
||||||
|
|
@ -70,6 +87,11 @@ export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
|
||||||
readonly batchSize?: number;
|
readonly batchSize?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Configuration for {@link createQuestDbIntradayFxReader}. */
|
||||||
|
export interface QuestDbIntradayFxReaderOptions extends VaultFenceContext {
|
||||||
|
readonly executor: QuestDbQueryExecutor;
|
||||||
|
}
|
||||||
|
|
||||||
interface InternalPlannedBars1mQuery {
|
interface InternalPlannedBars1mQuery {
|
||||||
readonly planned: PlannedQuestDbBars1mQuery;
|
readonly planned: PlannedQuestDbBars1mQuery;
|
||||||
readonly requestedListingIds: ReadonlySet<number>;
|
readonly requestedListingIds: ReadonlySet<number>;
|
||||||
|
|
@ -215,6 +237,67 @@ export function planBars1mQuery(
|
||||||
return planBars1mQueryInternal(q, ctx).planned;
|
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(
|
function parseListingIdSymbol(
|
||||||
row: Record<string, unknown>,
|
row: Record<string, unknown>,
|
||||||
rowIndex: number,
|
rowIndex: number,
|
||||||
|
|
@ -460,3 +543,140 @@ export function createQuestDbIntradayBarsReader(
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mapFx1mRows(
|
||||||
|
rows: readonly Record<string, unknown>[],
|
||||||
|
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<MarketDataStore, 'fx'> {
|
||||||
|
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<Table> {
|
||||||
|
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<string, unknown>[] }`.',
|
||||||
|
'rows'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return mapFx1mRows(
|
||||||
|
result.rows as readonly Record<string, unknown>[],
|
||||||
|
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<MarketDataStore, 'bars' | 'fx'> {
|
||||||
|
const barsReader = createQuestDbIntradayBarsReader(options);
|
||||||
|
const fxReader = createQuestDbIntradayFxReader(options);
|
||||||
|
return {
|
||||||
|
bars(q) {
|
||||||
|
return barsReader.bars(q);
|
||||||
|
},
|
||||||
|
fx(q) {
|
||||||
|
return fxReader.fx(q);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,8 +28,8 @@ import { type MarketDataStore, MarketDataStoreValidationError } from './market-d
|
||||||
export interface RoutedMarketDataStoreOptions {
|
export interface RoutedMarketDataStoreOptions {
|
||||||
/** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */
|
/** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */
|
||||||
readonly daily: MarketDataStore;
|
readonly daily: MarketDataStore;
|
||||||
/** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */
|
/** Backing intraday reader for `bars` (and optional `fx`) queries with `timeframe: '1m'`. */
|
||||||
readonly intraday: Pick<MarketDataStore, 'bars'>;
|
readonly intraday: Pick<MarketDataStore, 'bars'> & Partial<Pick<MarketDataStore, 'fx'>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const REQUIRED_DAILY_METHODS = [
|
const REQUIRED_DAILY_METHODS = [
|
||||||
|
|
@ -55,7 +55,7 @@ function isDelegateObject(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isIntraday1mBarsQuery(q: unknown): boolean {
|
function isIntraday1mQuery(q: unknown): boolean {
|
||||||
return (
|
return (
|
||||||
typeof q === 'object' &&
|
typeof q === 'object' &&
|
||||||
q !== null &&
|
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 daily = options.daily;
|
||||||
const intraday = options.intraday;
|
const intraday = options.intraday;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
bars(q) {
|
bars(q) {
|
||||||
if (isIntraday1mBarsQuery(q)) {
|
if (isIntraday1mQuery(q)) {
|
||||||
return intraday.bars(q);
|
return intraday.bars(q);
|
||||||
}
|
}
|
||||||
return daily.bars(q);
|
return daily.bars(q);
|
||||||
|
|
@ -182,6 +189,9 @@ export function createRoutedMarketDataStore(
|
||||||
},
|
},
|
||||||
|
|
||||||
fx(q) {
|
fx(q) {
|
||||||
|
if (intraday.fx !== undefined && isIntraday1mQuery(q)) {
|
||||||
|
return intraday.fx(q);
|
||||||
|
}
|
||||||
return daily.fx(q);
|
return daily.fx(q);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,17 @@ const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID';
|
||||||
const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT';
|
const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT';
|
||||||
const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS';
|
const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS';
|
||||||
const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES';
|
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 SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||||
const AGENT_PRINCIPAL_RE =
|
const AGENT_PRINCIPAL_RE =
|
||||||
|
|
@ -75,9 +86,27 @@ const rawHostEnvSchema = z
|
||||||
[ENV_LIBRARY_ROOT]: nonBlankEnvString,
|
[ENV_LIBRARY_ROOT]: nonBlankEnvString,
|
||||||
[ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString,
|
[ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString,
|
||||||
[ENV_EARLY_CLOSES]: nonBlankEnvString.optional(),
|
[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();
|
.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. */
|
/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */
|
||||||
export interface ResearchCopilotHostConfig {
|
export interface ResearchCopilotHostConfig {
|
||||||
readonly postgresUrl: string;
|
readonly postgresUrl: string;
|
||||||
|
|
@ -88,6 +117,7 @@ export interface ResearchCopilotHostConfig {
|
||||||
readonly libraryRoot: string;
|
readonly libraryRoot: string;
|
||||||
readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds'];
|
readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds'];
|
||||||
readonly earlyCloses?: EarlyCloseOverrides;
|
readonly earlyCloses?: EarlyCloseOverrides;
|
||||||
|
readonly questdb?: ResearchCopilotQuestDbConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -175,11 +205,11 @@ function defineDataProperty<T>(target: Record<string, T>, key: string, value: T)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function parsePostgresUrl(raw: string): string {
|
function parsePgWireUrl(raw: string, variable: string): string {
|
||||||
if (raw !== raw.trim()) {
|
if (raw !== raw.trim()) {
|
||||||
throw new ResearchCopilotHostConfigError(
|
throw new ResearchCopilotHostConfigError(
|
||||||
ENV_POSTGRES_URL,
|
variable,
|
||||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
|
`Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let parsed: URL;
|
let parsed: URL;
|
||||||
|
|
@ -187,8 +217,8 @@ function parsePostgresUrl(raw: string): string {
|
||||||
parsed = new URL(raw);
|
parsed = new URL(raw);
|
||||||
} catch {
|
} catch {
|
||||||
throw new ResearchCopilotHostConfigError(
|
throw new ResearchCopilotHostConfigError(
|
||||||
ENV_POSTGRES_URL,
|
variable,
|
||||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.`
|
`Invalid configuration variable "${variable}": expected a valid postgres:// or postgresql:// URL.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
|
|
@ -196,8 +226,8 @@ function parsePostgresUrl(raw: string): string {
|
||||||
parsed.hostname.length === 0
|
parsed.hostname.length === 0
|
||||||
) {
|
) {
|
||||||
throw new ResearchCopilotHostConfigError(
|
throw new ResearchCopilotHostConfigError(
|
||||||
ENV_POSTGRES_URL,
|
variable,
|
||||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.`
|
`Invalid configuration variable "${variable}": expected a postgres:// or postgresql:// URL with a non-empty host.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
|
@ -209,13 +239,152 @@ function parsePostgresUrl(raw: string): string {
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
throw new ResearchCopilotHostConfigError(
|
throw new ResearchCopilotHostConfigError(
|
||||||
ENV_POSTGRES_URL,
|
variable,
|
||||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.`
|
`Invalid configuration variable "${variable}": URL credentials contain invalid percent-encoding.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return raw;
|
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 {
|
function parsePostgresSchema(raw: string): string {
|
||||||
if (!SCHEMA_IDENT_RE.test(raw)) {
|
if (!SCHEMA_IDENT_RE.test(raw)) {
|
||||||
throw new ResearchCopilotHostConfigError(
|
throw new ResearchCopilotHostConfigError(
|
||||||
|
|
@ -526,6 +695,7 @@ export function parseResearchCopilotHostConfig(
|
||||||
data[ENV_EARLY_CLOSES] !== undefined
|
data[ENV_EARLY_CLOSES] !== undefined
|
||||||
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
|
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
|
||||||
: undefined;
|
: undefined;
|
||||||
|
const questdb = parseQuestDbConfig(data);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
postgresUrl,
|
postgresUrl,
|
||||||
|
|
@ -536,6 +706,7 @@ export function parseResearchCopilotHostConfig(
|
||||||
libraryRoot,
|
libraryRoot,
|
||||||
referenceListingIds,
|
referenceListingIds,
|
||||||
...(earlyCloses !== undefined ? { earlyCloses } : {}),
|
...(earlyCloses !== undefined ? { earlyCloses } : {}),
|
||||||
|
...(questdb !== undefined ? { questdb } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -554,13 +725,12 @@ function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
function collectUrlSecretNeedles(needles: Set<string>, rawUrl: string): void {
|
||||||
const needles = new Set<string>();
|
if (rawUrl.length > 0) {
|
||||||
if (postgresUrl.length > 0) {
|
needles.add(rawUrl);
|
||||||
needles.add(postgresUrl);
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const parsed = new URL(postgresUrl);
|
const parsed = new URL(rawUrl);
|
||||||
if (parsed.href.length > 0) {
|
if (parsed.href.length > 0) {
|
||||||
needles.add(parsed.href);
|
needles.add(parsed.href);
|
||||||
}
|
}
|
||||||
|
|
@ -591,7 +761,23 @@ function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} 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<string>();
|
||||||
|
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);
|
return Array.from(needles);
|
||||||
}
|
}
|
||||||
|
|
@ -708,7 +894,8 @@ export async function runResearchCopilotStdioHost(
|
||||||
|
|
||||||
const { config } = deps;
|
const { config } = deps;
|
||||||
const secretNeedles = collectSecretNeedles(
|
const secretNeedles = collectSecretNeedles(
|
||||||
typeof config.postgresUrl === 'string' ? config.postgresUrl : ''
|
typeof config.postgresUrl === 'string' ? config.postgresUrl : '',
|
||||||
|
config.questdb
|
||||||
);
|
);
|
||||||
|
|
||||||
const closers: Array<() => Promise<void> | void> = [];
|
const closers: Array<() => Promise<void> | void> = [];
|
||||||
|
|
|
||||||
|
|
@ -6,12 +6,14 @@ import {
|
||||||
analyzeSignalPanel,
|
analyzeSignalPanel,
|
||||||
} from '@stock-bot/calculations';
|
} from '@stock-bot/calculations';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import { parseFeatureRef } from '../../feature-library';
|
||||||
import {
|
import {
|
||||||
type BarRecord,
|
type BarRecord,
|
||||||
type MarketDataStore,
|
type MarketDataStore,
|
||||||
MarketDataStoreValidationError,
|
MarketDataStoreValidationError,
|
||||||
type Table,
|
type Table,
|
||||||
type TableRow,
|
type TableRow,
|
||||||
|
type UniverseRef,
|
||||||
type VaultFenceContext,
|
type VaultFenceContext,
|
||||||
} from '../../market-data-store';
|
} from '../../market-data-store';
|
||||||
import {
|
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. */
|
/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */
|
||||||
export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120;
|
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 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 =
|
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}$/;
|
/^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);
|
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
|
const shortsSignalSpecSchema = z
|
||||||
.object({
|
.object({
|
||||||
source: z.literal('shorts').describe('Signal data source ("shorts").'),
|
source: z.literal('shorts').describe('Signal data source ("shorts").'),
|
||||||
|
|
@ -118,9 +132,30 @@ const fundamentalsSignalSpecSchema = z
|
||||||
.strict()
|
.strict()
|
||||||
.describe('Point-in-time fundamentals signal specification.');
|
.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 "<name>@v<version>" (e.g. "ret_1d@v1").'
|
||||||
|
)
|
||||||
|
.describe('Canonical versioned feature reference ("<name>@v<version>"), e.g. "ret_1d@v1".'),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
.describe('Versioned curated feature signal specification.');
|
||||||
|
|
||||||
const signalSpecSchema = z
|
const signalSpecSchema = z
|
||||||
.discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema])
|
.discriminatedUnion('source', [
|
||||||
.describe('Discriminated signal source and field specification ("shorts" or "fundamentals").');
|
shortsSignalSpecSchema,
|
||||||
|
fundamentalsSignalSpecSchema,
|
||||||
|
featureSignalSpecSchema,
|
||||||
|
])
|
||||||
|
.describe(
|
||||||
|
'Discriminated signal source specification ("shorts", "fundamentals", or "feature").'
|
||||||
|
);
|
||||||
|
|
||||||
const analyzeSignalSharedFieldsSchema = z
|
const analyzeSignalSharedFieldsSchema = z
|
||||||
.object({
|
.object({
|
||||||
|
|
@ -227,7 +262,9 @@ export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema
|
||||||
message:
|
message:
|
||||||
data.signal.source === 'shorts'
|
data.signal.source === 'shorts'
|
||||||
? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).'
|
? '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 sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema);
|
||||||
const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema);
|
const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema);
|
||||||
const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema);
|
const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema);
|
||||||
|
const featureBranch = zodObjectToJsonSchema(featureSignalSpecSchema);
|
||||||
const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? {
|
const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? {
|
||||||
type: 'boolean' as const,
|
type: 'boolean' as const,
|
||||||
default: false,
|
default: false,
|
||||||
};
|
};
|
||||||
|
const featureRefProp = featureBranch.properties.featureRef ?? {
|
||||||
|
type: 'string' as const,
|
||||||
|
minLength: 1,
|
||||||
|
};
|
||||||
const signalProperty: JsonSchemaProperty = {
|
const signalProperty: JsonSchemaProperty = {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
description: signalSpecSchema.description,
|
description: signalSpecSchema.description,
|
||||||
properties: {
|
properties: {
|
||||||
source: {
|
source: {
|
||||||
type: 'string',
|
type: 'string',
|
||||||
enum: ['shorts', 'fundamentals'],
|
enum: ['shorts', 'fundamentals', 'feature'],
|
||||||
description: 'Signal data source ("shorts" or "fundamentals").',
|
description: 'Signal data source ("shorts", "fundamentals", or "feature").',
|
||||||
},
|
},
|
||||||
field: {
|
field: {
|
||||||
type: 'string',
|
type: 'string',
|
||||||
enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS],
|
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,
|
allowEstimatedLag: allowEstimatedLagProp,
|
||||||
|
featureRef: featureRefProp,
|
||||||
},
|
},
|
||||||
required: ['source', 'field'],
|
required: ['source'],
|
||||||
additionalProperties: false,
|
additionalProperties: false,
|
||||||
anyOf: [shortsBranch, fundamentalsBranch],
|
anyOf: [shortsBranch, fundamentalsBranch, featureBranch],
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
@ -732,6 +775,94 @@ function appendEligibleFundamentalsObservations(params: {
|
||||||
return latestKnownAtByListing;
|
return latestKnownAtByListing;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function deriveFeatureSessionQueries(
|
||||||
|
bars: readonly BarRecord[],
|
||||||
|
fencedAsOfMs: number,
|
||||||
|
vaultCutoffTs: number,
|
||||||
|
vaultCutoffDate: string
|
||||||
|
): Array<{ readonly sessionDate: string; readonly asOfMs: number }> {
|
||||||
|
const unique = new Map<string, { readonly sessionDate: string; readonly asOfMs: number }>();
|
||||||
|
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<number>;
|
||||||
|
readonly sessionQueryAsOfMs: number;
|
||||||
|
readonly seenKeys: Set<string>;
|
||||||
|
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: {
|
function buildCanonicalStudyExpression(params: {
|
||||||
readonly input: AnalyzeSignalInput;
|
readonly input: AnalyzeSignalInput;
|
||||||
readonly listingIds: readonly number[];
|
readonly listingIds: readonly number[];
|
||||||
|
|
@ -742,15 +873,23 @@ function buildCanonicalStudyExpression(params: {
|
||||||
}): SignalStudyExpression {
|
}): SignalStudyExpression {
|
||||||
const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } =
|
const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } =
|
||||||
params;
|
params;
|
||||||
|
const signalExprSuffix =
|
||||||
|
input.signal.source === 'feature'
|
||||||
|
? `feature:${input.signal.featureRef}`
|
||||||
|
: `${input.signal.source}:${input.signal.field}`;
|
||||||
return {
|
return {
|
||||||
expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`,
|
expression: `mcp:analyze_signal:v1:${signalExprSuffix}`,
|
||||||
params: {
|
params: {
|
||||||
version: 1,
|
version: 1,
|
||||||
signalSource: input.signal.source,
|
signalSource: input.signal.source,
|
||||||
signalField: input.signal.field,
|
...(input.signal.source === 'feature'
|
||||||
...(input.signal.source === 'fundamentals'
|
? { featureRef: input.signal.featureRef }
|
||||||
? { allowEstimatedLag: input.signal.allowEstimatedLag }
|
: {
|
||||||
: {}),
|
signalField: input.signal.field,
|
||||||
|
...(input.signal.source === 'fundamentals'
|
||||||
|
? { allowEstimatedLag: input.signal.allowEstimatedLag }
|
||||||
|
: {}),
|
||||||
|
}),
|
||||||
horizonSessions: input.horizonSessions,
|
horizonSessions: input.horizonSessions,
|
||||||
maxSignalAgeSessions: input.maxSignalAgeSessions ?? null,
|
maxSignalAgeSessions: input.maxSignalAgeSessions ?? null,
|
||||||
adjustment: input.adjustment,
|
adjustment: input.adjustment,
|
||||||
|
|
@ -824,12 +963,13 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number {
|
||||||
typeof options.store !== 'object' ||
|
typeof options.store !== 'object' ||
|
||||||
options.store === null ||
|
options.store === null ||
|
||||||
typeof options.store.bars !== 'function' ||
|
typeof options.store.bars !== 'function' ||
|
||||||
|
typeof options.store.crossSection !== 'function' ||
|
||||||
typeof options.store.shortsAsOf !== 'function' ||
|
typeof options.store.shortsAsOf !== 'function' ||
|
||||||
typeof options.store.fundamentalsAsOf !== 'function' ||
|
typeof options.store.fundamentalsAsOf !== 'function' ||
|
||||||
typeof options.store.universe !== 'function'
|
typeof options.store.universe !== 'function'
|
||||||
) {
|
) {
|
||||||
throw new MarketDataStoreValidationError(
|
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'
|
'store'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -875,7 +1015,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
||||||
return defineMcpTool({
|
return defineMcpTool({
|
||||||
name: 'analyze_signal',
|
name: 'analyze_signal',
|
||||||
description:
|
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,
|
inputSchema: analyzeSignalInputSchema,
|
||||||
jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA,
|
jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA,
|
||||||
async handler(input: AnalyzeSignalInput): Promise<McpToolCallResult> {
|
async handler(input: AnalyzeSignalInput): Promise<McpToolCallResult> {
|
||||||
|
|
@ -913,11 +1053,16 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
||||||
source: 'shorts',
|
source: 'shorts',
|
||||||
field: input.signal.field,
|
field: input.signal.field,
|
||||||
}
|
}
|
||||||
: {
|
: input.signal.source === 'fundamentals'
|
||||||
source: 'fundamentals',
|
? {
|
||||||
field: input.signal.field,
|
source: 'fundamentals',
|
||||||
allowEstimatedLag: input.signal.allowEstimatedLag,
|
field: input.signal.field,
|
||||||
};
|
allowEstimatedLag: input.signal.allowEstimatedLag,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
source: 'feature',
|
||||||
|
featureRef: input.signal.featureRef,
|
||||||
|
};
|
||||||
|
|
||||||
const basePayloadFields = {
|
const basePayloadFields = {
|
||||||
scope: 'vault_fenced' as const,
|
scope: 'vault_fenced' as const,
|
||||||
|
|
@ -996,6 +1141,50 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
||||||
fenced.vaultCutoffDate
|
fenced.vaultCutoffDate
|
||||||
);
|
);
|
||||||
signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field);
|
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<string>();
|
||||||
|
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 {
|
} else {
|
||||||
const { field: fundamentalsField, allowEstimatedLag } = input.signal;
|
const { field: fundamentalsField, allowEstimatedLag } = input.signal;
|
||||||
const snapshotDates = deriveMonthlySnapshotDates(eligibleBars);
|
const snapshotDates = deriveMonthlySnapshotDates(eligibleBars);
|
||||||
|
|
|
||||||
|
|
@ -249,6 +249,10 @@ const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
|
||||||
'adjustment',
|
'adjustment',
|
||||||
'scope',
|
'scope',
|
||||||
'limit',
|
'limit',
|
||||||
|
'countries',
|
||||||
|
'indicators',
|
||||||
|
'features',
|
||||||
|
'universe',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
||||||
|
|
|
||||||
|
|
@ -498,7 +498,7 @@ function createFakeDuckDbExecutor(fixture: QmFilingsFixture): {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sql.includes('events/year=*/part.parquet')) {
|
if (sql.includes('events/year=*/*.parquet')) {
|
||||||
// Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso]
|
// Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso]
|
||||||
const nIds = fixture.listingIds.length;
|
const nIds = fixture.listingIds.length;
|
||||||
const nKinds = params.length - nIds - 3;
|
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).toHaveLength(3);
|
||||||
expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata');
|
expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata');
|
||||||
expect(clean.duck.queries[1]!.sql).toContain('cum_total_factor');
|
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
|
// Every bound timestamp parameter (`asOfIso`, `fromIso`, `toIso`) in every data query
|
||||||
// is strictly `< vaultCutoffTs`.
|
// is strictly `< vaultCutoffTs`.
|
||||||
|
|
|
||||||
|
|
@ -446,8 +446,8 @@ describe('validateFeatureDefinition', () => {
|
||||||
() =>
|
() =>
|
||||||
validateFeatureDefinition(
|
validateFeatureDefinition(
|
||||||
makeSimpleDef({
|
makeSimpleDef({
|
||||||
inputs: ['macro' as FeatureDefinition['inputs'][number]],
|
inputs: ['bars_1m' as FeatureDefinition['inputs'][number]],
|
||||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}',
|
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1m}}',
|
||||||
})
|
})
|
||||||
),
|
),
|
||||||
'UNSUPPORTED_INPUT_DATASET'
|
'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', () => {
|
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.
|
// 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, {
|
const midyear = planFeatureBatch(RET_1D_V1, {
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import {
|
||||||
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
||||||
FX_1D_COLUMNS,
|
FX_1D_COLUMNS,
|
||||||
FX_PAIR_MAP,
|
FX_PAIR_MAP,
|
||||||
|
MACRO_COLUMNS,
|
||||||
MarketDataStoreNotImplementedError,
|
MarketDataStoreNotImplementedError,
|
||||||
MarketDataStoreValidationError,
|
MarketDataStoreValidationError,
|
||||||
type PinnedAdjFactorsArtifact,
|
type PinnedAdjFactorsArtifact,
|
||||||
|
|
@ -32,6 +33,7 @@ import {
|
||||||
planEventsQuery,
|
planEventsQuery,
|
||||||
planFundamentalsAsOfQuery,
|
planFundamentalsAsOfQuery,
|
||||||
planFx1dQuery,
|
planFx1dQuery,
|
||||||
|
planMacroAsOfQuery,
|
||||||
planShortsAsOfQuery,
|
planShortsAsOfQuery,
|
||||||
planUniverseQuery,
|
planUniverseQuery,
|
||||||
resolveDuckDbConnectionBudget,
|
resolveDuckDbConnectionBudget,
|
||||||
|
|
@ -386,7 +388,7 @@ describe('pure DuckDB query planners — exact SQL and bound parameters', () =>
|
||||||
expect(kinds).toEqual(['filing', 'earnings', 'filing']);
|
expect(kinds).toEqual(['filing', 'earnings', 'filing']);
|
||||||
expect(withListings.sql).toBe(
|
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 ' +
|
'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 <= ? ' +
|
'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'
|
'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(
|
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 ' +
|
'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 <= ? ' +
|
'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'
|
'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',
|
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) {
|
for (const c of cases) {
|
||||||
|
|
@ -3271,44 +3263,254 @@ describe('fundamentalsAsOf hostile request inputs', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('planCrossSectionQuery & createDuckDbMarketDataStore().crossSection()', () => {
|
describe('planMacroAsOfQuery and store.macroAsOf', () => {
|
||||||
it('plans Vault-fenced survivorship-free crossSection SQL and maps nullable feature values', async () => {
|
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);
|
expect(subpathPlanCrossSectionQuery).toBe(planCrossSectionQuery);
|
||||||
|
|
||||||
const planned = planCrossSectionQuery(
|
const planned = planCrossSectionQuery(
|
||||||
{
|
{
|
||||||
features: ['ret_1d@v1', 'mom_diff@v1', 'ret_1d@v1'],
|
features: ['ret_1d@v1', 'rsi_14@v2', 'ret_1d@v1'],
|
||||||
date: '2025-01-02',
|
date: '2025-06-10',
|
||||||
universe: 'US_EQ',
|
universe: 'US_CA_EQ',
|
||||||
asOf: '2025-01-02T22:00:00Z',
|
|
||||||
},
|
},
|
||||||
DEFAULT_CTX
|
DEFAULT_CTX
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(planned.sql).toContain(
|
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(
|
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(
|
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.sql).toContain('ORDER BY u.listing_id ASC');
|
||||||
expect(planned.params).toEqual([
|
expect(planned.params).toEqual([
|
||||||
'USD',
|
'USD',
|
||||||
'2024-12-26',
|
'CAD',
|
||||||
'2025-01-02',
|
'2025-06-03',
|
||||||
'2025-01-02T23:59:59.999999Z',
|
'2025-06-10',
|
||||||
'2025-01-02T22:00:00.000Z',
|
'2025-06-10T23:59:59.999999Z',
|
||||||
'2025-01-02T00:00:00.000Z',
|
'2025-06-10T23:59:59.999999Z',
|
||||||
'2025-01-02T23:59:59.999999Z',
|
2025,
|
||||||
'2025-01-02T22:00:00.000Z',
|
'2025-06-10T00:00:00.000Z',
|
||||||
'2025-01-02T00:00:00.000Z',
|
'2025-06-10T23:59:59.999999Z',
|
||||||
'2025-01-02T23:59:59.999999Z',
|
'2025-06-10T23:59:59.999999Z',
|
||||||
'2025-01-02T22:00:00.000Z',
|
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({
|
const fake = createRecordingExecutor({
|
||||||
onQuery: () => [
|
onQuery: () => [
|
||||||
{ listing_id: 1, 'ret_1d@v1': 0.1, 'mom_diff@v1': 1.0 },
|
{ 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 },
|
{ 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;
|
const beforeCalls = fake.calls.length;
|
||||||
await expect(
|
await expect(
|
||||||
store.crossSection({
|
store.crossSection({
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,19 @@ import {
|
||||||
type BarBatch,
|
type BarBatch,
|
||||||
type BarRecord,
|
type BarRecord,
|
||||||
DEFAULT_QUESTDB_BARS_BATCH_SIZE,
|
DEFAULT_QUESTDB_BARS_BATCH_SIZE,
|
||||||
|
FX_1M_COLUMNS,
|
||||||
MarketDataStoreNotImplementedError,
|
MarketDataStoreNotImplementedError,
|
||||||
MarketDataStoreValidationError,
|
MarketDataStoreValidationError,
|
||||||
type QuestDbBars1mQuery,
|
type QuestDbBars1mQuery,
|
||||||
|
type QuestDbFx1mQuery,
|
||||||
type QuestDbQueryExecutor,
|
type QuestDbQueryExecutor,
|
||||||
VaultHoldoutFenceError,
|
VaultHoldoutFenceError,
|
||||||
VaultScopeNotAuthorizedError,
|
VaultScopeNotAuthorizedError,
|
||||||
createQuestDbIntradayBarsReader,
|
createQuestDbIntradayBarsReader,
|
||||||
|
createQuestDbIntradayFxReader,
|
||||||
|
createQuestDbIntradayReader,
|
||||||
planBars1mQuery,
|
planBars1mQuery,
|
||||||
|
planFx1mQuery,
|
||||||
} from '@stock-bot/research';
|
} from '@stock-bot/research';
|
||||||
|
|
||||||
interface RecordedCall {
|
interface RecordedCall {
|
||||||
|
|
@ -766,3 +771,111 @@ describe('Malformed and out-of-fence row defence-in-depth', () => {
|
||||||
expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true);
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import {
|
||||||
type TableRow,
|
type TableRow,
|
||||||
createDuckDbMarketDataStore,
|
createDuckDbMarketDataStore,
|
||||||
createQuestDbIntradayBarsReader,
|
createQuestDbIntradayBarsReader,
|
||||||
|
createQuestDbIntradayReader,
|
||||||
createRoutedMarketDataStore,
|
createRoutedMarketDataStore,
|
||||||
} from '@stock-bot/research';
|
} from '@stock-bot/research';
|
||||||
import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb';
|
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);
|
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<Table> {
|
||||||
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import {
|
||||||
} from '../src/market-data-store';
|
} from '../src/market-data-store';
|
||||||
import {
|
import {
|
||||||
type BarsQuery,
|
type BarsQuery,
|
||||||
|
type CrossSectionQuery,
|
||||||
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
||||||
type FundamentalsAsOfQuery,
|
type FundamentalsAsOfQuery,
|
||||||
MarketDataStoreNotImplementedError,
|
MarketDataStoreNotImplementedError,
|
||||||
|
|
@ -288,6 +289,7 @@ interface FakeStoreState {
|
||||||
readonly barsCalls: BarsQuery[];
|
readonly barsCalls: BarsQuery[];
|
||||||
readonly shortsCalls: ShortsAsOfQuery[];
|
readonly shortsCalls: ShortsAsOfQuery[];
|
||||||
readonly fundamentalsCalls: FundamentalsAsOfQuery[];
|
readonly fundamentalsCalls: FundamentalsAsOfQuery[];
|
||||||
|
readonly crossSectionCalls: CrossSectionQuery[];
|
||||||
readonly universeCalls: UniverseQuery[];
|
readonly universeCalls: UniverseQuery[];
|
||||||
readonly store: MarketDataStore;
|
readonly store: MarketDataStore;
|
||||||
}
|
}
|
||||||
|
|
@ -296,17 +298,20 @@ function createFakeStore(options?: {
|
||||||
bars?: readonly BarRecord[];
|
bars?: readonly BarRecord[];
|
||||||
shortsTable?: Table;
|
shortsTable?: Table;
|
||||||
fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise<Table>;
|
fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise<Table>;
|
||||||
|
crossSectionResolver?: (q: CrossSectionQuery) => Table | Promise<Table>;
|
||||||
universeIds?: readonly number[];
|
universeIds?: readonly number[];
|
||||||
universeResolver?: (q: UniverseQuery) => number[];
|
universeResolver?: (q: UniverseQuery) => number[];
|
||||||
leaky?: boolean;
|
leaky?: boolean;
|
||||||
barsError?: Error;
|
barsError?: Error;
|
||||||
shortsError?: Error;
|
shortsError?: Error;
|
||||||
fundamentalsError?: Error;
|
fundamentalsError?: Error;
|
||||||
|
crossSectionError?: Error;
|
||||||
universeError?: Error;
|
universeError?: Error;
|
||||||
}): FakeStoreState {
|
}): FakeStoreState {
|
||||||
const barsCalls: BarsQuery[] = [];
|
const barsCalls: BarsQuery[] = [];
|
||||||
const shortsCalls: ShortsAsOfQuery[] = [];
|
const shortsCalls: ShortsAsOfQuery[] = [];
|
||||||
const fundamentalsCalls: FundamentalsAsOfQuery[] = [];
|
const fundamentalsCalls: FundamentalsAsOfQuery[] = [];
|
||||||
|
const crossSectionCalls: CrossSectionQuery[] = [];
|
||||||
const universeCalls: UniverseQuery[] = [];
|
const universeCalls: UniverseQuery[] = [];
|
||||||
|
|
||||||
const allBars = options?.bars ?? [];
|
const allBars = options?.bars ?? [];
|
||||||
|
|
@ -402,7 +407,14 @@ function createFakeStore(options?: {
|
||||||
return [...(options?.universeIds ?? [])];
|
return [...(options?.universeIds ?? [])];
|
||||||
},
|
},
|
||||||
|
|
||||||
crossSection() {
|
async crossSection(q: CrossSectionQuery): Promise<Table> {
|
||||||
|
crossSectionCalls.push(q);
|
||||||
|
if (options?.crossSectionError !== undefined) {
|
||||||
|
throw options.crossSectionError;
|
||||||
|
}
|
||||||
|
if (options?.crossSectionResolver !== undefined) {
|
||||||
|
return options.crossSectionResolver(q);
|
||||||
|
}
|
||||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||||
},
|
},
|
||||||
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
||||||
|
|
@ -426,7 +438,7 @@ function createFakeStore(options?: {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store };
|
return { barsCalls, shortsCalls, fundamentalsCalls, crossSectionCalls, universeCalls, store };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function callAnalyzeSignal(params: {
|
async function callAnalyzeSignal(params: {
|
||||||
|
|
@ -1898,16 +1910,19 @@ describe('MCP analyze_signal tool — fundamentals source', () => {
|
||||||
expect(signalSchema.additionalProperties).toBe(false);
|
expect(signalSchema.additionalProperties).toBe(false);
|
||||||
expect(Object.keys(signalSchema.properties).sort()).toEqual([
|
expect(Object.keys(signalSchema.properties).sort()).toEqual([
|
||||||
'allowEstimatedLag',
|
'allowEstimatedLag',
|
||||||
|
'featureRef',
|
||||||
'field',
|
'field',
|
||||||
'source',
|
'source',
|
||||||
]);
|
]);
|
||||||
expect(signalSchema.anyOf).toHaveLength(2);
|
expect(signalSchema.anyOf).toHaveLength(3);
|
||||||
expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false);
|
expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false);
|
||||||
expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts');
|
expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts');
|
||||||
expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false);
|
expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false);
|
||||||
expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals');
|
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.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]);
|
||||||
expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false);
|
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 = {
|
const validBase = {
|
||||||
listingIds: [70_001, 70_002],
|
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(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.');
|
||||||
expect(badTableLedger.rows).toHaveLength(0);
|
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);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1190,6 +1190,178 @@ describe('runResearchCopilotStdioHost', () => {
|
||||||
|
|
||||||
expect(caughtSafe).toBe(safeAggregate);
|
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<Record<string, string>> = [
|
||||||
|
{ 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', () => {
|
describe('stdio-host dependency-free source invariants', () => {
|
||||||
|
|
|
||||||
215
python/tests/test_events_copublish.py
Normal file
215
python/tests/test_events_copublish.py
Normal file
|
|
@ -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
|
||||||
113
scripts/questdb-init-m2.ts
Normal file
113
scripts/questdb-init-m2.ts
Normal file
|
|
@ -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<Record<string, string | undefined>>,
|
||||||
|
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<Record<string, string | undefined>> = 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<Record<string, string | undefined>> = 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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -70,7 +70,6 @@ describe('design/m2-gap-audit.md citations', () => {
|
||||||
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
|
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
|
||||||
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
['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_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/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/],
|
||||||
['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'],
|
['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'],
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -41,8 +41,8 @@ function citedRepoPaths(markdown: string): string[] {
|
||||||
.sort();
|
.sort();
|
||||||
}
|
}
|
||||||
|
|
||||||
function lineAt(file: string, line: number): string {
|
function fileContents(file: string): string {
|
||||||
return readFileSync(join(repoRoot, file), 'utf8').split('\n')[line - 1] ?? '';
|
return readFileSync(join(repoRoot, file), 'utf8');
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('design/m2-master-audit.md citations', () => {
|
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);
|
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
// [file, 1-based line the audit cites, text that line must contain]
|
// [file, symbol or test reported as landed that must still exist in the file]
|
||||||
const lineCitations: Array<[file: string, line: number, expected: string]> = [
|
// Gaps reported by the audit (such as `EventsDatasetExists` or the old `events/year=*/part.parquet`
|
||||||
['tools/curate-etl/src/parquet_posts.rs', 22, 'EVENT_KIND_POST'],
|
// glob) are intentionally omitted so closing those gaps does not break this citation guard.
|
||||||
['tools/curate-etl/src/run_curate_posts.rs', 133, 'EventsDatasetExists'],
|
const symbolCitations: Array<[file: string, expected: string]> = [
|
||||||
['tools/curate-etl/src/mongo_stream.rs', 53, 'pub enum SourceCollection'],
|
['tools/curate-etl/src/parquet_posts.rs', 'EVENT_KIND_POST'],
|
||||||
['tools/curate-etl/src/run_curate_fundamentals.rs', 113, 'pub struct CurateFundamentalsArgs'],
|
['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'],
|
||||||
['tools/curate-etl/src/cli.rs', 98, 'CurateBars1m('],
|
['tools/curate-etl/src/run_curate_fundamentals.rs', 'pub struct CurateFundamentalsArgs'],
|
||||||
['tools/curate-etl/src/cli.rs', 99, 'CurateQmBars1m('],
|
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
|
||||||
['tools/curate-etl/src/cli.rs', 100, 'CurateFx1m('],
|
['tools/curate-etl/src/cli.rs', 'CurateQmBars1m('],
|
||||||
['tools/curate-etl/src/cli.rs', 101, 'CuratePosts('],
|
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
||||||
['tools/curate-etl/src/cli.rs', 102, 'CurateFundamentals('],
|
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
|
||||||
['tools/curate-etl/src/cli.rs', 103, 'CurateMacro('],
|
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
|
||||||
['tools/curate-etl/src/cli.rs', 104, 'SendIlp('],
|
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
|
||||||
['tools/curate-etl/src/cli.rs', 1317, 'CliAction::CuratePosts'],
|
['tools/curate-etl/src/cli.rs', 'SendIlp('],
|
||||||
['tools/curate-etl/src/cli.rs', 1636, 'CliAction::CurateFundamentals'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::CuratePosts'],
|
||||||
['tools/curate-etl/src/cli.rs', 1689, 'CliAction::CurateMacro'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::CurateFundamentals'],
|
||||||
['tools/curate-etl/src/cli.rs', 2110, 'CliAction::CurateBars1m'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::CurateMacro'],
|
||||||
['tools/curate-etl/src/cli.rs', 2277, 'CliAction::CurateQmBars1m'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::CurateBars1m'],
|
||||||
['tools/curate-etl/src/cli.rs', 2381, 'CliAction::CurateFx1m'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::CurateQmBars1m'],
|
||||||
['tools/curate-etl/src/cli.rs', 2461, 'CliAction::SendIlp'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::CurateFx1m'],
|
||||||
['tools/curate-etl/src/main.rs', 22, 'run_send_ilp'],
|
['tools/curate-etl/src/cli.rs', 'CliAction::SendIlp'],
|
||||||
['tools/curate-etl/src/main.rs', 39, 'run_curate_qm_bars_1m'],
|
['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',
|
'tools/curate-etl/src/fundamentals_tests.rs',
|
||||||
104,
|
|
||||||
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
|
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'tools/curate-etl/src/parquet_fundamentals_tests.rs',
|
'tools/curate-etl/src/parquet_fundamentals_tests.rs',
|
||||||
1107,
|
|
||||||
'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm',
|
'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm',
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
|
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
|
||||||
402,
|
|
||||||
'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes',
|
'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', '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', 'TcpListener::bind("127.0.0.1:0")'],
|
||||||
[
|
[
|
||||||
'tools/curate-etl/tests/cli.rs',
|
'tools/curate-etl/tests/cli.rs',
|
||||||
1877,
|
|
||||||
'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage',
|
'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',
|
'tools/curate-etl/tests/curate_macro.rs',
|
||||||
178,
|
|
||||||
'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage',
|
'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage',
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'tools/curate-etl/tests/curate_macro.rs',
|
'tools/curate-etl/tests/curate_macro.rs',
|
||||||
471,
|
|
||||||
'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel',
|
'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',
|
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
|
||||||
336,
|
|
||||||
'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants',
|
'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants',
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
|
'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',
|
'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards',
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
|
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
|
||||||
622,
|
|
||||||
'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped',
|
'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`'],
|
['tools/curate-etl/src/run_curate_fx_1m.rs', 'bar-start `ts`'],
|
||||||
['libs/data/questdb/src/schema.ts', 33, 'fx_1m: {'],
|
['libs/data/questdb/src/schema.ts', 'fx_1m: {'],
|
||||||
['libs/data/questdb/src/schema.ts', 139, 'export function getM2IntradayDDL'],
|
['libs/data/questdb/src/schema.ts', 'export function getM2IntradayDDL'],
|
||||||
['libs/data/duckdb/src/research-copilot-store.ts', 33, 'export const openResearchCopilotStore'],
|
['libs/data/duckdb/src/research-copilot-store.ts', 'export const openResearchCopilotStore'],
|
||||||
['libs/data/duckdb/src/research-copilot-store.ts', 40, 'vaultOperatorAuthorized: false'],
|
['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'],
|
||||||
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 251, 'fundamentalsAsOf enforces restatement non-overwrite'],
|
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', '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', "timeframe === '1m'"],
|
||||||
['libs/research/src/market-data-store-duckdb.ts', 1529, "timeframe === '1m'"],
|
['libs/research/src/market-data-store-duckdb.ts', 'crossSection('],
|
||||||
['libs/research/src/market-data-store-duckdb.ts', 2283, 'crossSection('],
|
['libs/research/src/market-data-store-duckdb.ts', 'async fundamentalsAsOf('],
|
||||||
['libs/research/src/market-data-store-duckdb.ts', 2287, 'async fundamentalsAsOf('],
|
['libs/research/src/market-data-store-duckdb.ts', 'macroAsOf('],
|
||||||
['libs/research/src/market-data-store-duckdb.ts', 2294, 'macroAsOf('],
|
['libs/research/src/market-data-store-routed.ts', 'return daily.fx(q)'],
|
||||||
['libs/research/src/market-data-store-routed.ts', 185, 'return daily.fx(q)'],
|
['libs/research/src/mcp/tools/analyze-signal.ts', 'discriminatedUnion'],
|
||||||
['libs/research/src/mcp/tools/analyze-signal.ts', 122, 'discriminatedUnion'],
|
['libs/research/src/feature-library.ts', 'RET_1D_V1'],
|
||||||
['libs/research/src/feature-library.ts', 29, 'RET_1D_V1'],
|
['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'],
|
||||||
['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'],
|
['libs/research/src/notebook-snapshot-node.ts', 'export function createNodeNotebookCommandRunner'],
|
||||||
['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'],
|
['scripts/research-copilot-mcp.ts', 'export async function runResearchCopilotMcp'],
|
||||||
['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'],
|
['package.json', '"mcp:research-copilot"'],
|
||||||
['package.json', 56, '"mcp:research-copilot"'],
|
['design/MILESTONES.md', 'eodIntraday1M'],
|
||||||
['design/MILESTONES.md', 96, 'eodIntraday1M'],
|
['docker-compose.quant.yml', '1048576'],
|
||||||
['docker-compose.quant.yml', 35, '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(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', () => {
|
test('pins the audited master baseline and accepted M1 separately from the review branch', () => {
|
||||||
|
|
|
||||||
90
scripts/test/questdb-init-m2.test.ts
Normal file
90
scripts/test/questdb-init-m2.test.ts
Normal file
|
|
@ -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<Record<string, string>> = [
|
||||||
|
{ 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { randomUUID } from 'node:crypto';
|
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 { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { afterEach, describe, expect, test } from 'bun:test';
|
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 { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||||
import {
|
import {
|
||||||
|
CURATE_INPUT_FILES,
|
||||||
|
CurateInputExportError,
|
||||||
exportCurateInputs,
|
exportCurateInputs,
|
||||||
pinCurateInputSnapshot,
|
pinCurateInputSnapshot,
|
||||||
type SecurityMasterQueryable,
|
type SecurityMasterQueryable,
|
||||||
|
|
@ -95,14 +97,21 @@ async function seedFixtureData(pool: Pool) {
|
||||||
try {
|
try {
|
||||||
await client.query('BEGIN');
|
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(`
|
await client.query(`
|
||||||
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
|
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
|
||||||
VALUES
|
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'),
|
('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
|
||||||
('XNYS', 'XNYS', 'NYSE', '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'),
|
('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
|
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 instNoListedTo = await insertInstrument('US0000000035', '000000003', 'No ListedTo Corp', 'common', 'US');
|
||||||
const instNoQm = await insertInstrument('US0000000043', '000000004', 'No QM Mapping 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 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: {
|
const insertListing = async (params: {
|
||||||
instrumentId: number;
|
instrumentId: number;
|
||||||
|
|
@ -284,6 +300,76 @@ async function seedFixtureData(pool: Pool) {
|
||||||
delistReason: null,
|
delistReason: null,
|
||||||
terminalReturn: 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 (
|
const insertMapping = async (
|
||||||
source: string,
|
source: string,
|
||||||
|
|
@ -351,6 +437,13 @@ async function seedFixtureData(pool: Pool) {
|
||||||
noQmId,
|
noQmId,
|
||||||
noSuccQmFromId,
|
noSuccQmFromId,
|
||||||
noSuccQmToId,
|
noSuccQmToId,
|
||||||
|
arcxId,
|
||||||
|
xaseId,
|
||||||
|
batsId,
|
||||||
|
iexgId,
|
||||||
|
neoeId,
|
||||||
|
xtsxId,
|
||||||
|
xcnqId,
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await client.query('ROLLBACK').catch(() => {});
|
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.generationId).toBe(res5000.generationId);
|
||||||
expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path);
|
expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path);
|
||||||
expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path);
|
expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path);
|
||||||
|
expect(pinned5000.listingVenues).toBe(res5000.listingVenues.path);
|
||||||
expect(pinned5000.delistings).toBe(res5000.delistings.path);
|
expect(pinned5000.delistings).toBe(res5000.delistings.path);
|
||||||
|
|
||||||
// Verify chunkSize=1 actually paginated across multiple queries.
|
// 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.
|
// Byte-identical outputs between chunkSize=1 and chunkSize=5000.
|
||||||
const pm5000 = await readFile(res5000.providerMapping.path, 'utf8');
|
const pm5000 = await readFile(res5000.providerMapping.path, 'utf8');
|
||||||
const lc5000 = await readFile(res5000.listingCurrencies.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');
|
const dl5000 = await readFile(res5000.delistings.path, 'utf8');
|
||||||
|
|
||||||
expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000);
|
expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000);
|
||||||
expect(await readFile(res1.listingCurrencies.path, 'utf8')).toBe(lc5000);
|
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);
|
expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000);
|
||||||
|
|
||||||
// Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order).
|
// 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.noQmId}\tUSD`,
|
||||||
`${ids.noSuccQmFromId}\tUSD`,
|
`${ids.noSuccQmFromId}\tUSD`,
|
||||||
`${ids.noSuccQmToId}\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')
|
].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.
|
// Assert exact delistings.tsv content.
|
||||||
expect(dl5000).toBe(
|
expect(dl5000).toBe(
|
||||||
[
|
[
|
||||||
|
|
@ -473,13 +619,13 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
|
||||||
// Assert exact stats reconciliation.
|
// Assert exact stats reconciliation.
|
||||||
const stats = res5000.delistings.stats;
|
const stats = res5000.delistings.stats;
|
||||||
expect(stats).toEqual({
|
expect(stats).toEqual({
|
||||||
rowsIn: 12,
|
rowsIn: 19,
|
||||||
rowsOut: 3,
|
rowsOut: 3,
|
||||||
otcTransfersOut: 1,
|
otcTransfersOut: 1,
|
||||||
terminalDelistingsOut: 2,
|
terminalDelistingsOut: 2,
|
||||||
skippedTotal: 9,
|
skippedTotal: 16,
|
||||||
skipped: {
|
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
|
noOutcome: 2, // FB old, NOSUQ
|
||||||
missingListedTo: 1, // NLDT
|
missingListedTo: 1, // NLDT
|
||||||
missingOutgoingQmMapping: 1, // NOQM
|
missingOutgoingQmMapping: 1, // NOQM
|
||||||
|
|
@ -489,5 +635,80 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
|
||||||
});
|
});
|
||||||
expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal);
|
expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal);
|
||||||
expect(res1.delistings.stats).toEqual(stats);
|
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,
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -93,7 +93,6 @@ describe('design/m2-completion-audit.md citations', () => {
|
||||||
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
||||||
['tools/curate-etl/src/main.rs', 'run_send_ilp('],
|
['tools/curate-etl/src/main.rs', 'run_send_ilp('],
|
||||||
['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'],
|
['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/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'],
|
['tools/curate-etl/src/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'],
|
||||||
[
|
[
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,10 @@
|
||||||
* QA differential tests for the curate-etl TSV exporter (T-116).
|
* QA differential tests for the curate-etl TSV exporter (T-116).
|
||||||
*
|
*
|
||||||
* - The streaming PostgreSQL exporter (`exportCurateInputs`) and the pure core
|
* - The streaming PostgreSQL exporter (`exportCurateInputs`) and the pure core
|
||||||
* (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `buildDelistingExportRows` +
|
* (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `formatListingVenuesTsv`,
|
||||||
* `formatDelistingsTsv`) must produce byte-identical TSVs and identical skip stats on the same
|
* `buildDelistingExportRows` + `formatDelistingsTsv`) must produce byte-identical TSVs and
|
||||||
* seeded random security master, for every chunk size (including exact chunk-boundary sizes).
|
* 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`
|
* - 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,
|
* 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
|
* `resolve_for_listing_on_or_before` + successor `resolve(effective_date)` for OTC rows) against the
|
||||||
|
|
@ -20,7 +21,9 @@ import {
|
||||||
exportCurateInputs,
|
exportCurateInputs,
|
||||||
formatDelistingsTsv,
|
formatDelistingsTsv,
|
||||||
formatListingCurrenciesTsv,
|
formatListingCurrenciesTsv,
|
||||||
|
formatListingVenuesTsv,
|
||||||
formatProviderMappingTsv,
|
formatProviderMappingTsv,
|
||||||
|
resolveListingVenueForMic,
|
||||||
type ContinuityExportSourceRow,
|
type ContinuityExportSourceRow,
|
||||||
type ListingDelistingSourceRow,
|
type ListingDelistingSourceRow,
|
||||||
type ProviderMappingExportRow,
|
type ProviderMappingExportRow,
|
||||||
|
|
@ -68,6 +71,7 @@ function ymdToDay(ymd: string): number {
|
||||||
interface DbListing {
|
interface DbListing {
|
||||||
listing_id: number;
|
listing_id: number;
|
||||||
currency: string;
|
currency: string;
|
||||||
|
mic: string;
|
||||||
listed_to: string | null;
|
listed_to: string | null;
|
||||||
delist_reason: string | null;
|
delist_reason: string | null;
|
||||||
terminal_return: 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.
|
// 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<number>();
|
const otcSuccessorIds = new Set<number>();
|
||||||
for (let i = 0; i < ids.length; i++) {
|
for (let i = 0; i < ids.length; i++) {
|
||||||
const listingId = ids[i] as number;
|
const listingId = ids[i] as number;
|
||||||
|
|
@ -159,11 +169,13 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset {
|
||||||
const startDay = Math.floor(rng() * 3000);
|
const startDay = Math.floor(rng() * 3000);
|
||||||
const roll = rng();
|
const roll = rng();
|
||||||
const currency = pick(['USD', 'USD', 'CAD']);
|
const currency = pick(['USD', 'USD', 'CAD']);
|
||||||
|
const mic = micForListing(listingId, currency);
|
||||||
|
|
||||||
if (roll < 0.35) {
|
if (roll < 0.35) {
|
||||||
listings.push({
|
listings.push({
|
||||||
listing_id: listingId,
|
listing_id: listingId,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: null,
|
listed_to: null,
|
||||||
delist_reason: 'active',
|
delist_reason: 'active',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -183,6 +195,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset {
|
||||||
listings.push({
|
listings.push({
|
||||||
listing_id: listingId,
|
listing_id: listingId,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: dayToYmd(endDay),
|
listed_to: dayToYmd(endDay),
|
||||||
delist_reason: 'moved_to_otc',
|
delist_reason: 'moved_to_otc',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -203,6 +216,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset {
|
||||||
listings.push({
|
listings.push({
|
||||||
listing_id: successorId,
|
listing_id: successorId,
|
||||||
currency,
|
currency,
|
||||||
|
mic: micForListing(successorId, currency),
|
||||||
listed_to: successorCancelled ? dayToYmd(successorEnd) : null,
|
listed_to: successorCancelled ? dayToYmd(successorEnd) : null,
|
||||||
delist_reason: successorCancelled ? 'bankruptcy_cancelled' : 'active',
|
delist_reason: successorCancelled ? 'bankruptcy_cancelled' : 'active',
|
||||||
terminal_return: successorCancelled ? '-1.000000' : null,
|
terminal_return: successorCancelled ? '-1.000000' : null,
|
||||||
|
|
@ -230,6 +244,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset {
|
||||||
listings.push({
|
listings.push({
|
||||||
listing_id: listingId,
|
listing_id: listingId,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: missingDate ? null : dayToYmd(endDay),
|
listed_to: missingDate ? null : dayToYmd(endDay),
|
||||||
delist_reason: pick(['unknown_involuntary', 'bankruptcy_cancelled', 'merger_cash']),
|
delist_reason: pick(['unknown_involuntary', 'bankruptcy_cancelled', 'merger_cash']),
|
||||||
terminal_return: terminalReturn,
|
terminal_return: terminalReturn,
|
||||||
|
|
@ -248,6 +263,7 @@ function buildRandomDataset(seed: number, listingCount: number): Dataset {
|
||||||
listings.push({
|
listings.push({
|
||||||
listing_id: listingId,
|
listing_id: listingId,
|
||||||
currency,
|
currency,
|
||||||
|
mic,
|
||||||
listed_to: dayToYmd(endDay),
|
listed_to: dayToYmd(endDay),
|
||||||
delist_reason: rng() < 0.5 ? null : 'unknown',
|
delist_reason: rng() < 0.5 ? null : 'unknown',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -454,6 +470,7 @@ async function runExport(data: Dataset, chunkSize: number) {
|
||||||
recordedSql,
|
recordedSql,
|
||||||
providerMapping: await read(CURATE_INPUT_FILES.providerMapping),
|
providerMapping: await read(CURATE_INPUT_FILES.providerMapping),
|
||||||
listingCurrencies: await read(CURATE_INPUT_FILES.listingCurrencies),
|
listingCurrencies: await read(CURATE_INPUT_FILES.listingCurrencies),
|
||||||
|
listingVenues: await read(CURATE_INPUT_FILES.listingVenues),
|
||||||
delistings: await read(CURATE_INPUT_FILES.delistings),
|
delistings: await read(CURATE_INPUT_FILES.delistings),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -472,6 +489,15 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
rng
|
rng
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
const expectedListingVenues = formatListingVenuesTsv(
|
||||||
|
shuffle(
|
||||||
|
data.listings.map(l => ({
|
||||||
|
listingId: l.listing_id,
|
||||||
|
venue: resolveListingVenueForMic(l.mic),
|
||||||
|
})),
|
||||||
|
rng
|
||||||
|
)
|
||||||
|
);
|
||||||
const built = buildDelistingExportRows(
|
const built = buildDelistingExportRows(
|
||||||
shuffle(pure.delistingListings, rng),
|
shuffle(pure.delistingListings, rng),
|
||||||
shuffle(pure.continuities, 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));
|
const out = await runExport(data, Math.min(chunkSize, 5000));
|
||||||
expect(out.providerMapping).toBe(expectedProviderMapping);
|
expect(out.providerMapping).toBe(expectedProviderMapping);
|
||||||
expect(out.listingCurrencies).toBe(expectedListingCurrencies);
|
expect(out.listingCurrencies).toBe(expectedListingCurrencies);
|
||||||
|
expect(out.listingVenues).toBe(expectedListingVenues);
|
||||||
expect(out.delistings).toBe(expectedDelistings);
|
expect(out.delistings).toBe(expectedDelistings);
|
||||||
|
|
||||||
const s = out.result.delistings.stats;
|
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.rowsIn).toBe(mappingRows);
|
||||||
expect(out.result.providerMapping.rowsOut).toBe(mappingRows);
|
expect(out.result.providerMapping.rowsOut).toBe(mappingRows);
|
||||||
expect(out.result.listingCurrencies.rowsOut).toBe(listingRows);
|
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(
|
expect(out.result.totalBytesWritten).toBe(
|
||||||
Buffer.byteLength(out.providerMapping) +
|
Buffer.byteLength(out.providerMapping) +
|
||||||
Buffer.byteLength(out.listingCurrencies) +
|
Buffer.byteLength(out.listingCurrencies) +
|
||||||
|
Buffer.byteLength(out.listingVenues) +
|
||||||
Buffer.byteLength(out.delistings)
|
Buffer.byteLength(out.delistings)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -599,6 +629,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 1,
|
listing_id: 1,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'XNYS',
|
||||||
listed_to: '2023-01-03',
|
listed_to: '2023-01-03',
|
||||||
delist_reason: 'x',
|
delist_reason: 'x',
|
||||||
terminal_return: '0.000000',
|
terminal_return: '0.000000',
|
||||||
|
|
@ -606,6 +637,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 2,
|
listing_id: 2,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'XNAS',
|
||||||
listed_to: '2023-01-03',
|
listed_to: '2023-01-03',
|
||||||
delist_reason: 'x',
|
delist_reason: 'x',
|
||||||
terminal_return: '-0.000000',
|
terminal_return: '-0.000000',
|
||||||
|
|
@ -613,6 +645,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 3,
|
listing_id: 3,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'ARCX',
|
||||||
listed_to: '2023-01-03',
|
listed_to: '2023-01-03',
|
||||||
delist_reason: 'x',
|
delist_reason: 'x',
|
||||||
terminal_return: '-0.000001',
|
terminal_return: '-0.000001',
|
||||||
|
|
@ -620,6 +653,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 4,
|
listing_id: 4,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'XASE',
|
||||||
listed_to: '2023-01-03',
|
listed_to: '2023-01-03',
|
||||||
delist_reason: 'x',
|
delist_reason: 'x',
|
||||||
terminal_return: '-1.000000',
|
terminal_return: '-1.000000',
|
||||||
|
|
@ -627,6 +661,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 5,
|
listing_id: 5,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'OTCM',
|
||||||
listed_to: '2023-01-03',
|
listed_to: '2023-01-03',
|
||||||
delist_reason: 'x',
|
delist_reason: 'x',
|
||||||
terminal_return: '-0.300000',
|
terminal_return: '-0.300000',
|
||||||
|
|
@ -665,6 +700,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 10,
|
listing_id: 10,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'XNYS',
|
||||||
listed_to: '2023-03-10',
|
listed_to: '2023-03-10',
|
||||||
delist_reason: 'moved_to_otc',
|
delist_reason: 'moved_to_otc',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -672,6 +708,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 11,
|
listing_id: 11,
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
|
mic: 'OTCM',
|
||||||
listed_to: null,
|
listed_to: null,
|
||||||
delist_reason: 'active',
|
delist_reason: 'active',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -679,6 +716,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 20,
|
listing_id: 20,
|
||||||
currency: 'CAD',
|
currency: 'CAD',
|
||||||
|
mic: 'XTSX',
|
||||||
listed_to: '2023-03-10',
|
listed_to: '2023-03-10',
|
||||||
delist_reason: 'moved_to_otc',
|
delist_reason: 'moved_to_otc',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -686,6 +724,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
{
|
{
|
||||||
listing_id: 21,
|
listing_id: 21,
|
||||||
currency: 'CAD',
|
currency: 'CAD',
|
||||||
|
mic: 'XCNQ',
|
||||||
listed_to: null,
|
listed_to: null,
|
||||||
delist_reason: 'active',
|
delist_reason: 'active',
|
||||||
terminal_return: null,
|
terminal_return: null,
|
||||||
|
|
@ -730,6 +769,7 @@ describe('exportCurateInputs streaming vs pure core parity (seeded random securi
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
expect(out.listingCurrencies).toBe('10\tUSD\n11\tUSD\n20\tCAD\n21\tCAD\n');
|
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(
|
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'
|
'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'
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,16 @@
|
||||||
import { afterEach, describe, expect, test } from 'bun:test';
|
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 { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import {
|
import {
|
||||||
|
|
@ -10,7 +21,9 @@ import {
|
||||||
import {
|
import {
|
||||||
assertExportCurateInputsSafety,
|
assertExportCurateInputsSafety,
|
||||||
buildDelistingExportRows,
|
buildDelistingExportRows,
|
||||||
|
CURATE_INPUT_CURRENT_LINK,
|
||||||
CURATE_INPUT_FILES,
|
CURATE_INPUT_FILES,
|
||||||
|
CURATE_INPUT_GENERATIONS_DIR,
|
||||||
CURATE_INPUT_PUBLISH_LOCK,
|
CURATE_INPUT_PUBLISH_LOCK,
|
||||||
CurateInputExportError,
|
CurateInputExportError,
|
||||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||||
|
|
@ -19,16 +32,22 @@ import {
|
||||||
formatDelistingsTsv,
|
formatDelistingsTsv,
|
||||||
formatExportCurateInputsSummary,
|
formatExportCurateInputsSummary,
|
||||||
formatListingCurrenciesTsv,
|
formatListingCurrenciesTsv,
|
||||||
|
formatListingVenuesTsv,
|
||||||
formatPlainDecimal,
|
formatPlainDecimal,
|
||||||
formatProviderMappingTsv,
|
formatProviderMappingTsv,
|
||||||
|
ISO_EXCHANGE_SEEDS,
|
||||||
|
LISTING_STATUTORY_LAG_VENUES,
|
||||||
|
LISTING_VENUE_BY_MIC,
|
||||||
parseExportCurateInputsArgs,
|
parseExportCurateInputsArgs,
|
||||||
pinCurateInputSnapshot,
|
pinCurateInputSnapshot,
|
||||||
|
resolveListingVenueForMic,
|
||||||
runExportCurateInputs,
|
runExportCurateInputs,
|
||||||
runExportCurateInputsCli,
|
runExportCurateInputsCli,
|
||||||
type ContinuityExportSourceRow,
|
type ContinuityExportSourceRow,
|
||||||
type DelistingExportRow,
|
type DelistingExportRow,
|
||||||
type ListingCurrencyExportRow,
|
type ListingCurrencyExportRow,
|
||||||
type ListingDelistingSourceRow,
|
type ListingDelistingSourceRow,
|
||||||
|
type ListingVenueExportRow,
|
||||||
type ProviderMappingExportRow,
|
type ProviderMappingExportRow,
|
||||||
type SecurityMasterQueryable,
|
type SecurityMasterQueryable,
|
||||||
type SecurityMasterQueryResult,
|
type SecurityMasterQueryResult,
|
||||||
|
|
@ -93,6 +112,7 @@ async function expectExportErrorAsync(
|
||||||
interface InMemorySecurityMasterData {
|
interface InMemorySecurityMasterData {
|
||||||
readonly listings: readonly {
|
readonly listings: readonly {
|
||||||
readonly listing_id: number;
|
readonly listing_id: number;
|
||||||
|
readonly mic: string | null;
|
||||||
readonly currency: string | null;
|
readonly currency: string | null;
|
||||||
readonly listed_to: string | null;
|
readonly listed_to: string | null;
|
||||||
readonly delist_reason: 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', () => {
|
describe('buildDelistingExportRows and formatDelistingsTsv', () => {
|
||||||
test('handles OTC transfer + successor terminal delisting (SIVB -> SIVBQ -> -1), -0.3 Shumway, active/null skips, and stats conservation', () => {
|
test('handles OTC transfer + successor terminal delisting (SIVB -> SIVBQ -> -1), -0.3 Shumway, active/null skips, and stats conservation', () => {
|
||||||
const listings: ListingDelistingSourceRow[] = [
|
const listings: ListingDelistingSourceRow[] = [
|
||||||
|
|
@ -760,18 +909,21 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
const outDir = await makeTempDir('curate-inputs-atomic-');
|
const outDir = await makeTempDir('curate-inputs-atomic-');
|
||||||
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
||||||
const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies);
|
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 dlPath = join(outDir, CURATE_INPUT_FILES.delistings);
|
||||||
|
|
||||||
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
|
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
|
||||||
const origLc = '1\tUSD\n';
|
const origLc = '1\tUSD\n';
|
||||||
|
const origLv = '1\tus_tsx\n';
|
||||||
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
|
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
|
||||||
await writeFile(pmPath, origPm, 'utf8');
|
await writeFile(pmPath, origPm, 'utf8');
|
||||||
await writeFile(lcPath, origLc, 'utf8');
|
await writeFile(lcPath, origLc, 'utf8');
|
||||||
|
await writeFile(lvPath, origLv, 'utf8');
|
||||||
await writeFile(dlPath, origDl, 'utf8');
|
await writeFile(dlPath, origDl, 'utf8');
|
||||||
|
|
||||||
const baseData: InMemorySecurityMasterData = {
|
const baseData: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -782,11 +934,13 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
const assertIntact = async () => {
|
const assertIntact = async () => {
|
||||||
expect(await readFile(pmPath, 'utf8')).toBe(origPm);
|
expect(await readFile(pmPath, 'utf8')).toBe(origPm);
|
||||||
expect(await readFile(lcPath, 'utf8')).toBe(origLc);
|
expect(await readFile(lcPath, 'utf8')).toBe(origLc);
|
||||||
|
expect(await readFile(lvPath, 'utf8')).toBe(origLv);
|
||||||
expect(await readFile(dlPath, 'utf8')).toBe(origDl);
|
expect(await readFile(dlPath, 'utf8')).toBe(origDl);
|
||||||
const entries = (await readdir(outDir)).sort();
|
const entries = (await readdir(outDir)).sort();
|
||||||
expect(entries).toEqual([
|
expect(entries).toEqual([
|
||||||
CURATE_INPUT_FILES.delistings,
|
CURATE_INPUT_FILES.delistings,
|
||||||
CURATE_INPUT_FILES.listingCurrencies,
|
CURATE_INPUT_FILES.listingCurrencies,
|
||||||
|
CURATE_INPUT_FILES.listingVenues,
|
||||||
CURATE_INPUT_FILES.providerMapping,
|
CURATE_INPUT_FILES.providerMapping,
|
||||||
]);
|
]);
|
||||||
};
|
};
|
||||||
|
|
@ -798,7 +952,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
);
|
);
|
||||||
await assertIntact();
|
await assertIntact();
|
||||||
|
|
||||||
// 2. Mid-validation failure (tab inside source_id)
|
// 2a. Mid-validation failure (tab inside source_id)
|
||||||
const badDataClient = createInMemoryQueryable({
|
const badDataClient = createInMemoryQueryable({
|
||||||
...baseData,
|
...baseData,
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -813,6 +967,21 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
);
|
);
|
||||||
await assertIntact();
|
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)
|
// 3. Mid-rename failure on the 2nd top-level target symlink replacement (after staging->gen + 1st backup/link + 2nd backup)
|
||||||
let renameCalls = 0;
|
let renameCalls = 0;
|
||||||
const goodClient = createInMemoryQueryable(baseData);
|
const goodClient = createInMemoryQueryable(baseData);
|
||||||
|
|
@ -832,7 +1001,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
).rejects.toThrow('Simulated EIO on 2nd target publish rename');
|
).rejects.toThrow('Simulated EIO on 2nd target publish rename');
|
||||||
await assertIntact();
|
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);
|
const commitFailClient = createInMemoryQueryable(baseData);
|
||||||
await expect(
|
await expect(
|
||||||
exportCurateInputs(commitFailClient, {
|
exportCurateInputs(commitFailClient, {
|
||||||
|
|
@ -854,15 +1023,17 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-');
|
const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-');
|
||||||
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
||||||
const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies);
|
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 dlPath = join(outDir, CURATE_INPUT_FILES.delistings);
|
||||||
|
|
||||||
await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8');
|
await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8');
|
||||||
await writeFile(lcPath, '1\tUSD\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');
|
await writeFile(dlPath, 'OLD\t2023-01-01\t1\t\t-0.3\n', 'utf8');
|
||||||
|
|
||||||
const newData: InMemorySecurityMasterData = {
|
const newData: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
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(pmPath, 'utf8')).toBe('eod\tNEW.TO\t2022-01-01\t\t2\n');
|
||||||
expect(await readFile(lcPath, 'utf8')).toBe('2\tCAD\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('');
|
expect(await readFile(dlPath, 'utf8')).toBe('');
|
||||||
|
|
||||||
// Backup #1 and #3 were deleted; #2 failed and is reported in cleanupWarnings.
|
// Backups #1, #3, #4 were deleted; #2 failed and is reported in cleanupWarnings.
|
||||||
expect(backupUnlinkCalls).toBe(3);
|
expect(backupUnlinkCalls).toBe(4);
|
||||||
expect(result.cleanupWarnings).toHaveLength(1);
|
expect(result.cleanupWarnings).toHaveLength(1);
|
||||||
expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup');
|
expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup');
|
||||||
expect(result.cleanupWarnings[0]).toContain('.bak');
|
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 outDir = await makeTempDir('curate-inputs-restore-fail-');
|
||||||
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
|
||||||
const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies);
|
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 dlPath = join(outDir, CURATE_INPUT_FILES.delistings);
|
||||||
|
|
||||||
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
|
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
|
||||||
const origLc = '1\tUSD\n';
|
const origLc = '1\tUSD\n';
|
||||||
|
const origLv = '1\tus_tsx\n';
|
||||||
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
|
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
|
||||||
await writeFile(pmPath, origPm, 'utf8');
|
await writeFile(pmPath, origPm, 'utf8');
|
||||||
await writeFile(lcPath, origLc, 'utf8');
|
await writeFile(lcPath, origLc, 'utf8');
|
||||||
|
await writeFile(lvPath, origLv, 'utf8');
|
||||||
await writeFile(dlPath, origDl, 'utf8');
|
await writeFile(dlPath, origDl, 'utf8');
|
||||||
|
|
||||||
const newData: InMemorySecurityMasterData = {
|
const newData: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -928,7 +1103,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
outDir,
|
outDir,
|
||||||
fs: {
|
fs: {
|
||||||
rename: async (oldPath, newPath) => {
|
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')) {
|
if (String(newPath) === join(outDir, 'current')) {
|
||||||
throw new Error('Simulated commit EIO');
|
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('Simulated restore EIO');
|
||||||
expect(err.message).toContain('.bak');
|
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(lcPath, 'utf8')).toBe(origLc);
|
||||||
|
expect(await readFile(lvPath, 'utf8')).toBe(origLv);
|
||||||
expect(await readFile(dlPath, 'utf8')).toBe(origDl);
|
expect(await readFile(dlPath, 'utf8')).toBe(origDl);
|
||||||
|
|
||||||
// The unrestored provider_mapping backup MUST still exist on disk with original bytes!
|
// 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).
|
// Generation 1: only SIVB active (no SIVBQ successor yet).
|
||||||
const gen1Data: InMemorySecurityMasterData = {
|
const gen1Data: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -983,8 +1159,8 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
// Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings.
|
// Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings.
|
||||||
const gen2Data: InMemorySecurityMasterData = {
|
const gen2Data: InMemorySecurityMasterData = {
|
||||||
listings: [
|
listings: [
|
||||||
{ listing_id: 4, currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', 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, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
|
{ listing_id: 6, mic: 'OTCM', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
|
||||||
],
|
],
|
||||||
continuities: [
|
continuities: [
|
||||||
{ from_listing_id: 4, to_listing_id: 6, effective_date: '2023-03-28', kind: 'otc_delist_transfer' },
|
{ 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 });
|
const res2 = await exportCurateInputs(createInMemoryQueryable(gen2Data), { outDir });
|
||||||
expect(res2.generationId).not.toBe(res1.generationId);
|
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 consumer1Lc = await readFile(pinned1.listingCurrencies, 'utf8');
|
||||||
|
const consumer1Lv = await readFile(pinned1.listingVenues, 'utf8');
|
||||||
const consumer1Dl = await readFile(pinned1.delistings, 'utf8');
|
const consumer1Dl = await readFile(pinned1.delistings, 'utf8');
|
||||||
expect(consumer1Lc).toBe('4\tUSD\n');
|
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!)
|
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.
|
// 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'
|
'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.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');
|
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 = {
|
const snapA: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -1037,7 +1216,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
};
|
};
|
||||||
const snapB: InMemorySecurityMasterData = {
|
const snapB: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -1053,17 +1232,20 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
const pinned = await pinCurateInputSnapshot(outDir);
|
const pinned = await pinCurateInputSnapshot(outDir);
|
||||||
const pm = await readFile(pinned.providerMapping, 'utf8');
|
const pm = await readFile(pinned.providerMapping, 'utf8');
|
||||||
const lc = await readFile(pinned.listingCurrencies, 'utf8');
|
const lc = await readFile(pinned.listingCurrencies, 'utf8');
|
||||||
|
const lv = await readFile(pinned.listingVenues, 'utf8');
|
||||||
const dl = await readFile(pinned.delistings, 'utf8');
|
const dl = await readFile(pinned.delistings, 'utf8');
|
||||||
|
|
||||||
const isAllA =
|
const isAllA =
|
||||||
pinned.generationId === resA.generationId &&
|
pinned.generationId === resA.generationId &&
|
||||||
pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' &&
|
pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' &&
|
||||||
lc === '10\tUSD\n' &&
|
lc === '10\tUSD\n' &&
|
||||||
|
lv === '10\tus_tsx\n' &&
|
||||||
dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n';
|
dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n';
|
||||||
const isAllB =
|
const isAllB =
|
||||||
pinned.generationId === resB.generationId &&
|
pinned.generationId === resB.generationId &&
|
||||||
pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' &&
|
pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' &&
|
||||||
lc === '20\tCAD\n' &&
|
lc === '20\tCAD\n' &&
|
||||||
|
lv === '20\ttsxv_cse\n' &&
|
||||||
dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n';
|
dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n';
|
||||||
|
|
||||||
expect(isAllA || isAllB).toBe(true);
|
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 () => {
|
test('concurrent fresh-dir exports serialize publish/rollback so a failed export never deletes a committed export top-level links', async () => {
|
||||||
const snapA: InMemorySecurityMasterData = {
|
const snapA: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -1081,7 +1263,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
};
|
};
|
||||||
const snapB: InMemorySecurityMasterData = {
|
const snapB: InMemorySecurityMasterData = {
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -1145,10 +1327,14 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
||||||
'20\tCAD\n'
|
'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(
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(
|
||||||
'SNAP_B\t2024-01-15\t20\t\t-1\n'
|
'SNAP_B\t2024-01-15\t20\t\t-1\n'
|
||||||
);
|
);
|
||||||
const pinned = await pinCurateInputSnapshot(outDir);
|
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');
|
expect(await readFile(pinned.delistings, 'utf8')).toBe('SNAP_B\t2024-01-15\t20\t\t-1\n');
|
||||||
const entries = await readdir(outDir);
|
const entries = await readdir(outDir);
|
||||||
expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false);
|
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(
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
||||||
'20\tCAD\n'
|
'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(
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(
|
||||||
'SNAP_B\t2024-01-15\t20\t\t-1\n'
|
'SNAP_B\t2024-01-15\t20\t\t-1\n'
|
||||||
);
|
);
|
||||||
const pinned = await pinCurateInputSnapshot(outDir);
|
const pinned = await pinCurateInputSnapshot(outDir);
|
||||||
|
expect(await readFile(pinned.listingVenues, 'utf8')).toBe('20\ttsxv_cse\n');
|
||||||
expect(await readFile(pinned.providerMapping, 'utf8')).toBe(
|
expect(await readFile(pinned.providerMapping, 'utf8')).toBe(
|
||||||
'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n'
|
'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n'
|
||||||
);
|
);
|
||||||
|
|
@ -1258,6 +1448,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
listings: [
|
listings: [
|
||||||
{
|
{
|
||||||
listing_id: 1,
|
listing_id: 1,
|
||||||
|
mic: 'XNAS',
|
||||||
currency: 'USD',
|
currency: 'USD',
|
||||||
listed_to: null,
|
listed_to: null,
|
||||||
delist_reason: 'active',
|
delist_reason: 'active',
|
||||||
|
|
@ -1343,6 +1534,63 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
||||||
'chunkSize'
|
'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', () => {
|
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.
|
// 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 outDir = await makeTempDir('curate-inputs-golden-');
|
||||||
const queryable = createInMemoryQueryable({
|
const queryable = createInMemoryQueryable({
|
||||||
listings: dataset.delistingListings.map((l, idx) => ({
|
listings: dataset.delistingListings.map((l, idx) => ({
|
||||||
listing_id: l.listingId,
|
listing_id: l.listingId,
|
||||||
|
mic: goldenMics[idx]!,
|
||||||
currency: dataset.listings[idx]!.currency,
|
currency: dataset.listings[idx]!.currency,
|
||||||
listed_to: l.listedTo,
|
listed_to: l.listedTo,
|
||||||
delist_reason: l.delistReason,
|
delist_reason: l.delistReason,
|
||||||
|
|
@ -1400,8 +1656,15 @@ describe('golden fixtures cross-language parity', () => {
|
||||||
const result = await exportCurateInputs(queryable, { outDir, chunkSize: 2 });
|
const result = await exportCurateInputs(queryable, { outDir, chunkSize: 2 });
|
||||||
expect(await readFile(result.providerMapping.path, 'utf8')).toBe(expectedPm);
|
expect(await readFile(result.providerMapping.path, 'utf8')).toBe(expectedPm);
|
||||||
expect(await readFile(result.listingCurrencies.path, 'utf8')).toBe(expectedLc);
|
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(await readFile(result.delistings.path, 'utf8')).toBe(expectedDl);
|
||||||
expect(result.delistings.stats).toEqual(builtDelistings.stats);
|
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({
|
const queryable = createInMemoryQueryable({
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -1514,6 +1777,7 @@ describe('CLI args, safety guard, and runner', () => {
|
||||||
expect(output.summary).toBe(formatExportCurateInputsSummary(output.result));
|
expect(output.summary).toBe(formatExportCurateInputsSummary(output.result));
|
||||||
expect(stdoutText).toContain('provider_mapping.tsv: rows_in=1 rows_out=1');
|
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_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');
|
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({
|
const queryable = createInMemoryQueryable({
|
||||||
listings: [
|
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: [],
|
continuities: [],
|
||||||
providerMappings: [
|
providerMappings: [
|
||||||
|
|
@ -1586,6 +1850,9 @@ describe('CLI args, safety guard, and runner', () => {
|
||||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(
|
||||||
'qm\tAAPL\t2020-01-01\t\t1\n'
|
'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!
|
// Still rejects dev -> QA PostgreSQL even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true!
|
||||||
resetStockConfig();
|
resetStockConfig();
|
||||||
|
|
|
||||||
386
test/unit/security-master-export-listing-venues-qa.test.ts
Normal file
386
test/unit/security-master-export-listing-venues-qa.test.ts
Normal file
|
|
@ -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<string> {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), prefix));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ListingRow {
|
||||||
|
readonly listing_id: number;
|
||||||
|
readonly mic: string | null;
|
||||||
|
readonly currency: string | null;
|
||||||
|
readonly listed_to: string | null;
|
||||||
|
readonly delist_reason: string | null;
|
||||||
|
readonly terminal_return: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal in-memory stand-in for the read-only PostgreSQL snapshot: empty provider_mapping and
|
||||||
|
* continuity tables, keyset-paginated listing table. Records every SQL statement.
|
||||||
|
*/
|
||||||
|
function createListingOnlyQueryable(
|
||||||
|
listings: readonly ListingRow[],
|
||||||
|
recordedSql: string[] = []
|
||||||
|
): SecurityMasterQueryable {
|
||||||
|
const sorted = [...listings].sort((a, b) => a.listing_id - b.listing_id);
|
||||||
|
return {
|
||||||
|
async query<Row = Record<string, unknown>>(
|
||||||
|
text: string,
|
||||||
|
values?: readonly unknown[]
|
||||||
|
): Promise<SecurityMasterQueryResult<Row>> {
|
||||||
|
const normalized = text.replace(/\s+/g, ' ').trim();
|
||||||
|
recordedSql.push(normalized);
|
||||||
|
if (
|
||||||
|
normalized.startsWith('BEGIN') ||
|
||||||
|
normalized === 'COMMIT' ||
|
||||||
|
normalized === 'ROLLBACK' ||
|
||||||
|
normalized.startsWith('DECLARE ') ||
|
||||||
|
/^CLOSE \S+$/i.test(normalized) ||
|
||||||
|
/^FETCH FORWARD \d+ FROM \S+$/i.test(normalized)
|
||||||
|
) {
|
||||||
|
return { rows: [] };
|
||||||
|
}
|
||||||
|
if (normalized.includes('FROM corporate_action_continuity')) {
|
||||||
|
return { rows: [] };
|
||||||
|
}
|
||||||
|
if (normalized.includes('FROM provider_mapping')) {
|
||||||
|
return { rows: [] };
|
||||||
|
}
|
||||||
|
if (normalized.includes('FROM listing')) {
|
||||||
|
if (values && values.length === 1) {
|
||||||
|
return { rows: sorted.slice(0, values[0] as number) as unknown as Row[] };
|
||||||
|
}
|
||||||
|
const [lastId, limit] = values as [number, number];
|
||||||
|
return {
|
||||||
|
rows: sorted.filter(l => l.listing_id > lastId).slice(0, limit) as unknown as Row[],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected SQL in listing-only queryable: ${normalized}`);
|
||||||
|
},
|
||||||
|
release: () => {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function activeListing(listingId: number, mic: string | null, currency = 'USD'): ListingRow {
|
||||||
|
return {
|
||||||
|
listing_id: listingId,
|
||||||
|
mic,
|
||||||
|
currency,
|
||||||
|
listed_to: null,
|
||||||
|
delist_reason: 'active',
|
||||||
|
terminal_return: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** mulberry32 — deterministic seeded PRNG. */
|
||||||
|
function mulberry32(seed: number): () => number {
|
||||||
|
let a = seed >>> 0;
|
||||||
|
return () => {
|
||||||
|
a = (a + 0x6d2b79f5) >>> 0;
|
||||||
|
let t = a;
|
||||||
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||||
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||||
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TS port of Rust `parse_strict_positive_i32` (run_curate_bars.rs). */
|
||||||
|
function parseStrictPositiveI32(raw: string): number | null {
|
||||||
|
if (raw.length === 0 || !/^[0-9]+$/.test(raw)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const val = Number(raw);
|
||||||
|
if (!Number.isSafeInteger(val) || val > 2_147_483_647 || val <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TS port of Rust `load_listing_venues_tsv` + `read_tsv_lines`: strict headerless 2-column TSV,
|
||||||
|
* at most one trailing blank line, strictly positive i32 listing_id, `us_tsx|tsxv_cse`, no dups.
|
||||||
|
* Additionally asserts the stricter exporter contract (LF only, ascending listing_id).
|
||||||
|
*/
|
||||||
|
function loadListingVenuesTsvStrict(text: string): Map<number, ListingStatutoryLagVenue> {
|
||||||
|
const venues = new Map<number, ListingStatutoryLagVenue>();
|
||||||
|
if (text.length === 0) {
|
||||||
|
return venues;
|
||||||
|
}
|
||||||
|
if (text.includes('\r')) {
|
||||||
|
throw new Error('exporter must emit LF-only line endings');
|
||||||
|
}
|
||||||
|
if (!text.endsWith('\n')) {
|
||||||
|
throw new Error('exporter must terminate the last line with LF');
|
||||||
|
}
|
||||||
|
const lines = text.slice(0, -1).split('\n');
|
||||||
|
let prev = 0;
|
||||||
|
for (const [i, line] of lines.entries()) {
|
||||||
|
if (line.length === 0) {
|
||||||
|
throw new Error(`line ${i + 1}: interior blank line`);
|
||||||
|
}
|
||||||
|
const cols = line.split('\t');
|
||||||
|
if (cols.length !== 2) {
|
||||||
|
throw new Error(`line ${i + 1}: expected 2 tab-separated columns, got ${cols.length}`);
|
||||||
|
}
|
||||||
|
const id = parseStrictPositiveI32(cols[0]!);
|
||||||
|
if (id === null) {
|
||||||
|
throw new Error(`line ${i + 1}: invalid listing_id '${cols[0]}'`);
|
||||||
|
}
|
||||||
|
const venue = cols[1];
|
||||||
|
if (venue !== 'us_tsx' && venue !== 'tsxv_cse') {
|
||||||
|
throw new Error(`line ${i + 1}: unknown venue '${venue}'`);
|
||||||
|
}
|
||||||
|
if (venues.has(id)) {
|
||||||
|
throw new Error(`line ${i + 1}: duplicate listing_id ${id}`);
|
||||||
|
}
|
||||||
|
if (id <= prev) {
|
||||||
|
throw new Error(`line ${i + 1}: listing_id ${id} not strictly ascending after ${prev}`);
|
||||||
|
}
|
||||||
|
prev = id;
|
||||||
|
venues.set(id, venue);
|
||||||
|
}
|
||||||
|
return venues;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRandomListings(seed: number, count: number): ListingRow[] {
|
||||||
|
const rand = mulberry32(seed);
|
||||||
|
const mics = ISO_EXCHANGE_SEEDS.map(e => e.mic);
|
||||||
|
const usedIds = new Set<number>();
|
||||||
|
const rows: ListingRow[] = [];
|
||||||
|
while (rows.length < count) {
|
||||||
|
// Sparse ids (gaps) up to i32 max to exercise keyset pagination on non-contiguous keys.
|
||||||
|
const id = 1 + Math.floor(rand() * 2_147_483_646);
|
||||||
|
if (usedIds.has(id)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
usedIds.add(id);
|
||||||
|
const mic = mics[Math.floor(rand() * mics.length)]!;
|
||||||
|
rows.push(activeListing(id, mic, rand() < 0.5 ? 'CAD' : 'USD'));
|
||||||
|
}
|
||||||
|
// Shuffle insertion order so only the DB ORDER BY can produce sorted output.
|
||||||
|
for (let i = rows.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(rand() * (i + 1));
|
||||||
|
[rows[i], rows[j]] = [rows[j]!, rows[i]!];
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('listing_venues.tsv QA: streaming parity and Rust loader compliance', () => {
|
||||||
|
for (const seed of [7, 2026, 31337]) {
|
||||||
|
test(`seed ${seed}: streamed listing_venues.tsv is byte-identical to the pure formatter across chunk sizes and joins 1:1 with listing_currencies.tsv`, async () => {
|
||||||
|
// Arrange
|
||||||
|
const listings = buildRandomListings(seed, 257);
|
||||||
|
const expected = formatListingVenuesTsv(
|
||||||
|
listings.map(l => ({ listingId: l.listing_id, venue: LISTING_VENUE_BY_MIC[l.mic!]! }))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act / Assert
|
||||||
|
for (const chunkSize of [1, 16, 256, 257, 258, 5000]) {
|
||||||
|
const outDir = await makeTempDir(`curate-venues-parity-${seed}-${chunkSize}-`);
|
||||||
|
const res = await exportCurateInputs(createListingOnlyQueryable(listings), {
|
||||||
|
outDir,
|
||||||
|
chunkSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
const venuesText = await readFile(res.listingVenues.path, 'utf8');
|
||||||
|
const currenciesText = await readFile(res.listingCurrencies.path, 'utf8');
|
||||||
|
expect(venuesText).toBe(expected);
|
||||||
|
expect(res.listingVenues.rowsIn).toBe(257);
|
||||||
|
expect(res.listingVenues.rowsOut).toBe(257);
|
||||||
|
expect(res.listingVenues.bytesWritten).toBe(Buffer.byteLength(expected, 'utf8'));
|
||||||
|
expect(res.totalBytesWritten).toBe(
|
||||||
|
res.providerMapping.bytesWritten +
|
||||||
|
res.listingCurrencies.bytesWritten +
|
||||||
|
res.listingVenues.bytesWritten +
|
||||||
|
res.delistings.bytesWritten
|
||||||
|
);
|
||||||
|
|
||||||
|
const venues = loadListingVenuesTsvStrict(venuesText);
|
||||||
|
const currencyIds = currenciesText
|
||||||
|
.slice(0, -1)
|
||||||
|
.split('\n')
|
||||||
|
.map(line => Number(line.split('\t')[0]));
|
||||||
|
expect([...venues.keys()]).toEqual(currencyIds);
|
||||||
|
|
||||||
|
const micById = new Map(listings.map(l => [l.listing_id, l.mic!]));
|
||||||
|
for (const [id, venue] of venues) {
|
||||||
|
const mic = micById.get(id)!;
|
||||||
|
expect(venue).toBe(mic === 'XTSX' || mic === 'XCNQ' ? 'tsxv_cse' : 'us_tsx');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('empty listing table publishes a 0-byte listing_venues.tsv that the Rust loader accepts as an empty map', async () => {
|
||||||
|
// Arrange
|
||||||
|
const outDir = await makeTempDir('curate-venues-empty-');
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const res = await exportCurateInputs(createListingOnlyQueryable([]), { outDir });
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
const text = await readFile(res.listingVenues.path, 'utf8');
|
||||||
|
expect(text).toBe('');
|
||||||
|
expect(res.listingVenues).toMatchObject({ rowsIn: 0, rowsOut: 0, bytesWritten: 0 });
|
||||||
|
expect(loadListingVenuesTsvStrict(text).size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('i32-max listing_id is exported verbatim and parses under the Rust strict positive i32 rule', async () => {
|
||||||
|
// Arrange
|
||||||
|
const outDir = await makeTempDir('curate-venues-i32max-');
|
||||||
|
const listings = [activeListing(2_147_483_647, 'XCNQ', 'CAD'), activeListing(1, 'XTSE', 'CAD')];
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const res = await exportCurateInputs(createListingOnlyQueryable(listings), {
|
||||||
|
outDir,
|
||||||
|
chunkSize: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
const text = await readFile(res.listingVenues.path, 'utf8');
|
||||||
|
expect(text).toBe('1\tus_tsx\n2147483647\ttsxv_cse\n');
|
||||||
|
expect([...loadListingVenuesTsvStrict(text)]).toEqual([
|
||||||
|
[1, 'us_tsx'],
|
||||||
|
[2147483647, 'tsxv_cse'],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('top-level listing_venues.tsv resolves through current/ to the same generation pinned by pinCurateInputSnapshot, and only read-only SQL is issued', async () => {
|
||||||
|
// Arrange
|
||||||
|
const outDir = await makeTempDir('curate-venues-layout-');
|
||||||
|
const sql: string[] = [];
|
||||||
|
const listings = [activeListing(10, 'XTSX', 'CAD'), activeListing(20, 'XNYS')];
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const res = await exportCurateInputs(createListingOnlyQueryable(listings, sql), { outDir });
|
||||||
|
const pinned = await pinCurateInputSnapshot(outDir);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
const topLevel = join(outDir, CURATE_INPUT_FILES.listingVenues);
|
||||||
|
expect(await readlink(topLevel)).toBe(
|
||||||
|
join(CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES.listingVenues)
|
||||||
|
);
|
||||||
|
expect(await realpath(topLevel)).toBe(await realpath(res.listingVenues.path));
|
||||||
|
expect(pinned.listingVenues).toBe(res.listingVenues.path);
|
||||||
|
expect(pinned.generationDir).toBe(
|
||||||
|
await realpath(join(outDir, CURATE_INPUT_GENERATIONS_DIR, res.generationId))
|
||||||
|
);
|
||||||
|
expect(await readFile(topLevel, 'utf8')).toBe('10\ttsxv_cse\n20\tus_tsx\n');
|
||||||
|
|
||||||
|
expect(sql[0]).toMatch(/^BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY/i);
|
||||||
|
for (const stmt of sql) {
|
||||||
|
expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT)\b/i);
|
||||||
|
}
|
||||||
|
expect(sql.filter(s => s.includes('FROM listing')).every(s => /\bmic\b/.test(s))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('listing_venues.tsv QA: fail-closed MIC values from PostgreSQL', () => {
|
||||||
|
const badMics: ReadonlyArray<{ readonly mic: string | null; readonly code: string }> = [
|
||||||
|
{ mic: null, code: 'BLANK_FIELD' },
|
||||||
|
{ mic: '', code: 'BLANK_FIELD' },
|
||||||
|
{ mic: ' ', code: 'BLANK_FIELD' },
|
||||||
|
{ mic: ' XTSX', code: 'UNKNOWN_LISTING_MIC' },
|
||||||
|
{ mic: 'xtsx', code: 'UNKNOWN_LISTING_MIC' },
|
||||||
|
{ mic: 'XLON', code: 'UNKNOWN_LISTING_MIC' },
|
||||||
|
{ mic: 'hasOwnProperty', code: 'UNKNOWN_LISTING_MIC' },
|
||||||
|
{ mic: 'XT\tSX', code: 'FORBIDDEN_CONTROL_CHAR' },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const { mic, code } of badMics) {
|
||||||
|
test(`mic=${JSON.stringify(mic)} on a later page aborts with ${code} and leaves the previous 4-file generation byte-identical`, async () => {
|
||||||
|
// Arrange: publish a good generation first.
|
||||||
|
const outDir = await makeTempDir('curate-venues-badmic-');
|
||||||
|
const good = [activeListing(1, 'XTSE', 'CAD'), activeListing(2, 'XNAS')];
|
||||||
|
const first = await exportCurateInputs(createListingOnlyQueryable(good), { outDir });
|
||||||
|
const before = {
|
||||||
|
venues: await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8'),
|
||||||
|
currencies: await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8'),
|
||||||
|
generations: (await readdir(join(outDir, CURATE_INPUT_GENERATIONS_DIR))).sort(),
|
||||||
|
entries: (await readdir(outDir)).sort(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Act: the bad row sits on the 3rd chunk (chunkSize=1) after good rows were already staged.
|
||||||
|
const bad = [...good, activeListing(3, mic)];
|
||||||
|
let caught: unknown;
|
||||||
|
try {
|
||||||
|
await exportCurateInputs(createListingOnlyQueryable(bad), { outDir, chunkSize: 1 });
|
||||||
|
} catch (error) {
|
||||||
|
caught = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
expect(caught).toBeInstanceOf(CurateInputExportError);
|
||||||
|
expect((caught as CurateInputExportError).code).toBe(code as CurateInputExportError['code']);
|
||||||
|
expect((caught as CurateInputExportError).key).toContain('listing_id=3');
|
||||||
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(
|
||||||
|
before.venues
|
||||||
|
);
|
||||||
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
||||||
|
before.currencies
|
||||||
|
);
|
||||||
|
expect((await readdir(join(outDir, CURATE_INPUT_GENERATIONS_DIR))).sort()).toEqual(
|
||||||
|
before.generations
|
||||||
|
);
|
||||||
|
expect((await readdir(outDir)).sort()).toEqual(before.entries);
|
||||||
|
expect((await pinCurateInputSnapshot(outDir)).generationId).toBe(first.generationId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a pre-existing regular listing_venues.tsv (pre-generation layout) survives a failed export untouched', async () => {
|
||||||
|
// Arrange
|
||||||
|
const outDir = await makeTempDir('curate-venues-legacy-file-');
|
||||||
|
const legacy = '5\tus_tsx\n';
|
||||||
|
await writeFile(join(outDir, CURATE_INPUT_FILES.listingVenues), legacy, 'utf8');
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await expect(
|
||||||
|
exportCurateInputs(createListingOnlyQueryable([activeListing(1, 'XLON')]), { outDir })
|
||||||
|
).rejects.toMatchObject({ code: 'UNKNOWN_LISTING_MIC' });
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(legacy);
|
||||||
|
const leftovers = (await readdir(outDir)).filter(
|
||||||
|
e => e.endsWith('.tmp') || e.endsWith('.bak') || e === '.publish.lock'
|
||||||
|
);
|
||||||
|
expect(leftovers).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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.
|
- **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<str>` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope.
|
- **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc<str>` 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 `<out>/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 `<out>/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
|
### 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 \
|
curate-etl curate-posts \
|
||||||
--ceo-posts ceoPosts.bson \
|
--ceo-posts ceoPosts.bson \
|
||||||
--provider-mapping provider_mapping.tsv \
|
--provider-mapping provider_mapping.tsv \
|
||||||
--out ./out-posts \
|
--out ./out \
|
||||||
--timestamp-unit seconds
|
--timestamp-unit seconds
|
||||||
```
|
```
|
||||||
|
|
||||||
Inputs, defaults, and output rules:
|
Inputs, defaults, and output rules:
|
||||||
- `--ceo-posts <path>` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`).
|
- `--ceo-posts <path>` *(required)*: concatenated raw BSON (`mongodump` `ceoPosts.bson`).
|
||||||
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
|
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
|
||||||
- `--out <dir>` *(required, dedicated output directory)*: dataset root where `<out>/events/year=YYYY/part.parquet` is atomically published. Because `curate-events` (filings + earnings) writes to the same `<out>/events` directory layout, `curate-posts` requires a dedicated `--out` directory and fails closed before any write if `<out>/events` already contains any `year=*` entry (leaving existing partitions byte-identical).
|
- `--out <dir>` *(required)*: dataset root where `<out>/events/year=YYYY/part-posts.parquet` (`kind = "ceo_post"`) is atomically published. Co-publishes cleanly alongside `curate-events` (`<out>/events/year=YYYY/part.parquet`) under the shared `<out>/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 `<out>/events` being a regular file, `..` after a missing component, or any input path overlapping `--out`, `<out>/events/...`, or a target `events/year=YYYY/part-posts.parquet`.
|
||||||
- `--timestamp-unit <seconds|millis>` *(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.
|
- `--timestamp-unit <seconds|millis>` *(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`):
|
- Optional field-name overrides (defaults from `src/bson_ceo_posts.rs` / `get-posts.action.ts`):
|
||||||
- `--key-field` (default `ceoId`)
|
- `--key-field` (default `ceoId`)
|
||||||
|
|
|
||||||
808
tools/curate-etl/src/bars_1m_sort.rs
Normal file
808
tools/curate-etl/src/bars_1m_sort.rs
Normal file
|
|
@ -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
|
||||||
|
//! (`.<prefix>.sort-run-<run_id>-<seq>.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<listing_id>` (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<PathBuf>,
|
||||||
|
/// 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<PathBuf>, 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<File>,
|
||||||
|
remaining: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunReader {
|
||||||
|
fn open(run: &SpilledRun) -> Result<Self, Bars1mExternalSortError> {
|
||||||
|
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<Option<CompactBar1mRecord>, 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<Ordering> {
|
||||||
|
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<i32>, b: &Bar1mRow<i32>) -> 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<SpilledRun, Bars1mExternalSortError> {
|
||||||
|
let mut readers = Vec::with_capacity(runs.len());
|
||||||
|
let mut heap: BinaryHeap<Reverse<HeapEntry>> = 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<bool>,
|
||||||
|
last_listing_id: Option<i32>,
|
||||||
|
current_group_key: Option<(u8, i32, i64)>,
|
||||||
|
current_group: Vec<CompactBar1mRecord>,
|
||||||
|
listing_survivors: Vec<Bar1mRow<i32>>,
|
||||||
|
listing_splits: Option<&'a SplitTable<i32>>,
|
||||||
|
source: &'static str,
|
||||||
|
known_at_micros: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> GroupMerger<'a> {
|
||||||
|
fn new(
|
||||||
|
builder_stats: Bars1mStats,
|
||||||
|
num_keys: usize,
|
||||||
|
listing_splits: Option<&'a SplitTable<i32>>,
|
||||||
|
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<W: Write + Send>(
|
||||||
|
&mut self,
|
||||||
|
record: CompactBar1mRecord,
|
||||||
|
writer: &mut IlpShardedWriter<W>,
|
||||||
|
) -> 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<W: Write + Send>(
|
||||||
|
&mut self,
|
||||||
|
writer: &mut IlpShardedWriter<W>,
|
||||||
|
) -> 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<W: Write + Send>(
|
||||||
|
mut self,
|
||||||
|
writer: &mut IlpShardedWriter<W>,
|
||||||
|
) -> Result<CurateBars1mWriteReport, Bars1mExternalSortError> {
|
||||||
|
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<String, u32>,
|
||||||
|
buffer: Vec<CompactBar1mRecord>,
|
||||||
|
runs: Vec<SpilledRun>,
|
||||||
|
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<W: Write + Send>(
|
||||||
|
mut self,
|
||||||
|
listing_splits: Option<&SplitTable<i32>>,
|
||||||
|
source: &'static str,
|
||||||
|
writer: &mut IlpShardedWriter<W>,
|
||||||
|
known_at_micros: i64,
|
||||||
|
) -> Result<ExternalSortWriteOutcome, Bars1mExternalSortError> {
|
||||||
|
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<SpilledRun> = 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<Reverse<HeapEntry>> = 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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -492,6 +492,7 @@ where
|
||||||
/// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022
|
/// 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
|
/// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation
|
||||||
/// invariants and cross-`source_id` collision handling.
|
/// invariants and cross-`source_id` collision handling.
|
||||||
|
#[cfg(test)]
|
||||||
pub(crate) fn curate_and_write_bars_1m_by_listing<W, K, B>(
|
pub(crate) fn curate_and_write_bars_1m_by_listing<W, K, B>(
|
||||||
bars: B,
|
bars: B,
|
||||||
listing_splits: &SplitTable<i32>,
|
listing_splits: &SplitTable<i32>,
|
||||||
|
|
|
||||||
|
|
@ -32,8 +32,8 @@ use std::path::Path;
|
||||||
|
|
||||||
use crate::events::{parse_filing_timefiled, QmFiling};
|
use crate::events::{parse_filing_timefiled, QmFiling};
|
||||||
use crate::fundamentals::{
|
use crate::fundamentals::{
|
||||||
build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FundamentalsError,
|
build_fundamentals_rows_with_legacy, build_fundamentals_snapshots, FinancialObservation,
|
||||||
FundamentalsStats, StatutoryLagVenue,
|
FundamentalsError, FundamentalsStats, StatutoryLagVenue,
|
||||||
};
|
};
|
||||||
use crate::parquet_fundamentals::{
|
use crate::parquet_fundamentals::{
|
||||||
write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions,
|
write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions,
|
||||||
|
|
@ -172,6 +172,39 @@ where
|
||||||
K: AsRef<str>,
|
K: AsRef<str>,
|
||||||
IO: IntoIterator<Item = FinancialObservation<K>>,
|
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
IF: IntoIterator<Item = QmFiling<K>>,
|
IF: IntoIterator<Item = QmFiling<K>>,
|
||||||
|
{
|
||||||
|
curate_fundamentals_with_legacy(
|
||||||
|
observations,
|
||||||
|
std::iter::empty::<FinancialObservation<K>>(),
|
||||||
|
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<K, IO, ILO, IF>(
|
||||||
|
primary_observations: IO,
|
||||||
|
legacy_observations: ILO,
|
||||||
|
filings: IF,
|
||||||
|
mapping_source: &str,
|
||||||
|
mapping: &ProviderMappingTable,
|
||||||
|
venues: &BTreeMap<i32, StatutoryLagVenue>,
|
||||||
|
k: usize,
|
||||||
|
) -> Result<CurateFundamentalsOutput, CurateFundamentalsError>
|
||||||
|
where
|
||||||
|
K: AsRef<str>,
|
||||||
|
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
|
ILO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
|
IF: IntoIterator<Item = QmFiling<K>>,
|
||||||
{
|
{
|
||||||
if mapping_source.trim().is_empty() {
|
if mapping_source.trim().is_empty() {
|
||||||
return Err(CurateFundamentalsError::EmptyMappingSource);
|
return Err(CurateFundamentalsError::EmptyMappingSource);
|
||||||
|
|
@ -180,22 +213,42 @@ where
|
||||||
return Err(FundamentalsError::InvalidPeriodLimit { k }.into());
|
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 filings_iter = filings.into_iter();
|
||||||
|
|
||||||
let mut stats = CurateFundamentalsStats::default();
|
let mut stats = CurateFundamentalsStats::default();
|
||||||
let mut mapped_observations: Vec<FinancialObservation<i32>> =
|
let mut mapped_primary: Vec<FinancialObservation<i32>> =
|
||||||
Vec::with_capacity(obs_iter.size_hint().0);
|
Vec::with_capacity(primary_iter.size_hint().0);
|
||||||
|
let mut mapped_legacy: Vec<FinancialObservation<i32>> =
|
||||||
|
Vec::with_capacity(legacy_iter.size_hint().0);
|
||||||
let mut mapped_filings: Vec<QmFiling<i32>> = Vec::with_capacity(filings_iter.size_hint().0);
|
let mut mapped_filings: Vec<QmFiling<i32>> = Vec::with_capacity(filings_iter.size_hint().0);
|
||||||
|
|
||||||
for obs in obs_iter {
|
for obs in primary_iter {
|
||||||
stats.observations_in += 1;
|
stats.observations_in += 1;
|
||||||
let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end)
|
let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end)
|
||||||
else {
|
else {
|
||||||
stats.observations_dropped_unmapped += 1;
|
stats.observations_dropped_unmapped += 1;
|
||||||
continue;
|
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,
|
key: listing_id,
|
||||||
period_end: obs.period_end,
|
period_end: obs.period_end,
|
||||||
fiscal_period: obs.fiscal_period,
|
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;
|
stats.build = built.stats;
|
||||||
|
|
||||||
let snapshots = build_fundamentals_snapshots(&built.rows, k)?;
|
let snapshots = build_fundamentals_snapshots(&built.rows, k)?;
|
||||||
|
|
@ -269,7 +323,50 @@ where
|
||||||
IO: IntoIterator<Item = FinancialObservation<K>>,
|
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
IF: IntoIterator<Item = QmFiling<K>>,
|
IF: IntoIterator<Item = QmFiling<K>>,
|
||||||
{
|
{
|
||||||
let curated = curate_fundamentals(observations, filings, mapping_source, mapping, venues, k)?;
|
curate_and_write_fundamentals_with_legacy(
|
||||||
|
out_dir,
|
||||||
|
observations,
|
||||||
|
std::iter::empty::<FinancialObservation<K>>(),
|
||||||
|
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
|
||||||
|
/// `<out_dir>/fundamentals_pit/year=YYYY/part.parquet`.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn curate_and_write_fundamentals_with_legacy<P, K, IO, ILO, IF>(
|
||||||
|
out_dir: P,
|
||||||
|
primary_observations: IO,
|
||||||
|
legacy_observations: ILO,
|
||||||
|
filings: IF,
|
||||||
|
mapping_source: &str,
|
||||||
|
mapping: &ProviderMappingTable,
|
||||||
|
venues: &BTreeMap<i32, StatutoryLagVenue>,
|
||||||
|
k: usize,
|
||||||
|
options: FundamentalsPitWriteOptions,
|
||||||
|
) -> Result<CurateFundamentalsWriteReport, CurateFundamentalsWriteError>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
K: AsRef<str>,
|
||||||
|
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
|
ILO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
|
IF: IntoIterator<Item = QmFiling<K>>,
|
||||||
|
{
|
||||||
|
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)?;
|
let write_stats = write_fundamentals_pit_dataset(out_dir, &curated.rows, options)?;
|
||||||
Ok(CurateFundamentalsWriteReport {
|
Ok(CurateFundamentalsWriteReport {
|
||||||
curate_stats: curated.stats,
|
curate_stats: curated.stats,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
//! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`],
|
//! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`],
|
||||||
//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::parquet_posts`], and
|
//! [`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
|
//! # Contract & Point-in-Time Rules
|
||||||
//! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication,
|
//! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication,
|
||||||
|
|
@ -32,7 +32,7 @@ use std::fmt;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use crate::parquet_events::{
|
use crate::parquet_events::{
|
||||||
write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
|
write_posts_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
|
||||||
ParquetEventsError,
|
ParquetEventsError,
|
||||||
};
|
};
|
||||||
use crate::parquet_posts::{POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL};
|
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
|
/// Thin end-to-end wrapper running [`curate_posts`] and publishing the resulting contract rows
|
||||||
/// via [`write_events_dataset`] to `<out_dir>/events/year=YYYY/part.parquet`.
|
/// via [`write_posts_events_dataset`] to `<out_dir>/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.
|
/// `out_dir` untouched.
|
||||||
pub fn curate_and_write_posts<P, K, I>(
|
pub fn curate_and_write_posts<P, K, I>(
|
||||||
out_dir: P,
|
out_dir: P,
|
||||||
|
|
@ -288,7 +288,7 @@ where
|
||||||
I: IntoIterator<Item = CeoPost<K>>,
|
I: IntoIterator<Item = CeoPost<K>>,
|
||||||
{
|
{
|
||||||
let curated = curate_posts(posts, mapping_source, mapping)?;
|
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 {
|
Ok(CuratePostsWriteReport {
|
||||||
curate_stats: curated.stats,
|
curate_stats: curated.stats,
|
||||||
write_stats,
|
write_stats,
|
||||||
|
|
|
||||||
|
|
@ -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(&2024), Some(&2));
|
||||||
assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&1));
|
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_2024 = dir.path().join("events/year=2024/part-posts.parquet");
|
||||||
let path_2025 = dir.path().join("events/year=2025/part.parquet");
|
let path_2025 = dir.path().join("events/year=2025/part-posts.parquet");
|
||||||
assert!(path_2024.exists());
|
assert!(path_2024.exists());
|
||||||
assert!(path_2025.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.source().is_some());
|
||||||
assert!(err.to_string().contains("posts Parquet write failed"));
|
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]
|
#[test]
|
||||||
|
|
@ -1376,8 +1376,9 @@ fn same_listing_same_timestamp_tie_breaks_on_subtype_then_payload_and_round_trip
|
||||||
.expect("write");
|
.expect("write");
|
||||||
assert_eq!(report.curate_stats, pure.stats);
|
assert_eq!(report.curate_stats, pure.stats);
|
||||||
assert_eq!(report.write_stats.rows_written, 4);
|
assert_eq!(report.write_stats.rows_written, 4);
|
||||||
let read =
|
let read = read_events_parquet_and_verify_zstd(
|
||||||
read_events_parquet_and_verify_zstd(&dir.path().join("events/year=2024/part.parquet"));
|
&dir.path().join("events/year=2024/part-posts.parquet"),
|
||||||
|
);
|
||||||
assert_eq!(read, pure.rows);
|
assert_eq!(read, pure.rows);
|
||||||
assert_strictly_ascending_by_tuple(&read);
|
assert_strictly_ascending_by_tuple(&read);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -75,7 +75,7 @@
|
||||||
|
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
|
@ -408,6 +408,7 @@ struct EligibleObservation<K> {
|
||||||
report_date: Option<i32>,
|
report_date: Option<i32>,
|
||||||
venue: StatutoryLagVenue,
|
venue: StatutoryLagVenue,
|
||||||
fields: FundamentalsFields,
|
fields: FundamentalsFields,
|
||||||
|
is_legacy: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
|
@ -428,6 +429,7 @@ struct ParsedPeriodicFiling<K> {
|
||||||
struct CandidateRow<K> {
|
struct CandidateRow<K> {
|
||||||
row: FundamentalsRow<K>,
|
row: FundamentalsRow<K>,
|
||||||
report_date: Option<i32>,
|
report_date: Option<i32>,
|
||||||
|
is_legacy: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic
|
/// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic
|
||||||
|
|
@ -444,12 +446,65 @@ where
|
||||||
IO: IntoIterator<Item = FinancialObservation<K>>,
|
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
IF: IntoIterator<Item = QmFiling<K>>,
|
IF: IntoIterator<Item = QmFiling<K>>,
|
||||||
{
|
{
|
||||||
let obs_iter = observations.into_iter();
|
build_fundamentals_rows_with_legacy(
|
||||||
let mut stats = FundamentalsStats::default();
|
observations,
|
||||||
let mut eligible_obs: Vec<EligibleObservation<K>> = Vec::with_capacity(obs_iter.size_hint().0);
|
std::iter::empty::<FinancialObservation<K>>(),
|
||||||
let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new();
|
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<K, IO, ILO, IF>(
|
||||||
|
primary_observations: IO,
|
||||||
|
legacy_observations: ILO,
|
||||||
|
filings: IF,
|
||||||
|
venues: &BTreeMap<K, StatutoryLagVenue>,
|
||||||
|
) -> FundamentalsBuild<K>
|
||||||
|
where
|
||||||
|
K: Ord + Clone,
|
||||||
|
IO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
|
ILO: IntoIterator<Item = FinancialObservation<K>>,
|
||||||
|
IF: IntoIterator<Item = QmFiling<K>>,
|
||||||
|
{
|
||||||
|
let primary_iter = primary_observations.into_iter();
|
||||||
|
let legacy_iter = legacy_observations.into_iter();
|
||||||
|
let mut stats = FundamentalsStats::default();
|
||||||
|
let mut eligible_obs: Vec<EligibleObservation<K>> = 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;
|
stats.observations_in += 1;
|
||||||
|
|
||||||
let Some(&venue) = venues.get(&obs.key) else {
|
let Some(&venue) = venues.get(&obs.key) else {
|
||||||
|
|
@ -483,6 +538,14 @@ where
|
||||||
})
|
})
|
||||||
.or_insert(obs.period_end);
|
.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 {
|
eligible_obs.push(EligibleObservation {
|
||||||
key: obs.key,
|
key: obs.key,
|
||||||
period_end: obs.period_end,
|
period_end: obs.period_end,
|
||||||
|
|
@ -491,6 +554,7 @@ where
|
||||||
report_date: obs.report_date,
|
report_date: obs.report_date,
|
||||||
venue,
|
venue,
|
||||||
fields: obs.fields.normalize_zeros(),
|
fields: obs.fields.normalize_zeros(),
|
||||||
|
is_legacy,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -559,31 +623,85 @@ where
|
||||||
let mut candidates: Vec<CandidateRow<K>> = Vec::with_capacity(eligible_obs.len());
|
let mut candidates: Vec<CandidateRow<K>> = Vec::with_capacity(eligible_obs.len());
|
||||||
|
|
||||||
for obs in eligible_obs {
|
for obs in eligible_obs {
|
||||||
let linked_micros = filing_index
|
// An undated legacy (`qmFinancials-old`) observation carries no `report_date` proving
|
||||||
.get(&(obs.key.clone(), obs.fiscal_period))
|
// which filing produced its values. If any primary or dated vintage exists for the same
|
||||||
.and_then(|bucket| match obs.report_date {
|
// `(key, period_end, fiscal_period)`, withhold the undated legacy row rather than risking
|
||||||
Some(rd) => {
|
// publishing an overwritten revision before an amendment.
|
||||||
// Earliest matching periodic filing (amended or unamended) on Eastern day `rd`.
|
if obs.is_legacy
|
||||||
// `rd > obs.period_end` is guaranteed by validation above.
|
&& obs.report_date.is_none()
|
||||||
let pos = bucket.partition_point(|f| f.et_date < rd);
|
&& anchored_or_primary_periods.contains(&(
|
||||||
bucket
|
obs.key.clone(),
|
||||||
.get(pos)
|
obs.period_end,
|
||||||
.filter(|f| f.et_date == rd)
|
obs.fiscal_period,
|
||||||
.map(|f| f.utc_micros)
|
))
|
||||||
}
|
{
|
||||||
None => {
|
stats.observations_dropped_unanchored_vintage += 1;
|
||||||
// Earliest matching non-amended periodic filing strictly after `period_end`
|
continue;
|
||||||
// and within the inclusive calendar-day inference window.
|
}
|
||||||
|
|
||||||
|
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)
|
let window_end = i64::from(obs.period_end)
|
||||||
+ i64::from(obs.fiscal_period.undated_link_window_days());
|
+ i64::from(obs.fiscal_period.undated_link_window_days());
|
||||||
let pos = bucket.partition_point(|f| f.et_date <= obs.period_end);
|
let pos = bucket.partition_point(|f| f.et_date <= obs.period_end);
|
||||||
bucket[pos..]
|
let mut earliest_unamended: Option<i64> = None;
|
||||||
|
let mut latest_amendment: Option<i64> = None;
|
||||||
|
for f in bucket[pos..]
|
||||||
.iter()
|
.iter()
|
||||||
.take_while(|f| i64::from(f.et_date) <= window_end)
|
.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 {
|
let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros {
|
||||||
(micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP)
|
(micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP)
|
||||||
|
|
@ -602,7 +720,7 @@ where
|
||||||
stats.observations_dropped_date_out_of_range += 1;
|
stats.observations_dropped_date_out_of_range += 1;
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let Ok(micros) = et_to_utc_micros(
|
let Ok(lag_micros) = et_to_utc_micros(
|
||||||
lag_date,
|
lag_date,
|
||||||
FUNDAMENTALS_FALLBACK_HOUR_ET,
|
FUNDAMENTALS_FALLBACK_HOUR_ET,
|
||||||
FUNDAMENTALS_FALLBACK_MINUTE_ET,
|
FUNDAMENTALS_FALLBACK_MINUTE_ET,
|
||||||
|
|
@ -611,6 +729,10 @@ where
|
||||||
stats.observations_dropped_date_out_of_range += 1;
|
stats.observations_dropped_date_out_of_range += 1;
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
let micros = match legacy_filing_lower_bound_micros {
|
||||||
|
Some(lb) => lag_micros.max(lb),
|
||||||
|
None => lag_micros,
|
||||||
|
};
|
||||||
(micros, KNOWN_AT_SOURCE_STATUTORY_LAG)
|
(micros, KNOWN_AT_SOURCE_STATUTORY_LAG)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -625,6 +747,7 @@ where
|
||||||
fields: obs.fields,
|
fields: obs.fields,
|
||||||
},
|
},
|
||||||
report_date: obs.report_date,
|
report_date: obs.report_date,
|
||||||
|
is_legacy: obs.is_legacy,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -650,11 +773,13 @@ where
|
||||||
pe_end += 1;
|
pe_end += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for
|
// Track the newest accepted `report_date` (and whether any row was already accepted) at
|
||||||
// each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag
|
// an earlier `known_at_utc_micros` for each `FiscalPeriod` so only accepted earlier
|
||||||
// estimate.
|
// versions can suppress a stale statutory-lag estimate.
|
||||||
let mut max_accepted_rd_q: Option<i32> = None;
|
let mut max_accepted_rd_q: Option<i32> = None;
|
||||||
let mut max_accepted_rd_fy: Option<i32> = None;
|
let mut max_accepted_rd_fy: Option<i32> = None;
|
||||||
|
let mut has_accepted_q = false;
|
||||||
|
let mut has_accepted_fy = false;
|
||||||
|
|
||||||
let mut g_start = pe_start;
|
let mut g_start = pe_start;
|
||||||
while g_start < pe_end {
|
while g_start < pe_end {
|
||||||
|
|
@ -664,21 +789,26 @@ where
|
||||||
g_end += 1;
|
g_end += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter out stale dated statutory-lag candidates before duplicate/conflict checks
|
// Filter out stale statutory-lag candidates before duplicate/conflict checks so a
|
||||||
// so a superseded estimate cannot cause an eligible estimate at the same fallback
|
// superseded estimate cannot cause an eligible estimate at the same fallback
|
||||||
// timestamp to be rejected as conflicting.
|
// timestamp to be rejected as conflicting.
|
||||||
survivors.clear();
|
survivors.clear();
|
||||||
for idx in g_start..g_end {
|
for idx in g_start..g_end {
|
||||||
let cand = &candidates[idx];
|
let cand = &candidates[idx];
|
||||||
let prior_max_rd = match cand.row.fiscal_period {
|
let (prior_max_rd, prior_has_accepted) = match cand.row.fiscal_period {
|
||||||
FiscalPeriod::Quarterly => max_accepted_rd_q,
|
FiscalPeriod::Quarterly => (max_accepted_rd_q, has_accepted_q),
|
||||||
FiscalPeriod::Annual => max_accepted_rd_fy,
|
FiscalPeriod::Annual => (max_accepted_rd_fy, has_accepted_fy),
|
||||||
};
|
};
|
||||||
let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG
|
let is_stale_dated_estimate =
|
||||||
&& cand
|
cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG
|
||||||
.report_date
|
&& cand
|
||||||
.is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a));
|
.report_date
|
||||||
if is_stale_estimate {
|
.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;
|
stats.observations_dropped_stale_estimate += 1;
|
||||||
} else {
|
} else {
|
||||||
survivors.push(idx);
|
survivors.push(idx);
|
||||||
|
|
@ -690,6 +820,32 @@ where
|
||||||
continue;
|
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 first = &candidates[survivors[0]].row;
|
||||||
let all_identical = survivors[1..].iter().all(|&idx| {
|
let all_identical = survivors[1..].iter().all(|&idx| {
|
||||||
let other = &candidates[idx].row;
|
let other = &candidates[idx].row;
|
||||||
|
|
@ -711,12 +867,19 @@ where
|
||||||
group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd)));
|
group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(rd) = group_max_rd {
|
match first.fiscal_period {
|
||||||
let slot = match first.fiscal_period {
|
FiscalPeriod::Quarterly => {
|
||||||
FiscalPeriod::Quarterly => &mut max_accepted_rd_q,
|
has_accepted_q = true;
|
||||||
FiscalPeriod::Annual => &mut max_accepted_rd_fy,
|
if let Some(rd) = group_max_rd {
|
||||||
};
|
max_accepted_rd_q = Some(max_accepted_rd_q.map_or(rd, |m| m.max(rd)));
|
||||||
*slot = Some(slot.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;
|
stats.duplicate_collapsed += survivors.len() - 1;
|
||||||
|
|
|
||||||
|
|
@ -1067,3 +1067,678 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() {
|
||||||
assert!(fy_snap.has_estimated_lag);
|
assert!(fy_snap.has_estimated_lag);
|
||||||
assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_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<T>(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::<FinancialObservation<String>>(),
|
||||||
|
filings.clone(),
|
||||||
|
&venues,
|
||||||
|
),
|
||||||
|
build_fundamentals_rows(primary, filings, &venues),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
pub mod adj;
|
pub mod adj;
|
||||||
pub mod bars;
|
pub mod bars;
|
||||||
pub mod bars_1m;
|
pub mod bars_1m;
|
||||||
|
pub(crate) mod bars_1m_sort;
|
||||||
pub mod bench;
|
pub mod bench;
|
||||||
pub mod bson_ceo_posts;
|
pub mod bson_ceo_posts;
|
||||||
pub mod bson_ceo_shorts;
|
pub mod bson_ceo_shorts;
|
||||||
|
|
@ -137,11 +138,11 @@ pub use events::{
|
||||||
KNOWN_AT_SOURCE_STATUTORY_LAG,
|
KNOWN_AT_SOURCE_STATUTORY_LAG,
|
||||||
};
|
};
|
||||||
pub use fundamentals::{
|
pub use fundamentals::{
|
||||||
as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_snapshots,
|
as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_rows_with_legacy,
|
||||||
FinancialObservation, FiscalPeriod, FundamentalsBuild, FundamentalsError, FundamentalsFields,
|
build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, FundamentalsBuild,
|
||||||
FundamentalsPeriodSlot, FundamentalsRow, FundamentalsSnapshot, FundamentalsStats,
|
FundamentalsError, FundamentalsFields, FundamentalsPeriodSlot, FundamentalsRow,
|
||||||
FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, ANNUAL_FILING_LINK_WINDOW_DAYS,
|
FundamentalsSnapshot, FundamentalsStats, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields,
|
||||||
FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET,
|
ANNUAL_FILING_LINK_WINDOW_DAYS, FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET,
|
||||||
QUARTERLY_FILING_LINK_WINDOW_DAYS, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS,
|
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_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS,
|
||||||
STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, TTM_CONSECUTIVE_QUARTER_MAX_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 mod curate_fundamentals;
|
||||||
pub use curate_fundamentals::{
|
pub use curate_fundamentals::{
|
||||||
curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError,
|
curate_and_write_fundamentals, curate_and_write_fundamentals_with_legacy, curate_fundamentals,
|
||||||
CurateFundamentalsOutput, CurateFundamentalsStats, CurateFundamentalsWriteError,
|
curate_fundamentals_with_legacy, CurateFundamentalsError, CurateFundamentalsOutput,
|
||||||
CurateFundamentalsWriteReport,
|
CurateFundamentalsStats, CurateFundamentalsWriteError, CurateFundamentalsWriteReport,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub mod curate_macro;
|
pub mod curate_macro;
|
||||||
|
|
@ -336,20 +337,21 @@ pub use run_curate_bars::{
|
||||||
|
|
||||||
pub mod run_curate_bars_1m;
|
pub mod run_curate_bars_1m;
|
||||||
pub use 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,
|
format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_from_readers_to_dir,
|
||||||
CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError,
|
run_curate_bars_1m_with_readers, CurateBars1mArgs, CurateBars1mRunReport,
|
||||||
DEFAULT_BARS_1M_MAPPING_SOURCE,
|
RunCurateBars1mError, DEFAULT_BARS_1M_MAPPING_SOURCE,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub mod run_curate_fx_1m;
|
pub mod run_curate_fx_1m;
|
||||||
pub use 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,
|
format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_from_reader_to_dir,
|
||||||
CurateFx1mRunReport, RunCurateFx1mError,
|
run_curate_fx_1m_with_readers, CurateFx1mArgs, CurateFx1mRunReport, RunCurateFx1mError,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub mod run_curate_qm_bars_1m;
|
pub mod run_curate_qm_bars_1m;
|
||||||
pub use 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,
|
CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError,
|
||||||
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
|
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
|
||||||
};
|
};
|
||||||
|
|
@ -384,15 +386,16 @@ pub use run_curate_posts::{
|
||||||
pub mod run_curate_fundamentals;
|
pub mod run_curate_fundamentals;
|
||||||
pub use run_curate_fundamentals::{
|
pub use run_curate_fundamentals::{
|
||||||
format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals,
|
format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals,
|
||||||
run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod,
|
run_curate_fundamentals_with_optional_old_readers, run_curate_fundamentals_with_readers,
|
||||||
CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
|
CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport,
|
||||||
|
RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub mod run_curate_macro;
|
pub mod run_curate_macro;
|
||||||
pub use run_curate_macro::{
|
pub use run_curate_macro::{
|
||||||
format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro,
|
format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro,
|
||||||
run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap,
|
run_curate_macro_from_reader, run_curate_macro_with_readers, CurateMacroArgs,
|
||||||
RunCurateMacroError, MACRO_SERIES_MAP_HEADER,
|
CurateMacroRunReport, MacroSeriesMap, RunCurateMacroError, MACRO_SERIES_MAP_HEADER,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub mod run_curate_shorts;
|
pub mod run_curate_shorts;
|
||||||
|
|
@ -409,10 +412,14 @@ pub use run_curate_events::{
|
||||||
|
|
||||||
pub mod run_mongo;
|
pub mod run_mongo;
|
||||||
pub use run_mongo::{
|
pub use run_mongo::{
|
||||||
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
|
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_bars_1m_mongo,
|
||||||
run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo,
|
run_curate_corporate_actions_mongo, run_curate_events_mongo, run_curate_fundamentals_mongo,
|
||||||
CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs,
|
run_curate_fx_1d_mongo, run_curate_fx_1m_mongo, run_curate_macro_mongo, run_curate_posts_mongo,
|
||||||
CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError,
|
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)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -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_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_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
|
||||||
use curate_etl::run_mongo::{
|
use curate_etl::run_mongo::{
|
||||||
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
|
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_bars_1m_mongo,
|
||||||
run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_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");
|
const NAME: &str = env!("CARGO_PKG_NAME");
|
||||||
|
|
@ -216,6 +218,18 @@ fn main() -> ExitCode {
|
||||||
ExitCode::FAILURE
|
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(CliAction::CurateQmBars1m(curate_args)) => match run_curate_qm_bars_1m(&curate_args) {
|
||||||
Ok(report) => {
|
Ok(report) => {
|
||||||
println!("{}", format_curate_qm_bars_1m_report(&report));
|
println!("{}", format_curate_qm_bars_1m_report(&report));
|
||||||
|
|
@ -227,6 +241,19 @@ fn main() -> ExitCode {
|
||||||
ExitCode::FAILURE
|
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(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) {
|
||||||
Ok(report) => {
|
Ok(report) => {
|
||||||
println!("{}", format_curate_fx_1m_report(&report));
|
println!("{}", format_curate_fx_1m_report(&report));
|
||||||
|
|
@ -237,6 +264,18 @@ fn main() -> ExitCode {
|
||||||
ExitCode::FAILURE
|
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(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) {
|
||||||
Ok(report) => {
|
Ok(report) => {
|
||||||
println!("{}", format_curate_posts_report(&report));
|
println!("{}", format_curate_posts_report(&report));
|
||||||
|
|
@ -247,6 +286,18 @@ fn main() -> ExitCode {
|
||||||
ExitCode::FAILURE
|
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)) => {
|
Ok(CliAction::CurateFundamentals(curate_args)) => {
|
||||||
match run_curate_fundamentals(&curate_args) {
|
match run_curate_fundamentals(&curate_args) {
|
||||||
Ok(report) => {
|
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(CliAction::CurateMacro(curate_args)) => match run_curate_macro(&curate_args) {
|
||||||
Ok(report) => {
|
Ok(report) => {
|
||||||
println!("{}", format_curate_macro_report(&report));
|
println!("{}", format_curate_macro_report(&report));
|
||||||
|
|
@ -269,6 +332,18 @@ fn main() -> ExitCode {
|
||||||
ExitCode::FAILURE
|
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(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) {
|
||||||
Ok(report) => {
|
Ok(report) => {
|
||||||
println!("{}", format_ilp_send_report(&report));
|
println!("{}", format_ilp_send_report(&report));
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@
|
||||||
//! backed by `mongodb::sync`.
|
//! backed by `mongodb::sync`.
|
||||||
//!
|
//!
|
||||||
//! # Safety & Sealing Guarantees
|
//! # 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
|
//! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API
|
||||||
//! accepts a free-form collection name string.
|
//! accepts a free-form collection name string.
|
||||||
//! - Sealed read-only driver surface: [`ReadOnlyMongoClient`] requires a
|
//! - 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`).
|
/// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`).
|
||||||
pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000;
|
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
|
/// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in
|
||||||
/// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`.
|
/// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`.
|
||||||
|
|
@ -59,11 +59,17 @@ pub enum SourceCollection {
|
||||||
CeoShorts,
|
CeoShorts,
|
||||||
QmFilings,
|
QmFilings,
|
||||||
QmEarnings,
|
QmEarnings,
|
||||||
|
QmFinancials,
|
||||||
|
QmFinancialsOld,
|
||||||
|
CeoPosts,
|
||||||
|
TeData,
|
||||||
|
EodIntraday1M,
|
||||||
|
QmIntraday,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SourceCollection {
|
impl SourceCollection {
|
||||||
/// All 8 allowlisted M1 source collections in canonical order.
|
/// All 14 allowlisted M1+M2 source collections in canonical order.
|
||||||
pub const ALL: [SourceCollection; 8] = [
|
pub const ALL: [SourceCollection; 14] = [
|
||||||
Self::EodPrices,
|
Self::EodPrices,
|
||||||
Self::QmSplits,
|
Self::QmSplits,
|
||||||
Self::QmDividends,
|
Self::QmDividends,
|
||||||
|
|
@ -72,6 +78,12 @@ impl SourceCollection {
|
||||||
Self::CeoShorts,
|
Self::CeoShorts,
|
||||||
Self::QmFilings,
|
Self::QmFilings,
|
||||||
Self::QmEarnings,
|
Self::QmEarnings,
|
||||||
|
Self::QmFinancials,
|
||||||
|
Self::QmFinancialsOld,
|
||||||
|
Self::CeoPosts,
|
||||||
|
Self::TeData,
|
||||||
|
Self::EodIntraday1M,
|
||||||
|
Self::QmIntraday,
|
||||||
];
|
];
|
||||||
|
|
||||||
/// Exact MongoDB collection name.
|
/// Exact MongoDB collection name.
|
||||||
|
|
@ -85,6 +97,12 @@ impl SourceCollection {
|
||||||
Self::CeoShorts => "ceoShorts",
|
Self::CeoShorts => "ceoShorts",
|
||||||
Self::QmFilings => "qmFilings",
|
Self::QmFilings => "qmFilings",
|
||||||
Self::QmEarnings => "qmEarnings",
|
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::CeoShorts => "symbol",
|
||||||
Self::QmFilings => "symbol",
|
Self::QmFilings => "symbol",
|
||||||
Self::QmEarnings => "qmSearchCode",
|
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`
|
/// 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> {
|
pub const fn date_field(self) -> Option<&'static str> {
|
||||||
match self {
|
match self {
|
||||||
Self::EodPrices => Some("date"),
|
Self::EodPrices => Some("date"),
|
||||||
|
|
@ -114,18 +139,31 @@ impl SourceCollection {
|
||||||
Self::CeoShorts => Some("timestamp"),
|
Self::CeoShorts => Some("timestamp"),
|
||||||
Self::QmFilings => Some("timefiled"),
|
Self::QmFilings => Some("timefiled"),
|
||||||
Self::QmEarnings => Some("reportDate"),
|
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
|
/// 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`):
|
/// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md` /
|
||||||
/// `qmEarnings.reportDate` (100% BSON `DateTime`) and `ceoShorts.timestamp`
|
/// `design/DATA-CONTRACTS.md` §1): `qmEarnings.reportDate`, `ceoShorts.timestamp`,
|
||||||
/// (BSON `DateTime`), while `eodPrices.date`, `qmPrices.date`, `qmSplits.date`,
|
/// 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.
|
/// `qmDividends.date`, and `qmFilings.timefiled` are UTF-8 strings.
|
||||||
pub const fn date_field_is_bson_datetime(self) -> bool {
|
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),
|
IsoString(String),
|
||||||
/// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch.
|
/// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch.
|
||||||
BsonDateTimeMillis(i64),
|
BsonDateTimeMillis(i64),
|
||||||
|
/// UTC Unix timestamp expressed as integer seconds (`Bson::Int64`), used by `eodIntraday1M`.
|
||||||
|
EpochSeconds(i64),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FilterDateValue {
|
impl FilterDateValue {
|
||||||
|
|
@ -149,6 +189,7 @@ impl FilterDateValue {
|
||||||
match self {
|
match self {
|
||||||
Self::IsoString(s) => Bson::String(s.clone()),
|
Self::IsoString(s) => Bson::String(s.clone()),
|
||||||
Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)),
|
Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)),
|
||||||
|
Self::EpochSeconds(secs) => Bson::Int64(*secs),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -259,20 +300,49 @@ impl MongoReadSpec {
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
|
Some(
|
||||||
Err(MongoStreamError::InvalidDateRange {
|
FilterDateValue::BsonDateTimeMillis(_)
|
||||||
collection,
|
| FilterDateValue::EpochSeconds(_),
|
||||||
detail: "qmFilings.timefiled is stored as an Eastern Time string; \
|
) => Err(MongoStreamError::InvalidDateRange {
|
||||||
only Eastern calendar-day boundaries (YYYY-MM-DD) are \
|
collection,
|
||||||
supported for server-side ranges"
|
detail: "qmFilings.timefiled is stored as an Eastern Time string; \
|
||||||
.to_owned(),
|
only Eastern calendar-day boundaries (YYYY-MM-DD) are \
|
||||||
})
|
supported for server-side ranges"
|
||||||
}
|
.to_owned(),
|
||||||
|
}),
|
||||||
None => Ok(()),
|
None => Ok(()),
|
||||||
};
|
};
|
||||||
validate_et_calendar_day(range.gte.as_ref(), "gte")?;
|
validate_et_calendar_day(range.gte.as_ref(), "gte")?;
|
||||||
validate_et_calendar_day(range.lt.as_ref(), "lt")?;
|
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) {
|
if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) {
|
||||||
match (gte, lt) {
|
match (gte, lt) {
|
||||||
(FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => {
|
(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 {
|
return Err(MongoStreamError::InvalidDateRange {
|
||||||
collection,
|
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 result = String::with_capacity(text.len());
|
||||||
let mut cursor = 0usize;
|
let mut cursor = 0usize;
|
||||||
let lower = text.to_ascii_lowercase();
|
let lower = text.to_ascii_lowercase();
|
||||||
|
|
@ -1198,8 +1276,9 @@ impl MongoCliOptions {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds a [`MongoReadSpec`] using the collection's native BSON date representation:
|
/// Builds a [`MongoReadSpec`] using the collection's native BSON date representation:
|
||||||
/// `BsonDateTimeMillis` (UTC midnight) for BSON `DateTime` collections (`qmEarnings`,
|
/// `EpochSeconds` (UTC midnight seconds) for `eodIntraday1M`, `BsonDateTimeMillis`
|
||||||
/// `ceoShorts`) and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`,
|
/// (UTC midnight millis) for BSON `DateTime` collections (`qmEarnings`, `ceoShorts`,
|
||||||
|
/// `qmIntraday`), and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`,
|
||||||
/// `qmSplits`, `qmDividends`, `qmFilings`).
|
/// `qmSplits`, `qmDividends`, `qmFilings`).
|
||||||
pub fn to_read_spec_for_collection(
|
pub fn to_read_spec_for_collection(
|
||||||
&self,
|
&self,
|
||||||
|
|
@ -1210,25 +1289,45 @@ impl MongoCliOptions {
|
||||||
if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) {
|
if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) {
|
||||||
return self.to_read_spec(key_eq, false);
|
return self.to_read_spec(key_eq, false);
|
||||||
}
|
}
|
||||||
if !collection.date_field_is_bson_datetime() {
|
if collection.date_field_is_epoch_seconds() {
|
||||||
return self.to_read_spec(key_eq, true);
|
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 {
|
if collection.date_field_is_bson_datetime() {
|
||||||
match parse_ymd_strict_days(raw) {
|
let to_dt = |raw: &String| -> FilterDateValue {
|
||||||
Some(days) => FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY),
|
match parse_ymd_strict_days(raw) {
|
||||||
None => FilterDateValue::IsoString(raw.clone()),
|
Some(days) => {
|
||||||
}
|
FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY)
|
||||||
};
|
}
|
||||||
MongoReadSpec {
|
None => FilterDateValue::IsoString(raw.clone()),
|
||||||
key_eq,
|
}
|
||||||
date_range: Some(MongoDateRange {
|
};
|
||||||
gte: self.date_gte.as_ref().map(to_dt),
|
return MongoReadSpec {
|
||||||
lt: self.date_lt.as_ref().map(to_dt),
|
key_eq,
|
||||||
}),
|
date_range: Some(MongoDateRange {
|
||||||
batch_size: self.batch_size,
|
gte: self.date_gte.as_ref().map(to_dt),
|
||||||
limit: self.limit,
|
lt: self.date_lt.as_ref().map(to_dt),
|
||||||
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
|
}),
|
||||||
|
batch_size: self.batch_size,
|
||||||
|
limit: self.limit,
|
||||||
|
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
self.to_read_spec(key_eq, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,11 +5,16 @@ use std::path::PathBuf;
|
||||||
use bson::raw::{cstr, RawDocumentBuf};
|
use bson::raw::{cstr, RawDocumentBuf};
|
||||||
use bson::{Bson, DateTime};
|
use bson::{Bson, DateTime};
|
||||||
|
|
||||||
|
use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit};
|
||||||
use crate::bson_qm_events::QmFilingsFieldNames;
|
use crate::bson_qm_events::QmFilingsFieldNames;
|
||||||
|
use crate::bson_qm_financials::{QmFinancialsFieldNames, QmFinancialsFiscalPeriod};
|
||||||
use crate::bson_stream::{
|
use crate::bson_stream::{
|
||||||
decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream,
|
decode_ceo_posts_stream, decode_eod_intraday_stream, decode_eod_price_stream,
|
||||||
decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES,
|
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::{
|
use crate::mongo_safety::{
|
||||||
assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri,
|
assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri,
|
||||||
};
|
};
|
||||||
|
|
@ -213,7 +218,8 @@ fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() {
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).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",
|
"eodPrices",
|
||||||
"qmSplits",
|
"qmSplits",
|
||||||
"qmDividends",
|
"qmDividends",
|
||||||
|
|
@ -222,18 +228,23 @@ fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() {
|
||||||
"ceoShorts",
|
"ceoShorts",
|
||||||
"qmFilings",
|
"qmFilings",
|
||||||
"qmEarnings",
|
"qmEarnings",
|
||||||
|
"qmFinancials",
|
||||||
|
"qmFinancials-old",
|
||||||
|
"ceoPosts",
|
||||||
|
"teData",
|
||||||
|
"eodIntraday1M",
|
||||||
|
"qmIntraday",
|
||||||
];
|
];
|
||||||
|
|
||||||
assert_eq!(rust_names, expected);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ts_names,
|
ts_name_refs, expected_ts,
|
||||||
rust_names
|
"RAW_BSON_EXPORT_COLLECTIONS must match the 14 M1+M2 collections in exact names and order"
|
||||||
.iter()
|
);
|
||||||
.map(|s| (*s).to_owned())
|
assert_eq!(
|
||||||
.collect::<Vec<_>>(),
|
rust_names, ts_name_refs,
|
||||||
"SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order"
|
"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]
|
#[test]
|
||||||
fn source_collection_exhaustive_key_date_and_display_mappings() {
|
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,
|
SourceCollection::EodPrices,
|
||||||
"eodPrices",
|
"eodPrices",
|
||||||
"eodSearchCode",
|
"eodSearchCode",
|
||||||
Some("date"),
|
Some("date"),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::QmSplits,
|
SourceCollection::QmSplits,
|
||||||
"qmSplits",
|
"qmSplits",
|
||||||
"qmSearchCode",
|
"qmSearchCode",
|
||||||
Some("date"),
|
Some("date"),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::QmDividends,
|
SourceCollection::QmDividends,
|
||||||
"qmDividends",
|
"qmDividends",
|
||||||
"qmSearchCode",
|
"qmSearchCode",
|
||||||
Some("date"),
|
Some("date"),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::QmPrices,
|
SourceCollection::QmPrices,
|
||||||
"qmPrices",
|
"qmPrices",
|
||||||
"qmSearchCode",
|
"qmSearchCode",
|
||||||
Some("date"),
|
Some("date"),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::TeMarketData,
|
SourceCollection::TeMarketData,
|
||||||
"teMarketData",
|
"teMarketData",
|
||||||
"teSymbol",
|
"teSymbol",
|
||||||
None,
|
None,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::CeoShorts,
|
SourceCollection::CeoShorts,
|
||||||
"ceoShorts",
|
"ceoShorts",
|
||||||
"symbol",
|
"symbol",
|
||||||
Some("timestamp"),
|
Some("timestamp"),
|
||||||
|
true,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::QmFilings,
|
SourceCollection::QmFilings,
|
||||||
"qmFilings",
|
"qmFilings",
|
||||||
"symbol",
|
"symbol",
|
||||||
Some("timefiled"),
|
Some("timefiled"),
|
||||||
|
false,
|
||||||
|
false,
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
SourceCollection::QmEarnings,
|
SourceCollection::QmEarnings,
|
||||||
"qmEarnings",
|
"qmEarnings",
|
||||||
"qmSearchCode",
|
"qmSearchCode",
|
||||||
Some("reportDate"),
|
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());
|
assert_eq!(SourceCollection::ALL.len(), expected.len());
|
||||||
for (actual, (exp_variant, exp_name, exp_key, exp_date)) in
|
for (
|
||||||
SourceCollection::ALL.into_iter().zip(expected)
|
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, exp_variant);
|
||||||
assert_eq!(actual.as_str(), exp_name);
|
assert_eq!(actual.as_str(), exp_name);
|
||||||
assert_eq!(format!("{actual}"), exp_name);
|
assert_eq!(format!("{actual}"), exp_name);
|
||||||
assert_eq!(actual.key_field(), exp_key);
|
assert_eq!(actual.key_field(), exp_key);
|
||||||
assert_eq!(actual.date_field(), exp_date);
|
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)))
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
//! Streaming, atomic, year-partitioned Zstd Parquet writer for `events`.
|
//! Streaming, atomic, year-partitioned Zstd Parquet writer for `events`.
|
||||||
//!
|
//!
|
||||||
//! Writes `<out_dir>/events/year=YYYY/part.parquet` files matching the 7-column contract schema in
|
//! Writes `<out_dir>/events/year=YYYY/part.parquet` (filings & earnings via
|
||||||
|
//! [`write_events_dataset`]) or `<out_dir>/events/year=YYYY/part-posts.parquet`
|
||||||
|
//! (`ceoPosts` via [`write_posts_events_dataset`]) matching the 7-column contract schema in
|
||||||
//! `design/DATA-CONTRACTS.md` (§3A):
|
//! `design/DATA-CONTRACTS.md` (§3A):
|
||||||
//!
|
//!
|
||||||
//! 1. `listing_id` (`INT32`, `REQUIRED`)
|
//! 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};
|
pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL};
|
||||||
|
|
||||||
|
/// Target Parquet file name under `<out_dir>/events/year=YYYY/` for filings & earnings.
|
||||||
|
pub const EVENTS_PART_FILE_NAME: &str = "part.parquet";
|
||||||
|
|
||||||
|
/// Target Parquet file name under `<out_dir>/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.
|
/// Single `events` row matching the `design/DATA-CONTRACTS.md` Parquet schema.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct EventsParquetRow {
|
pub struct EventsParquetRow {
|
||||||
|
|
@ -494,6 +502,7 @@ impl YearWriter {
|
||||||
fn open(
|
fn open(
|
||||||
events_dir: &Path,
|
events_dir: &Path,
|
||||||
year: i32,
|
year: i32,
|
||||||
|
part_file_name: &str,
|
||||||
run_id: &str,
|
run_id: &str,
|
||||||
schema: &TypePtr,
|
schema: &TypePtr,
|
||||||
props: &WriterPropertiesPtr,
|
props: &WriterPropertiesPtr,
|
||||||
|
|
@ -507,7 +516,7 @@ impl YearWriter {
|
||||||
|
|
||||||
let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?;
|
let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?;
|
||||||
staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone()));
|
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 buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file);
|
||||||
let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err(
|
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
|
||||||
|
/// `<out_dir>/events/year=YYYY/part-posts.parquet`.
|
||||||
|
///
|
||||||
|
/// Shares `<out_dir>/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<P, I, R>(
|
||||||
|
out_dir: P,
|
||||||
|
rows: I,
|
||||||
|
options: EventsWriteOptions,
|
||||||
|
) -> Result<EventsWriteStats, ParquetEventsError>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
I: IntoIterator<Item = R>,
|
||||||
|
R: Borrow<EventsParquetRow>,
|
||||||
|
{
|
||||||
|
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<P, I, R, F>(
|
fn write_events_dataset_with_hooks<P, I, R, F>(
|
||||||
out_dir: P,
|
out_dir: P,
|
||||||
rows: I,
|
rows: I,
|
||||||
|
|
@ -705,6 +743,7 @@ where
|
||||||
{
|
{
|
||||||
write_events_dataset_with_lock_and_backup_hooks(
|
write_events_dataset_with_lock_and_backup_hooks(
|
||||||
out_dir,
|
out_dir,
|
||||||
|
EVENTS_PART_FILE_NAME,
|
||||||
rows,
|
rows,
|
||||||
options,
|
options,
|
||||||
lock_timeout,
|
lock_timeout,
|
||||||
|
|
@ -715,6 +754,7 @@ where
|
||||||
|
|
||||||
fn write_events_dataset_with_lock_and_backup_hooks<P, I, R, G, F>(
|
fn write_events_dataset_with_lock_and_backup_hooks<P, I, R, G, F>(
|
||||||
out_dir: P,
|
out_dir: P,
|
||||||
|
part_file_name: &str,
|
||||||
rows: I,
|
rows: I,
|
||||||
options: EventsWriteOptions,
|
options: EventsWriteOptions,
|
||||||
lock_timeout: Duration,
|
lock_timeout: Duration,
|
||||||
|
|
@ -812,6 +852,7 @@ where
|
||||||
let opened = YearWriter::open(
|
let opened = YearWriter::open(
|
||||||
&events_dir,
|
&events_dir,
|
||||||
year,
|
year,
|
||||||
|
part_file_name,
|
||||||
&run_id,
|
&run_id,
|
||||||
&schema,
|
&schema,
|
||||||
&props,
|
&props,
|
||||||
|
|
|
||||||
|
|
@ -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::tests::{assert_no_transient_files, make_event_row, read_parquet_rows, utc_micros, TempDirGuard};
|
||||||
use super::{
|
use super::{
|
||||||
write_events_dataset, write_events_dataset_with_hooks,
|
write_events_dataset, write_events_dataset_with_hooks,
|
||||||
write_events_dataset_with_lock_and_backup_hooks, EventsParquetRow, EventsWriteOptions,
|
write_events_dataset_with_lock_and_backup_hooks, write_posts_events_dataset, EventsParquetRow,
|
||||||
EventsWriteStats, ParquetEventsError, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
|
EventsWriteOptions, EventsWriteStats, ParquetEventsError, DEFAULT_ZSTD_LEVEL,
|
||||||
|
EVENTS_PART_FILE_NAME, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, POSTS_PART_FILE_NAME,
|
||||||
};
|
};
|
||||||
use crate::events::{
|
use crate::events::{
|
||||||
build_events, partition_year_utc, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING,
|
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(
|
write_events_dataset_with_lock_and_backup_hooks(
|
||||||
&out_2,
|
&out_2,
|
||||||
|
EVENTS_PART_FILE_NAME,
|
||||||
iter,
|
iter,
|
||||||
EventsWriteOptions::default(),
|
EventsWriteOptions::default(),
|
||||||
DEFAULT_LOCK_TIMEOUT,
|
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_eq!(total_read, rows.len());
|
||||||
assert_no_transient_files(&tmp.path().join("events"));
|
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"));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
//! Adapter mapping curated `ceoPosts` rows ([`PostRow<i32>`] / [`PostsBuild<i32>`]) into the
|
//! Adapter mapping curated `ceoPosts` rows ([`PostRow<i32>`] / [`PostsBuild<i32>`]) 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`:
|
//! 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
|
//! - `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
|
//! [`POST_SUBTYPE_RETAIL`] (`"retail"`) otherwise, so wire releases are never pooled with crowd
|
||||||
//! chat.
|
//! chat.
|
||||||
|
|
@ -19,7 +19,7 @@ use crate::parquet_events::EventsParquetRow;
|
||||||
use crate::posts::{PostRow, PostsBuild};
|
use crate::posts::{PostRow, PostsBuild};
|
||||||
|
|
||||||
/// Canonical `events.kind` label for curated `ceoPosts` rows.
|
/// 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.
|
/// Canonical `events.subtype` label for `bot == "1"` newswire posts.
|
||||||
pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire";
|
pub const POST_SUBTYPE_NEWSWIRE: &str = "newswire";
|
||||||
|
|
@ -89,7 +89,7 @@ impl From<PostRow<i32>> for EventsParquetRow {
|
||||||
|
|
||||||
/// Converts both `newswire` and `retail` streams of a [`PostsBuild<i32>`] into
|
/// Converts both `newswire` and `retail` streams of a [`PostsBuild<i32>`] into
|
||||||
/// [`EventsParquetRow`] records sorted in the exact order required by
|
/// [`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)`.
|
/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`.
|
||||||
pub fn posts_to_event_rows(build: &PostsBuild<i32>) -> Vec<EventsParquetRow> {
|
pub fn posts_to_event_rows(build: &PostsBuild<i32>) -> Vec<EventsParquetRow> {
|
||||||
let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len());
|
let mut rows = Vec::with_capacity(build.newswire.len() + build.retail.len());
|
||||||
|
|
|
||||||
|
|
@ -265,7 +265,9 @@ fn maps_retail_unedited_edited_newswire_and_clamped_edit_for_borrowed_and_owned(
|
||||||
}
|
}
|
||||||
|
|
||||||
let mapped = posts_to_event_rows(&build);
|
let mapped = posts_to_event_rows(&build);
|
||||||
|
assert_eq!(EVENT_KIND_POST, "ceo_post");
|
||||||
assert_eq!(mapped.len(), 4);
|
assert_eq!(mapped.len(), 4);
|
||||||
|
assert!(mapped.iter().all(|row| row.kind.as_ref() == "ceo_post"));
|
||||||
|
|
||||||
// 101: retail unedited
|
// 101: retail unedited
|
||||||
assert_eq!(
|
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());
|
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"));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -48,23 +48,22 @@
|
||||||
//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors
|
//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors
|
||||||
//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`].
|
//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`].
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::fs::{self, File, OpenOptions};
|
use std::fs::{self, File, OpenOptions};
|
||||||
use std::io::{self, BufWriter, Write};
|
use std::io::{self, BufWriter, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Instant;
|
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_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecodeStats};
|
||||||
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
||||||
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
|
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
|
||||||
use crate::curate_bars_1m::{
|
use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError};
|
||||||
curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError,
|
|
||||||
};
|
|
||||||
use crate::ilp::{
|
use crate::ilp::{
|
||||||
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M,
|
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M,
|
||||||
};
|
};
|
||||||
|
|
@ -241,7 +240,6 @@ impl Error for RunCurateBars1mError {
|
||||||
|
|
||||||
struct LoadedReferenceInputs {
|
struct LoadedReferenceInputs {
|
||||||
mapping: ProviderMappingTable,
|
mapping: ProviderMappingTable,
|
||||||
eod_keys: HashSet<Arc<str>>,
|
|
||||||
splits: SplitTable<i32>,
|
splits: SplitTable<i32>,
|
||||||
splits_docs_framed: u64,
|
splits_docs_framed: u64,
|
||||||
splits_bytes_read: u64,
|
splits_bytes_read: u64,
|
||||||
|
|
@ -378,9 +376,7 @@ fn load_reference_inputs<RS: io::Read>(
|
||||||
let mapping_rows =
|
let mapping_rows =
|
||||||
load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?;
|
load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?;
|
||||||
let EodMappingIndex {
|
let EodMappingIndex {
|
||||||
eod_keys,
|
eod_by_listing, ..
|
||||||
eod_by_listing,
|
|
||||||
..
|
|
||||||
} = build_eod_mapping_index(&mapping_rows, false);
|
} = build_eod_mapping_index(&mapping_rows, false);
|
||||||
|
|
||||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||||
|
|
@ -416,7 +412,6 @@ fn load_reference_inputs<RS: io::Read>(
|
||||||
|
|
||||||
Ok(LoadedReferenceInputs {
|
Ok(LoadedReferenceInputs {
|
||||||
mapping,
|
mapping,
|
||||||
eod_keys,
|
|
||||||
splits,
|
splits,
|
||||||
splits_docs_framed,
|
splits_docs_framed,
|
||||||
splits_bytes_read,
|
splits_bytes_read,
|
||||||
|
|
@ -425,47 +420,28 @@ fn load_reference_inputs<RS: io::Read>(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
fn map_sort_error(err: Bars1mExternalSortError) -> RunCurateBars1mError {
|
||||||
fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) {
|
match err {
|
||||||
total.bars_in += chunk.bars_in;
|
Bars1mExternalSortError::Io { path, source } => RunCurateBars1mError::Io { path, source },
|
||||||
total.rows_out += chunk.rows_out;
|
Bars1mExternalSortError::Ilp(err) => {
|
||||||
total.keys_out += chunk.keys_out;
|
RunCurateBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(err))
|
||||||
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 stream_intraday_chunks_to_writer<RI, W>(
|
fn stream_intraday_chunks_to_writer<RI, W>(
|
||||||
args: &CurateBars1mArgs,
|
args: &CurateBars1mArgs,
|
||||||
reference: LoadedReferenceInputs,
|
reference: LoadedReferenceInputs,
|
||||||
intraday: RI,
|
intraday: RI,
|
||||||
mut writer: IlpShardedWriter<W>,
|
writer: IlpShardedWriter<W>,
|
||||||
|
sort_config: Bars1mSortConfig,
|
||||||
start: Instant,
|
start: Instant,
|
||||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
) -> Result<(CurateBars1mRunReport, ExternalSortMetrics), RunCurateBars1mError>
|
||||||
where
|
where
|
||||||
RI: io::Read,
|
RI: io::Read,
|
||||||
W: Write + Send,
|
W: Write + Send,
|
||||||
{
|
{
|
||||||
|
let mut writer = writer;
|
||||||
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|
||||||
|source| RunCurateBars1mError::BsonStream {
|
|source| RunCurateBars1mError::BsonStream {
|
||||||
label: "eod-intraday",
|
label: "eod-intraday",
|
||||||
|
|
@ -475,14 +451,13 @@ where
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut intraday_decode = BsonEodIntradayDecodeStats::default();
|
let mut intraday_decode = BsonEodIntradayDecodeStats::default();
|
||||||
let mut curate_stats = CurateBars1mStats::default();
|
|
||||||
let mut chunks: usize = 0;
|
let mut chunks: usize = 0;
|
||||||
let mut max_rows_per_chunk: 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.
|
// Bounded-memory external sort/merge resolves same-key duplicates and cross-source listing
|
||||||
let mut chunk_bars: Vec<EodIntradayBar<Arc<str>>> = Vec::new();
|
// collisions globally across BSON chunks without retaining all rows in RAM.
|
||||||
let mut unknown_keys: HashMap<String, Arc<str>> = HashMap::new();
|
let mut sorter =
|
||||||
|
Bars1mExternalSorter::new(&reference.mapping, &args.mapping_source, sort_config);
|
||||||
|
|
||||||
while let Some(chunk) =
|
while let Some(chunk) =
|
||||||
reader
|
reader
|
||||||
|
|
@ -493,67 +468,75 @@ where
|
||||||
source,
|
source,
|
||||||
})?
|
})?
|
||||||
{
|
{
|
||||||
chunk_bars.clear();
|
let mut chunk_rows = 0usize;
|
||||||
unknown_keys.clear();
|
let mut spill_err: Option<Bars1mExternalSortError> = None;
|
||||||
|
|
||||||
let chunk_decode = decode_eod_intraday_buffer(
|
let chunk_decode = decode_eod_intraday_buffer(
|
||||||
chunk.bytes,
|
chunk.bytes,
|
||||||
|raw| {
|
|raw| {
|
||||||
let key = if let Some(existing) = reference.eod_keys.get(raw.eod_search_code) {
|
if spill_err.is_some() {
|
||||||
Arc::clone(existing)
|
return;
|
||||||
} else if let Some(existing) = unknown_keys.get(raw.eod_search_code) {
|
}
|
||||||
Arc::clone(existing)
|
chunk_rows += 1;
|
||||||
} else {
|
if let Err(err) = sorter.push_raw(
|
||||||
let arc: Arc<str> = Arc::from(raw.eod_search_code);
|
raw.eod_search_code,
|
||||||
unknown_keys.insert(raw.eod_search_code.to_owned(), Arc::clone(&arc));
|
raw.ts,
|
||||||
arc
|
raw.open,
|
||||||
};
|
raw.high,
|
||||||
chunk_bars.push(raw.into_eod_intraday_bar(|_, _| key));
|
raw.low,
|
||||||
|
raw.close,
|
||||||
|
raw.volume,
|
||||||
|
) {
|
||||||
|
spill_err = Some(err);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|_local_offset, _err| {},
|
|_local_offset, _err| {},
|
||||||
);
|
);
|
||||||
|
if let Some(err) = spill_err {
|
||||||
|
return Err(map_sort_error(err));
|
||||||
|
}
|
||||||
intraday_decode += chunk_decode;
|
intraday_decode += chunk_decode;
|
||||||
|
|
||||||
chunks += 1;
|
chunks += 1;
|
||||||
let chunk_len = chunk_bars.len();
|
if chunk_rows > max_rows_per_chunk {
|
||||||
if chunk_len > max_rows_per_chunk {
|
max_rows_per_chunk = chunk_rows;
|
||||||
max_rows_per_chunk = chunk_len;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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_docs_framed = reader.docs_framed();
|
||||||
let intraday_bytes_read = reader.bytes_read();
|
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)?;
|
let ilp_stats = writer.finish().map_err(RunCurateBars1mError::Ilp)?;
|
||||||
|
|
||||||
Ok(CurateBars1mRunReport {
|
Ok((
|
||||||
intraday_docs_framed,
|
CurateBars1mRunReport {
|
||||||
intraday_bytes_read,
|
intraday_docs_framed,
|
||||||
intraday_decode,
|
intraday_bytes_read,
|
||||||
splits_docs_framed: reference.splits_docs_framed,
|
intraday_decode,
|
||||||
splits_bytes_read: reference.splits_bytes_read,
|
splits_docs_framed: reference.splits_docs_framed,
|
||||||
splits_decode: reference.splits_decode,
|
splits_bytes_read: reference.splits_bytes_read,
|
||||||
split_rekey: reference.split_rekey,
|
splits_decode: reference.splits_decode,
|
||||||
chunks,
|
split_rekey: reference.split_rekey,
|
||||||
max_rows_per_chunk,
|
chunks,
|
||||||
curate_stats,
|
max_rows_per_chunk,
|
||||||
rows_written,
|
curate_stats: write_report.curate_stats,
|
||||||
ilp_stats,
|
rows_written: write_report.rows_written,
|
||||||
shard_count: args.shard_count,
|
ilp_stats,
|
||||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
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
|
/// 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`
|
/// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits`
|
||||||
/// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] +
|
/// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] +
|
||||||
/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits,
|
/// [`decode_eod_intraday_buffer`] into the bounded-memory external sorter/merger with listing-keyed
|
||||||
/// and calls [`IlpShardedWriter::finish`] exactly once after EOF.
|
/// splits, and calls [`IlpShardedWriter::finish`] exactly once after EOF.
|
||||||
pub fn run_curate_bars_1m_with_readers<RI, RS, W>(
|
pub fn run_curate_bars_1m_with_readers<RI, RS, W>(
|
||||||
args: &CurateBars1mArgs,
|
args: &CurateBars1mArgs,
|
||||||
intraday: RI,
|
intraday: RI,
|
||||||
|
|
@ -584,7 +567,10 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?;
|
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
|
/// 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 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)?;
|
publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?;
|
||||||
Ok(report)
|
Ok(report)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn run_curate_bars_1m_from_readers_to_dir_with_sort_config<RI, RS>(
|
||||||
|
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<SyncedBufFile> = 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 `<out_dir>/bars_1m.shard-<NN>.ilp`, and rollback
|
||||||
|
/// cleanup on failure with zero intermediate `.bson` scratch files.
|
||||||
|
pub fn run_curate_bars_1m_from_readers_to_dir<RI, RS>(
|
||||||
|
args: &CurateBars1mArgs,
|
||||||
|
intraday: RI,
|
||||||
|
splits: RS,
|
||||||
|
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||||
|
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
|
/// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly
|
||||||
/// `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`).
|
/// `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`).
|
||||||
pub fn run_curate_bars_1m(
|
pub fn run_curate_bars_1m(
|
||||||
|
|
@ -783,13 +842,7 @@ pub fn run_curate_bars_1m(
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
run_curate_bars_1m_to_dir_with_hooks(
|
run_curate_bars_1m_from_readers_to_dir(args, intraday_file, splits_file)
|
||||||
args,
|
|
||||||
intraday_file,
|
|
||||||
splits_file,
|
|
||||||
|_shard_idx, file| SyncedBufFile::new(file),
|
|
||||||
|_shard_idx, _final_path| {},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
/// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||||
|
|
|
||||||
|
|
@ -4,13 +4,14 @@ use std::fs;
|
||||||
use std::io::{self, Cursor, Write};
|
use std::io::{self, Cursor, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use bson::raw::{cstr, RawDocumentBuf};
|
use bson::raw::{cstr, RawDocumentBuf};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::bars::Bar1dRow;
|
use crate::bars::Bar1dRow;
|
||||||
use crate::bars_1m::{
|
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::curate_bars_1m::check_curated_session_closes;
|
||||||
use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M};
|
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_report_conservation(&report);
|
||||||
assert_eq!(report.chunks, 2);
|
assert_eq!(report.chunks, 2);
|
||||||
assert_eq!(report.max_rows_per_chunk, 1);
|
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.listing_collision_collapsed, 0);
|
||||||
assert_eq!(report.curate_stats.listings_out, 2);
|
assert_eq!(report.curate_stats.listings_out, 1);
|
||||||
assert_eq!(report.curate_stats.builder.keys_out, 2);
|
assert_eq!(report.curate_stats.builder.keys_out, 1);
|
||||||
assert_eq!(report.rows_written, 2);
|
assert_eq!(report.rows_written, 1);
|
||||||
|
|
||||||
let rows = decode_ilp_bars_1m(&sink);
|
let rows = decode_ilp_bars_1m(&sink);
|
||||||
assert_eq!(rows.len(), 2);
|
assert_eq!(rows.len(), 1);
|
||||||
assert_eq!(rows[0], rows[1]);
|
|
||||||
assert_eq!(rows[0].listing_id, 505);
|
assert_eq!(rows[0].listing_id, 505);
|
||||||
assert_eq!(rows[0].ts, ts * 1_000_000);
|
assert_eq!(rows[0].ts, ts * 1_000_000);
|
||||||
|
|
||||||
let formatted = format_curate_bars_1m_report(&report);
|
let formatted = format_curate_bars_1m_report(&report);
|
||||||
assert!(formatted.contains("cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)"));
|
assert!(formatted.contains("dup_collapsed=1"));
|
||||||
assert!(formatted.contains("listings_out_per_chunk_sum=2"));
|
assert!(formatted.contains("listings_out_per_chunk_sum=1"));
|
||||||
assert!(formatted.contains("keys_out_per_chunk_sum=2"));
|
assert!(formatted.contains("keys_out_per_chunk_sum=1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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));
|
let oth = get(88, et_ts_sec(2025, 5, 20, 10, 0));
|
||||||
assert_eq!((oth.close, oth.volume), (20.5, 50.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<u8> = 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<T>(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<u8> = 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<Vec<u8>> = 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"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -63,7 +63,8 @@ use crate::bson_stream::{
|
||||||
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
|
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
|
||||||
};
|
};
|
||||||
use crate::curate_fundamentals::{
|
use crate::curate_fundamentals::{
|
||||||
curate_and_write_fundamentals, CurateFundamentalsStats, CurateFundamentalsWriteError,
|
curate_and_write_fundamentals_with_legacy, CurateFundamentalsStats,
|
||||||
|
CurateFundamentalsWriteError,
|
||||||
};
|
};
|
||||||
use crate::events::QmFiling;
|
use crate::events::QmFiling;
|
||||||
use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue};
|
use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue};
|
||||||
|
|
@ -112,6 +113,7 @@ impl CurateFundamentalsFiscalPeriod {
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct CurateFundamentalsArgs {
|
pub struct CurateFundamentalsArgs {
|
||||||
pub qm_financials: PathBuf,
|
pub qm_financials: PathBuf,
|
||||||
|
pub qm_financials_old: Option<PathBuf>,
|
||||||
pub qm_filings: PathBuf,
|
pub qm_filings: PathBuf,
|
||||||
pub provider_mapping: PathBuf,
|
pub provider_mapping: PathBuf,
|
||||||
pub listing_venues: PathBuf,
|
pub listing_venues: PathBuf,
|
||||||
|
|
@ -165,6 +167,7 @@ impl CurateFundamentalsArgs {
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
qm_financials,
|
qm_financials,
|
||||||
|
qm_financials_old: None,
|
||||||
qm_filings,
|
qm_filings,
|
||||||
provider_mapping,
|
provider_mapping,
|
||||||
listing_venues,
|
listing_venues,
|
||||||
|
|
@ -618,7 +621,7 @@ fn validate_out_dir_and_inputs(
|
||||||
let resolved_out = resolve_normalized_path(&args.out_dir);
|
let resolved_out = resolve_normalized_path(&args.out_dir);
|
||||||
let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir);
|
let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir);
|
||||||
|
|
||||||
let resolved_inputs = [
|
let mut resolved_inputs = vec![
|
||||||
(
|
(
|
||||||
"qm-financials",
|
"qm-financials",
|
||||||
&args.qm_financials,
|
&args.qm_financials,
|
||||||
|
|
@ -640,6 +643,13 @@ fn validate_out_dir_and_inputs(
|
||||||
resolve_normalized_path(&args.listing_venues),
|
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 {
|
for (label, input_path, resolved_in) in &resolved_inputs {
|
||||||
if *resolved_in == resolved_out
|
if *resolved_in == resolved_out
|
||||||
|
|
@ -774,12 +784,13 @@ fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn map_financials_stream_error(
|
fn map_financials_stream_error(
|
||||||
|
label: &'static str,
|
||||||
path: &Path,
|
path: &Path,
|
||||||
err: BsonQmFinancialsStreamError,
|
err: BsonQmFinancialsStreamError,
|
||||||
) -> RunCurateFundamentalsError {
|
) -> RunCurateFundamentalsError {
|
||||||
match err {
|
match err {
|
||||||
BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream {
|
BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream {
|
||||||
label: "qm-financials",
|
label,
|
||||||
path: path.to_path_buf(),
|
path: path.to_path_buf(),
|
||||||
source,
|
source,
|
||||||
},
|
},
|
||||||
|
|
@ -847,6 +858,7 @@ struct DecodedFundamentalsInputs {
|
||||||
mapping: ProviderMappingTable,
|
mapping: ProviderMappingTable,
|
||||||
venues: BTreeMap<i32, StatutoryLagVenue>,
|
venues: BTreeMap<i32, StatutoryLagVenue>,
|
||||||
observations: Vec<FinancialObservation<Arc<str>>>,
|
observations: Vec<FinancialObservation<Arc<str>>>,
|
||||||
|
legacy_observations: Vec<FinancialObservation<Arc<str>>>,
|
||||||
filings: Vec<QmFiling<Arc<str>>>,
|
filings: Vec<QmFiling<Arc<str>>>,
|
||||||
financials_docs_framed: u64,
|
financials_docs_framed: u64,
|
||||||
financials_bytes_read: u64,
|
financials_bytes_read: u64,
|
||||||
|
|
@ -858,14 +870,17 @@ struct DecodedFundamentalsInputs {
|
||||||
filings_decode: BsonQmFilingsDecodeStats,
|
filings_decode: BsonQmFilingsDecodeStats,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode_inputs_from_openers<RF, FF, RL, FL>(
|
fn decode_inputs_from_openers<RF, FF, RO, FO, RL, FL>(
|
||||||
args: &CurateFundamentalsArgs,
|
args: &CurateFundamentalsArgs,
|
||||||
open_financials: FF,
|
open_financials: FF,
|
||||||
|
open_financials_old: Option<(&Path, FO)>,
|
||||||
open_filings: FL,
|
open_filings: FL,
|
||||||
) -> Result<DecodedFundamentalsInputs, RunCurateFundamentalsError>
|
) -> Result<DecodedFundamentalsInputs, RunCurateFundamentalsError>
|
||||||
where
|
where
|
||||||
RF: io::Read,
|
RF: io::Read,
|
||||||
FF: FnOnce() -> Result<RF, RunCurateFundamentalsError>,
|
FF: FnOnce() -> Result<RF, RunCurateFundamentalsError>,
|
||||||
|
RO: io::Read,
|
||||||
|
FO: FnOnce() -> Result<RO, RunCurateFundamentalsError>,
|
||||||
RL: io::Read,
|
RL: io::Read,
|
||||||
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
|
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
|
||||||
{
|
{
|
||||||
|
|
@ -916,10 +931,10 @@ where
|
||||||
// Stream and decode qmFinancials, releasing the chunk reader immediately afterward.
|
// Stream and decode qmFinancials, releasing the chunk reader immediately afterward.
|
||||||
let (
|
let (
|
||||||
observations,
|
observations,
|
||||||
financials_docs_framed,
|
mut financials_docs_framed,
|
||||||
financials_bytes_read,
|
mut financials_bytes_read,
|
||||||
financials_peak_chunk_bytes,
|
mut financials_peak_chunk_bytes,
|
||||||
financials_decode,
|
mut financials_decode,
|
||||||
) = {
|
) = {
|
||||||
let financials_stream = open_financials()?;
|
let financials_stream = open_financials()?;
|
||||||
let mut financials_reader =
|
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,
|
observations,
|
||||||
|
|
@ -955,6 +970,42 @@ where
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Optionally stream and decode legacy qmFinancials-old, accumulating framing & decode stats.
|
||||||
|
let mut legacy_observations: Vec<FinancialObservation<Arc<str>>> = 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.
|
// 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, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = {
|
||||||
let filings_stream = open_filings()?;
|
let filings_stream = open_filings()?;
|
||||||
|
|
@ -986,6 +1037,7 @@ where
|
||||||
mapping,
|
mapping,
|
||||||
venues,
|
venues,
|
||||||
observations,
|
observations,
|
||||||
|
legacy_observations,
|
||||||
filings,
|
filings,
|
||||||
financials_docs_framed,
|
financials_docs_framed,
|
||||||
financials_bytes_read,
|
financials_bytes_read,
|
||||||
|
|
@ -998,25 +1050,29 @@ where
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_curate_fundamentals_from_openers<RF, FF, RL, FL>(
|
fn run_curate_fundamentals_from_openers<RF, FF, RO, FO, RL, FL>(
|
||||||
args: &CurateFundamentalsArgs,
|
args: &CurateFundamentalsArgs,
|
||||||
open_financials: FF,
|
open_financials: FF,
|
||||||
|
open_financials_old: Option<(&Path, FO)>,
|
||||||
open_filings: FL,
|
open_filings: FL,
|
||||||
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError>
|
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError>
|
||||||
where
|
where
|
||||||
RF: io::Read,
|
RF: io::Read,
|
||||||
FF: FnOnce() -> Result<RF, RunCurateFundamentalsError>,
|
FF: FnOnce() -> Result<RF, RunCurateFundamentalsError>,
|
||||||
|
RO: io::Read,
|
||||||
|
FO: FnOnce() -> Result<RO, RunCurateFundamentalsError>,
|
||||||
RL: io::Read,
|
RL: io::Read,
|
||||||
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
|
FL: FnOnce() -> Result<RL, RunCurateFundamentalsError>,
|
||||||
{
|
{
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
validate_out_dir_and_inputs(args)?;
|
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,
|
&args.out_dir,
|
||||||
decoded.observations,
|
decoded.observations,
|
||||||
|
decoded.legacy_observations,
|
||||||
decoded.filings,
|
decoded.filings,
|
||||||
&args.mapping_source,
|
&args.mapping_source,
|
||||||
&decoded.mapping,
|
&decoded.mapping,
|
||||||
|
|
@ -1045,7 +1101,7 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via
|
/// 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
|
/// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error
|
||||||
/// returns before touching `args.out_dir`, leaving any pre-existing
|
/// returns before touching `args.out_dir`, leaving any pre-existing
|
||||||
|
|
@ -1053,6 +1109,17 @@ where
|
||||||
pub fn run_curate_fundamentals(
|
pub fn run_curate_fundamentals(
|
||||||
args: &CurateFundamentalsArgs,
|
args: &CurateFundamentalsArgs,
|
||||||
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
|
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
|
||||||
|
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(
|
run_curate_fundamentals_from_openers(
|
||||||
args,
|
args,
|
||||||
|| {
|
|| {
|
||||||
|
|
@ -1064,6 +1131,7 @@ pub fn run_curate_fundamentals(
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
open_old,
|
||||||
|| {
|
|| {
|
||||||
File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput {
|
File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput {
|
||||||
label: "qm-filings",
|
label: "qm-filings",
|
||||||
|
|
@ -1082,7 +1150,35 @@ pub fn run_curate_fundamentals_with_readers<RF: io::Read, RL: io::Read>(
|
||||||
financials_reader: RF,
|
financials_reader: RF,
|
||||||
filings_reader: RL,
|
filings_reader: RL,
|
||||||
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
|
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
|
||||||
run_curate_fundamentals_from_openers(args, || Ok(financials_reader), || Ok(filings_reader))
|
run_curate_fundamentals_with_optional_old_readers(
|
||||||
|
args,
|
||||||
|
financials_reader,
|
||||||
|
None::<io::Empty>,
|
||||||
|
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<RF: io::Read, RO: io::Read, RL: io::Read>(
|
||||||
|
args: &CurateFundamentalsArgs,
|
||||||
|
financials_reader: RF,
|
||||||
|
financials_old_reader: Option<RO>,
|
||||||
|
filings_reader: RL,
|
||||||
|
) -> Result<CurateFundamentalsRunReport, RunCurateFundamentalsError> {
|
||||||
|
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`
|
/// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value`
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,9 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals,
|
format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals,
|
||||||
run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod,
|
run_curate_fundamentals_with_optional_old_readers, run_curate_fundamentals_with_readers,
|
||||||
CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
|
CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport,
|
||||||
|
RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
|
||||||
};
|
};
|
||||||
use crate::bson_qm_events::decode_qm_filing_buffer;
|
use crate::bson_qm_events::decode_qm_filing_buffer;
|
||||||
use crate::bson_qm_financials::decode_qm_financials_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!(matches!(err, RunCurateFundamentalsError::OpenInput { ref path, .. } if path.ends_with("nope.tsv")));
|
||||||
assert!(err.to_string().contains(&path.display().to_string()));
|
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}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 `<out_dir>/fx_1m.shard-<NN>.ilp`, and rollback cleanup on failure
|
||||||
|
/// with zero intermediate `.bson` scratch files.
|
||||||
|
pub fn run_curate_fx_1m_from_reader_to_dir<R>(
|
||||||
|
args: &CurateFx1mArgs,
|
||||||
|
intraday: R,
|
||||||
|
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
|
||||||
|
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
|
/// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB
|
||||||
/// ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`).
|
/// ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`).
|
||||||
pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result<CurateFx1mRunReport, RunCurateFx1mError> {
|
pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result<CurateFx1mRunReport, RunCurateFx1mError> {
|
||||||
|
|
@ -489,12 +508,7 @@ pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result<CurateFx1mRunReport, Ru
|
||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
run_curate_fx_1m_to_dir_with_hooks(
|
run_curate_fx_1m_from_reader_to_dir(args, intraday_file)
|
||||||
args,
|
|
||||||
intraday_file,
|
|
||||||
|_shard_idx, file| SyncedBufFile::new(file),
|
|
||||||
|_shard_idx, _final_path| {},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||||
|
|
|
||||||
|
|
@ -207,7 +207,7 @@ pub enum RunCurateMacroError {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RunCurateMacroError {
|
impl RunCurateMacroError {
|
||||||
fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self {
|
pub(crate) fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self {
|
||||||
match self {
|
match self {
|
||||||
Self::ReadInput {
|
Self::ReadInput {
|
||||||
role,
|
role,
|
||||||
|
|
@ -521,19 +521,11 @@ pub fn load_macro_series_map_tsv<R: io::Read>(
|
||||||
Ok(map)
|
Ok(map)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and
|
fn run_curate_macro_with_map<RT: io::Read>(
|
||||||
/// the series-map TSV, publishing `<out_dir>/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 `<out_dir>/macro/part.parquet` untouched.
|
|
||||||
pub fn run_curate_macro_with_readers<RT: io::Read, RM: io::Read>(
|
|
||||||
mut te_data: RT,
|
mut te_data: RT,
|
||||||
series_map: RM,
|
map: &MacroSeriesMap,
|
||||||
out_dir: &Path,
|
out_dir: &Path,
|
||||||
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
||||||
let map = load_macro_series_map_tsv(series_map)?;
|
|
||||||
|
|
||||||
let mut te_data_buf = Vec::new();
|
let mut te_data_buf = Vec::new();
|
||||||
te_data
|
te_data
|
||||||
.read_to_end(&mut te_data_buf)
|
.read_to_end(&mut te_data_buf)
|
||||||
|
|
@ -577,6 +569,57 @@ pub fn run_curate_macro_with_readers<RT: io::Read, RM: io::Read>(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn load_macro_series_map_file(
|
||||||
|
series_map_path: &Path,
|
||||||
|
) -> Result<MacroSeriesMap, RunCurateMacroError> {
|
||||||
|
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<RT: io::Read>(
|
||||||
|
te_data_path: &Path,
|
||||||
|
te_data: RT,
|
||||||
|
map: &MacroSeriesMap,
|
||||||
|
out_dir: &Path,
|
||||||
|
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
||||||
|
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 `<out_dir>/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 `<out_dir>/macro/part.parquet` untouched.
|
||||||
|
pub fn run_curate_macro_with_readers<RT: io::Read, RM: io::Read>(
|
||||||
|
te_data: RT,
|
||||||
|
series_map: RM,
|
||||||
|
out_dir: &Path,
|
||||||
|
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
||||||
|
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<RT: io::Read>(
|
||||||
|
te_data_path: &Path,
|
||||||
|
te_data: RT,
|
||||||
|
series_map_path: &Path,
|
||||||
|
out_dir: &Path,
|
||||||
|
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
||||||
|
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
|
/// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating
|
||||||
/// to [`run_curate_macro_with_readers`].
|
/// to [`run_curate_macro_with_readers`].
|
||||||
///
|
///
|
||||||
|
|
|
||||||
|
|
@ -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
|
//! Streams a concatenated raw BSON `ceoPosts` dump file alongside `provider_mapping.tsv` into an
|
||||||
//! atomically published `<out_dir>/events/year=YYYY/part.parquet` dataset via
|
//! atomically published `<out_dir>/events/year=YYYY/part-posts.parquet` dataset via
|
||||||
//! [`curate_and_write_posts`].
|
//! [`curate_posts`] and [`write_posts_events_dataset`].
|
||||||
//!
|
//!
|
||||||
//! # Dedicated Output Directory & Clobber Guard
|
//! # Co-Publication with `curate-events`
|
||||||
//! `write_events_dataset` replaces whole `<out_dir>/events/year=YYYY/part.parquet` files, and
|
//! [`crate::run_curate_events`] (filings + earnings) writes `<out_dir>/events/year=YYYY/part.parquet`
|
||||||
//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `<out_dir>/events`
|
//! and this runner writes `<out_dir>/events/year=YYYY/part-posts.parquet` (`kind = "ceo_post"`).
|
||||||
//! directory. To prevent silently clobbering another stage's partitions, this runner **requires a
|
//! Both share `<out_dir>/events/.write.lock` and remain independently re-runnable in the same
|
||||||
//! dedicated output directory** and fails closed with [`RunCuratePostsError::EventsDatasetExists`]
|
//! `curatedRoot` without clobbering each other's partition files.
|
||||||
//! before any write whenever `<out_dir>/events` already contains any `year=*` entry. Combining
|
|
||||||
//! filings, earnings, and posts into one `events` dataset is a separate follow-up.
|
|
||||||
//!
|
//!
|
||||||
//! # Contract & Point-in-Time Rules
|
//! # Contract & Point-in-Time Rules
|
||||||
//! - Field names are supplied via [`CuratePostsArgs`] (validated via
|
//! - Field names are supplied via [`CuratePostsArgs`] (validated via
|
||||||
|
|
@ -30,10 +28,10 @@
|
||||||
//! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires.
|
//! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires.
|
||||||
//! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and
|
//! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and
|
||||||
//! `files_written == 0` without creating `<out_dir>/events`.
|
//! `files_written == 0` without creating `<out_dir>/events`.
|
||||||
//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `<out_dir>/events/year=*` entries,
|
//! - **Fail-closed safety:** invalid `out_dir`, input-output path overlap, invalid field names,
|
||||||
//! invalid field names, blank `mapping_source`, unreadable inputs, malformed/overlapping
|
//! blank `mapping_source`, unreadable inputs, malformed/overlapping `provider_mapping.tsv`,
|
||||||
//! `provider_mapping.tsv`, truncated/corrupt BSON framing or element bytes, and curation
|
//! truncated/corrupt BSON framing or element bytes, and curation timestamp overflow errors return
|
||||||
//! timestamp overflow errors return a typed [`RunCuratePostsError`] before touching `out_dir`.
|
//! a typed [`RunCuratePostsError`] before touching `out_dir`.
|
||||||
//!
|
//!
|
||||||
//! # Counter Conservation Invariants
|
//! # Counter Conservation Invariants
|
||||||
//! Every successful [`CuratePostsRunReport`] satisfies:
|
//! 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`
|
//! - `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`
|
//! - `write_stats.rows_written == curate_stats.rows_out`
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::{BTreeSet, HashSet};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Write as _};
|
use std::fmt::{self, Write as _};
|
||||||
use std::fs::{self, File};
|
use std::fs::{self, File};
|
||||||
|
|
@ -59,8 +57,12 @@ use crate::bson_stream::{
|
||||||
decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions,
|
decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions,
|
||||||
RawBsonChunkReader,
|
RawBsonChunkReader,
|
||||||
};
|
};
|
||||||
use crate::curate_posts::{curate_and_write_posts, CuratePostsStats, CuratePostsWriteError};
|
use crate::curate_posts::{curate_posts, CuratePostsStats, CuratePostsWriteError};
|
||||||
use crate::parquet_events::{EventsWriteOptions, EventsWriteStats};
|
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::posts::CeoPost;
|
||||||
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
|
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
|
||||||
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
||||||
|
|
@ -130,9 +132,6 @@ pub enum RunCuratePostsError {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
source: io::Error,
|
source: io::Error,
|
||||||
},
|
},
|
||||||
EventsDatasetExists {
|
|
||||||
path: PathBuf,
|
|
||||||
},
|
|
||||||
InvalidFieldNames {
|
InvalidFieldNames {
|
||||||
source: BsonCeoPostsError,
|
source: BsonCeoPostsError,
|
||||||
},
|
},
|
||||||
|
|
@ -212,11 +211,6 @@ impl fmt::Display for RunCuratePostsError {
|
||||||
path.display()
|
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::InvalidFieldNames { source } => write!(w, "{source}"),
|
||||||
Self::EmptyMappingSource => {
|
Self::EmptyMappingSource => {
|
||||||
write!(w, "invalid --mapping-source: must not be empty or blank")
|
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::BsonStream { source, .. } => Some(source),
|
||||||
Self::CorruptBson { source, .. } => Some(source),
|
Self::CorruptBson { source, .. } => Some(source),
|
||||||
Self::CurateWrite { source, .. } => Some(source),
|
Self::CurateWrite { source, .. } => Some(source),
|
||||||
Self::InvalidOutDir { .. }
|
Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None,
|
||||||
| Self::EventsDatasetExists { .. }
|
|
||||||
| 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() {
|
if out_dir.as_os_str().is_empty() {
|
||||||
return Err(RunCuratePostsError::InvalidOutDir {
|
return Err(RunCuratePostsError::InvalidOutDir {
|
||||||
path: out_dir.to_path_buf(),
|
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
|
// 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
|
// unresolved path, while `create_dir_all` would create the missing component and traverse `..`.
|
||||||
// `..` into an existing directory, bypassing the events clobber guard.
|
|
||||||
let mut prefix = PathBuf::new();
|
let mut prefix = PathBuf::new();
|
||||||
let mut saw_missing = false;
|
let mut saw_missing = false;
|
||||||
for component in out_dir.components() {
|
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) {
|
match fs::metadata(out_dir) {
|
||||||
Ok(meta) if !meta.is_dir() => {
|
Ok(meta) if !meta.is_dir() => {
|
||||||
return Err(RunCuratePostsError::InvalidOutDir {
|
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(),
|
detail: "path exists and is not a directory".to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Ok(_) => {}
|
Ok(_) => match fs::metadata(&events_dir) {
|
||||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
|
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) => {
|
Err(source) => {
|
||||||
return Err(RunCuratePostsError::InspectOutDir {
|
return Err(RunCuratePostsError::InspectOutDir {
|
||||||
path: out_dir.to_path_buf(),
|
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");
|
let resolved_out = resolve_normalized_path(out_dir);
|
||||||
match fs::metadata(&events_dir) {
|
let resolved_events = resolve_normalized_path(&events_dir);
|
||||||
Ok(meta) if !meta.is_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 {
|
return Err(RunCuratePostsError::InvalidOutDir {
|
||||||
path: events_dir,
|
path: out_dir.to_path_buf(),
|
||||||
detail: "events output path exists and is not a directory".to_string(),
|
detail: format!(
|
||||||
});
|
"output directory would overlap {label} input '{}'",
|
||||||
}
|
input_path.display()
|
||||||
Ok(_) => {}
|
),
|
||||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
|
|
||||||
Err(source) => {
|
|
||||||
return Err(RunCuratePostsError::InspectOutDir {
|
|
||||||
path: events_dir,
|
|
||||||
source,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir {
|
Ok(())
|
||||||
path: events_dir.clone(),
|
}
|
||||||
source,
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let mut existing_year_entry: Option<PathBuf> = None;
|
/// Checks each destination `year=YYYY` partition directory and its `part-posts.parquet` path
|
||||||
for entry_res in entries {
|
/// against all resolved input paths before publishing.
|
||||||
let entry = entry_res.map_err(|source| RunCuratePostsError::InspectOutDir {
|
///
|
||||||
path: events_dir.clone(),
|
/// Catches symlinked year directories (e.g. `<out>/events/year=2024 -> /external/dir`) whose
|
||||||
source,
|
/// resolved target lies outside `<out>/events` and would otherwise let
|
||||||
})?;
|
/// `write_posts_events_dataset` overwrite an input located at `/external/dir/part-posts.parquet`.
|
||||||
let name = entry.file_name();
|
fn validate_partition_outputs_and_inputs(
|
||||||
if name.to_string_lossy().starts_with("year=") {
|
out_dir: &Path,
|
||||||
let candidate = entry.path();
|
ceo_posts_path: &Path,
|
||||||
if existing_year_entry
|
provider_mapping_path: &Path,
|
||||||
.as_ref()
|
rows: &[EventsParquetRow],
|
||||||
.is_none_or(|current| candidate < *current)
|
) -> 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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -545,7 +643,7 @@ where
|
||||||
F: FnOnce() -> Result<R, RunCuratePostsError>,
|
F: FnOnce() -> Result<R, RunCuratePostsError>,
|
||||||
{
|
{
|
||||||
let start = Instant::now();
|
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(
|
let decoded = decode_inputs_from_opener(
|
||||||
provider_mapping_path,
|
provider_mapping_path,
|
||||||
|
|
@ -556,28 +654,37 @@ where
|
||||||
open_posts,
|
open_posts,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
// Re-check output directory and clobber guard immediately before curating/writing.
|
let curated = curate_posts(decoded.posts, mapping_source, &decoded.mapping).map_err(|err| {
|
||||||
validate_out_dir_and_events_guard(out_dir)?;
|
RunCuratePostsError::CurateWrite {
|
||||||
|
out_dir: out_dir.to_path_buf(),
|
||||||
let write_report = curate_and_write_posts(
|
source: CuratePostsWriteError::Curate(err),
|
||||||
out_dir,
|
}
|
||||||
decoded.posts,
|
|
||||||
mapping_source,
|
|
||||||
&decoded.mapping,
|
|
||||||
EventsWriteOptions::default(),
|
|
||||||
)
|
|
||||||
.map_err(|source| RunCuratePostsError::CurateWrite {
|
|
||||||
out_dir: out_dir.to_path_buf(),
|
|
||||||
source,
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
// 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 {
|
Ok(CuratePostsRunReport {
|
||||||
docs_framed: decoded.docs_framed,
|
docs_framed: decoded.docs_framed,
|
||||||
bytes_read: decoded.bytes_read,
|
bytes_read: decoded.bytes_read,
|
||||||
peak_chunk_bytes: decoded.peak_chunk_bytes,
|
peak_chunk_bytes: decoded.peak_chunk_bytes,
|
||||||
decode: decoded.decode,
|
decode: decoded.decode,
|
||||||
curate_stats: write_report.curate_stats,
|
curate_stats: curated.stats,
|
||||||
write_stats: write_report.write_stats,
|
write_stats,
|
||||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,13 +15,16 @@ use crate::bson_ceo_posts::{
|
||||||
DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD,
|
DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD,
|
||||||
};
|
};
|
||||||
use crate::curate_posts::{curate_posts, CuratePostsError, CuratePostsWriteError};
|
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::{
|
use crate::parquet_posts::{
|
||||||
EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP,
|
EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP,
|
||||||
POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL,
|
POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL,
|
||||||
};
|
};
|
||||||
use crate::posts::PostsError;
|
use crate::posts::PostsError;
|
||||||
use crate::provider_mapping::ProviderMappingRow;
|
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;
|
use crate::split::ymd_to_epoch_days;
|
||||||
|
|
||||||
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
@ -270,7 +273,7 @@ fn read_all_event_partitions(out_dir: &Path) -> Vec<EventsParquetRow> {
|
||||||
let mut all = Vec::new();
|
let mut all = Vec::new();
|
||||||
for yd in year_dirs {
|
for yd in year_dirs {
|
||||||
all.extend(read_events_parquet_and_verify_zstd(
|
all.extend(read_events_parquet_and_verify_zstd(
|
||||||
&yd.join("part.parquet"),
|
&yd.join(POSTS_PART_FILE_NAME),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
all.sort_by(|a, b| {
|
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);
|
assert_eq!(report_a.write_stats, report_b.write_stats);
|
||||||
|
|
||||||
for year in ["year=2024", "year=2025"] {
|
for year in ["year=2024", "year=2025"] {
|
||||||
let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a");
|
let a = fs::read(out_a.join("events").join(year).join(POSTS_PART_FILE_NAME))
|
||||||
let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b");
|
.expect("read a");
|
||||||
|
let b = fs::read(out_b.join("events").join(year).join(POSTS_PART_FILE_NAME))
|
||||||
|
.expect("read b");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
a, b,
|
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);
|
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<u8> {
|
||||||
|
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<u8> {
|
||||||
|
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]
|
#[test]
|
||||||
fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() {
|
fn copublishes_with_curate_events_in_both_orders_and_preserves_sibling_bytes_on_rerun() {
|
||||||
let dir = TempDirGuard::new("clobber");
|
let dir = TempDirGuard::new("copublish-both-orders");
|
||||||
let map_path = dir.path().join("mapping.tsv");
|
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 fields = CeoPostsFieldNames::default();
|
||||||
let bson_path = dir.path().join("posts.bson");
|
let posts_v1 = dir.path().join("posts_v1.bson");
|
||||||
write_bytes(
|
write_bytes(
|
||||||
&bson_path,
|
&posts_v1,
|
||||||
&make_post_doc(
|
&make_post_doc(
|
||||||
&fields,
|
&fields,
|
||||||
"CEO_RY",
|
"CEO_RY",
|
||||||
"sp-1",
|
"sp-1",
|
||||||
utc_ms(2024, 6, 15, 14, 0, 0),
|
utc_ms(2024, 6, 15, 14, 0, 0),
|
||||||
|
Some(utc_ms(2024, 6, 15, 21, 0, 0)),
|
||||||
None,
|
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,
|
None,
|
||||||
|
Some("1"),
|
||||||
None,
|
None,
|
||||||
"hi",
|
"v2 wire",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// 1. Pre-existing events/year=2024/part.parquet with sentinel bytes
|
let filings_path = dir.path().join("filings.bson");
|
||||||
let out_a = dir.path().join("out_existing_parquet");
|
write_bytes(
|
||||||
let year_2024 = out_a.join("events/year=2024");
|
&filings_path,
|
||||||
fs::create_dir_all(&year_2024).unwrap();
|
&make_filing_doc("RY:CA", "2024-06-10T16:15:00 EDT", "8-K"),
|
||||||
let sentinel_path = year_2024.join("part.parquet");
|
);
|
||||||
let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-EVENTS-PARQUET".to_vec();
|
let earnings_path = dir.path().join("earnings.bson");
|
||||||
write_bytes(&sentinel_path, &sentinel_bytes);
|
write_bytes(
|
||||||
|
&earnings_path,
|
||||||
|
&make_earning_doc("RY:CA", "2024-06-12", "AMC"),
|
||||||
|
);
|
||||||
|
|
||||||
let args_a = default_args(
|
// Order 1: curate-events first, then curate-posts, then re-run curate-posts.
|
||||||
bson_path.clone(),
|
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(),
|
map_path.clone(),
|
||||||
out_a.clone(),
|
out_ef_first.clone(),
|
||||||
CeoPostsTimestampUnit::Millis,
|
))
|
||||||
);
|
.expect("run_curate_events");
|
||||||
let err = run_curate_posts(&args_a).unwrap_err();
|
assert_eq!(ev_report.write_stats.rows_written, 2);
|
||||||
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);
|
|
||||||
|
|
||||||
// 2. Pre-existing year=* directory without a Parquet file must also fail closed
|
let events_part = out_ef_first
|
||||||
let out_b = dir.path().join("out_empty_year_dir");
|
.join("events/year=2024")
|
||||||
let year_2025 = out_b.join("events/year=2025");
|
.join(EVENTS_PART_FILE_NAME);
|
||||||
fs::create_dir_all(&year_2025).unwrap();
|
let posts_part = out_ef_first
|
||||||
let args_b = default_args(
|
.join("events/year=2024")
|
||||||
bson_path,
|
.join(POSTS_PART_FILE_NAME);
|
||||||
map_path,
|
let events_bytes = fs::read(&events_part).unwrap();
|
||||||
out_b.clone(),
|
|
||||||
|
let p1_report = run_curate_posts(&default_args(
|
||||||
|
posts_v1.clone(),
|
||||||
|
map_path.clone(),
|
||||||
|
out_ef_first.clone(),
|
||||||
CeoPostsTimestampUnit::Millis,
|
CeoPostsTimestampUnit::Millis,
|
||||||
);
|
))
|
||||||
let err = run_curate_posts(&args_b).unwrap_err();
|
.expect("run_curate_posts alongside events");
|
||||||
assert!(matches!(
|
assert_report_invariants(&p1_report);
|
||||||
err,
|
assert_eq!(p1_report.write_stats.rows_written, 1);
|
||||||
RunCuratePostsError::EventsDatasetExists { .. }
|
assert_eq!(fs::read(&events_part).unwrap(), events_bytes);
|
||||||
));
|
let post_rows_v1 = read_events_parquet_and_verify_zstd(&posts_part);
|
||||||
let msg = assert_single_line_err(&err);
|
assert_eq!(post_rows_v1.len(), 1);
|
||||||
assert!(msg.contains("year=2025"), "expected year=2025 in {msg}");
|
assert_eq!(post_rows_v1[0].kind.as_ref(), "ceo_post");
|
||||||
assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0);
|
|
||||||
|
// 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]
|
#[test]
|
||||||
|
|
@ -1161,29 +1263,6 @@ fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir()
|
||||||
assert!(!out_unmapped.join("events").exists());
|
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<F: FnMut()> {
|
|
||||||
bytes: Vec<u8>,
|
|
||||||
pos: usize,
|
|
||||||
on_eof: Option<F>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F: FnMut()> Read for EofHookReader<F> {
|
|
||||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
|
||||||
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<String> {
|
fn sorted_names(p: &Path) -> Vec<String> {
|
||||||
let mut names: Vec<String> = fs::read_dir(p)
|
let mut names: Vec<String> = fs::read_dir(p)
|
||||||
.expect("read dir")
|
.expect("read dir")
|
||||||
|
|
@ -1194,12 +1273,10 @@ fn sorted_names(p: &Path) -> Vec<String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes() {
|
fn input_path_overlap_with_out_dir_events_or_partition_target_fails_closed() {
|
||||||
let dir = TempDirGuard::new("guard-recheck");
|
let dir = TempDirGuard::new("input-overlap");
|
||||||
let map_path = dir.path().join("mapping.tsv");
|
|
||||||
write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n");
|
|
||||||
let fields = CeoPostsFieldNames::default();
|
let fields = CeoPostsFieldNames::default();
|
||||||
let doc = make_post_doc(
|
let valid_doc = make_post_doc(
|
||||||
&fields,
|
&fields,
|
||||||
"CEO_RY",
|
"CEO_RY",
|
||||||
"sp-1",
|
"sp-1",
|
||||||
|
|
@ -1210,46 +1287,80 @@ fn post_decode_guard_rejects_partition_created_during_decode_and_preserves_bytes
|
||||||
"hi",
|
"hi",
|
||||||
);
|
);
|
||||||
|
|
||||||
let out_dir = dir.path().join("out");
|
// 1. ceo_posts inside <out>/events/
|
||||||
let partition = out_dir.join("events").join("year=2024");
|
let out_a = dir.path().join("out_a");
|
||||||
let sentinel_path = partition.join("part.parquet");
|
let events_a = out_a.join("events");
|
||||||
let sentinel = b"SENTINEL-CONCURRENT-FILINGS".to_vec();
|
fs::create_dir_all(&events_a).unwrap();
|
||||||
assert!(
|
let posts_inside_events = events_a.join("ceoPosts.bson");
|
||||||
!out_dir.exists(),
|
write_bytes(&posts_inside_events, &valid_doc);
|
||||||
"first guard must see a fresh output root"
|
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 err = run_curate_posts(&default_args(
|
||||||
let hook_sentinel_path = sentinel_path.clone();
|
posts_inside_events.clone(),
|
||||||
let hook_sentinel = sentinel.clone();
|
map_a.clone(),
|
||||||
let err = run_curate_posts_with_reader(
|
out_a.clone(),
|
||||||
&map_path,
|
|
||||||
DEFAULT_MAPPING_SOURCE,
|
|
||||||
&fields,
|
|
||||||
CeoPostsTimestampUnit::Millis,
|
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();
|
.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 <out>/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!(
|
assert!(
|
||||||
matches!(&err, RunCuratePostsError::EventsDatasetExists { path } if path == &partition),
|
msg.contains("provider-mapping"),
|
||||||
"expected EventsDatasetExists for {partition:?}, got {err:?}"
|
"expected provider-mapping in {msg}"
|
||||||
);
|
);
|
||||||
assert_single_line_err(&err);
|
assert_eq!(
|
||||||
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel);
|
fs::read(&map_inside_year).unwrap(),
|
||||||
assert_eq!(sorted_names(&out_dir.join("events")), vec!["year=2024"]);
|
b"ceo\tCEO_RY\t2020-01-01\t\t101\n"
|
||||||
assert_eq!(sorted_names(&partition), vec!["part.parquet"]);
|
);
|
||||||
|
|
||||||
|
// 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]
|
#[test]
|
||||||
|
|
@ -1285,16 +1396,20 @@ fn events_dir_with_only_non_year_entries_is_published_and_non_year_entries_prese
|
||||||
out_dir.clone(),
|
out_dir.clone(),
|
||||||
CeoPostsTimestampUnit::Millis,
|
CeoPostsTimestampUnit::Millis,
|
||||||
))
|
))
|
||||||
.expect("non-year entries must not trip the clobber guard");
|
.expect("non-year entries must be preserved");
|
||||||
|
|
||||||
assert_report_invariants(&report);
|
assert_report_invariants(&report);
|
||||||
assert_eq!(report.write_stats.rows_written, 1);
|
assert_eq!(report.write_stats.rows_written, 1);
|
||||||
assert_eq!(fs::read(&readme).unwrap(), b"not a partition");
|
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), vec!["README.txt", "year=2024"]);
|
||||||
|
assert_eq!(
|
||||||
|
sorted_names(&events_dir.join("year=2024")),
|
||||||
|
vec![POSTS_PART_FILE_NAME]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 dir = TempDirGuard::new("parent-existing");
|
||||||
let map_path = dir.path().join("mapping.tsv");
|
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\n");
|
||||||
|
|
@ -1318,26 +1433,25 @@ fn parent_dir_through_existing_components_still_hits_events_guard() {
|
||||||
let shared_partition = exports.join("shared/events/year=2024");
|
let shared_partition = exports.join("shared/events/year=2024");
|
||||||
fs::create_dir_all(&shared_partition).unwrap();
|
fs::create_dir_all(&shared_partition).unwrap();
|
||||||
fs::create_dir_all(exports.join("scratch")).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");
|
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 out = exports.join("scratch").join("..").join("shared");
|
||||||
let err = run_curate_posts(&default_args(
|
let report = run_curate_posts(&default_args(
|
||||||
bson_path,
|
bson_path,
|
||||||
map_path,
|
map_path,
|
||||||
out,
|
out,
|
||||||
CeoPostsTimestampUnit::Millis,
|
CeoPostsTimestampUnit::Millis,
|
||||||
))
|
))
|
||||||
.unwrap_err();
|
.expect("copublish through existing parent component");
|
||||||
assert!(
|
assert_report_invariants(&report);
|
||||||
matches!(err, RunCuratePostsError::EventsDatasetExists { .. }),
|
assert_eq!(report.write_stats.rows_written, 1);
|
||||||
"got {err:?}"
|
|
||||||
);
|
|
||||||
assert_single_line_err(&err);
|
|
||||||
assert_eq!(fs::read(&sentinel_path).unwrap(), b"SENTINEL");
|
assert_eq!(fs::read(&sentinel_path).unwrap(), b"SENTINEL");
|
||||||
assert_eq!(sorted_names(&exports), vec!["scratch", "shared"]);
|
assert_eq!(
|
||||||
assert!(sorted_names(&exports.join("scratch")).is_empty());
|
sorted_names(&shared_partition),
|
||||||
|
vec![POSTS_PART_FILE_NAME, EVENTS_PART_FILE_NAME]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -59,18 +59,20 @@ use std::io::{self, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::Instant;
|
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_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats};
|
||||||
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
|
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
|
||||||
use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError};
|
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::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions};
|
||||||
use crate::parquet_bars::RollbackFailure;
|
use crate::parquet_bars::RollbackFailure;
|
||||||
use crate::parquet_publish::{next_run_id, StagingFileGuard};
|
use crate::parquet_publish::{next_run_id, StagingFileGuard};
|
||||||
use crate::provider_mapping::ProviderMappingTable;
|
use crate::provider_mapping::ProviderMappingTable;
|
||||||
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
||||||
use crate::run_curate_bars_1m::{
|
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,
|
publish_staged_shards_for_table, ShardPublishError, SyncedBufFile,
|
||||||
};
|
};
|
||||||
use crate::run_curate_fx_1m::cleanup_armed_staged_shards;
|
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<R, W>(
|
fn stream_qm_intraday_chunks_to_writer<R, W>(
|
||||||
args: &CurateQmBars1mArgs,
|
args: &CurateQmBars1mArgs,
|
||||||
mapping: &ProviderMappingTable,
|
mapping: &ProviderMappingTable,
|
||||||
intraday: R,
|
intraday: R,
|
||||||
mut writer: IlpShardedWriter<W>,
|
mut writer: IlpShardedWriter<W>,
|
||||||
|
sort_config: Bars1mSortConfig,
|
||||||
start: Instant,
|
start: Instant,
|
||||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
) -> Result<(CurateQmBars1mRunReport, ExternalSortMetrics), RunCurateQmBars1mError>
|
||||||
where
|
where
|
||||||
R: io::Read,
|
R: io::Read,
|
||||||
W: Write + Send,
|
W: Write + Send,
|
||||||
|
|
@ -306,10 +318,12 @@ where
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut intraday_decode = BsonQmIntradayDecodeStats::default();
|
let mut intraday_decode = BsonQmIntradayDecodeStats::default();
|
||||||
let mut curate_stats = CurateBars1mStats::default();
|
|
||||||
let mut chunks: usize = 0;
|
let mut chunks: usize = 0;
|
||||||
let mut max_rows_per_chunk: 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) =
|
while let Some(chunk) =
|
||||||
reader
|
reader
|
||||||
|
|
@ -320,51 +334,66 @@ where
|
||||||
source,
|
source,
|
||||||
})?
|
})?
|
||||||
{
|
{
|
||||||
let mut chunk_bars: Vec<EodIntradayBar<&str>> = Vec::new();
|
let mut chunk_rows = 0usize;
|
||||||
|
let mut spill_err: Option<Bars1mExternalSortError> = None;
|
||||||
|
|
||||||
let chunk_decode = decode_qm_intraday_buffer(
|
let chunk_decode = decode_qm_intraday_buffer(
|
||||||
chunk.bytes,
|
chunk.bytes,
|
||||||
|raw| {
|
|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| {},
|
|_local_offset, _err| {},
|
||||||
);
|
);
|
||||||
|
if let Some(err) = spill_err {
|
||||||
|
return Err(map_sort_error(err));
|
||||||
|
}
|
||||||
intraday_decode.merge(&chunk_decode);
|
intraday_decode.merge(&chunk_decode);
|
||||||
|
|
||||||
chunks += 1;
|
chunks += 1;
|
||||||
let chunk_len = chunk_bars.len();
|
if chunk_rows > max_rows_per_chunk {
|
||||||
if chunk_len > max_rows_per_chunk {
|
max_rows_per_chunk = chunk_rows;
|
||||||
max_rows_per_chunk = chunk_len;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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_docs_framed = reader.docs_framed();
|
||||||
let intraday_bytes_read = reader.bytes_read();
|
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)?;
|
let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?;
|
||||||
|
|
||||||
Ok(CurateQmBars1mRunReport {
|
Ok((
|
||||||
intraday_docs_framed,
|
CurateQmBars1mRunReport {
|
||||||
intraday_bytes_read,
|
intraday_docs_framed,
|
||||||
intraday_decode,
|
intraday_bytes_read,
|
||||||
chunks,
|
intraday_decode,
|
||||||
max_rows_per_chunk,
|
chunks,
|
||||||
curate_stats,
|
max_rows_per_chunk,
|
||||||
rows_written,
|
curate_stats: write_report.curate_stats,
|
||||||
ilp_stats,
|
rows_written: write_report.rows_written,
|
||||||
shard_count: args.shard_count,
|
ilp_stats,
|
||||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
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
|
/// 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,
|
/// 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
|
/// 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
|
/// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through
|
||||||
/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once
|
/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`] into the bounded-memory
|
||||||
/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once
|
/// external sorter/merger without split un-adjustment, and calls [`IlpShardedWriter::finish`]
|
||||||
/// after clean EOF.
|
/// exactly once after clean EOF.
|
||||||
pub fn run_curate_qm_bars_1m_with_readers<R, W, F>(
|
pub fn run_curate_qm_bars_1m_with_readers<R, W, F>(
|
||||||
args: &CurateQmBars1mArgs,
|
args: &CurateQmBars1mArgs,
|
||||||
intraday: R,
|
intraday: R,
|
||||||
|
|
@ -398,7 +427,10 @@ where
|
||||||
let writer =
|
let writer =
|
||||||
IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?;
|
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<RF>(
|
fn fail_with_staging_cleanup<RF>(
|
||||||
|
|
@ -493,9 +525,16 @@ where
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
|
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(
|
||||||
Ok(report) => report,
|
args,
|
||||||
|
&mapping,
|
||||||
|
intraday,
|
||||||
|
writer,
|
||||||
|
sort_config,
|
||||||
|
start,
|
||||||
|
) {
|
||||||
|
Ok(pair) => pair,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
return Err(fail_with_staging_cleanup(
|
return Err(fail_with_staging_cleanup(
|
||||||
err,
|
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 `<out_dir>/bars_1m_qm.shard-<NN>.ilp`,
|
||||||
|
/// and rollback cleanup on failure with zero intermediate `.bson` scratch files.
|
||||||
|
pub fn run_curate_qm_bars_1m_from_reader_to_dir<R>(
|
||||||
|
args: &CurateQmBars1mArgs,
|
||||||
|
intraday: R,
|
||||||
|
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||||
|
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<R>(
|
||||||
|
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<SyncedBufFile> = 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
|
/// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing
|
||||||
/// exactly `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`).
|
/// exactly `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`).
|
||||||
pub fn run_curate_qm_bars_1m(
|
pub fn run_curate_qm_bars_1m(
|
||||||
|
|
@ -558,12 +703,7 @@ pub fn run_curate_qm_bars_1m(
|
||||||
source,
|
source,
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
run_curate_qm_bars_1m_to_dir_with_hooks(
|
run_curate_qm_bars_1m_from_reader_to_dir(args, intraday_file)
|
||||||
args,
|
|
||||||
intraday_file,
|
|
||||||
|_shard_idx, file| SyncedBufFile::new(file),
|
|
||||||
|_shard_idx, _final_path| {},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ use bson::DateTime as BsonDateTime;
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::bars_1m::{IntradaySession, BARS_1M_SOURCE_QM};
|
use crate::bars_1m::{IntradaySession, BARS_1M_SOURCE_QM};
|
||||||
use crate::bson_stream::MIN_BSON_DOC_BYTES;
|
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::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M};
|
||||||
use crate::run_curate_bars_1m::tests::TempDirGuard;
|
use crate::run_curate_bars_1m::tests::TempDirGuard;
|
||||||
use crate::shorts::et_to_utc_micros;
|
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.curate_stats.post_rows_out, 1);
|
||||||
assert_eq!(report.rows_written, 3);
|
assert_eq!(report.rows_written, 3);
|
||||||
|
|
||||||
// Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks emits both
|
// Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks collapses
|
||||||
// rows (relying on QuestDB DEDUP UPSERT KEYS(ts, listing_id)) and sums listings_out/keys_out.
|
// 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 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 doc_len = dup_doc.as_bytes().len();
|
||||||
let cross_chunk_bytes = concat_docs(&[dup_doc.clone(), dup_doc]);
|
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");
|
.expect("cross-chunk duplicate run should succeed");
|
||||||
assert_report_conservation(&cross_report);
|
assert_report_conservation(&cross_report);
|
||||||
assert_eq!(cross_report.chunks, 2);
|
assert_eq!(cross_report.chunks, 2);
|
||||||
assert_eq!(cross_report.rows_written, 2);
|
assert_eq!(cross_report.rows_written, 1);
|
||||||
assert_eq!(cross_report.curate_stats.listings_out, 2);
|
assert_eq!(cross_report.curate_stats.builder.duplicate_collapsed, 1);
|
||||||
assert_eq!(cross_report.curate_stats.builder.keys_out, 2);
|
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());
|
let emitted = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap());
|
||||||
assert_eq!(emitted.len(), 2);
|
assert_eq!(emitted.len(), 1);
|
||||||
assert_eq!(emitted[0], emitted[1]);
|
assert_eq!(emitted[0].listing_id, 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -1537,7 +1539,7 @@ fn file_mode_single_chunk_shards_match_pure_stage_byte_for_byte() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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 dir = TempDirGuard::new("qm-bars1m-qa-chunk-bytes");
|
||||||
let mapping_path = write_mapping_tsv(
|
let mapping_path = write_mapping_tsv(
|
||||||
dir.path(),
|
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.chunks, 6);
|
||||||
assert_eq!(report.max_rows_per_chunk, 1);
|
assert_eq!(report.max_rows_per_chunk, 1);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
report.curate_stats.listings_out, 6,
|
report.curate_stats.listings_out, 2,
|
||||||
"per-chunk sum, not distinct"
|
"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 mapping = load_provider_mapping_table(&mapping_path).unwrap();
|
||||||
let chunks: Vec<&[u8]> = bytes.chunks(doc_len).collect();
|
|
||||||
let expected = pure_stage_shard_bytes(
|
let expected = pure_stage_shard_bytes(
|
||||||
&chunks,
|
&[bytes.as_slice()],
|
||||||
&mapping,
|
&mapping,
|
||||||
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
|
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
|
||||||
2,
|
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());
|
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"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -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`])
|
//! Uses [`ReadOnlyMongoClient`] (constructed strictly from [`crate::ValidatedReadOnlyMongoUri`])
|
||||||
//! to open zero-copy raw-BSON cursors over allowlisted [`SourceCollection`]s and feeds them
|
//! 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.
|
//! scratch files.
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit};
|
||||||
use crate::bson_ceo_shorts::CeoShortsFieldNames;
|
use crate::bson_ceo_shorts::CeoShortsFieldNames;
|
||||||
use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames};
|
use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames};
|
||||||
|
use crate::bson_stream::BsonStreamOptions;
|
||||||
use crate::curate_adj::AdjPointInTimeFence;
|
use crate::curate_adj::AdjPointInTimeFence;
|
||||||
|
use crate::ilp::IlpWriterOptions;
|
||||||
use crate::mongo_stream::{
|
use crate::mongo_stream::{
|
||||||
MongoCliOptions, MongoReadSpec, MongoStreamError, ReadOnlyMongoClient, SourceCollection,
|
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,
|
load_provider_mapping_tsv, run_curate_bars_1d_with_readers, CurateBars1dRunReport,
|
||||||
RunCurateBarsError,
|
RunCurateBarsError,
|
||||||
};
|
};
|
||||||
|
use crate::run_curate_bars_1m::{
|
||||||
|
run_curate_bars_1m_from_readers_to_dir, CurateBars1mArgs, CurateBars1mRunReport,
|
||||||
|
RunCurateBars1mError,
|
||||||
|
};
|
||||||
use crate::run_curate_corporate_actions::{
|
use crate::run_curate_corporate_actions::{
|
||||||
run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport,
|
run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport,
|
||||||
RunCurateCorporateActionsError,
|
RunCurateCorporateActionsError,
|
||||||
|
|
@ -30,9 +38,27 @@ use crate::run_curate_corporate_actions::{
|
||||||
use crate::run_curate_events::{
|
use crate::run_curate_events::{
|
||||||
run_curate_events_with_readers, CurateEventsRunReport, RunCurateEventsError,
|
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::{
|
use crate::run_curate_fx::{
|
||||||
run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE,
|
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::{
|
use crate::run_curate_shorts::{
|
||||||
run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError,
|
run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError,
|
||||||
};
|
};
|
||||||
|
|
@ -47,6 +73,12 @@ pub enum RunMongoCurateError {
|
||||||
Fx(RunCurateFxError),
|
Fx(RunCurateFxError),
|
||||||
Shorts(RunCurateShortsError),
|
Shorts(RunCurateShortsError),
|
||||||
Events(RunCurateEventsError),
|
Events(RunCurateEventsError),
|
||||||
|
Fundamentals(RunCurateFundamentalsError),
|
||||||
|
Posts(RunCuratePostsError),
|
||||||
|
Macro(RunCurateMacroError),
|
||||||
|
Bars1m(RunCurateBars1mError),
|
||||||
|
QmBars1m(RunCurateQmBars1mError),
|
||||||
|
Fx1m(RunCurateFx1mError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for RunMongoCurateError {
|
impl fmt::Display for RunMongoCurateError {
|
||||||
|
|
@ -59,6 +91,12 @@ impl fmt::Display for RunMongoCurateError {
|
||||||
Self::Fx(e) => write!(f, "{e}"),
|
Self::Fx(e) => write!(f, "{e}"),
|
||||||
Self::Shorts(e) => write!(f, "{e}"),
|
Self::Shorts(e) => write!(f, "{e}"),
|
||||||
Self::Events(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::Fx(e) => Some(e),
|
||||||
Self::Shorts(e) => Some(e),
|
Self::Shorts(e) => Some(e),
|
||||||
Self::Events(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,
|
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<String>,
|
||||||
|
pub financials_net_income_field: Option<String>,
|
||||||
|
pub financials_operating_cash_flow_field: Option<String>,
|
||||||
|
pub financials_total_assets_field: Option<String>,
|
||||||
|
pub financials_total_equity_field: Option<String>,
|
||||||
|
pub financials_shares_outstanding_field: Option<String>,
|
||||||
|
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<String>,
|
||||||
|
pub filings_url_field: Option<String>,
|
||||||
|
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 {
|
fn mongo_virtual_path(collection: SourceCollection) -> PathBuf {
|
||||||
PathBuf::from(format!("mongodb://{}", collection.as_str()))
|
PathBuf::from(format!("mongodb://{}", collection.as_str()))
|
||||||
}
|
}
|
||||||
|
|
@ -165,6 +378,20 @@ fn connect_and_validate_specs(
|
||||||
mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo)
|
mongo.uri_source.connect().map_err(RunMongoCurateError::Mongo)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn with_mongo_client<T, F>(
|
||||||
|
mongo: &MongoCliOptions,
|
||||||
|
checks: &[(SourceCollection, MongoReadSpec)],
|
||||||
|
f: F,
|
||||||
|
) -> Result<T, RunMongoCurateError>
|
||||||
|
where
|
||||||
|
F: FnOnce(&ReadOnlyMongoClient) -> Result<T, RunMongoCurateError>,
|
||||||
|
{
|
||||||
|
let client = connect_and_validate_specs(mongo, checks)?;
|
||||||
|
let result = f(&client);
|
||||||
|
client.shutdown();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
fn unique_mapping_keys_for_source(
|
fn unique_mapping_keys_for_source(
|
||||||
provider_mapping_path: &Path,
|
provider_mapping_path: &Path,
|
||||||
source: &str,
|
source: &str,
|
||||||
|
|
@ -496,8 +723,326 @@ pub fn run_curate_events_mongo(
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn fundamentals_read_specs(
|
||||||
|
args: &CurateFundamentalsMongoArgs,
|
||||||
|
) -> (MongoReadSpec, Option<MongoReadSpec>, 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<RF: io::Read, RO: io::Read, RL: io::Read>(
|
||||||
|
args: &CurateFundamentalsMongoArgs,
|
||||||
|
financials_reader: RF,
|
||||||
|
financials_old_reader: Option<RO>,
|
||||||
|
filings_reader: RL,
|
||||||
|
) -> Result<CurateFundamentalsRunReport, RunMongoCurateError> {
|
||||||
|
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<CurateFundamentalsRunReport, RunMongoCurateError> {
|
||||||
|
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<R: io::Read>(
|
||||||
|
args: &CuratePostsMongoArgs,
|
||||||
|
posts_reader: R,
|
||||||
|
) -> Result<CuratePostsRunReport, RunMongoCurateError> {
|
||||||
|
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<CuratePostsRunReport, RunMongoCurateError> {
|
||||||
|
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<R: io::Read>(
|
||||||
|
args: &CurateMacroMongoArgs,
|
||||||
|
te_data_reader: R,
|
||||||
|
) -> Result<CurateMacroRunReport, RunMongoCurateError> {
|
||||||
|
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<CurateMacroRunReport, RunMongoCurateError> {
|
||||||
|
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<RI: io::Read, RS: io::Read>(
|
||||||
|
args: &CurateBars1mMongoArgs,
|
||||||
|
intraday_reader: RI,
|
||||||
|
splits_reader: RS,
|
||||||
|
) -> Result<CurateBars1mRunReport, RunMongoCurateError> {
|
||||||
|
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
|
||||||
|
/// `<out_dir>/bars_1m.shard-<NN>.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<CurateBars1mRunReport, RunMongoCurateError> {
|
||||||
|
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<R: io::Read>(
|
||||||
|
args: &CurateQmBars1mMongoArgs,
|
||||||
|
intraday_reader: R,
|
||||||
|
) -> Result<CurateQmBars1mRunReport, RunMongoCurateError> {
|
||||||
|
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
|
||||||
|
/// `<out_dir>/bars_1m_qm.shard-<NN>.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<CurateQmBars1mRunReport, RunMongoCurateError> {
|
||||||
|
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<R: io::Read>(
|
||||||
|
args: &CurateFx1mMongoArgs,
|
||||||
|
intraday_reader: R,
|
||||||
|
) -> Result<CurateFx1mRunReport, RunMongoCurateError> {
|
||||||
|
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
|
||||||
|
/// `<out_dir>/fx_1m.shard-<NN>.ilp`.
|
||||||
|
pub fn run_curate_fx_1m_mongo(
|
||||||
|
args: &CurateFx1mMongoArgs,
|
||||||
|
) -> Result<CurateFx1mRunReport, RunMongoCurateError> {
|
||||||
|
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).
|
/// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly).
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn _assert_path_ref(path: &Path) -> &Path {
|
fn _assert_path_ref(path: &Path) -> &Path {
|
||||||
path
|
path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "run_mongo_tests.rs"]
|
||||||
|
mod tests;
|
||||||
|
|
|
||||||
1823
tools/curate-etl/src/run_mongo_tests.rs
Normal file
1823
tools/curate-etl/src/run_mongo_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -619,7 +619,10 @@ fn curate_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothin
|
||||||
assert!(!output.status.success());
|
assert!(!output.status.success());
|
||||||
assert!(output.stdout.is_empty());
|
assert!(output.stdout.is_empty());
|
||||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
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("curate-bars-1m --eod-intraday"), "usage expected: {stderr}");
|
||||||
assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}");
|
assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}");
|
||||||
assert!(!out.exists(), "parse failure must not create --out");
|
assert!(!out.exists(), "parse failure must not create --out");
|
||||||
|
|
|
||||||
|
|
@ -493,7 +493,7 @@ fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() {
|
||||||
let mut lines_mongo = stderr_mongo.lines();
|
let mut lines_mongo = stderr_mongo.lines();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
lines_mongo.next(),
|
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_eq!(lines_mongo.next(), Some("Usage:"));
|
||||||
assert!(
|
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"],
|
&["--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"],
|
&["--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/<gen> + 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");
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -430,7 +430,7 @@ fn cli_invalid_flags_print_error_and_usage_without_touching_out() {
|
||||||
"--out",
|
"--out",
|
||||||
"out_from_mongo",
|
"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 (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
|
||||||
let cli_out = dir.0.join("cli_out");
|
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()
|
let result = cli()
|
||||||
.arg("--te-data")
|
.arg("--te-data")
|
||||||
.arg(&te_data_path)
|
.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:?}");
|
assert!(result.stdout.is_empty(), "{result:?}");
|
||||||
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
|
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
|
||||||
assert!(
|
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:?}"
|
"{stderr:?}"
|
||||||
);
|
);
|
||||||
assert!(stderr.contains("Usage:"), "{stderr:?}");
|
assert!(stderr.contains("Usage:"), "{stderr:?}");
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,9 @@ use parquet::record::RowAccessor;
|
||||||
|
|
||||||
const POSTED: i64 = 1_718_460_000;
|
const POSTED: i64 = 1_718_460_000;
|
||||||
const EDITED: i64 = POSTED + 3_600;
|
const EDITED: i64 = POSTED + 3_600;
|
||||||
const PARTITION: &str = "events/year=2024/part.parquet";
|
const PARTITION: &str = "events/year=2024/part-posts.parquet";
|
||||||
const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\n";
|
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] = &[
|
const CUSTOM_FLAGS: &[&str] = &[
|
||||||
"--key-field=channel",
|
"--key-field=channel",
|
||||||
"--spiel-id-field=id",
|
"--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");
|
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]
|
#[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.
|
// 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()));
|
let path = std::env::temp_dir().join(format!("curate-posts-cli-{}", std::process::id()));
|
||||||
fs::create_dir(&path).expect("create isolated test directory");
|
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_int(0).unwrap(), listing);
|
||||||
assert_eq!(row.get_timestamp_micros(1).unwrap(), POSTED * 1_000_000);
|
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_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);
|
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 - 1));
|
||||||
assert!(edited_text_visible(EDITED * 1_000_000));
|
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");
|
write_posts(&bson, 1_000, "replacement");
|
||||||
let retry = curate(&dir.0, "millis", "millis");
|
let retry = curate(&dir.0, "millis", "millis");
|
||||||
assert_eq!(retry.status.code(), Some(1));
|
assert!(retry.status.success(), "curate-posts rerun: {:?}", retry);
|
||||||
assert!(retry.stdout.is_empty());
|
assert!(retry.stderr.is_empty());
|
||||||
assert!(String::from_utf8_lossy(&retry.stderr)
|
assert_eq!(fs::read(&events_part).unwrap(), events_bytes);
|
||||||
.starts_with("error: refusing to overwrite existing events partition"));
|
let rerun_reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap();
|
||||||
assert_eq!(fs::read(partition).unwrap(), baseline);
|
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]
|
#[test]
|
||||||
fn cli_reports_usage_for_invalid_posts_flags() {
|
fn cli_reports_usage_for_invalid_posts_flags() {
|
||||||
for (args, error) in [
|
for (args, error) in [
|
||||||
(
|
(
|
||||||
&["--from-mongo"][..],
|
&["--from-mongo", "--ceo-posts", "p.bson"][..],
|
||||||
"unknown flag '--from-mongo' for curate-posts",
|
"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"][..],
|
&["--timestamp-unit", "--out=x"][..],
|
||||||
|
|
|
||||||
|
|
@ -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.status.success());
|
||||||
assert!(output.stdout.is_empty());
|
assert!(output.stdout.is_empty());
|
||||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
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!(
|
assert!(
|
||||||
stderr.contains("curate-qm-bars-1m --qm-intraday"),
|
stderr.contains("curate-qm-bars-1m --qm-intraday"),
|
||||||
"usage expected: {stderr}"
|
"usage expected: {stderr}"
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue