Merge branch 'dev' into feat/corp-actions-curate-stage
# Conflicts: # tools/curate-etl/README.md # tools/curate-etl/src/bench.rs # tools/curate-etl/src/cli.rs # tools/curate-etl/src/lib.rs # tools/curate-etl/src/main.rs
This commit is contained in:
commit
11ff35054c
31 changed files with 17618 additions and 75 deletions
|
|
@ -64,6 +64,21 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/sto
|
|||
- **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside inclusive `[1 - 0.02, 1 + 0.02]`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`.
|
||||
- **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload.
|
||||
|
||||
## Pass 4a Sample-Close & USD/CAD Reader (`sample-closes.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/sample-closes.ts` provides the read-only MongoDB reader (`buildSampleCloseFilter`, `readSampleCloses`) that streams cross-sectional sample closes from `eodPrices`, `qmPrices`, and `CAD.FOREX` into `SampleCloseRecord[]` and `FxRateByDateRecord[]` for `crossCheckPrices`:
|
||||
|
||||
- **Date storage finding & `$in` type:** `eodPrices` (`apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts`) explicitly enforces and persists `date` as an exact `YYYY-MM-DD` string. `qmPrices` (`apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts`) copies the provider's `price.date` field verbatim and derives a BSON `Date` separately in `dateTime`, so exact `YYYY-MM-DD` formatting on `qmPrices.date` is an assumption based on the QuoteMedia payload until verified against live QA MongoDB or a captured provider fixture. Keeping the approved string query, `buildSampleCloseFilter` emits date-first `{ date: { $in: string[] } }` filters (sorted `YYYY-MM-DD` strings, aligning with `BAR_SPAN_COLLECTIONS` in `src/normalization/bar-spans.ts` and `design/DATA-CONTRACTS.md`) so queries use `{ date: 1, eodSearchCode: 1 }` and `{ qmSearchCode: 1, date: 1 }`. On decode, both `Date` instances and string dates are normalized to UTC `YYYY-MM-DD` via `normalizeBarDate`; because any format or BSON-type mismatch on `date` would exclude rows before decode, row counts should be verified on the first live read-only Pass 4 run.
|
||||
- **Read-only streaming, raw prices, and FX isolation:** Uses `ReadOnlySourceSymbolReader` (rejecting non-read-only readers before any `find` and rejecting buffered array results with `TypeError`), closes cursors in `finally` on success and error, projects only `_id: 0`, id, `date`, and raw `close` (`eodPrices` / `CAD.FOREX`) or raw `unadjustedclose` (`qmPrices` — never `close` or `adjustedclose`), strips `CAD.FOREX` from equity reads so FX never leaks into `closes`, preserves untrimmed non-blank IDs (T-49), chunks large ID sets (`idChunkSize`, default `10,000`), skips empty sources (`findsRun: 0`), and reconciles `docsRead === emitted + skippedTotal` per source.
|
||||
- **Local synthetic benchmark (zero MongoDB):** Run the headless 500,025-doc streaming benchmark with:
|
||||
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts
|
||||
```
|
||||
|
||||
- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):**
|
||||
- Workload: `500,025` synthetic docs (`25` sample dates × `20,000` IDs split `10,000` `eodPrices` + `10,000` `qmPrices`, plus `25` `CAD.FOREX` FX docs).
|
||||
- Observed throughput: `2,627,752 docs/s` (`190.3 ms` elapsed, `25.36 MiB` heap delta).
|
||||
|
||||
## Security Master Persistence (`persistSecurityMaster`)
|
||||
`apps/stock/data-pipeline/src/security-master/persist.ts` persists in-memory Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 (`delisting-chains`) results into the `master` track PostgreSQL tables inside a single transaction guarded by `pg_advisory_xact_lock(0x534d5053, hashtext(current_schema()))`:
|
||||
|
||||
|
|
@ -191,3 +206,27 @@ All four files are deterministic and byte-identical for identical inputs (no wal
|
|||
- `conflicts.csv` — Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6.
|
||||
- `override-template.sql` — Commented SQL template for director-reviewed `override` entries.
|
||||
- `run-stats.json` — Canonical ASCII-key-sorted JSON summary of exchange, reader, security-type, bar-span, composer, and report stats (`pass4Wired: false`).
|
||||
|
||||
## Read-Only Source Field-Shape Probe (`source-field-shapes.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` and its CLI `probe-source-field-shapes.ts` sample raw MongoDB collections read-only to report exact field names, BSON/JS value types (`string`, `int`, `double`, `bool`, `date`, `null`, `objectId`, `array`, `object`, `other`), one-level nested `parent.child` keys, string pattern classes (`ymd`, `isoDatetime`, `numeric`, `emptyOrWhitespace`, `other`), and bounded sanitized examples (never emitted for `_id` / `_id.*`).
|
||||
|
||||
- **Bounded read-only contract:** Initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`), refuses non-read-only readers before issuing any query, and runs strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` (default `limit = 1,000`, max `10,000`) over allowlisted collections (`ceoShorts`, `qmSplits`, `qmDividends`, `qmFilings`, `qmEarnings`, `qmPrices`, `eodPrices`, `teMarketData`) — no aggregations, no `$sample`, no writes, and no index operations.
|
||||
- **Host live-run command (read-only QA MongoDB):**
|
||||
|
||||
```bash
|
||||
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
|
||||
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts \
|
||||
--out ./tmp/source-field-shapes.md \
|
||||
--limit 1000
|
||||
```
|
||||
|
||||
- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 80,000-doc streaming benchmark (`8` collections × `10,000` limit) with:
|
||||
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
|
||||
```
|
||||
|
||||
- **Recorded baselines (`2026-11-28`, local sandbox, in-memory async cursor fake reader):**
|
||||
- Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`.
|
||||
- Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta).
|
||||
- After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,358 @@
|
|||
/**
|
||||
* Reproducible headless benchmark for Pass 4b `runSecurityMaster` end-to-end wiring.
|
||||
* Streams 20,000 EOD<->QM candidate pairs x 25 sample dates (1,000,025 sample-close/FX docs)
|
||||
* through in-memory async-generator fake readers with zero database or disk writes.
|
||||
*
|
||||
* Usage:
|
||||
* bun run apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts
|
||||
*/
|
||||
|
||||
import type {
|
||||
BarSpanAggregateReader,
|
||||
GroupedBarSpanRow,
|
||||
} from '../src/normalization/bar-spans';
|
||||
import {
|
||||
FX_USD_CAD_SOURCE_ID,
|
||||
runSecurityMaster,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
} from '../src/security-master';
|
||||
|
||||
const PAIR_COUNT = 20_000;
|
||||
const SAMPLE_DATE_COUNT = 25;
|
||||
const MISMATCH_EVERY = 200; // 100 ratio_mismatch pairs, 19,900 confirmed pairs
|
||||
const AS_OF_DATE = '2026-01-15';
|
||||
const FIRST_BAR_DATE = '2020-01-02';
|
||||
const LAST_BAR_DATE = '2026-01-14';
|
||||
|
||||
function computeIsinCheckDigit(isinBody11: string): string {
|
||||
let digits = '';
|
||||
for (let i = 0; i < isinBody11.length; i++) {
|
||||
const code = isinBody11.charCodeAt(i);
|
||||
if (code >= 65 && code <= 90) {
|
||||
digits += String(code - 55);
|
||||
} else {
|
||||
digits += isinBody11[i] ?? '';
|
||||
}
|
||||
}
|
||||
let sum = 0;
|
||||
let doubleDigit = true;
|
||||
for (let i = digits.length - 1; i >= 0; i--) {
|
||||
let val = digits.charCodeAt(i) - 48;
|
||||
if (doubleDigit) {
|
||||
val *= 2;
|
||||
if (val > 9) {
|
||||
val -= 9;
|
||||
}
|
||||
}
|
||||
sum += val;
|
||||
doubleDigit = !doubleDigit;
|
||||
}
|
||||
return String((10 - (sum % 10)) % 10);
|
||||
}
|
||||
|
||||
function makeSyntheticIsin(index: number): string {
|
||||
const body = `US${String(100_000_000 + index).padStart(9, '0')}`;
|
||||
return `${body}${computeIsinCheckDigit(body)}`;
|
||||
}
|
||||
|
||||
function makePureLetterTicker(index: number): string {
|
||||
let n = index;
|
||||
const c3 = String.fromCharCode(65 + (n % 26));
|
||||
n = Math.floor(n / 26);
|
||||
const c2 = String.fromCharCode(65 + (n % 26));
|
||||
n = Math.floor(n / 26);
|
||||
const c1 = String.fromCharCode(65 + (n % 26));
|
||||
n = Math.floor(n / 26);
|
||||
const c0 = String.fromCharCode(65 + (n % 26));
|
||||
return `${c0}${c1}${c2}${c3}`;
|
||||
}
|
||||
|
||||
function deterministicClose(pairIndex: number, dateIndex: number): number {
|
||||
// Deterministic non-constant trajectory per pair so log-return variance is strictly positive.
|
||||
const base = 20 + (pairIndex % 180);
|
||||
const wave = ((pairIndex * 31 + dateIndex * 17) % 37) * 0.45;
|
||||
const trend = dateIndex * (0.35 + (pairIndex % 7) * 0.05);
|
||||
return Number((base + wave + trend).toFixed(4));
|
||||
}
|
||||
|
||||
function createBenchmarkMongo(pairCount: number): {
|
||||
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
|
||||
readonly barSpanReader: BarSpanAggregateReader;
|
||||
} {
|
||||
const tickers = new Array<string>(pairCount);
|
||||
const isins = new Array<string>(pairCount);
|
||||
const eodIndexById = new Map<string, number>();
|
||||
const qmIndexById = new Map<string, number>();
|
||||
|
||||
for (let i = 0; i < pairCount; i++) {
|
||||
const ticker = makePureLetterTicker(i);
|
||||
tickers[i] = ticker;
|
||||
isins[i] = makeSyntheticIsin(i);
|
||||
eodIndexById.set(`${ticker}.US`, i);
|
||||
qmIndexById.set(`${ticker}:US`, i);
|
||||
}
|
||||
|
||||
const eodExchanges = [
|
||||
{ Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' },
|
||||
];
|
||||
const ibExchanges = [{ exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' }];
|
||||
const qmExchanges = [{ exchange: 'NSD', country: 'US', currency: 'USD' }];
|
||||
|
||||
const mongoCollectionClient: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly(): boolean {
|
||||
return true;
|
||||
},
|
||||
getCollection(collectionName: string) {
|
||||
return {
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
filter: Record<string, unknown> = {}
|
||||
) {
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
if (collectionName === 'eodExchanges') {
|
||||
for (const doc of eodExchanges) {
|
||||
yield doc as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (collectionName === 'ibExchanges') {
|
||||
for (const doc of ibExchanges) {
|
||||
yield doc as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (collectionName === 'qmExchanges') {
|
||||
for (const doc of qmExchanges) {
|
||||
yield doc as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
collectionName === 'ceoExchanges' ||
|
||||
collectionName === 'ibSymbols' ||
|
||||
collectionName === 'ceoSymbols' ||
|
||||
collectionName === 'eodSymbolChange'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (collectionName === 'eodSymbols') {
|
||||
for (let i = 0; i < pairCount; i++) {
|
||||
const ticker = tickers[i];
|
||||
const isin = isins[i];
|
||||
if (ticker === undefined || isin === undefined) {
|
||||
continue;
|
||||
}
|
||||
yield {
|
||||
eodSearchCode: `${ticker}.US`,
|
||||
Code: ticker,
|
||||
Exchange: 'NASDAQ',
|
||||
Country: 'USA',
|
||||
Currency: 'USD',
|
||||
Isin: isin,
|
||||
Name: `Bench Corp ${ticker}`,
|
||||
Type: 'Common Stock',
|
||||
delisted: false,
|
||||
} as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (collectionName === 'qmSymbols') {
|
||||
for (let i = 0; i < pairCount; i++) {
|
||||
const ticker = tickers[i];
|
||||
if (ticker === undefined) {
|
||||
continue;
|
||||
}
|
||||
yield {
|
||||
qmSearchCode: `${ticker}:US`,
|
||||
symbol: ticker,
|
||||
exchange: 'NSD',
|
||||
countryCode: 'US',
|
||||
currency: 'USD',
|
||||
name: `Bench Corp ${ticker}`,
|
||||
active: true,
|
||||
} as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const dates = ((filter.date as { $in?: string[] } | undefined)?.$in ?? []) as string[];
|
||||
if (collectionName === 'eodPrices') {
|
||||
const ids =
|
||||
((filter.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[];
|
||||
if (ids.length === 1 && ids[0] === FX_USD_CAD_SOURCE_ID) {
|
||||
for (let d = 0; d < dates.length; d++) {
|
||||
yield {
|
||||
eodSearchCode: FX_USD_CAD_SOURCE_ID,
|
||||
date: dates[d],
|
||||
close: Number((1.34 + (d % 7) * 0.005).toFixed(4)),
|
||||
} as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let d = 0; d < dates.length; d++) {
|
||||
const date = dates[d];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const id = ids[i];
|
||||
if (id === undefined) {
|
||||
continue;
|
||||
}
|
||||
const idx = eodIndexById.get(id);
|
||||
if (idx === undefined) {
|
||||
continue;
|
||||
}
|
||||
yield {
|
||||
eodSearchCode: id,
|
||||
date,
|
||||
close: deterministicClose(idx, d),
|
||||
} as unknown as T;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (collectionName === 'qmPrices') {
|
||||
const ids =
|
||||
((filter.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[];
|
||||
for (let d = 0; d < dates.length; d++) {
|
||||
const date = dates[d];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const id = ids[i];
|
||||
if (id === undefined) {
|
||||
continue;
|
||||
}
|
||||
const idx = qmIndexById.get(id);
|
||||
if (idx === undefined) {
|
||||
continue;
|
||||
}
|
||||
const baseClose = deterministicClose(idx, d);
|
||||
const mult = idx % MISMATCH_EVERY === 0 ? 2 : 1;
|
||||
yield {
|
||||
qmSearchCode: id,
|
||||
date,
|
||||
unadjustedclose: Number((baseClose * mult).toFixed(4)),
|
||||
} as unknown as T;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
// No-op for in-memory benchmark cursor.
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const barSpanReader: BarSpanAggregateReader = {
|
||||
aggregate<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
pipeline: Record<string, unknown>[]
|
||||
): AsyncIterable<T> {
|
||||
let requestedIds: string[] = [];
|
||||
for (const stage of pipeline) {
|
||||
const match = stage.$match as Record<string, unknown> | undefined;
|
||||
if (match && typeof match === 'object') {
|
||||
for (const value of Object.values(match)) {
|
||||
if (
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
Array.isArray((value as { $in?: unknown }).$in)
|
||||
) {
|
||||
requestedIds = (value as { $in: string[] }).$in;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const isEod = collectionName === 'eodPrices';
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (let i = 0; i < requestedIds.length; i++) {
|
||||
const id = requestedIds[i];
|
||||
if (id === undefined) {
|
||||
continue;
|
||||
}
|
||||
const exists = isEod ? eodIndexById.has(id) : qmIndexById.has(id);
|
||||
if (!exists) {
|
||||
continue;
|
||||
}
|
||||
const row: GroupedBarSpanRow = {
|
||||
_id: id,
|
||||
firstBarDate: FIRST_BAR_DATE,
|
||||
lastBarDate: LAST_BAR_DATE,
|
||||
barCount: 1510,
|
||||
};
|
||||
yield row as unknown as T;
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return { mongoCollectionClient, barSpanReader };
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { mongoCollectionClient, barSpanReader } = createBenchmarkMongo(PAIR_COUNT);
|
||||
|
||||
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
|
||||
Bun.gc(true);
|
||||
}
|
||||
const heapBefore = process.memoryUsage().heapUsed;
|
||||
const startedAt = performance.now();
|
||||
|
||||
const result = await runSecurityMaster(
|
||||
{
|
||||
mongoCollectionClient,
|
||||
barSpanReader,
|
||||
writeFile: () => {},
|
||||
writeStdout: () => {},
|
||||
},
|
||||
{
|
||||
asOfDate: AS_OF_DATE,
|
||||
outDir: '/virtual/benchmark-out',
|
||||
batchSize: 5_000,
|
||||
pass4: { enabled: true, sampleDateCount: SAMPLE_DATE_COUNT },
|
||||
}
|
||||
);
|
||||
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
const heapAfter = process.memoryUsage().heapUsed;
|
||||
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
|
||||
|
||||
if (result.composed.pass4 === null || result.sampleCloses === null) {
|
||||
throw new Error('Benchmark failed: Pass 4 did not execute');
|
||||
}
|
||||
|
||||
const expectedMismatches = Math.ceil(PAIR_COUNT / MISMATCH_EVERY);
|
||||
const expectedConfirmed = PAIR_COUNT - expectedMismatches;
|
||||
const { pairsIn, byVerdict } = result.composed.pass4.stats;
|
||||
if (
|
||||
pairsIn !== PAIR_COUNT ||
|
||||
byVerdict.confirmed !== expectedConfirmed ||
|
||||
byVerdict.ratio_mismatch !== expectedMismatches
|
||||
) {
|
||||
throw new Error(
|
||||
`Benchmark verdict mismatch: pairsIn=${pairsIn}, confirmed=${byVerdict.confirmed} (expected ${expectedConfirmed}), ratio_mismatch=${byVerdict.ratio_mismatch} (expected ${expectedMismatches})`
|
||||
);
|
||||
}
|
||||
|
||||
const totalDocsRead =
|
||||
result.sampleCloses.stats.eod.docsRead +
|
||||
result.sampleCloses.stats.qm.docsRead +
|
||||
result.sampleCloses.stats.fx.docsRead;
|
||||
const pairsPerSec = Math.round(PAIR_COUNT / (elapsedMs / 1000));
|
||||
const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000));
|
||||
|
||||
const lines = [
|
||||
'Pass 4b runSecurityMaster benchmark (in-memory async cursor, zero DB, zero disk)',
|
||||
` Workload: ${PAIR_COUNT.toLocaleString('en-US')} EOD<->QM pairs x ${SAMPLE_DATE_COUNT} dates (${totalDocsRead.toLocaleString('en-US')} sample-close/FX docs)`,
|
||||
` Verdicts: confirmed=${byVerdict.confirmed.toLocaleString('en-US')}, ratio_mismatch=${byVerdict.ratio_mismatch.toLocaleString('en-US')}, low_correlation=${byVerdict.low_correlation}, insufficient_data=${byVerdict.insufficient_data}`,
|
||||
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
|
||||
` Throughput: ${pairsPerSec.toLocaleString('en-US')} pairs/s | ${docsPerSec.toLocaleString('en-US')} docs/s`,
|
||||
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
|
||||
];
|
||||
process.stdout.write(`${lines.join('\n')}\n`);
|
||||
}
|
||||
|
||||
await main();
|
||||
187
apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts
Normal file
187
apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
/**
|
||||
* Reproducible headless benchmark for Pass 4a `readSampleCloses`.
|
||||
* Streams 500,025 synthetic documents (25 sample dates × 20,000 IDs split across
|
||||
* eodPrices + qmPrices, plus 25 CAD.FOREX FX documents) through an in-memory
|
||||
* async-generator fake reader with zero MongoDB or network dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts
|
||||
*/
|
||||
|
||||
import {
|
||||
FX_USD_CAD_SOURCE_ID,
|
||||
readSampleCloses,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SampleCloseSourceReadStats,
|
||||
} from '../src/security-master/sample-closes';
|
||||
|
||||
const SAMPLE_DATE_COUNT = 25;
|
||||
const EOD_ID_COUNT = 10_000;
|
||||
const QM_ID_COUNT = 10_000;
|
||||
|
||||
function buildSampleDates(count: number): string[] {
|
||||
const dates: string[] = [];
|
||||
let year = 2024;
|
||||
let month = 1;
|
||||
let day = 2;
|
||||
while (dates.length < count) {
|
||||
dates.push(
|
||||
`${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
);
|
||||
day += 14;
|
||||
if (day > 28) {
|
||||
day -= 28;
|
||||
month += 1;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
function buildIds(prefix: string, suffix: string, count: number): string[] {
|
||||
const ids = new Array<string>(count);
|
||||
for (let i = 0; i < count; i++) {
|
||||
ids[i] = `${prefix}${String(i).padStart(5, '0')}${suffix}`;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function assertStatsReconcile(label: string, stats: SampleCloseSourceReadStats): void {
|
||||
const skipSum =
|
||||
stats.skipped.missingId +
|
||||
stats.skipped.unrequestedId +
|
||||
stats.skipped.invalidDate +
|
||||
stats.skipped.unrequestedDate +
|
||||
stats.skipped.invalidClose;
|
||||
if (stats.skippedTotal !== skipSum || stats.docsRead !== stats.emitted + stats.skippedTotal) {
|
||||
throw new Error(
|
||||
`Stats reconciliation failed for ${label}: docsRead=${stats.docsRead}, emitted=${stats.emitted}, skippedTotal=${stats.skippedTotal}, skipSum=${skipSum}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function createStreamingBenchmarkReader(
|
||||
sampleDates: readonly string[],
|
||||
eodIds: readonly string[],
|
||||
qmIds: readonly string[]
|
||||
): ReadOnlySourceSymbolReader {
|
||||
return {
|
||||
isReadOnly(): boolean {
|
||||
return true;
|
||||
},
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
filter?: Record<string, unknown>
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
const idFilter =
|
||||
collectionName === 'eodPrices'
|
||||
? ((filter?.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? [])
|
||||
: ((filter?.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []);
|
||||
|
||||
const isFxCall =
|
||||
collectionName === 'eodPrices' &&
|
||||
idFilter.length === 1 &&
|
||||
idFilter[0] === FX_USD_CAD_SOURCE_ID;
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
if (isFxCall) {
|
||||
for (let d = 0; d < sampleDates.length; d++) {
|
||||
yield {
|
||||
eodSearchCode: FX_USD_CAD_SOURCE_ID,
|
||||
date: sampleDates[d],
|
||||
close: 1.34 + (d % 7) * 0.005,
|
||||
} as unknown as T;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (collectionName === 'eodPrices') {
|
||||
const ids = idFilter.length > 0 ? idFilter : eodIds;
|
||||
for (let d = 0; d < sampleDates.length; d++) {
|
||||
const date = sampleDates[d];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
yield {
|
||||
eodSearchCode: ids[i],
|
||||
date,
|
||||
close: 10 + ((i + d) % 250) + 0.25,
|
||||
} as unknown as T;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (collectionName === 'qmPrices') {
|
||||
const ids = idFilter.length > 0 ? idFilter : qmIds;
|
||||
for (let d = 0; d < sampleDates.length; d++) {
|
||||
const date = sampleDates[d];
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
yield {
|
||||
qmSearchCode: ids[i],
|
||||
date,
|
||||
unadjustedclose: 10 + ((i + d) % 250) + 0.25,
|
||||
} as unknown as T;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
// No-op for in-memory benchmark cursor.
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const sampleDates = buildSampleDates(SAMPLE_DATE_COUNT);
|
||||
const eodIds = buildIds('EOD', '.US', EOD_ID_COUNT);
|
||||
const qmIds = buildIds('QM', '', QM_ID_COUNT);
|
||||
const reader = createStreamingBenchmarkReader(sampleDates, eodIds, qmIds);
|
||||
|
||||
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
|
||||
Bun.gc(true);
|
||||
}
|
||||
const heapBefore = process.memoryUsage().heapUsed;
|
||||
const startedAt = performance.now();
|
||||
|
||||
const result = await readSampleCloses(reader, {
|
||||
sampleDates,
|
||||
sourceIdsBySource: { eod: eodIds, qm: qmIds },
|
||||
batchSize: 5_000,
|
||||
});
|
||||
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
const heapAfter = process.memoryUsage().heapUsed;
|
||||
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
|
||||
|
||||
assertStatsReconcile('eod', result.stats.eod);
|
||||
assertStatsReconcile('qm', result.stats.qm);
|
||||
assertStatsReconcile('fx', result.stats.fx);
|
||||
|
||||
const totalDocsRead =
|
||||
result.stats.eod.docsRead + result.stats.qm.docsRead + result.stats.fx.docsRead;
|
||||
const expectedEquityDocs = SAMPLE_DATE_COUNT * (EOD_ID_COUNT + QM_ID_COUNT);
|
||||
if (result.closes.length !== expectedEquityDocs || result.fxRates.length !== SAMPLE_DATE_COUNT) {
|
||||
throw new Error(
|
||||
`Unexpected emitted counts: closes=${result.closes.length} (expected ${expectedEquityDocs}), fxRates=${result.fxRates.length} (expected ${SAMPLE_DATE_COUNT})`
|
||||
);
|
||||
}
|
||||
|
||||
const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000));
|
||||
const lines = [
|
||||
'Pass 4a sample-closes benchmark (in-memory async cursor, zero MongoDB)',
|
||||
` Workload: ${totalDocsRead.toLocaleString('en-US')} docs (${SAMPLE_DATE_COUNT} dates x ${(EOD_ID_COUNT + QM_ID_COUNT).toLocaleString('en-US')} ids + ${SAMPLE_DATE_COUNT} FX)`,
|
||||
` Emitted: ${result.closes.length.toLocaleString('en-US')} closes, ${result.fxRates.length.toLocaleString('en-US')} fxRates`,
|
||||
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
|
||||
` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`,
|
||||
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
|
||||
];
|
||||
process.stdout.write(`${lines.join('\n')}\n`);
|
||||
}
|
||||
|
||||
await main();
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
/**
|
||||
* Reproducible headless benchmark for `readFieldShapes` + `renderFieldShapesMarkdown`.
|
||||
* Streams 80,000 fixed-seed synthetic documents (8 allowlisted collections × 10,000 limit)
|
||||
* with mixed BSON/JS types, one-level nested objects, and all 5 string pattern classes
|
||||
* through an in-memory async-generator fake reader with zero MongoDB or network dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
|
||||
*/
|
||||
|
||||
import {
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
FIELD_VALUE_TYPES,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
STRING_PATTERN_CLASSES,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
const DOCS_PER_COLLECTION = MAX_FIELD_SHAPE_LIMIT;
|
||||
|
||||
function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeSyntheticDoc(collectionIndex: number, docIndex: number, rng: () => number): Record<string, unknown> {
|
||||
const r = rng();
|
||||
const day = String((docIndex % 28) + 1).padStart(2, '0');
|
||||
const month = String(((docIndex + collectionIndex) % 12) + 1).padStart(2, '0');
|
||||
const dateStr = `2025-${month}-${day}`;
|
||||
const isoStr = `${dateStr}T14:30:00Z`;
|
||||
|
||||
const doc: Record<string, unknown> = {
|
||||
_id: {
|
||||
_bsontype: 'ObjectId',
|
||||
toString: () =>
|
||||
`${String(collectionIndex).padStart(2, '0')}${String(docIndex).padStart(22, '0')}`,
|
||||
},
|
||||
symbol: `SYM${String(docIndex % 2000).padStart(4, '0')}`,
|
||||
date: r < 0.85 ? dateStr : r < 0.95 ? isoStr : '',
|
||||
value:
|
||||
r < 0.5
|
||||
? { _bsontype: 'Double', toString: () => (10 + (docIndex % 500) * 0.25).toFixed(2) }
|
||||
: r < 0.8
|
||||
? { _bsontype: 'Int32', toString: () => String(docIndex % 10000) }
|
||||
: r < 0.92
|
||||
? String((docIndex % 1000) / 10)
|
||||
: null,
|
||||
active: docIndex % 5 !== 0,
|
||||
updatedAt: new Date(1735689600000 + (docIndex % 365) * 86_400_000),
|
||||
meta: {
|
||||
exchange: docIndex % 2 === 0 ? 'NYSE' : 'TSX',
|
||||
version: { _bsontype: 'Int32', toString: () => '2' },
|
||||
},
|
||||
};
|
||||
|
||||
if (docIndex % 7 === 0) {
|
||||
doc.tags = ['equity', 'na'];
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
function createSyntheticBenchmarkReader(): ReadOnlySourceSymbolReader {
|
||||
return {
|
||||
isReadOnly(): boolean {
|
||||
return true;
|
||||
},
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
_filter?: Record<string, unknown>,
|
||||
options?: SourceSymbolFindOptions
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
const colIdx = FIELD_SHAPE_PROBE_COLLECTIONS.indexOf(
|
||||
collectionName as (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]
|
||||
);
|
||||
const count = Math.min(DOCS_PER_COLLECTION, options?.limit ?? DOCS_PER_COLLECTION);
|
||||
const rng = mulberry32(0x5eed108 + (colIdx + 1) * 7919);
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (let i = 0; i < count; i++) {
|
||||
yield makeSyntheticDoc(colIdx, i, rng) as T;
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
// No-op for in-memory benchmark cursor.
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const reader = createSyntheticBenchmarkReader();
|
||||
|
||||
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
|
||||
Bun.gc(true);
|
||||
}
|
||||
const heapBefore = process.memoryUsage().heapUsed;
|
||||
const startedAt = performance.now();
|
||||
|
||||
const result = await readFieldShapes(reader, {
|
||||
limit: DOCS_PER_COLLECTION,
|
||||
batchSize: 2_000,
|
||||
});
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
const heapAfter = process.memoryUsage().heapUsed;
|
||||
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
|
||||
|
||||
const expectedTotal = FIELD_SHAPE_PROBE_COLLECTIONS.length * DOCS_PER_COLLECTION;
|
||||
if (result.totalDocsSampled !== expectedTotal) {
|
||||
throw new Error(
|
||||
`Unexpected totalDocsSampled=${result.totalDocsSampled} (expected ${expectedTotal})`
|
||||
);
|
||||
}
|
||||
|
||||
for (const col of result.collections) {
|
||||
for (const field of col.fields) {
|
||||
if (field.presentCount + field.missingCount !== col.docCount) {
|
||||
throw new Error(`Presence mismatch on ${col.collection}.${field.field}`);
|
||||
}
|
||||
let typeSum = 0;
|
||||
for (const typeName of FIELD_VALUE_TYPES) {
|
||||
typeSum += field.typeCounts[typeName];
|
||||
}
|
||||
if (typeSum !== field.presentCount) {
|
||||
throw new Error(`Type sum mismatch on ${col.collection}.${field.field}`);
|
||||
}
|
||||
if (field.stringStats !== null) {
|
||||
let patternSum = 0;
|
||||
for (const p of STRING_PATTERN_CLASSES) {
|
||||
patternSum += field.stringStats.patterns[p];
|
||||
}
|
||||
if (patternSum !== field.typeCounts.string) {
|
||||
throw new Error(`Pattern sum mismatch on ${col.collection}.${field.field}`);
|
||||
}
|
||||
}
|
||||
if ((field.field === '_id' || field.field.startsWith('_id.')) && field.examples.length > 0) {
|
||||
throw new Error(`_id example leaked on ${col.collection}.${field.field}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const docsPerSec = Math.round(result.totalDocsSampled / (elapsedMs / 1000));
|
||||
const lines = [
|
||||
'Source field-shapes probe benchmark (in-memory async cursor, zero MongoDB)',
|
||||
` Workload: ${result.totalDocsSampled.toLocaleString('en-US')} docs (${FIELD_SHAPE_PROBE_COLLECTIONS.length} collections x ${DOCS_PER_COLLECTION.toLocaleString('en-US')} limit)`,
|
||||
` Markdown: ${markdown.length.toLocaleString('en-US')} chars`,
|
||||
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
|
||||
` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`,
|
||||
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
|
||||
];
|
||||
process.stdout.write(`${lines.join('\n')}\n`);
|
||||
}
|
||||
|
||||
await main();
|
||||
|
|
@ -217,18 +217,40 @@ export {
|
|||
|
||||
export {
|
||||
assertSecurityMasterPersistSafety,
|
||||
buildSampleDateCalendar,
|
||||
formatRunSecurityMasterSummary,
|
||||
parseRunSecurityMasterArgs,
|
||||
RUN_SECURITY_MASTER_USAGE,
|
||||
runSecurityMaster,
|
||||
SECURITY_MASTER_OUTPUT_FILES,
|
||||
type ParsedRunSecurityMasterArgs,
|
||||
type Pass4SkippedReason,
|
||||
type RunSecurityMasterDeps,
|
||||
type RunSecurityMasterOptions,
|
||||
type RunSecurityMasterOutput,
|
||||
type RunSecurityMasterPass4Options,
|
||||
type RunSecurityMasterPass4Summary,
|
||||
type SecurityMasterPostgresHandle,
|
||||
} from './run-security-master';
|
||||
|
||||
export {
|
||||
buildSampleCloseFilter,
|
||||
DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE,
|
||||
EOD_SAMPLE_CLOSES_PROJECTION,
|
||||
FX_USD_CAD_SOURCE_ID,
|
||||
MAX_SAMPLE_DATES,
|
||||
QM_SAMPLE_CLOSES_PROJECTION,
|
||||
readSampleCloses,
|
||||
type ReadSampleClosesOptions,
|
||||
type ReadSampleClosesResult,
|
||||
type ReadSampleClosesStats,
|
||||
type SampleCloseSkipCounts,
|
||||
type SampleCloseSkipReason,
|
||||
type SampleCloseSource,
|
||||
type SampleCloseSourceIdsBySource,
|
||||
type SampleCloseSourceReadStats,
|
||||
} from './sample-closes';
|
||||
|
||||
export {
|
||||
buildSecurityTypeByIsin,
|
||||
buildSecurityTypeByIsinForStageA,
|
||||
|
|
@ -243,6 +265,47 @@ export {
|
|||
type UnknownSecurityTypeCount,
|
||||
} from './security-type';
|
||||
|
||||
export {
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
PROBE_SOURCE_FIELD_SHAPES_USAGE,
|
||||
runCli as runProbeSourceFieldShapesCli,
|
||||
runSourceFieldShapesProbe,
|
||||
type ParsedProbeSourceFieldShapesArgs,
|
||||
type RunSourceFieldShapesProbeDeps,
|
||||
type RunSourceFieldShapesProbeOptions,
|
||||
type RunSourceFieldShapesProbeOutput,
|
||||
} from './probe-source-field-shapes';
|
||||
|
||||
export {
|
||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
DEFAULT_MAX_EXAMPLE_LENGTH,
|
||||
DEFAULT_MAX_EXAMPLES,
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
FIELD_VALUE_TYPES,
|
||||
isFieldShapeProbeCollection,
|
||||
MAX_EXAMPLE_LENGTH_CAP,
|
||||
MAX_EXAMPLES_CAP,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
normalizeProbeCollections,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
STRING_PATTERN_CLASSES,
|
||||
summarizeFieldShapes,
|
||||
UnknownProbeCollectionError,
|
||||
type CollectionFieldShapesProbeResult,
|
||||
type CollectionFieldShapesSummary,
|
||||
type FieldShapeProbeCollection,
|
||||
type FieldShapeSummary,
|
||||
type FieldStringStats,
|
||||
type FieldValueType,
|
||||
type FieldValueTypeCounts,
|
||||
type ReadFieldShapesOptions,
|
||||
type ReadFieldShapesResult,
|
||||
type StringPatternClass,
|
||||
type StringPatternCounts,
|
||||
type SummarizeFieldShapesOptions,
|
||||
} from './source-field-shapes';
|
||||
|
||||
export {
|
||||
adaptCeoSymbolDoc,
|
||||
adaptEodSymbolChangeDoc,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,291 @@
|
|||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
|
||||
import {
|
||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
normalizeProbeCollections,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
type FieldShapeProbeCollection,
|
||||
type ReadFieldShapesResult,
|
||||
} from './source-field-shapes';
|
||||
import {
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
} from './source-symbol-readers';
|
||||
|
||||
export const PROBE_SOURCE_FIELD_SHAPES_USAGE = [
|
||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --out <path> [--limit <n>] [--collections <c1,c2,...>] [--help]',
|
||||
'',
|
||||
'Options:',
|
||||
' --out <path> Required. Output Markdown report file path.',
|
||||
` --limit <n> Optional. Max documents sampled per collection (1..${MAX_FIELD_SHAPE_LIMIT}, default: ${DEFAULT_FIELD_SHAPE_LIMIT}).`,
|
||||
` --collections <list> Optional. Comma-separated allowlisted collections (default: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(',')}).`,
|
||||
' --help Show this help message and exit.',
|
||||
].join('\n');
|
||||
|
||||
export type ParsedProbeSourceFieldShapesArgs =
|
||||
| { readonly help: true }
|
||||
| {
|
||||
readonly help: false;
|
||||
readonly outPath: string;
|
||||
readonly limit: number;
|
||||
readonly collections: readonly FieldShapeProbeCollection[];
|
||||
};
|
||||
|
||||
export interface RunSourceFieldShapesProbeDeps {
|
||||
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
|
||||
readonly closeMongo?: () => Promise<void> | void;
|
||||
readonly writeFile?: (filePath: string, content: string) => Promise<void> | void;
|
||||
readonly writeStdout?: (text: string) => void;
|
||||
}
|
||||
|
||||
export interface RunSourceFieldShapesProbeOptions {
|
||||
readonly outPath: string;
|
||||
readonly limit?: number;
|
||||
readonly collections?: readonly string[];
|
||||
readonly maxExamples?: number;
|
||||
readonly maxExampleLength?: number;
|
||||
readonly batchSize?: number;
|
||||
}
|
||||
|
||||
export interface RunSourceFieldShapesProbeOutput {
|
||||
readonly outPath: string;
|
||||
readonly result: ReadFieldShapesResult;
|
||||
readonly markdown: string;
|
||||
readonly summary: string;
|
||||
}
|
||||
|
||||
const STRICT_INT_PATTERN = /^-?\d+$/;
|
||||
|
||||
function usageError(message: string): Error {
|
||||
return new Error(`${message}\n\n${PROBE_SOURCE_FIELD_SHAPES_USAGE}`);
|
||||
}
|
||||
|
||||
function parseLimitArg(raw: string): number {
|
||||
if (!STRICT_INT_PATTERN.test(raw)) {
|
||||
throw usageError(
|
||||
`Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}`
|
||||
);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_FIELD_SHAPE_LIMIT) {
|
||||
throw usageError(
|
||||
`Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}`
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseCollectionsArg(raw: string): FieldShapeProbeCollection[] {
|
||||
const parts = raw
|
||||
.split(',')
|
||||
.map(part => part.trim())
|
||||
.filter(part => part.length > 0);
|
||||
if (parts.length === 0) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
return normalizeProbeCollections(parts);
|
||||
}
|
||||
|
||||
export function parseProbeSourceFieldShapesArgs(
|
||||
argv: readonly string[]
|
||||
): ParsedProbeSourceFieldShapesArgs {
|
||||
let help = false;
|
||||
let outPath: string | undefined;
|
||||
let limit = DEFAULT_FIELD_SHAPE_LIMIT;
|
||||
let collectionsRaw: string[] | undefined;
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--help') {
|
||||
help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--out') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --out');
|
||||
}
|
||||
outPath = value.trim();
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--out=')) {
|
||||
const value = arg.slice('--out='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --out');
|
||||
}
|
||||
outPath = value;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--limit') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --limit');
|
||||
}
|
||||
limit = parseLimitArg(value.trim());
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--limit=')) {
|
||||
const value = arg.slice('--limit='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --limit');
|
||||
}
|
||||
limit = parseLimitArg(value);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--collections') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
const parsed = parseCollectionsArg(value);
|
||||
collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--collections=')) {
|
||||
const value = arg.slice('--collections='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
const parsed = parseCollectionsArg(value);
|
||||
collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed;
|
||||
continue;
|
||||
}
|
||||
throw usageError(`Unknown argument: ${String(arg)}`);
|
||||
}
|
||||
|
||||
if (help) {
|
||||
return { help: true };
|
||||
}
|
||||
|
||||
if (outPath === undefined || outPath.trim().length === 0) {
|
||||
throw usageError('Missing required argument: --out <path>');
|
||||
}
|
||||
|
||||
const collections = normalizeProbeCollections(collectionsRaw);
|
||||
return {
|
||||
help: false,
|
||||
outPath,
|
||||
limit,
|
||||
collections,
|
||||
};
|
||||
}
|
||||
|
||||
async function defaultWriteFile(filePath: string, content: string): Promise<void> {
|
||||
await mkdir(dirname(filePath), { recursive: true });
|
||||
await writeFile(filePath, content, 'utf8');
|
||||
}
|
||||
|
||||
export async function runSourceFieldShapesProbe(
|
||||
deps: RunSourceFieldShapesProbeDeps,
|
||||
options: RunSourceFieldShapesProbeOptions
|
||||
): Promise<RunSourceFieldShapesProbeOutput> {
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
let output: RunSourceFieldShapesProbeOutput | undefined;
|
||||
|
||||
try {
|
||||
if (typeof options.outPath !== 'string' || options.outPath.trim().length === 0) {
|
||||
throw new Error('outPath must be a non-empty string');
|
||||
}
|
||||
|
||||
const reader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient);
|
||||
const result = await readFieldShapes(reader, {
|
||||
limit: options.limit,
|
||||
collections: options.collections,
|
||||
maxExamples: options.maxExamples,
|
||||
maxExampleLength: options.maxExampleLength,
|
||||
batchSize: options.batchSize,
|
||||
});
|
||||
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
const writer = deps.writeFile ?? defaultWriteFile;
|
||||
await writer(options.outPath, markdown);
|
||||
|
||||
const summary = [
|
||||
`Source field-shape probe complete (limit=${result.limit})`,
|
||||
` Collections: ${result.collections.length} | Documents sampled: ${result.totalDocsSampled}`,
|
||||
` Report written: ${options.outPath}`,
|
||||
].join('\n');
|
||||
|
||||
output = {
|
||||
outPath: options.outPath,
|
||||
result,
|
||||
markdown,
|
||||
summary: `${summary}\n`,
|
||||
};
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
hasPrimaryError = true;
|
||||
} finally {
|
||||
if (deps.closeMongo) {
|
||||
try {
|
||||
await deps.closeMongo();
|
||||
} catch (closeError) {
|
||||
if (!hasPrimaryError) {
|
||||
primaryError = closeError;
|
||||
hasPrimaryError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPrimaryError) {
|
||||
throw primaryError;
|
||||
}
|
||||
if (output === undefined) {
|
||||
throw new Error('Source field-shape probe completed without producing output');
|
||||
}
|
||||
|
||||
const writeStdout =
|
||||
deps.writeStdout ??
|
||||
((text: string) => {
|
||||
process.stdout.write(text);
|
||||
});
|
||||
writeStdout(output.summary);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise<void> {
|
||||
const parsed = parseProbeSourceFieldShapesArgs(argv);
|
||||
if (parsed.help) {
|
||||
process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
const logger = getLogger('source-field-shapes-probe');
|
||||
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
||||
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
|
||||
const mongo = new MongoDBClient(mongoConfig, logger);
|
||||
|
||||
await mongo.connect();
|
||||
await runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: mongo,
|
||||
closeMongo: () => mongo.disconnect(),
|
||||
},
|
||||
{
|
||||
outPath: parsed.outPath,
|
||||
limit: parsed.limit,
|
||||
collections: parsed.collections,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
runCli().catch(error => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
process.stderr.write(`Error: ${message}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
|
@ -36,7 +36,18 @@ import {
|
|||
type SecurityMasterQueryable,
|
||||
type SecurityMasterQueryResult,
|
||||
} from './persist';
|
||||
import {
|
||||
DEFAULT_SAMPLE_DATE_COUNT,
|
||||
selectSampleDates,
|
||||
type PriceCrossCheckVerdictCounts,
|
||||
} from './price-cross-check';
|
||||
import { composeSecurityMasterRun, type ComposeSecurityMasterRunResult } from './run';
|
||||
import {
|
||||
MAX_SAMPLE_DATES,
|
||||
readSampleCloses,
|
||||
type ReadSampleClosesResult,
|
||||
type ReadSampleClosesStats,
|
||||
} from './sample-closes';
|
||||
import {
|
||||
createExchangeSourceLookup,
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
|
|
@ -54,13 +65,15 @@ export const SECURITY_MASTER_OUTPUT_FILES = Object.freeze({
|
|||
} as const);
|
||||
|
||||
export const RUN_SECURITY_MASTER_USAGE = [
|
||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of <YYYY-MM-DD> --out-dir <dir> [--persist] [--help]',
|
||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of <YYYY-MM-DD> --out-dir <dir> [--persist] [--skip-price-cross-check] [--sample-dates <n>] [--help]',
|
||||
'',
|
||||
'Options:',
|
||||
' --as-of <YYYY-MM-DD> Required. Calendar reference date for Pass 6 delisting classification.',
|
||||
' --out-dir <dir> Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.',
|
||||
' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).',
|
||||
' --help Show this help message and exit.',
|
||||
' --as-of <YYYY-MM-DD> Required. Calendar reference date for Pass 6 delisting classification.',
|
||||
' --out-dir <dir> Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.',
|
||||
' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).',
|
||||
' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).',
|
||||
` --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`,
|
||||
' --help Show this help message and exit.',
|
||||
].join('\n');
|
||||
|
||||
export type ParsedRunSecurityMasterArgs =
|
||||
|
|
@ -70,8 +83,27 @@ export type ParsedRunSecurityMasterArgs =
|
|||
readonly asOfDate: string;
|
||||
readonly outDir: string;
|
||||
readonly persist: boolean;
|
||||
readonly skipPriceCrossCheck: boolean;
|
||||
readonly sampleDateCount: number;
|
||||
};
|
||||
|
||||
export interface RunSecurityMasterPass4Options {
|
||||
readonly enabled?: boolean;
|
||||
readonly sampleDateCount?: number;
|
||||
}
|
||||
|
||||
export type Pass4SkippedReason = 'disabled' | 'no_sample_dates' | 'no_candidate_pairs';
|
||||
|
||||
export interface RunSecurityMasterPass4Summary {
|
||||
readonly sampleDates: readonly string[];
|
||||
readonly candidatePairs: number;
|
||||
readonly eodIdsRequested: number;
|
||||
readonly qmIdsRequested: number;
|
||||
readonly stats: ReadSampleClosesStats | null;
|
||||
readonly byVerdict: PriceCrossCheckVerdictCounts | null;
|
||||
readonly skippedReason: Pass4SkippedReason | null;
|
||||
}
|
||||
|
||||
export interface SecurityMasterPostgresHandle {
|
||||
readonly queryable: SecurityMasterQueryable;
|
||||
close(): Promise<void> | void;
|
||||
|
|
@ -88,6 +120,8 @@ export interface RunSecurityMasterDeps {
|
|||
| Promise<SecurityMasterPostgresHandle>
|
||||
| SecurityMasterPostgresHandle;
|
||||
readonly persistFn?: typeof persistSecurityMaster;
|
||||
readonly readSampleClosesFn?: typeof readSampleCloses;
|
||||
readonly composeFn?: typeof composeSecurityMasterRun;
|
||||
readonly writeFile?: (filePath: string, content: string) => Promise<void> | void;
|
||||
readonly writeStdout?: (text: string) => void;
|
||||
}
|
||||
|
|
@ -99,6 +133,7 @@ export interface RunSecurityMasterOptions {
|
|||
readonly countries?: readonly string[] | null;
|
||||
readonly batchSize?: number;
|
||||
readonly barSpans?: Omit<ComputeBarSpansOptions, 'sourceIdsBySource'>;
|
||||
readonly pass4?: RunSecurityMasterPass4Options;
|
||||
}
|
||||
|
||||
export interface RunSecurityMasterOutput {
|
||||
|
|
@ -110,6 +145,8 @@ export interface RunSecurityMasterOutput {
|
|||
readonly exchangeCountsByCollection: Readonly<Record<ExchangeSource, number>>;
|
||||
readonly sources: SecurityMasterSourcesResult;
|
||||
readonly barSpans: ComputeBarSpansResult;
|
||||
readonly sampleCloses: ReadSampleClosesResult | null;
|
||||
readonly pass4: RunSecurityMasterPass4Summary;
|
||||
readonly composed: ComposeSecurityMasterRunResult;
|
||||
readonly persistResult: PersistSecurityMasterResult | null;
|
||||
readonly runStatsJson: string;
|
||||
|
|
@ -117,6 +154,166 @@ export interface RunSecurityMasterOutput {
|
|||
}
|
||||
|
||||
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const STRICT_INT_PATTERN = /^-?\d+$/;
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
function parseYmdComponents(value: string): { year: number; month: number; day: number } | null {
|
||||
if (!EXACT_YMD_PATTERN.test(value)) {
|
||||
return null;
|
||||
}
|
||||
const year =
|
||||
(value.charCodeAt(0) - 48) * 1000 +
|
||||
(value.charCodeAt(1) - 48) * 100 +
|
||||
(value.charCodeAt(2) - 48) * 10 +
|
||||
(value.charCodeAt(3) - 48);
|
||||
const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48);
|
||||
const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48);
|
||||
if (year < 1 || year > 9999 || month < 1 || month > 12) {
|
||||
return null;
|
||||
}
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0);
|
||||
if (day < 1 || day > maxDay) {
|
||||
return null;
|
||||
}
|
||||
return { year, month, day };
|
||||
}
|
||||
|
||||
function daysFromCivil(year: number, month: number, day: number): number {
|
||||
const y = month <= 2 ? year - 1 : year;
|
||||
const era = Math.floor(y / 400);
|
||||
const yoe = y - era * 400;
|
||||
const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
|
||||
const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
|
||||
return era * 146097 + doe - 719468;
|
||||
}
|
||||
|
||||
function civilFromDays(daysSinceEpoch: number): { year: number; month: number; day: number } {
|
||||
const shifted = daysSinceEpoch + 719468;
|
||||
const era = Math.floor(shifted / 146097);
|
||||
const doe = shifted - era * 146097;
|
||||
const yoe = Math.floor(
|
||||
(doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365
|
||||
);
|
||||
const y = yoe + era * 400;
|
||||
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
|
||||
const mp = Math.floor((5 * doy + 2) / 153);
|
||||
const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
|
||||
const month = mp + (mp < 10 ? 3 : -9);
|
||||
const year = y + (month <= 2 ? 1 : 0);
|
||||
return { year, month, day };
|
||||
}
|
||||
|
||||
function formatUtcYmd(year: number, month: number, day: number): string {
|
||||
const y = String(year).padStart(4, '0');
|
||||
const m = month < 10 ? `0${String(month)}` : String(month);
|
||||
const d = day < 10 ? `0${String(day)}` : String(day);
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a deterministic ascending Mon-Fri YYYY-MM-DD calendar over the overlapping
|
||||
* date window where both EOD and QM have observed bars, clamped to `asOfDate`.
|
||||
*/
|
||||
export function buildSampleDateCalendar(
|
||||
barSpans: Pick<ComputeBarSpansResult, 'index'>,
|
||||
asOfDate: string
|
||||
): string[] {
|
||||
if (!barSpans || !barSpans.index || !isValidAsOfDate(asOfDate)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let minEodFirst: string | null = null;
|
||||
let maxEodLast: string | null = null;
|
||||
let minQmFirst: string | null = null;
|
||||
let maxQmLast: string | null = null;
|
||||
|
||||
for (const span of barSpans.index) {
|
||||
if (
|
||||
!span ||
|
||||
typeof span.barCount !== 'number' ||
|
||||
!Number.isFinite(span.barCount) ||
|
||||
span.barCount <= 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (span.source !== 'eod' && span.source !== 'qm') {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
parseYmdComponents(span.firstBarDate) === null ||
|
||||
parseYmdComponents(span.lastBarDate) === null ||
|
||||
span.firstBarDate > span.lastBarDate
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (span.source === 'eod') {
|
||||
if (minEodFirst === null || span.firstBarDate < minEodFirst) {
|
||||
minEodFirst = span.firstBarDate;
|
||||
}
|
||||
if (maxEodLast === null || span.lastBarDate > maxEodLast) {
|
||||
maxEodLast = span.lastBarDate;
|
||||
}
|
||||
} else {
|
||||
if (minQmFirst === null || span.firstBarDate < minQmFirst) {
|
||||
minQmFirst = span.firstBarDate;
|
||||
}
|
||||
if (maxQmLast === null || span.lastBarDate > maxQmLast) {
|
||||
maxQmLast = span.lastBarDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (minEodFirst === null || maxEodLast === null || minQmFirst === null || maxQmLast === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const start = minEodFirst > minQmFirst ? minEodFirst : minQmFirst;
|
||||
const overlapEnd = maxEodLast < maxQmLast ? maxEodLast : maxQmLast;
|
||||
const end = overlapEnd < asOfDate ? overlapEnd : asOfDate;
|
||||
|
||||
if (start > end) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const startParts = parseYmdComponents(start);
|
||||
const endParts = parseYmdComponents(end);
|
||||
if (startParts === null || endParts === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const startDay = daysFromCivil(startParts.year, startParts.month, startParts.day);
|
||||
const endDay = daysFromCivil(endParts.year, endParts.month, endParts.day);
|
||||
const calendar: string[] = [];
|
||||
|
||||
for (let dayNum = startDay; dayNum <= endDay; dayNum++) {
|
||||
const dow = (((dayNum + 4) % 7) + 7) % 7;
|
||||
if (dow >= 1 && dow <= 5) {
|
||||
const civil = civilFromDays(dayNum);
|
||||
calendar.push(formatUtcYmd(civil.year, civil.month, civil.day));
|
||||
}
|
||||
}
|
||||
|
||||
return calendar;
|
||||
}
|
||||
|
||||
function parseSampleDateCountArg(raw: string): number {
|
||||
if (!STRICT_INT_PATTERN.test(raw)) {
|
||||
throw usageError(
|
||||
`Invalid --sample-dates value "${raw}": expected an integer between 1 and ${MAX_SAMPLE_DATES}`
|
||||
);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_SAMPLE_DATES) {
|
||||
throw usageError(
|
||||
`Invalid --sample-dates value "${raw}": expected an integer between 1 and ${MAX_SAMPLE_DATES}`
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function isValidAsOfDate(value: string): boolean {
|
||||
return EXACT_YMD_PATTERN.test(value) && normalizeBarDate(value) === value;
|
||||
|
|
@ -152,6 +349,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
|
|||
let asOfDate: string | undefined;
|
||||
let outDir: string | undefined;
|
||||
let persist = false;
|
||||
let skipPriceCrossCheck = false;
|
||||
let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT;
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
|
|
@ -163,6 +362,27 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
|
|||
persist = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--skip-price-cross-check') {
|
||||
skipPriceCrossCheck = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--sample-dates') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --sample-dates');
|
||||
}
|
||||
sampleDateCount = parseSampleDateCountArg(value);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--sample-dates=')) {
|
||||
const value = arg.slice('--sample-dates='.length);
|
||||
if (value.trim().length === 0) {
|
||||
throw usageError('Missing value for --sample-dates');
|
||||
}
|
||||
sampleDateCount = parseSampleDateCountArg(value);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--as-of') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
|
|
@ -221,6 +441,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
|
|||
asOfDate,
|
||||
outDir,
|
||||
persist,
|
||||
skipPriceCrossCheck,
|
||||
sampleDateCount,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -262,9 +484,9 @@ export function formatRunSecurityMasterSummary(
|
|||
params: Pick<
|
||||
RunSecurityMasterOutput,
|
||||
'asOfDate' | 'outDir' | 'persist' | 'filesWritten' | 'composed'
|
||||
>
|
||||
> & { readonly pass4?: RunSecurityMasterPass4Summary }
|
||||
): string {
|
||||
const { asOfDate, outDir, persist, composed } = params;
|
||||
const { asOfDate, outDir, persist, composed, pass4 } = params;
|
||||
const resolutionParts = composed.report.resolutionBySource.map(row => {
|
||||
const pct =
|
||||
row.eligibleResolvedPct === null
|
||||
|
|
@ -280,11 +502,25 @@ export function formatRunSecurityMasterSummary(
|
|||
SECURITY_MASTER_OUTPUT_FILES.runStatsJson,
|
||||
];
|
||||
|
||||
const pass4StatusLabel =
|
||||
composed.stats.pass4.status === 'skipped' && pass4?.skippedReason
|
||||
? `skipped (${pass4.skippedReason})`
|
||||
: composed.stats.pass4.status;
|
||||
const pass4DateCount = pass4?.sampleDates.length ?? 0;
|
||||
const byVerdict = composed.pass4?.stats.byVerdict ?? pass4?.byVerdict ?? null;
|
||||
const pass4Line =
|
||||
` Pass 4 price cross-check: ${pass4StatusLabel} ` +
|
||||
`(dates=${pass4DateCount}, ` +
|
||||
`confirmed=${byVerdict?.confirmed ?? 0}, ` +
|
||||
`ratio_mismatch=${byVerdict?.ratio_mismatch ?? 0}, ` +
|
||||
`low_correlation=${byVerdict?.low_correlation ?? 0}, ` +
|
||||
`insufficient_data=${byVerdict?.insufficient_data ?? 0})`;
|
||||
|
||||
const lines = [
|
||||
`Security master run complete (as-of ${asOfDate})`,
|
||||
` Instruments: ${composed.stageA.instruments.length} | Listings: ${composed.stageB.listings.length} | Conflicts: ${composed.report.conflicts.length}`,
|
||||
` Resolution (eligible): ${resolutionParts.length > 0 ? resolutionParts.join(', ') : 'none'}`,
|
||||
` Pass 4 price cross-check: ${composed.stats.pass4.status} (sample closes not yet wired)`,
|
||||
pass4Line,
|
||||
` Files written (${outDir}): ${fileNames.join(', ')}`,
|
||||
` Persisted: ${persist ? 'yes' : 'no (dry-run)'}`,
|
||||
];
|
||||
|
|
@ -313,6 +549,37 @@ export async function runSecurityMaster(
|
|||
throw wrapStepError('validate-options', new Error('outDir must be a non-empty string'));
|
||||
}
|
||||
|
||||
let pass4Enabled = true;
|
||||
let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT;
|
||||
if (options.pass4 !== undefined) {
|
||||
if (options.pass4 === null || typeof options.pass4 !== 'object') {
|
||||
throw wrapStepError('validate-options', new Error('pass4 options must be an object'));
|
||||
}
|
||||
if (options.pass4.enabled !== undefined) {
|
||||
if (typeof options.pass4.enabled !== 'boolean') {
|
||||
throw wrapStepError('validate-options', new Error('pass4.enabled must be a boolean'));
|
||||
}
|
||||
pass4Enabled = options.pass4.enabled;
|
||||
}
|
||||
if (options.pass4.sampleDateCount !== undefined) {
|
||||
const count = options.pass4.sampleDateCount;
|
||||
if (
|
||||
typeof count !== 'number' ||
|
||||
!Number.isSafeInteger(count) ||
|
||||
count < 1 ||
|
||||
count > MAX_SAMPLE_DATES
|
||||
) {
|
||||
throw wrapStepError(
|
||||
'validate-options',
|
||||
new Error(
|
||||
`Invalid pass4.sampleDateCount "${String(count)}": expected a positive safe integer <= ${MAX_SAMPLE_DATES}`
|
||||
)
|
||||
);
|
||||
}
|
||||
sampleDateCount = count;
|
||||
}
|
||||
}
|
||||
|
||||
// Step 1: Environment safety check before opening PostgreSQL or reading Mongo when --persist is requested.
|
||||
if (persist) {
|
||||
try {
|
||||
|
|
@ -405,10 +672,11 @@ export async function runSecurityMaster(
|
|||
throw wrapStepError('compute-bar-spans', error);
|
||||
}
|
||||
|
||||
// Step 5: Compose Stage A -> Stage B -> Pass 6 -> Report + PersistInput (Pass 4 omitted).
|
||||
// Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs.
|
||||
const composeFn = deps.composeFn ?? composeSecurityMasterRun;
|
||||
let composed: ComposeSecurityMasterRunResult;
|
||||
try {
|
||||
composed = composeSecurityMasterRun(
|
||||
composed = composeFn(
|
||||
{
|
||||
sources,
|
||||
barSpans,
|
||||
|
|
@ -422,10 +690,100 @@ export async function runSecurityMaster(
|
|||
throw wrapStepError('compose', error);
|
||||
}
|
||||
|
||||
// Step 5b: Read targeted sample closes + USD/CAD FX and re-compose with Pass 4 when applicable.
|
||||
let pass4Wired = false;
|
||||
let sampleCloses: ReadSampleClosesResult | null = null;
|
||||
let pass4SampleDates: string[] = [];
|
||||
let pass4EodIds: string[] = [];
|
||||
let pass4QmIds: string[] = [];
|
||||
let pass4SkippedReason: Pass4SkippedReason | null = null;
|
||||
const candidatePairsCount = composed.pass4CandidatePairs.length;
|
||||
|
||||
if (!pass4Enabled) {
|
||||
pass4SkippedReason = 'disabled';
|
||||
} else {
|
||||
const calendar = buildSampleDateCalendar(barSpans, options.asOfDate);
|
||||
pass4SampleDates =
|
||||
calendar.length > 0 ? selectSampleDates(calendar, { count: sampleDateCount }) : [];
|
||||
|
||||
if (pass4SampleDates.length === 0) {
|
||||
pass4SkippedReason = 'no_sample_dates';
|
||||
} else {
|
||||
const eodRawIds: string[] = [];
|
||||
const qmRawIds: string[] = [];
|
||||
for (let i = 0; i < composed.pass4CandidatePairs.length; i++) {
|
||||
const pair = composed.pass4CandidatePairs[i];
|
||||
if (!pair) {
|
||||
continue;
|
||||
}
|
||||
if (pair.left.source === 'eod') {
|
||||
eodRawIds.push(pair.left.sourceId);
|
||||
} else if (pair.left.source === 'qm') {
|
||||
qmRawIds.push(pair.left.sourceId);
|
||||
}
|
||||
if (pair.right.source === 'eod') {
|
||||
eodRawIds.push(pair.right.sourceId);
|
||||
} else if (pair.right.source === 'qm') {
|
||||
qmRawIds.push(pair.right.sourceId);
|
||||
}
|
||||
}
|
||||
pass4EodIds = collectSortedUniqueIds(eodRawIds);
|
||||
pass4QmIds = collectSortedUniqueIds(qmRawIds);
|
||||
|
||||
if (candidatePairsCount === 0 || (pass4EodIds.length === 0 && pass4QmIds.length === 0)) {
|
||||
pass4SkippedReason = 'no_candidate_pairs';
|
||||
} else {
|
||||
const readSampleClosesFn = deps.readSampleClosesFn ?? readSampleCloses;
|
||||
try {
|
||||
sampleCloses = await readSampleClosesFn(sourceReader, {
|
||||
sampleDates: pass4SampleDates,
|
||||
sourceIdsBySource: {
|
||||
eod: pass4EodIds,
|
||||
qm: pass4QmIds,
|
||||
},
|
||||
includeFx: true,
|
||||
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
|
||||
});
|
||||
pass4Wired = true;
|
||||
} catch (error) {
|
||||
throw wrapStepError('read-sample-closes', error);
|
||||
}
|
||||
|
||||
try {
|
||||
composed = composeFn(
|
||||
{
|
||||
sources,
|
||||
barSpans,
|
||||
exchanges,
|
||||
sampleCloses: sampleCloses.closes,
|
||||
fxRates: sampleCloses.fxRates,
|
||||
},
|
||||
{
|
||||
asOfDate: options.asOfDate,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
throw wrapStepError('compose', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pass4Summary: RunSecurityMasterPass4Summary = {
|
||||
sampleDates: pass4SampleDates,
|
||||
candidatePairs: candidatePairsCount,
|
||||
eodIdsRequested: pass4EodIds.length,
|
||||
qmIdsRequested: pass4QmIds.length,
|
||||
stats: sampleCloses?.stats ?? null,
|
||||
byVerdict: composed.pass4?.stats.byVerdict ?? null,
|
||||
skippedReason: pass4SkippedReason,
|
||||
};
|
||||
|
||||
// Step 6: Write deterministic artifacts into outDir.
|
||||
const statsArtifact = {
|
||||
asOfDate: options.asOfDate,
|
||||
pass4Wired: false,
|
||||
pass4Wired,
|
||||
pass4: pass4Summary,
|
||||
exchanges: {
|
||||
countsByCollection: exchangeCountsByCollection,
|
||||
mapped: exchanges.mapped.length,
|
||||
|
|
@ -516,6 +874,7 @@ export async function runSecurityMaster(
|
|||
persist,
|
||||
filesWritten,
|
||||
composed,
|
||||
pass4: pass4Summary,
|
||||
});
|
||||
|
||||
output = {
|
||||
|
|
@ -527,6 +886,8 @@ export async function runSecurityMaster(
|
|||
exchangeCountsByCollection,
|
||||
sources,
|
||||
barSpans,
|
||||
sampleCloses,
|
||||
pass4: pass4Summary,
|
||||
composed,
|
||||
persistResult,
|
||||
runStatsJson,
|
||||
|
|
@ -664,6 +1025,10 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
|||
asOfDate: parsed.asOfDate,
|
||||
outDir: parsed.outDir,
|
||||
persist: parsed.persist,
|
||||
pass4: {
|
||||
enabled: !parsed.skipPriceCrossCheck,
|
||||
sampleDateCount: parsed.sampleDateCount,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
|
|||
519
apps/stock/data-pipeline/src/security-master/sample-closes.ts
Normal file
519
apps/stock/data-pipeline/src/security-master/sample-closes.ts
Normal file
|
|
@ -0,0 +1,519 @@
|
|||
import {
|
||||
BAR_SPAN_COLLECTIONS,
|
||||
normalizeBarDate,
|
||||
type BarSpanSource,
|
||||
} from '../normalization/bar-spans';
|
||||
import { compareAscii } from './exchange-pass1';
|
||||
import type { FxRateByDateRecord, SampleCloseRecord } from './price-cross-check';
|
||||
import type {
|
||||
ReadOnlySourceSymbolCursor,
|
||||
ReadOnlySourceSymbolReader,
|
||||
SourceSymbolFindOptions,
|
||||
} from './source-symbol-readers';
|
||||
|
||||
export type SampleCloseSource = BarSpanSource;
|
||||
|
||||
export const MAX_SAMPLE_DATES = 64;
|
||||
export const DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE = 10_000;
|
||||
export const FX_USD_CAD_SOURCE_ID = 'CAD.FOREX';
|
||||
|
||||
export const EOD_SAMPLE_CLOSES_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
|
||||
_id: 0,
|
||||
[BAR_SPAN_COLLECTIONS.eod.idField]: 1,
|
||||
[BAR_SPAN_COLLECTIONS.eod.dateField]: 1,
|
||||
close: 1,
|
||||
});
|
||||
|
||||
export const QM_SAMPLE_CLOSES_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
|
||||
_id: 0,
|
||||
[BAR_SPAN_COLLECTIONS.qm.idField]: 1,
|
||||
[BAR_SPAN_COLLECTIONS.qm.dateField]: 1,
|
||||
unadjustedclose: 1,
|
||||
});
|
||||
|
||||
export interface SampleCloseSourceIdsBySource {
|
||||
readonly eod: readonly string[];
|
||||
readonly qm: readonly string[];
|
||||
}
|
||||
|
||||
export interface ReadSampleClosesOptions {
|
||||
readonly sampleDates: readonly string[];
|
||||
readonly sourceIdsBySource: SampleCloseSourceIdsBySource;
|
||||
readonly includeFx?: boolean;
|
||||
readonly batchSize?: number;
|
||||
readonly idChunkSize?: number;
|
||||
}
|
||||
|
||||
export interface SampleCloseSkipCounts {
|
||||
missingId: number;
|
||||
unrequestedId: number;
|
||||
invalidDate: number;
|
||||
unrequestedDate: number;
|
||||
invalidClose: number;
|
||||
}
|
||||
|
||||
export type SampleCloseSkipReason = keyof SampleCloseSkipCounts;
|
||||
|
||||
export interface SampleCloseSourceReadStats {
|
||||
collection: string;
|
||||
findsRun: number;
|
||||
docsRead: number;
|
||||
emitted: number;
|
||||
skippedTotal: number;
|
||||
skipped: SampleCloseSkipCounts;
|
||||
}
|
||||
|
||||
export interface ReadSampleClosesStats {
|
||||
eod: SampleCloseSourceReadStats;
|
||||
qm: SampleCloseSourceReadStats;
|
||||
fx: SampleCloseSourceReadStats;
|
||||
}
|
||||
|
||||
export interface ReadSampleClosesResult {
|
||||
sampleDates: string[];
|
||||
closes: SampleCloseRecord[];
|
||||
fxRates: FxRateByDateRecord[];
|
||||
stats: ReadSampleClosesStats;
|
||||
}
|
||||
|
||||
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
function isSampleCloseSource(value: unknown): value is SampleCloseSource {
|
||||
return value === 'eod' || value === 'qm';
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
|
||||
return (
|
||||
value !== null &&
|
||||
(typeof value === 'object' || typeof value === 'function') &&
|
||||
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function validatePositiveSafeInt(value: unknown, name: string): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
||||
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
|
||||
if (
|
||||
reader === null ||
|
||||
reader === undefined ||
|
||||
typeof reader !== 'object' ||
|
||||
typeof reader.isReadOnly !== 'function' ||
|
||||
typeof reader.find !== 'function' ||
|
||||
reader.isReadOnly() !== true
|
||||
) {
|
||||
throw new Error(
|
||||
'Sample close reader requires a read-only MongoDB reader (isReadOnly() must be true)'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates, deduplicates, and ASCII-sorts exact Gregorian `YYYY-MM-DD` sample dates.
|
||||
* Rejects empty lists, malformed/padded/rollover dates, and lists exceeding `MAX_SAMPLE_DATES`.
|
||||
*/
|
||||
function normalizeSampleDates(sampleDates: readonly string[]): string[] {
|
||||
if (!Array.isArray(sampleDates)) {
|
||||
throw new RangeError('sampleDates must be a non-empty array of YYYY-MM-DD strings');
|
||||
}
|
||||
if (sampleDates.length === 0) {
|
||||
throw new RangeError('sampleDates must not be empty');
|
||||
}
|
||||
|
||||
const unique = new Set<string>();
|
||||
for (let i = 0; i < sampleDates.length; i++) {
|
||||
const raw = sampleDates[i];
|
||||
if (
|
||||
typeof raw !== 'string' ||
|
||||
!EXACT_YMD_PATTERN.test(raw) ||
|
||||
normalizeBarDate(raw) !== raw
|
||||
) {
|
||||
throw new RangeError(
|
||||
`sampleDates[${i}] must be a valid exact YYYY-MM-DD date, received ${JSON.stringify(raw)}`
|
||||
);
|
||||
}
|
||||
unique.add(raw);
|
||||
}
|
||||
|
||||
if (unique.size > MAX_SAMPLE_DATES) {
|
||||
throw new RangeError(
|
||||
`sampleDates exceeds maximum allowed count of ${MAX_SAMPLE_DATES} (received ${unique.size})`
|
||||
);
|
||||
}
|
||||
|
||||
return Array.from(unique).sort(compareAscii);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates, deduplicates, and ASCII-sorts requested source IDs without trimming non-blank strings
|
||||
* (T-49). Whitespace-only entries are dropped; `CAD.FOREX` is excluded when `excludeFx` is true.
|
||||
*/
|
||||
function normalizeRequestedIds(
|
||||
rawIds: readonly string[],
|
||||
fieldName: string,
|
||||
options?: { readonly excludeFx?: boolean }
|
||||
): string[] {
|
||||
if (!Array.isArray(rawIds)) {
|
||||
throw new TypeError(`${fieldName} must be an array of strings`);
|
||||
}
|
||||
|
||||
const excludeFx = options?.excludeFx === true;
|
||||
const unique = new Set<string>();
|
||||
for (let i = 0; i < rawIds.length; i++) {
|
||||
const raw = rawIds[i];
|
||||
if (typeof raw !== 'string') {
|
||||
throw new TypeError(`${fieldName}[${i}] must be a string, received ${typeof raw}`);
|
||||
}
|
||||
if (raw.trim().length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (excludeFx && raw === FX_USD_CAD_SOURCE_ID) {
|
||||
continue;
|
||||
}
|
||||
unique.add(raw);
|
||||
}
|
||||
|
||||
return Array.from(unique).sort(compareAscii);
|
||||
}
|
||||
|
||||
function createEmptySkipCounts(): SampleCloseSkipCounts {
|
||||
return {
|
||||
missingId: 0,
|
||||
unrequestedId: 0,
|
||||
invalidDate: 0,
|
||||
unrequestedDate: 0,
|
||||
invalidClose: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function createSourceStats(collection: string): SampleCloseSourceReadStats {
|
||||
return {
|
||||
collection,
|
||||
findsRun: 0,
|
||||
docsRead: 0,
|
||||
emitted: 0,
|
||||
skippedTotal: 0,
|
||||
skipped: createEmptySkipCounts(),
|
||||
};
|
||||
}
|
||||
|
||||
function recordSkip(stats: SampleCloseSourceReadStats, reason: SampleCloseSkipReason): void {
|
||||
stats.skipped[reason] += 1;
|
||||
stats.skippedTotal += 1;
|
||||
}
|
||||
|
||||
function wrapCollectionReadError(collectionName: string, error: unknown): Error {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
const message = detail.includes(collectionName)
|
||||
? detail
|
||||
: `Failed reading collection "${collectionName}": ${detail}`;
|
||||
return new Error(message, { cause: error });
|
||||
}
|
||||
|
||||
async function streamSampleCloseFind(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
collectionName: string,
|
||||
filter: Record<string, unknown>,
|
||||
findOptions: SourceSymbolFindOptions,
|
||||
onDoc: (doc: unknown) => void
|
||||
): Promise<void> {
|
||||
assertReadOnlyReader(reader);
|
||||
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
|
||||
null;
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
let isInvalidCursorError = false;
|
||||
|
||||
try {
|
||||
const rawCursor = await reader.find<Record<string, unknown>>(
|
||||
collectionName,
|
||||
filter,
|
||||
findOptions
|
||||
);
|
||||
if (
|
||||
rawCursor !== null &&
|
||||
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
|
||||
) {
|
||||
closableHandle = rawCursor as Pick<
|
||||
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
|
||||
'close'
|
||||
>;
|
||||
}
|
||||
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(rawCursor)) {
|
||||
isInvalidCursorError = true;
|
||||
throw new TypeError(
|
||||
`Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)`
|
||||
);
|
||||
}
|
||||
for await (const doc of rawCursor) {
|
||||
onDoc(doc);
|
||||
}
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
hasPrimaryError = true;
|
||||
} finally {
|
||||
if (closableHandle !== null && typeof closableHandle.close === 'function') {
|
||||
try {
|
||||
await closableHandle.close();
|
||||
} catch (closeError) {
|
||||
if (!hasPrimaryError) {
|
||||
primaryError = closeError;
|
||||
hasPrimaryError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPrimaryError) {
|
||||
if (isInvalidCursorError) {
|
||||
throw primaryError;
|
||||
}
|
||||
throw wrapCollectionReadError(collectionName, primaryError);
|
||||
}
|
||||
}
|
||||
|
||||
function compareSampleCloses(a: SampleCloseRecord, b: SampleCloseRecord): number {
|
||||
return (
|
||||
compareAscii(a.source, b.source) ||
|
||||
compareAscii(a.sourceId, b.sourceId) ||
|
||||
compareAscii(a.date, b.date) ||
|
||||
a.close - b.close
|
||||
);
|
||||
}
|
||||
|
||||
function compareFxRates(a: FxRateByDateRecord, b: FxRateByDateRecord): number {
|
||||
return compareAscii(a.date, b.date) || a.usdCad - b.usdCad;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a plain date-first MongoDB `find` filter for Pass 4 sample-close queries:
|
||||
* `{ date: { $in: [...] } }`, optionally AND-ed with `{ eodSearchCode | qmSearchCode: { $in: [...] } }`.
|
||||
*
|
||||
* `eodPrices` (`price-storage.ts`) enforces `YYYY-MM-DD` strings for `date`, while
|
||||
* `qmPrices` (`prices.action.ts`) copies the provider's `date` field verbatim (assumed
|
||||
* `YYYY-MM-DD`, with BSON `Date` stored separately in `dateTime`), so `$in` emits sorted
|
||||
* `YYYY-MM-DD` strings.
|
||||
*/
|
||||
export function buildSampleCloseFilter(
|
||||
source: SampleCloseSource,
|
||||
sampleDates: readonly string[],
|
||||
sourceIds?: readonly string[]
|
||||
): Record<string, unknown> {
|
||||
if (!isSampleCloseSource(source)) {
|
||||
throw new RangeError(`Unsupported sample close source: "${String(source)}"`);
|
||||
}
|
||||
|
||||
const normalizedDates = normalizeSampleDates(sampleDates);
|
||||
const spec = BAR_SPAN_COLLECTIONS[source];
|
||||
const filter: Record<string, unknown> = {
|
||||
[spec.dateField]: { $in: normalizedDates },
|
||||
};
|
||||
|
||||
if (sourceIds !== undefined) {
|
||||
const normalizedIds = normalizeRequestedIds(sourceIds, 'sourceIds');
|
||||
filter[spec.idField] = { $in: normalizedIds };
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams read-only Pass 4 sample closes from `eodPrices` (raw `close`), `qmPrices`
|
||||
* (raw `unadjustedclose`), and USD/CAD FX rates from `eodPrices` (`CAD.FOREX`) using
|
||||
* date-first `{ date: { $in: sampleDates } }` filters over `ReadOnlySourceSymbolReader`.
|
||||
*/
|
||||
export async function readSampleCloses(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
options: ReadSampleClosesOptions
|
||||
): Promise<ReadSampleClosesResult> {
|
||||
assertReadOnlyReader(reader);
|
||||
|
||||
if (options === null || typeof options !== 'object') {
|
||||
throw new TypeError('options must be an object');
|
||||
}
|
||||
if (options.sourceIdsBySource === null || typeof options.sourceIdsBySource !== 'object') {
|
||||
throw new TypeError('options.sourceIdsBySource must be an object');
|
||||
}
|
||||
|
||||
const sampleDates = normalizeSampleDates(options.sampleDates);
|
||||
const sampleDateSet = new Set<string>(sampleDates);
|
||||
|
||||
const eodIds = normalizeRequestedIds(options.sourceIdsBySource.eod, 'sourceIdsBySource.eod', {
|
||||
excludeFx: true,
|
||||
});
|
||||
const qmIds = normalizeRequestedIds(options.sourceIdsBySource.qm, 'sourceIdsBySource.qm');
|
||||
|
||||
const includeFx = options.includeFx ?? true;
|
||||
if (typeof includeFx !== 'boolean') {
|
||||
throw new TypeError('options.includeFx must be a boolean');
|
||||
}
|
||||
|
||||
const batchSize =
|
||||
options.batchSize !== undefined
|
||||
? validatePositiveSafeInt(options.batchSize, 'options.batchSize')
|
||||
: undefined;
|
||||
const idChunkSize =
|
||||
options.idChunkSize !== undefined
|
||||
? validatePositiveSafeInt(options.idChunkSize, 'options.idChunkSize')
|
||||
: DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE;
|
||||
|
||||
const eodFindOptions: SourceSymbolFindOptions =
|
||||
batchSize !== undefined
|
||||
? { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, batchSize }
|
||||
: { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION } };
|
||||
const qmFindOptions: SourceSymbolFindOptions =
|
||||
batchSize !== undefined
|
||||
? { projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, batchSize }
|
||||
: { projection: { ...QM_SAMPLE_CLOSES_PROJECTION } };
|
||||
|
||||
const stats: ReadSampleClosesStats = {
|
||||
eod: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection),
|
||||
qm: createSourceStats(BAR_SPAN_COLLECTIONS.qm.collection),
|
||||
fx: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection),
|
||||
};
|
||||
|
||||
const closes: SampleCloseRecord[] = [];
|
||||
const fxRates: FxRateByDateRecord[] = [];
|
||||
|
||||
const readEquitySource = async (
|
||||
source: SampleCloseSource,
|
||||
ids: readonly string[],
|
||||
findOptions: SourceSymbolFindOptions
|
||||
): Promise<void> => {
|
||||
if (ids.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const spec = BAR_SPAN_COLLECTIONS[source];
|
||||
const closeField = source === 'eod' ? 'close' : 'unadjustedclose';
|
||||
const sourceStats = stats[source];
|
||||
|
||||
for (let offset = 0; offset < ids.length; offset += idChunkSize) {
|
||||
const chunkIds = ids.slice(offset, offset + idChunkSize);
|
||||
const chunkIdSet = new Set<string>(chunkIds);
|
||||
const filter = buildSampleCloseFilter(source, sampleDates, chunkIds);
|
||||
sourceStats.findsRun += 1;
|
||||
|
||||
await streamSampleCloseFind(reader, spec.collection, filter, findOptions, doc => {
|
||||
sourceStats.docsRead += 1;
|
||||
|
||||
if (!isPlainRecord(doc)) {
|
||||
recordSkip(sourceStats, 'missingId');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawId = doc[spec.idField];
|
||||
if (typeof rawId !== 'string' || rawId.trim().length === 0) {
|
||||
recordSkip(sourceStats, 'missingId');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!chunkIdSet.has(rawId)) {
|
||||
recordSkip(sourceStats, 'unrequestedId');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawDate = doc[spec.dateField];
|
||||
const normalizedDate =
|
||||
typeof rawDate === 'string' && sampleDateSet.has(rawDate)
|
||||
? rawDate
|
||||
: normalizeBarDate(rawDate);
|
||||
if (normalizedDate === null) {
|
||||
recordSkip(sourceStats, 'invalidDate');
|
||||
return;
|
||||
}
|
||||
if (!sampleDateSet.has(normalizedDate)) {
|
||||
recordSkip(sourceStats, 'unrequestedDate');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawClose = doc[closeField];
|
||||
if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) {
|
||||
recordSkip(sourceStats, 'invalidClose');
|
||||
return;
|
||||
}
|
||||
|
||||
closes.push({
|
||||
source,
|
||||
sourceId: rawId,
|
||||
date: normalizedDate,
|
||||
close: rawClose,
|
||||
});
|
||||
sourceStats.emitted += 1;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
await readEquitySource('eod', eodIds, eodFindOptions);
|
||||
await readEquitySource('qm', qmIds, qmFindOptions);
|
||||
|
||||
if (includeFx) {
|
||||
const eodSpec = BAR_SPAN_COLLECTIONS.eod;
|
||||
const fxFilter = buildSampleCloseFilter('eod', sampleDates, [FX_USD_CAD_SOURCE_ID]);
|
||||
stats.fx.findsRun += 1;
|
||||
|
||||
await streamSampleCloseFind(reader, eodSpec.collection, fxFilter, eodFindOptions, doc => {
|
||||
stats.fx.docsRead += 1;
|
||||
|
||||
if (!isPlainRecord(doc)) {
|
||||
recordSkip(stats.fx, 'missingId');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawId = doc[eodSpec.idField];
|
||||
if (typeof rawId !== 'string' || rawId.trim().length === 0) {
|
||||
recordSkip(stats.fx, 'missingId');
|
||||
return;
|
||||
}
|
||||
|
||||
if (rawId !== FX_USD_CAD_SOURCE_ID) {
|
||||
recordSkip(stats.fx, 'unrequestedId');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawDate = doc[eodSpec.dateField];
|
||||
const normalizedDate =
|
||||
typeof rawDate === 'string' && sampleDateSet.has(rawDate)
|
||||
? rawDate
|
||||
: normalizeBarDate(rawDate);
|
||||
if (normalizedDate === null) {
|
||||
recordSkip(stats.fx, 'invalidDate');
|
||||
return;
|
||||
}
|
||||
if (!sampleDateSet.has(normalizedDate)) {
|
||||
recordSkip(stats.fx, 'unrequestedDate');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawClose = doc.close;
|
||||
if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) {
|
||||
recordSkip(stats.fx, 'invalidClose');
|
||||
return;
|
||||
}
|
||||
|
||||
fxRates.push({
|
||||
date: normalizedDate,
|
||||
usdCad: rawClose,
|
||||
});
|
||||
stats.fx.emitted += 1;
|
||||
});
|
||||
}
|
||||
|
||||
closes.sort(compareSampleCloses);
|
||||
fxRates.sort(compareFxRates);
|
||||
|
||||
return {
|
||||
sampleDates,
|
||||
closes,
|
||||
fxRates,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,915 @@
|
|||
import { compareAscii } from './exchange-pass1';
|
||||
import type {
|
||||
ReadOnlySourceSymbolCursor,
|
||||
ReadOnlySourceSymbolReader,
|
||||
SourceSymbolFindOptions,
|
||||
} from './source-symbol-readers';
|
||||
|
||||
export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([
|
||||
'ceoShorts',
|
||||
'qmSplits',
|
||||
'qmDividends',
|
||||
'qmFilings',
|
||||
'qmEarnings',
|
||||
'qmPrices',
|
||||
'eodPrices',
|
||||
'teMarketData',
|
||||
] as const);
|
||||
|
||||
export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number];
|
||||
|
||||
export const FIELD_VALUE_TYPES = Object.freeze([
|
||||
'string',
|
||||
'int',
|
||||
'double',
|
||||
'bool',
|
||||
'date',
|
||||
'null',
|
||||
'objectId',
|
||||
'array',
|
||||
'object',
|
||||
'other',
|
||||
] as const);
|
||||
|
||||
export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number];
|
||||
|
||||
export const STRING_PATTERN_CLASSES = Object.freeze([
|
||||
'ymd',
|
||||
'isoDatetime',
|
||||
'numeric',
|
||||
'emptyOrWhitespace',
|
||||
'other',
|
||||
] as const);
|
||||
|
||||
export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number];
|
||||
|
||||
export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000;
|
||||
export const MAX_FIELD_SHAPE_LIMIT = 10_000;
|
||||
export const DEFAULT_MAX_EXAMPLES = 3;
|
||||
export const MAX_EXAMPLES_CAP = 10;
|
||||
export const DEFAULT_MAX_EXAMPLE_LENGTH = 48;
|
||||
export const MAX_EXAMPLE_LENGTH_CAP = 120;
|
||||
|
||||
const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet<string> = new Set<string>(
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS
|
||||
);
|
||||
|
||||
export class UnknownProbeCollectionError extends Error {
|
||||
readonly collectionName: string;
|
||||
readonly allowedCollections: readonly FieldShapeProbeCollection[];
|
||||
|
||||
constructor(collectionName: string) {
|
||||
super(
|
||||
`Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}`
|
||||
);
|
||||
this.name = 'UnknownProbeCollectionError';
|
||||
this.collectionName = collectionName;
|
||||
this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export type FieldValueTypeCounts = Record<FieldValueType, number>;
|
||||
export type StringPatternCounts = Record<StringPatternClass, number>;
|
||||
|
||||
export interface FieldStringStats {
|
||||
minLength: number;
|
||||
maxLength: number;
|
||||
patterns: StringPatternCounts;
|
||||
}
|
||||
|
||||
export interface FieldShapeSummary {
|
||||
field: string;
|
||||
presentCount: number;
|
||||
missingCount: number;
|
||||
typeCounts: FieldValueTypeCounts;
|
||||
stringStats: FieldStringStats | null;
|
||||
examples: string[];
|
||||
}
|
||||
|
||||
export interface SummarizeFieldShapesOptions {
|
||||
readonly maxExamples?: number;
|
||||
readonly maxExampleLength?: number;
|
||||
}
|
||||
|
||||
export interface CollectionFieldShapesSummary {
|
||||
docCount: number;
|
||||
fields: FieldShapeSummary[];
|
||||
}
|
||||
|
||||
export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions {
|
||||
readonly collections?: readonly string[];
|
||||
readonly limit?: number;
|
||||
readonly batchSize?: number;
|
||||
}
|
||||
|
||||
export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary {
|
||||
collection: FieldShapeProbeCollection;
|
||||
}
|
||||
|
||||
export interface ReadFieldShapesResult {
|
||||
limit: number;
|
||||
maxExamples: number;
|
||||
maxExampleLength: number;
|
||||
totalDocsSampled: number;
|
||||
collections: CollectionFieldShapesProbeResult[];
|
||||
}
|
||||
|
||||
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const STRICT_ISO_DATETIME_PATTERN =
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/;
|
||||
const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
function isValidCalendarDate(year: number, month: number, day: number): boolean {
|
||||
if (year < 1 || year > 9999 || month < 1 || month > 12) {
|
||||
return false;
|
||||
}
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0);
|
||||
return day >= 1 && day <= maxDay;
|
||||
}
|
||||
|
||||
function isValidYmd(value: string): boolean {
|
||||
if (!EXACT_YMD_PATTERN.test(value)) {
|
||||
return false;
|
||||
}
|
||||
const year =
|
||||
(value.charCodeAt(0) - 48) * 1000 +
|
||||
(value.charCodeAt(1) - 48) * 100 +
|
||||
(value.charCodeAt(2) - 48) * 10 +
|
||||
(value.charCodeAt(3) - 48);
|
||||
const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48);
|
||||
const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48);
|
||||
return isValidCalendarDate(year, month, day);
|
||||
}
|
||||
|
||||
function isValidIsoDatetime(value: string): boolean {
|
||||
const match = STRICT_ISO_DATETIME_PATTERN.exec(value);
|
||||
if (match === null) {
|
||||
return false;
|
||||
}
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
const hour = Number(match[4]);
|
||||
const minute = Number(match[5]);
|
||||
const second = Number(match[6]);
|
||||
|
||||
if (!isValidCalendarDate(year, month, day)) {
|
||||
return false;
|
||||
}
|
||||
if (hour > 23 || minute > 59 || second > 59) {
|
||||
return false;
|
||||
}
|
||||
if (match[7] !== undefined) {
|
||||
const tzHour = Number(match[8]);
|
||||
const tzMinute = Number(match[9]);
|
||||
if (tzHour > 23 || tzMinute > 59) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function classifyStringPattern(value: string): StringPatternClass {
|
||||
if (value.length === 0 || value.trim().length === 0) {
|
||||
return 'emptyOrWhitespace';
|
||||
}
|
||||
if (value.length === 10 && isValidYmd(value)) {
|
||||
return 'ymd';
|
||||
}
|
||||
if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) {
|
||||
return 'isoDatetime';
|
||||
}
|
||||
if (NUMERIC_STRING_PATTERN.test(value)) {
|
||||
return 'numeric';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function createEmptyTypeCounts(): FieldValueTypeCounts {
|
||||
return {
|
||||
string: 0,
|
||||
int: 0,
|
||||
double: 0,
|
||||
bool: 0,
|
||||
date: 0,
|
||||
null: 0,
|
||||
objectId: 0,
|
||||
array: 0,
|
||||
object: 0,
|
||||
other: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function createEmptyStringPatternCounts(): StringPatternCounts {
|
||||
return {
|
||||
ymd: 0,
|
||||
isoDatetime: 0,
|
||||
numeric: 0,
|
||||
emptyOrWhitespace: 0,
|
||||
other: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function isNonPlainBuiltInObject(value: object): boolean {
|
||||
return (
|
||||
value instanceof Date ||
|
||||
Array.isArray(value) ||
|
||||
ArrayBuffer.isView(value) ||
|
||||
value instanceof ArrayBuffer ||
|
||||
value instanceof RegExp ||
|
||||
value instanceof Map ||
|
||||
value instanceof Set
|
||||
);
|
||||
}
|
||||
|
||||
function getBsonTypeTag(value: object): string | null {
|
||||
const tag = (value as { _bsontype?: unknown })._bsontype;
|
||||
return typeof tag === 'string' && tag.length > 0 ? tag : null;
|
||||
}
|
||||
|
||||
function isPlainNestedObject(value: unknown): value is Record<string, unknown> {
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
if (isNonPlainBuiltInObject(value)) {
|
||||
return false;
|
||||
}
|
||||
if (getBsonTypeTag(value) !== null) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function classifyValueType(value: unknown): FieldValueType {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
const primitiveType = typeof value;
|
||||
if (primitiveType === 'string') {
|
||||
return 'string';
|
||||
}
|
||||
if (primitiveType === 'boolean') {
|
||||
return 'bool';
|
||||
}
|
||||
if (primitiveType === 'number') {
|
||||
return Number.isInteger(value) ? 'int' : 'double';
|
||||
}
|
||||
if (primitiveType === 'bigint') {
|
||||
return 'int';
|
||||
}
|
||||
if (primitiveType !== 'object') {
|
||||
return 'other';
|
||||
}
|
||||
|
||||
const obj = value as object;
|
||||
if (obj instanceof Date) {
|
||||
return 'date';
|
||||
}
|
||||
if (Array.isArray(obj)) {
|
||||
return 'array';
|
||||
}
|
||||
|
||||
const bsonTag = getBsonTypeTag(obj);
|
||||
if (bsonTag !== null) {
|
||||
if (bsonTag === 'Int32' || bsonTag === 'Long') {
|
||||
return 'int';
|
||||
}
|
||||
if (bsonTag === 'Double') {
|
||||
return 'double';
|
||||
}
|
||||
if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') {
|
||||
return 'objectId';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
if (isNonPlainBuiltInObject(obj)) {
|
||||
return 'other';
|
||||
}
|
||||
|
||||
return 'object';
|
||||
}
|
||||
|
||||
function escapeFieldSegment(segment: string): string {
|
||||
if (!segment.includes('.') && !segment.includes('\\')) {
|
||||
return segment;
|
||||
}
|
||||
return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
|
||||
}
|
||||
|
||||
function formatFieldPath(parentKey: string, childKey?: string): string {
|
||||
const escapedParent = escapeFieldSegment(parentKey);
|
||||
return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`;
|
||||
}
|
||||
|
||||
function sanitizeAndTruncateExample(raw: string, maxLength: number): string {
|
||||
let cleaned = '';
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const code = raw.charCodeAt(i);
|
||||
if (code === 9 || code === 10 || code === 13) {
|
||||
cleaned += ' ';
|
||||
} else if (code >= 32 && code !== 127) {
|
||||
cleaned += raw[i];
|
||||
}
|
||||
}
|
||||
if (cleaned.length <= maxLength) {
|
||||
return cleaned;
|
||||
}
|
||||
if (maxLength <= 3) {
|
||||
return cleaned.slice(0, maxLength);
|
||||
}
|
||||
return `${cleaned.slice(0, maxLength - 3)}...`;
|
||||
}
|
||||
|
||||
function extractScalarExample(
|
||||
value: unknown,
|
||||
valueType: FieldValueType,
|
||||
maxExampleLength: number
|
||||
): string | null {
|
||||
if (valueType === 'null' || valueType === 'array' || valueType === 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
let raw: string | null = null;
|
||||
if (valueType === 'string') {
|
||||
raw = value as string;
|
||||
} else if (valueType === 'bool') {
|
||||
raw = (value as boolean) ? 'true' : 'false';
|
||||
} else if (valueType === 'int' || valueType === 'double') {
|
||||
if (typeof value === 'number' || typeof value === 'bigint') {
|
||||
raw = String(value);
|
||||
} else if (value !== null && typeof value === 'object') {
|
||||
raw = String(value);
|
||||
}
|
||||
} else if (valueType === 'date' && value instanceof Date) {
|
||||
raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
|
||||
} else if (valueType === 'objectId') {
|
||||
raw = String(value);
|
||||
} else if (valueType === 'other' && value !== null && typeof value === 'object') {
|
||||
const bsonTag = getBsonTypeTag(value);
|
||||
if (bsonTag === 'Decimal128' || bsonTag === 'UUID') {
|
||||
raw = String(value);
|
||||
}
|
||||
}
|
||||
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
return sanitizeAndTruncateExample(raw, maxExampleLength);
|
||||
}
|
||||
|
||||
function validateBoundedInt(value: unknown, name: string, min: number, max: number): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
|
||||
throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validatePositiveSafeInt(value: unknown, name: string): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
||||
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): {
|
||||
maxExamples: number;
|
||||
maxExampleLength: number;
|
||||
} {
|
||||
if (options !== undefined && (options === null || typeof options !== 'object')) {
|
||||
throw new TypeError('options must be an object');
|
||||
}
|
||||
const maxExamples =
|
||||
options?.maxExamples !== undefined
|
||||
? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP)
|
||||
: DEFAULT_MAX_EXAMPLES;
|
||||
const maxExampleLength =
|
||||
options?.maxExampleLength !== undefined
|
||||
? validateBoundedInt(
|
||||
options.maxExampleLength,
|
||||
'options.maxExampleLength',
|
||||
1,
|
||||
MAX_EXAMPLE_LENGTH_CAP
|
||||
)
|
||||
: DEFAULT_MAX_EXAMPLE_LENGTH;
|
||||
return { maxExamples, maxExampleLength };
|
||||
}
|
||||
|
||||
interface MutableFieldAccumulator {
|
||||
presentCount: number;
|
||||
typeCounts: FieldValueTypeCounts;
|
||||
stringStats: FieldStringStats | null;
|
||||
examples: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes`
|
||||
* and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field.
|
||||
*/
|
||||
class FieldShapeAccumulator {
|
||||
private readonly maxExamples: number;
|
||||
private readonly maxExampleLength: number;
|
||||
private readonly fields = new Map<string, MutableFieldAccumulator>();
|
||||
private docCount = 0;
|
||||
|
||||
constructor(maxExamples: number, maxExampleLength: number) {
|
||||
this.maxExamples = maxExamples;
|
||||
this.maxExampleLength = maxExampleLength;
|
||||
}
|
||||
|
||||
addDocument(doc: unknown): void {
|
||||
this.docCount += 1;
|
||||
if (!isPlainNestedObject(doc)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = Object.keys(doc);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
if (key === undefined) {
|
||||
continue;
|
||||
}
|
||||
const value = doc[key];
|
||||
if (value === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suppressExamples = key === '_id';
|
||||
const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples);
|
||||
if (valueType === 'object' && isPlainNestedObject(value)) {
|
||||
const childKeys = Object.keys(value);
|
||||
for (let j = 0; j < childKeys.length; j++) {
|
||||
const childKey = childKeys[j];
|
||||
if (childKey === undefined) {
|
||||
continue;
|
||||
}
|
||||
const childValue = value[childKey];
|
||||
if (childValue === undefined) {
|
||||
continue;
|
||||
}
|
||||
this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
finalize(): CollectionFieldShapesSummary {
|
||||
const sortedNames = Array.from(this.fields.keys()).sort(compareAscii);
|
||||
const summaries: FieldShapeSummary[] = [];
|
||||
for (let i = 0; i < sortedNames.length; i++) {
|
||||
const fieldName = sortedNames[i];
|
||||
if (fieldName === undefined) {
|
||||
continue;
|
||||
}
|
||||
const acc = this.fields.get(fieldName);
|
||||
if (acc === undefined) {
|
||||
continue;
|
||||
}
|
||||
summaries.push({
|
||||
field: fieldName,
|
||||
presentCount: acc.presentCount,
|
||||
missingCount: this.docCount - acc.presentCount,
|
||||
typeCounts: { ...acc.typeCounts },
|
||||
stringStats:
|
||||
acc.stringStats === null
|
||||
? null
|
||||
: {
|
||||
minLength: acc.stringStats.minLength,
|
||||
maxLength: acc.stringStats.maxLength,
|
||||
patterns: { ...acc.stringStats.patterns },
|
||||
},
|
||||
examples: [...acc.examples],
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
docCount: this.docCount,
|
||||
fields: summaries,
|
||||
};
|
||||
}
|
||||
|
||||
private recordFieldValue(
|
||||
fieldPath: string,
|
||||
value: unknown,
|
||||
suppressExamples: boolean
|
||||
): FieldValueType {
|
||||
let acc = this.fields.get(fieldPath);
|
||||
if (acc === undefined) {
|
||||
acc = {
|
||||
presentCount: 0,
|
||||
typeCounts: createEmptyTypeCounts(),
|
||||
stringStats: null,
|
||||
examples: [],
|
||||
};
|
||||
this.fields.set(fieldPath, acc);
|
||||
}
|
||||
|
||||
const valueType = classifyValueType(value);
|
||||
acc.presentCount += 1;
|
||||
acc.typeCounts[valueType] += 1;
|
||||
|
||||
if (valueType === 'string') {
|
||||
const str = value as string;
|
||||
const len = str.length;
|
||||
if (acc.stringStats === null) {
|
||||
acc.stringStats = {
|
||||
minLength: len,
|
||||
maxLength: len,
|
||||
patterns: createEmptyStringPatternCounts(),
|
||||
};
|
||||
} else {
|
||||
if (len < acc.stringStats.minLength) {
|
||||
acc.stringStats.minLength = len;
|
||||
}
|
||||
if (len > acc.stringStats.maxLength) {
|
||||
acc.stringStats.maxLength = len;
|
||||
}
|
||||
}
|
||||
acc.stringStats.patterns[classifyStringPattern(str)] += 1;
|
||||
}
|
||||
|
||||
if (this.maxExamples > 0 && !suppressExamples) {
|
||||
const example = extractScalarExample(value, valueType, this.maxExampleLength);
|
||||
if (example !== null) {
|
||||
this.insertExample(acc.examples, example);
|
||||
}
|
||||
}
|
||||
|
||||
return valueType;
|
||||
}
|
||||
|
||||
private insertExample(examples: string[], candidate: string): void {
|
||||
const len = examples.length;
|
||||
const last = len > 0 ? examples[len - 1] : undefined;
|
||||
if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let insertAt = len;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const existing = examples[i];
|
||||
if (existing === undefined) {
|
||||
continue;
|
||||
}
|
||||
const cmp = compareAscii(candidate, existing);
|
||||
if (cmp === 0) {
|
||||
return;
|
||||
}
|
||||
if (cmp < 0) {
|
||||
insertAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
examples.splice(insertAt, 0, candidate);
|
||||
if (examples.length > this.maxExamples) {
|
||||
examples.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, deterministic summarizer for field names, BSON/JS value types, string patterns,
|
||||
* and bounded sanitized examples across an iterable of documents from one collection.
|
||||
*/
|
||||
export function summarizeFieldShapes(
|
||||
docs: Iterable<Record<string, unknown>>,
|
||||
options?: SummarizeFieldShapesOptions
|
||||
): CollectionFieldShapesSummary {
|
||||
if (
|
||||
docs === null ||
|
||||
docs === undefined ||
|
||||
typeof (docs as unknown as Record<symbol, unknown>)[Symbol.iterator] !== 'function'
|
||||
) {
|
||||
throw new TypeError('docs must be an Iterable of document objects');
|
||||
}
|
||||
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
|
||||
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
|
||||
for (const doc of docs) {
|
||||
accumulator.addDocument(doc);
|
||||
}
|
||||
return accumulator.finalize();
|
||||
}
|
||||
|
||||
export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection {
|
||||
return ALLOWED_PROBE_COLLECTION_SET.has(value);
|
||||
}
|
||||
|
||||
export function normalizeProbeCollections(
|
||||
collections?: readonly string[]
|
||||
): FieldShapeProbeCollection[] {
|
||||
const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections;
|
||||
if (!Array.isArray(source) || source.length === 0) {
|
||||
throw new RangeError('collections must be a non-empty array of allowed probe collection names');
|
||||
}
|
||||
const unique = new Set<FieldShapeProbeCollection>();
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const name = source[i];
|
||||
if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) {
|
||||
throw new UnknownProbeCollectionError(String(name));
|
||||
}
|
||||
unique.add(name);
|
||||
}
|
||||
return Array.from(unique).sort(compareAscii);
|
||||
}
|
||||
|
||||
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
|
||||
if (
|
||||
reader === null ||
|
||||
reader === undefined ||
|
||||
typeof reader !== 'object' ||
|
||||
typeof reader.isReadOnly !== 'function' ||
|
||||
typeof reader.find !== 'function' ||
|
||||
reader.isReadOnly() !== true
|
||||
) {
|
||||
throw new Error(
|
||||
'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
|
||||
return (
|
||||
value !== null &&
|
||||
(typeof value === 'object' || typeof value === 'function') &&
|
||||
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function wrapCollectionReadError(collectionName: string, error: unknown): Error {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
const message = detail.includes(collectionName)
|
||||
? detail
|
||||
: `Failed reading collection "${collectionName}": ${detail}`;
|
||||
return new Error(message, { cause: error });
|
||||
}
|
||||
|
||||
async function streamBoundedCollectionIntoAccumulator(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
collectionName: FieldShapeProbeCollection,
|
||||
limit: number,
|
||||
findOptions: SourceSymbolFindOptions,
|
||||
accumulator: FieldShapeAccumulator
|
||||
): Promise<void> {
|
||||
assertReadOnlyReader(reader);
|
||||
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
|
||||
null;
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
let isInvalidCursorError = false;
|
||||
|
||||
try {
|
||||
const rawCursor = await reader.find<Record<string, unknown>>(collectionName, {}, findOptions);
|
||||
if (
|
||||
rawCursor !== null &&
|
||||
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
|
||||
) {
|
||||
closableHandle = rawCursor as Pick<
|
||||
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
|
||||
'close'
|
||||
>;
|
||||
}
|
||||
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(rawCursor)) {
|
||||
isInvalidCursorError = true;
|
||||
throw new TypeError(
|
||||
`Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)`
|
||||
);
|
||||
}
|
||||
|
||||
let seen = 0;
|
||||
if (limit > 0) {
|
||||
for await (const doc of rawCursor) {
|
||||
accumulator.addDocument(doc);
|
||||
seen += 1;
|
||||
if (seen >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
hasPrimaryError = true;
|
||||
} finally {
|
||||
if (closableHandle !== null && typeof closableHandle.close === 'function') {
|
||||
try {
|
||||
await closableHandle.close();
|
||||
} catch (closeError) {
|
||||
if (!hasPrimaryError) {
|
||||
primaryError = closeError;
|
||||
hasPrimaryError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPrimaryError) {
|
||||
if (isInvalidCursorError) {
|
||||
throw primaryError;
|
||||
}
|
||||
throw wrapCollectionReadError(collectionName, primaryError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded, read-only MongoDB field-shape probe over allowlisted source collections.
|
||||
* Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })`
|
||||
* with zero aggregations, `$sample`, writes, or index operations.
|
||||
*/
|
||||
export async function readFieldShapes(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
options?: ReadFieldShapesOptions
|
||||
): Promise<ReadFieldShapesResult> {
|
||||
assertReadOnlyReader(reader);
|
||||
|
||||
if (options !== undefined && (options === null || typeof options !== 'object')) {
|
||||
throw new TypeError('options must be an object');
|
||||
}
|
||||
|
||||
const limit =
|
||||
options?.limit !== undefined
|
||||
? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT)
|
||||
: DEFAULT_FIELD_SHAPE_LIMIT;
|
||||
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
|
||||
const batchSize =
|
||||
options?.batchSize !== undefined
|
||||
? validatePositiveSafeInt(options.batchSize, 'options.batchSize')
|
||||
: undefined;
|
||||
const collections = normalizeProbeCollections(options?.collections);
|
||||
|
||||
const findOptions: SourceSymbolFindOptions = {
|
||||
limit,
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
...(batchSize !== undefined ? { batchSize } : {}),
|
||||
};
|
||||
|
||||
const results: CollectionFieldShapesProbeResult[] = [];
|
||||
let totalDocsSampled = 0;
|
||||
|
||||
for (const collection of collections) {
|
||||
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
|
||||
await streamBoundedCollectionIntoAccumulator(
|
||||
reader,
|
||||
collection,
|
||||
limit,
|
||||
findOptions,
|
||||
accumulator
|
||||
);
|
||||
const summary = accumulator.finalize();
|
||||
totalDocsSampled += summary.docCount;
|
||||
results.push({
|
||||
collection,
|
||||
docCount: summary.docCount,
|
||||
fields: summary.fields,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
limit,
|
||||
maxExamples,
|
||||
maxExampleLength,
|
||||
totalDocsSampled,
|
||||
collections: results,
|
||||
};
|
||||
}
|
||||
|
||||
function formatHtmlCodeElement(value: string): string {
|
||||
const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => {
|
||||
switch (ch) {
|
||||
case '&':
|
||||
return '&';
|
||||
case '<':
|
||||
return '<';
|
||||
case '>':
|
||||
return '>';
|
||||
case '|':
|
||||
return '|';
|
||||
default:
|
||||
return `&#${ch.charCodeAt(0)};`;
|
||||
}
|
||||
});
|
||||
return `<code>${escaped}</code>`;
|
||||
}
|
||||
|
||||
function formatMarkdownCodeCell(value: string): string {
|
||||
const normalized = value.replace(/\r\n|\r|\n/g, ' ');
|
||||
// Empty spans cannot be written with backtick fences; values containing `\|`
|
||||
// would become `\\|` under pipe escaping, which GFM/micromark parses as an
|
||||
// escaped backslash followed by a cell-splitting pipe. Use an HTML <code>
|
||||
// element with entity-encoded pipes and Markdown metacharacters instead.
|
||||
if (normalized.length === 0 || normalized.includes('\\|')) {
|
||||
return formatHtmlCodeElement(normalized);
|
||||
}
|
||||
const tableSafe = normalized.replace(/\|/g, '\\|');
|
||||
let maxBacktickRun = 0;
|
||||
let currentRun = 0;
|
||||
for (let i = 0; i < tableSafe.length; i++) {
|
||||
if (tableSafe.charCodeAt(i) === 96) {
|
||||
currentRun += 1;
|
||||
if (currentRun > maxBacktickRun) {
|
||||
maxBacktickRun = currentRun;
|
||||
}
|
||||
} else {
|
||||
currentRun = 0;
|
||||
}
|
||||
}
|
||||
const fence = '`'.repeat(maxBacktickRun + 1);
|
||||
const startsWithBacktick = tableSafe.charCodeAt(0) === 96;
|
||||
const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96;
|
||||
const startsAndEndsWithSpace =
|
||||
tableSafe.charCodeAt(0) === 32 &&
|
||||
tableSafe.charCodeAt(tableSafe.length - 1) === 32 &&
|
||||
tableSafe.trim().length > 0;
|
||||
const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace;
|
||||
return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`;
|
||||
}
|
||||
|
||||
function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string {
|
||||
const parts: string[] = [];
|
||||
for (const typeName of FIELD_VALUE_TYPES) {
|
||||
const count = typeCounts[typeName];
|
||||
if (count > 0) {
|
||||
parts.push(`${typeName}: ${count}`);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(', ') : '—';
|
||||
}
|
||||
|
||||
function formatStringStatsCell(stringStats: FieldStringStats | null): string {
|
||||
if (stringStats === null) {
|
||||
return '—';
|
||||
}
|
||||
const parts: string[] = [];
|
||||
for (const pattern of STRING_PATTERN_CLASSES) {
|
||||
const count = stringStats.patterns[pattern];
|
||||
if (count > 0) {
|
||||
parts.push(`${pattern}: ${count}`);
|
||||
}
|
||||
}
|
||||
const patternText = parts.length > 0 ? parts.join(', ') : 'none';
|
||||
return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`;
|
||||
}
|
||||
|
||||
function formatExamplesCell(examples: readonly string[]): string {
|
||||
if (examples.length === 0) {
|
||||
return '—';
|
||||
}
|
||||
return examples.map(formatMarkdownCodeCell).join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or
|
||||
* filesystem paths). Identical results always produce byte-identical Markdown.
|
||||
*/
|
||||
export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string {
|
||||
const sortedCollections = [...result.collections].sort((a, b) =>
|
||||
compareAscii(a.collection, b.collection)
|
||||
);
|
||||
|
||||
const lines: string[] = [
|
||||
'# Source Field Shapes Report',
|
||||
'',
|
||||
'- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)',
|
||||
`- **Sample limit per collection:** ${result.limit}`,
|
||||
`- **Collections probed:** ${sortedCollections.length}`,
|
||||
`- **Total documents sampled:** ${result.totalDocsSampled}`,
|
||||
];
|
||||
|
||||
for (const col of sortedCollections) {
|
||||
lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, '');
|
||||
|
||||
if (col.docCount === 0) {
|
||||
lines.push('_No documents sampled._');
|
||||
continue;
|
||||
}
|
||||
|
||||
const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field));
|
||||
if (sortedFields.length === 0) {
|
||||
lines.push('_No fields observed._');
|
||||
continue;
|
||||
}
|
||||
|
||||
lines.push('| Field | Presence | Types | String Patterns | Examples |');
|
||||
lines.push('| --- | --- | --- | --- | --- |');
|
||||
|
||||
for (const field of sortedFields) {
|
||||
const pct = ((field.presentCount / col.docCount) * 100).toFixed(1);
|
||||
const fieldCell = formatMarkdownCodeCell(field.field);
|
||||
const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`;
|
||||
const typesCell = formatTypeCountsCell(field.typeCounts);
|
||||
const patternsCell = formatStringStatsCell(field.stringStats);
|
||||
const examplesCell = formatExamplesCell(field.examples);
|
||||
lines.push(
|
||||
`| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
|
@ -53,6 +53,9 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US',
|
|||
export interface SourceSymbolFindOptions {
|
||||
projection?: Record<string, 0 | 1>;
|
||||
batchSize?: number;
|
||||
limit?: number;
|
||||
promoteValues?: boolean;
|
||||
promoteLongs?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
330
apps/stock/data-pipeline/test/sample-closes-edge.test.ts
Normal file
330
apps/stock/data-pipeline/test/sample-closes-edge.test.ts
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
buildSampleCloseFilter,
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
EOD_SAMPLE_CLOSES_PROJECTION,
|
||||
FX_USD_CAD_SOURCE_ID,
|
||||
MAX_SAMPLE_DATES,
|
||||
QM_SAMPLE_CLOSES_PROJECTION,
|
||||
readSampleCloses,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SampleCloseSource,
|
||||
type SampleCloseSourceReadStats,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
// QA edge cases for the Pass 4a sample-close reader that complement sample-closes.test.ts.
|
||||
// All readers are in-memory; no MongoDB / PostgreSQL / network.
|
||||
|
||||
interface RecordedCall {
|
||||
collectionName: string;
|
||||
filter: Record<string, unknown> | undefined;
|
||||
options: SourceSymbolFindOptions | undefined;
|
||||
}
|
||||
|
||||
function unfilteredReader(docsByCollection: Record<string, readonly unknown[]>): {
|
||||
reader: ReadOnlySourceSymbolReader;
|
||||
calls: RecordedCall[];
|
||||
} {
|
||||
const calls: RecordedCall[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
filter?: Record<string, unknown>,
|
||||
options?: SourceSymbolFindOptions
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
calls.push({ collectionName, filter, options });
|
||||
const docs = docsByCollection[collectionName] ?? [];
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (const doc of docs) {
|
||||
yield doc as T;
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
return { reader, calls };
|
||||
}
|
||||
|
||||
function expectReconciled(stats: SampleCloseSourceReadStats): void {
|
||||
const s = stats.skipped;
|
||||
expect(stats.skippedTotal).toBe(
|
||||
s.missingId + s.unrequestedId + s.invalidDate + s.unrequestedDate + s.invalidClose
|
||||
);
|
||||
expect(stats.docsRead).toBe(stats.emitted + stats.skippedTotal);
|
||||
}
|
||||
|
||||
function makeDistinctDates(count: number): string[] {
|
||||
const out: string[] = [];
|
||||
const start = Date.UTC(2020, 0, 1);
|
||||
for (let i = 0; i < count; i++) {
|
||||
out.push(new Date(start + i * 86_400_000).toISOString().slice(0, 10));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('Pass 4a sample-closes reader — QA edge cases', () => {
|
||||
test('streams end to end through createReadOnlyMongoSourceSymbolReader, forwarding filter/projection/batchSize and closing driver cursors', async () => {
|
||||
const collectionCalls: Array<{
|
||||
name: string;
|
||||
filter: Record<string, unknown>;
|
||||
options: SourceSymbolFindOptions | undefined;
|
||||
}> = [];
|
||||
let driverCursorsClosed = 0;
|
||||
const store: Record<string, Record<string, unknown>[]> = {
|
||||
eodPrices: [
|
||||
{ eodSearchCode: 'RY.TO', date: '2024-03-01', close: 130.5 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-03-01', close: 1.355 },
|
||||
],
|
||||
qmPrices: [{ qmSearchCode: 'RY', date: '2024-03-01', unadjustedclose: 96.3 }],
|
||||
};
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection(name: string) {
|
||||
return {
|
||||
find(filter: Record<string, unknown>, options?: SourceSymbolFindOptions) {
|
||||
collectionCalls.push({ name, filter, options });
|
||||
const idField = name === 'eodPrices' ? 'eodSearchCode' : 'qmSearchCode';
|
||||
const ids = (filter[idField] as { $in: string[] }).$in;
|
||||
const dates = (filter.date as { $in: string[] }).$in;
|
||||
const docs = (store[name] ?? []).filter(
|
||||
d => ids.includes(d[idField] as string) && dates.includes(d.date as string)
|
||||
);
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield* docs;
|
||||
},
|
||||
async close() {
|
||||
driverCursorsClosed += 1;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const result = await readSampleCloses(createReadOnlyMongoSourceSymbolReader(client), {
|
||||
sampleDates: ['2024-03-01'],
|
||||
sourceIdsBySource: { eod: ['RY.TO'], qm: ['RY'] },
|
||||
batchSize: 1000,
|
||||
});
|
||||
|
||||
expect(collectionCalls.map(c => c.name)).toEqual(['eodPrices', 'qmPrices', 'eodPrices']);
|
||||
expect(collectionCalls[0]?.options).toEqual({
|
||||
projection: { ...EOD_SAMPLE_CLOSES_PROJECTION },
|
||||
batchSize: 1000,
|
||||
});
|
||||
expect(collectionCalls[1]?.options).toEqual({
|
||||
projection: { ...QM_SAMPLE_CLOSES_PROJECTION },
|
||||
batchSize: 1000,
|
||||
});
|
||||
for (const call of collectionCalls) {
|
||||
expect(Object.keys(call.filter)[0]).toBe('date');
|
||||
}
|
||||
expect(driverCursorsClosed).toBe(3);
|
||||
expect(result.closes).toEqual([
|
||||
{ source: 'eod', sourceId: 'RY.TO', date: '2024-03-01', close: 130.5 },
|
||||
{ source: 'qm', sourceId: 'RY', date: '2024-03-01', close: 96.3 },
|
||||
]);
|
||||
expect(result.fxRates).toEqual([{ date: '2024-03-01', usdCad: 1.355 }]);
|
||||
});
|
||||
|
||||
test('accepts exactly MAX_SAMPLE_DATES dates and applies the cap after de-duplication', async () => {
|
||||
const exact = makeDistinctDates(MAX_SAMPLE_DATES);
|
||||
const { reader } = unfilteredReader({});
|
||||
const atCap = await readSampleCloses(reader, {
|
||||
sampleDates: exact,
|
||||
sourceIdsBySource: { eod: ['A.US'], qm: [] },
|
||||
includeFx: false,
|
||||
});
|
||||
expect(atCap.sampleDates).toHaveLength(MAX_SAMPLE_DATES);
|
||||
|
||||
const withDuplicates = [...exact, ...exact.slice(0, 10)];
|
||||
expect(withDuplicates.length).toBeGreaterThan(MAX_SAMPLE_DATES);
|
||||
const deduped = await readSampleCloses(reader, {
|
||||
sampleDates: withDuplicates,
|
||||
sourceIdsBySource: { eod: ['A.US'], qm: [] },
|
||||
includeFx: false,
|
||||
});
|
||||
expect(deduped.sampleDates).toEqual(exact);
|
||||
});
|
||||
|
||||
test('chunked finds never emit a row twice and count other-chunk ids as unrequested', async () => {
|
||||
const ids = ['A.US', 'B.US', 'C.US', 'D.US'];
|
||||
const { reader, calls } = unfilteredReader({
|
||||
eodPrices: ids.map((id, i) => ({ eodSearchCode: id, date: '2024-02-01', close: 10 + i })),
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(reader, {
|
||||
sampleDates: ['2024-02-01'],
|
||||
sourceIdsBySource: { eod: ids, qm: [] },
|
||||
idChunkSize: 2,
|
||||
includeFx: false,
|
||||
});
|
||||
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(result.stats.eod.findsRun).toBe(2);
|
||||
expect(result.closes.map(c => c.sourceId)).toEqual(ids);
|
||||
expect(result.stats.eod.docsRead).toBe(8);
|
||||
expect(result.stats.eod.emitted).toBe(4);
|
||||
expect(result.stats.eod.skipped.unrequestedId).toBe(4);
|
||||
expectReconciled(result.stats.eod);
|
||||
});
|
||||
|
||||
test('wraps synchronous throws and rejected find() promises with the collection name and cause', async () => {
|
||||
const syncCause = new Error('auth failed');
|
||||
const syncReader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find: () => {
|
||||
throw syncCause;
|
||||
},
|
||||
};
|
||||
const syncError = await readSampleCloses(syncReader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: [], qm: ['AAPL'] },
|
||||
includeFx: false,
|
||||
}).catch((e: unknown) => e);
|
||||
expect(syncError).toBeInstanceOf(Error);
|
||||
expect((syncError as Error).message).toContain('qmPrices');
|
||||
expect((syncError as Error).message).toContain('auth failed');
|
||||
expect((syncError as Error).cause).toBe(syncCause);
|
||||
|
||||
const asyncCause = new Error('server selection timed out');
|
||||
const asyncReader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find: () => Promise.reject(asyncCause),
|
||||
};
|
||||
const asyncError = await readSampleCloses(asyncReader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
includeFx: false,
|
||||
}).catch((e: unknown) => e);
|
||||
expect((asyncError as Error).message).toContain('eodPrices');
|
||||
expect((asyncError as Error).cause).toBe(asyncCause);
|
||||
});
|
||||
|
||||
test('requested ids with surrounding spaces do not match trimmed stored ids, and blank-only id lists issue no finds', async () => {
|
||||
const { reader, calls } = unfilteredReader({
|
||||
eodPrices: [{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185 }],
|
||||
qmPrices: [{ qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185 }],
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US '], qm: [' ', ''] },
|
||||
includeFx: false,
|
||||
});
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]?.filter?.eodSearchCode).toEqual({ $in: ['AAPL.US '] });
|
||||
expect(result.closes).toEqual([]);
|
||||
expect(result.stats.eod.skipped.unrequestedId).toBe(1);
|
||||
expect(result.stats.qm.findsRun).toBe(0);
|
||||
});
|
||||
|
||||
test('stops before the next find when the reader stops reporting read-only mid-run', async () => {
|
||||
let readOnly = true;
|
||||
const collections: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => readOnly,
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
collections.push(collectionName);
|
||||
readOnly = false;
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
// empty
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
readSampleCloses(reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: ['AAPL'] },
|
||||
})
|
||||
).rejects.toThrow(/isReadOnly/);
|
||||
expect(collections).toEqual(['eodPrices']);
|
||||
});
|
||||
|
||||
test('qm rows never fall back to close/adjustedclose when unadjustedclose is missing', async () => {
|
||||
const { reader } = unfilteredReader({
|
||||
qmPrices: [
|
||||
{ qmSearchCode: 'AAPL', date: '2024-01-02', close: 185, adjustedclose: 184 },
|
||||
{ qmSearchCode: 'AAPL', date: '2024-01-03', unadjustedclose: null, close: 186 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(reader, {
|
||||
sampleDates: ['2024-01-02', '2024-01-03'],
|
||||
sourceIdsBySource: { eod: [], qm: ['AAPL'] },
|
||||
includeFx: false,
|
||||
});
|
||||
|
||||
expect(result.closes).toEqual([]);
|
||||
expect(result.stats.qm.skipped.invalidClose).toBe(2);
|
||||
expectReconciled(result.stats.qm);
|
||||
});
|
||||
|
||||
test('FX rates keep CAD-per-USD orientation and includeFx=false issues no FX find', async () => {
|
||||
const docs = { eodPrices: [{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.35 }] };
|
||||
|
||||
const withFx = await readSampleCloses(unfilteredReader(docs).reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: [], qm: [] },
|
||||
});
|
||||
expect(withFx.fxRates).toEqual([{ date: '2024-01-02', usdCad: 1.35 }]);
|
||||
|
||||
const noFx = unfilteredReader(docs);
|
||||
const withoutFx = await readSampleCloses(noFx.reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: [], qm: [] },
|
||||
includeFx: false,
|
||||
});
|
||||
expect(noFx.calls).toHaveLength(0);
|
||||
expect(withoutFx.fxRates).toEqual([]);
|
||||
expect(withoutFx.stats.fx.findsRun).toBe(0);
|
||||
});
|
||||
|
||||
test('does not mutate caller inputs', async () => {
|
||||
const sampleDates = ['2024-01-03', '2024-01-02', '2024-01-03'];
|
||||
const eod = ['B.US', 'A.US', FX_USD_CAD_SOURCE_ID];
|
||||
const qm = ['B', 'A'];
|
||||
const { reader } = unfilteredReader({});
|
||||
|
||||
buildSampleCloseFilter('eod', sampleDates, eod);
|
||||
await readSampleCloses(reader, { sampleDates, sourceIdsBySource: { eod, qm } });
|
||||
|
||||
expect(sampleDates).toEqual(['2024-01-03', '2024-01-02', '2024-01-03']);
|
||||
expect(eod).toEqual(['B.US', 'A.US', FX_USD_CAD_SOURCE_ID]);
|
||||
expect(qm).toEqual(['B', 'A']);
|
||||
});
|
||||
|
||||
test('rejects unsupported sources and non-string requested ids before any find', async () => {
|
||||
expect(() =>
|
||||
buildSampleCloseFilter('ib' as unknown as SampleCloseSource, ['2024-01-02'])
|
||||
).toThrow(RangeError);
|
||||
|
||||
const { reader, calls } = unfilteredReader({});
|
||||
await expect(
|
||||
readSampleCloses(reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['A.US'], qm: [42 as unknown as string] },
|
||||
})
|
||||
).rejects.toThrow(TypeError);
|
||||
await expect(
|
||||
readSampleCloses(reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['A.US'], qm: [] },
|
||||
batchSize: 1.5,
|
||||
})
|
||||
).rejects.toThrow(RangeError);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
860
apps/stock/data-pipeline/test/sample-closes.test.ts
Normal file
860
apps/stock/data-pipeline/test/sample-closes.test.ts
Normal file
|
|
@ -0,0 +1,860 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
buildSampleCloseFilter,
|
||||
crossCheckPrices,
|
||||
DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE,
|
||||
EOD_SAMPLE_CLOSES_PROJECTION,
|
||||
FX_USD_CAD_SOURCE_ID,
|
||||
MAX_SAMPLE_DATES,
|
||||
QM_SAMPLE_CLOSES_PROJECTION,
|
||||
readSampleCloses,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SampleCloseSourceReadStats,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
interface RecordedFindCall {
|
||||
collectionName: string;
|
||||
filter: Record<string, unknown> | undefined;
|
||||
options: SourceSymbolFindOptions | undefined;
|
||||
}
|
||||
|
||||
interface FakeReaderOptions {
|
||||
readOnly?: boolean;
|
||||
applyFilter?: boolean;
|
||||
applyProjection?: boolean;
|
||||
failOnCallIndex?: number;
|
||||
failAfterDocs?: number;
|
||||
failMessage?: string;
|
||||
failCloseOnCallIndex?: number;
|
||||
}
|
||||
|
||||
interface FakeReaderHandle {
|
||||
reader: ReadOnlySourceSymbolReader;
|
||||
calls: RecordedFindCall[];
|
||||
closedCount: () => number;
|
||||
}
|
||||
|
||||
function matchesSimpleFilter(
|
||||
doc: unknown,
|
||||
filter: Record<string, unknown> | undefined
|
||||
): boolean {
|
||||
if (filter === undefined) {
|
||||
return true;
|
||||
}
|
||||
if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
|
||||
return false;
|
||||
}
|
||||
const record = doc as Record<string, unknown>;
|
||||
for (const [key, condition] of Object.entries(filter)) {
|
||||
if (
|
||||
condition !== null &&
|
||||
typeof condition === 'object' &&
|
||||
!Array.isArray(condition) &&
|
||||
'$in' in condition
|
||||
) {
|
||||
const allowed = (condition as { $in: unknown[] }).$in;
|
||||
if (!allowed.includes(record[key])) {
|
||||
return false;
|
||||
}
|
||||
} else if (record[key] !== condition) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function projectDoc(
|
||||
doc: unknown,
|
||||
projection: Record<string, 0 | 1> | undefined
|
||||
): Record<string, unknown> {
|
||||
if (projection === undefined || doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
|
||||
return doc as Record<string, unknown>;
|
||||
}
|
||||
const record = doc as Record<string, unknown>;
|
||||
const projected: Record<string, unknown> = {};
|
||||
for (const [key, include] of Object.entries(projection)) {
|
||||
if (include === 1 && key in record) {
|
||||
projected[key] = record[key];
|
||||
}
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
function createFakeReader(
|
||||
docsByCollection: Record<string, readonly unknown[]>,
|
||||
options: FakeReaderOptions = {}
|
||||
): FakeReaderHandle {
|
||||
const calls: RecordedFindCall[] = [];
|
||||
let closed = 0;
|
||||
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly(): boolean {
|
||||
return options.readOnly ?? true;
|
||||
},
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
filter?: Record<string, unknown>,
|
||||
findOptions?: SourceSymbolFindOptions
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
const callIndex = calls.length;
|
||||
calls.push({ collectionName, filter, options: findOptions });
|
||||
|
||||
const rawDocs = docsByCollection[collectionName] ?? [];
|
||||
const shouldFail = options.failOnCallIndex === callIndex;
|
||||
const failAfter = options.failAfterDocs ?? 0;
|
||||
const failMessage = options.failMessage ?? 'simulated cursor read failure';
|
||||
const shouldFailClose = options.failCloseOnCallIndex === callIndex;
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
let yielded = 0;
|
||||
for (let i = 0; i < rawDocs.length; i++) {
|
||||
const rawDoc = rawDocs[i];
|
||||
if (options.applyFilter && !matchesSimpleFilter(rawDoc, filter)) {
|
||||
continue;
|
||||
}
|
||||
if (shouldFail && yielded >= failAfter) {
|
||||
throw new Error(failMessage);
|
||||
}
|
||||
const out = options.applyProjection
|
||||
? projectDoc(rawDoc, findOptions?.projection)
|
||||
: rawDoc;
|
||||
yielded += 1;
|
||||
yield out as T;
|
||||
}
|
||||
if (shouldFail && yielded >= failAfter) {
|
||||
throw new Error(failMessage);
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
closed += 1;
|
||||
if (shouldFailClose) {
|
||||
throw new Error('simulated cursor close failure');
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
reader,
|
||||
calls,
|
||||
closedCount: () => closed,
|
||||
};
|
||||
}
|
||||
|
||||
function assertStatsReconcile(stats: SampleCloseSourceReadStats): void {
|
||||
const skipSum =
|
||||
stats.skipped.missingId +
|
||||
stats.skipped.unrequestedId +
|
||||
stats.skipped.invalidDate +
|
||||
stats.skipped.unrequestedDate +
|
||||
stats.skipped.invalidClose;
|
||||
expect(stats.skippedTotal).toBe(skipSum);
|
||||
expect(stats.docsRead).toBe(stats.emitted + stats.skippedTotal);
|
||||
}
|
||||
|
||||
function makeSampleDates(count: number): string[] {
|
||||
const dates: string[] = [];
|
||||
let year = 2024;
|
||||
let month = 1;
|
||||
let day = 1;
|
||||
while (dates.length < count) {
|
||||
dates.push(
|
||||
`${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
);
|
||||
day += 1;
|
||||
if (day > 28) {
|
||||
day = 1;
|
||||
month += 1;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
describe('Pass 4a sample-closes reader', () => {
|
||||
test('sample-closes.ts has zero runtime DB, FS, or network imports', () => {
|
||||
const srcPath = resolve(import.meta.dir, '../src/security-master/sample-closes.ts');
|
||||
const source = readFileSync(srcPath, 'utf8');
|
||||
const importLines = source
|
||||
.split('\n')
|
||||
.filter(line => /^\s*import\b/.test(line) && !/^\s*import\s+type\b/.test(line));
|
||||
|
||||
for (const line of importLines) {
|
||||
expect(line).not.toContain('mongodb');
|
||||
expect(line).not.toContain('postgres');
|
||||
expect(line).not.toContain('node:fs');
|
||||
expect(line).not.toContain('node:net');
|
||||
expect(line).not.toContain('node:http');
|
||||
expect(line).not.toContain('node:https');
|
||||
}
|
||||
expect(source).toContain('BAR_SPAN_COLLECTIONS');
|
||||
expect(source).not.toContain("collection: 'eodPrices'");
|
||||
expect(source).not.toContain("collection: 'qmPrices'");
|
||||
});
|
||||
|
||||
test('buildSampleCloseFilter emits date-first filters and preserves explicit empty id lists', () => {
|
||||
const dates = ['2024-06-14', '2024-01-05', '2024-06-14'];
|
||||
const eodFilter = buildSampleCloseFilter('eod', dates, ['MSFT.US', 'AAPL.US', 'AAPL.US']);
|
||||
expect(Object.keys(eodFilter)).toEqual(['date', 'eodSearchCode']);
|
||||
expect(eodFilter).toEqual({
|
||||
date: { $in: ['2024-01-05', '2024-06-14'] },
|
||||
eodSearchCode: { $in: ['AAPL.US', 'MSFT.US'] },
|
||||
});
|
||||
|
||||
const qmFilter = buildSampleCloseFilter('qm', dates, ['AAPL']);
|
||||
expect(Object.keys(qmFilter)).toEqual(['date', 'qmSearchCode']);
|
||||
expect(qmFilter).toEqual({
|
||||
date: { $in: ['2024-01-05', '2024-06-14'] },
|
||||
qmSearchCode: { $in: ['AAPL'] },
|
||||
});
|
||||
|
||||
const dateOnlyFilter = buildSampleCloseFilter('eod', dates);
|
||||
expect(Object.keys(dateOnlyFilter)).toEqual(['date']);
|
||||
|
||||
const explicitEmptyFilter = buildSampleCloseFilter('qm', dates, []);
|
||||
expect(Object.keys(explicitEmptyFilter)).toEqual(['date', 'qmSearchCode']);
|
||||
expect(explicitEmptyFilter.qmSearchCode).toEqual({ $in: [] });
|
||||
});
|
||||
|
||||
test('passes date-first filter, strict projections, and batchSize to fake reader', async () => {
|
||||
const fake = createFakeReader(
|
||||
{
|
||||
eodPrices: [
|
||||
{
|
||||
eodSearchCode: 'AAPL.US',
|
||||
date: '2024-01-05',
|
||||
close: 181.18,
|
||||
adjustedClose: 180.5,
|
||||
volume: 999999,
|
||||
},
|
||||
{
|
||||
eodSearchCode: FX_USD_CAD_SOURCE_ID,
|
||||
date: '2024-01-05',
|
||||
close: 1.3365,
|
||||
},
|
||||
],
|
||||
qmPrices: [
|
||||
{
|
||||
qmSearchCode: 'AAPL',
|
||||
date: '2024-01-05',
|
||||
close: 999.99,
|
||||
adjustedclose: 180.5,
|
||||
unadjustedclose: 181.18,
|
||||
},
|
||||
],
|
||||
},
|
||||
{ applyFilter: true, applyProjection: true }
|
||||
);
|
||||
|
||||
const result = await readSampleCloses(fake.reader, {
|
||||
sampleDates: ['2024-06-14', '2024-01-05'],
|
||||
sourceIdsBySource: {
|
||||
eod: ['AAPL.US'],
|
||||
qm: ['AAPL'],
|
||||
},
|
||||
batchSize: 2500,
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(3);
|
||||
|
||||
// 1. eodPrices equity call
|
||||
expect(fake.calls[0]?.collectionName).toBe('eodPrices');
|
||||
expect(Object.keys(fake.calls[0]?.filter ?? {})).toEqual(['date', 'eodSearchCode']);
|
||||
expect(fake.calls[0]?.filter).toEqual({
|
||||
date: { $in: ['2024-01-05', '2024-06-14'] },
|
||||
eodSearchCode: { $in: ['AAPL.US'] },
|
||||
});
|
||||
expect(fake.calls[0]?.options).toEqual({
|
||||
projection: { ...EOD_SAMPLE_CLOSES_PROJECTION },
|
||||
batchSize: 2500,
|
||||
});
|
||||
|
||||
// 2. qmPrices equity call
|
||||
expect(fake.calls[1]?.collectionName).toBe('qmPrices');
|
||||
expect(Object.keys(fake.calls[1]?.filter ?? {})).toEqual(['date', 'qmSearchCode']);
|
||||
expect(fake.calls[1]?.filter).toEqual({
|
||||
date: { $in: ['2024-01-05', '2024-06-14'] },
|
||||
qmSearchCode: { $in: ['AAPL'] },
|
||||
});
|
||||
expect(fake.calls[1]?.options).toEqual({
|
||||
projection: { ...QM_SAMPLE_CLOSES_PROJECTION },
|
||||
batchSize: 2500,
|
||||
});
|
||||
expect(fake.calls[1]?.options?.projection).toEqual({
|
||||
_id: 0,
|
||||
qmSearchCode: 1,
|
||||
date: 1,
|
||||
unadjustedclose: 1,
|
||||
});
|
||||
|
||||
// 3. FX call on eodPrices for CAD.FOREX
|
||||
expect(fake.calls[2]?.collectionName).toBe('eodPrices');
|
||||
expect(Object.keys(fake.calls[2]?.filter ?? {})).toEqual(['date', 'eodSearchCode']);
|
||||
expect(fake.calls[2]?.filter).toEqual({
|
||||
date: { $in: ['2024-01-05', '2024-06-14'] },
|
||||
eodSearchCode: { $in: [FX_USD_CAD_SOURCE_ID] },
|
||||
});
|
||||
expect(fake.calls[2]?.options).toEqual({
|
||||
projection: { ...EOD_SAMPLE_CLOSES_PROJECTION },
|
||||
batchSize: 2500,
|
||||
});
|
||||
|
||||
expect(fake.closedCount()).toBe(3);
|
||||
expect(result.closes).toEqual([
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-05', close: 181.18 },
|
||||
{ source: 'qm', sourceId: 'AAPL', date: '2024-01-05', close: 181.18 },
|
||||
]);
|
||||
expect(result.fxRates).toEqual([{ date: '2024-01-05', usdCad: 1.3365 }]);
|
||||
assertStatsReconcile(result.stats.eod);
|
||||
assertStatsReconcile(result.stats.qm);
|
||||
assertStatsReconcile(result.stats.fx);
|
||||
});
|
||||
|
||||
test('uses raw close for eod, unadjustedclose for qm, and isolates CAD.FOREX exclusively to fxRates', async () => {
|
||||
const fake = createFakeReader({
|
||||
eodPrices: [
|
||||
{ eodSearchCode: 'NVDA.US', date: '2024-05-01', close: 830.41, adjustedClose: 83.04 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-05-01', close: 1.3742 },
|
||||
],
|
||||
qmPrices: [
|
||||
{
|
||||
qmSearchCode: 'NVDA',
|
||||
date: '2024-05-01',
|
||||
close: 83.04,
|
||||
adjustedclose: 83.04,
|
||||
unadjustedclose: 830.41,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(fake.reader, {
|
||||
sampleDates: ['2024-05-01'],
|
||||
sourceIdsBySource: {
|
||||
// Explicitly request CAD.FOREX in eod to prove it is stripped from equity reads.
|
||||
eod: ['NVDA.US', FX_USD_CAD_SOURCE_ID],
|
||||
qm: ['NVDA'],
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.closes).toEqual([
|
||||
{ source: 'eod', sourceId: 'NVDA.US', date: '2024-05-01', close: 830.41 },
|
||||
{ source: 'qm', sourceId: 'NVDA', date: '2024-05-01', close: 830.41 },
|
||||
]);
|
||||
expect(result.closes.some(row => row.sourceId === FX_USD_CAD_SOURCE_ID)).toBe(false);
|
||||
expect(result.fxRates).toEqual([{ date: '2024-05-01', usdCad: 1.3742 }]);
|
||||
|
||||
// During the eod equity scan, the unfiltered fake reader also yielded CAD.FOREX,
|
||||
// which must be skipped as unrequestedId rather than emitted into closes.
|
||||
expect(result.stats.eod.docsRead).toBe(2);
|
||||
expect(result.stats.eod.emitted).toBe(1);
|
||||
expect(result.stats.eod.skipped.unrequestedId).toBe(1);
|
||||
assertStatsReconcile(result.stats.eod);
|
||||
assertStatsReconcile(result.stats.qm);
|
||||
assertStatsReconcile(result.stats.fx);
|
||||
});
|
||||
|
||||
test('normalizes Date and string dates to UTC YYYY-MM-DD and reconciles all skip reasons', async () => {
|
||||
const fake = createFakeReader({
|
||||
eodPrices: [
|
||||
// Valid: exact string, Date UTC midnight, Date non-midnight UTC, ISO offset crossing into 2024-01-03 UTC
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 },
|
||||
{ eodSearchCode: 'AAPL.US', date: new Date('2024-01-03T00:00:00Z'), close: 184.25 },
|
||||
{ eodSearchCode: 'AAPL.US', date: new Date('2024-01-04T21:30:00Z'), close: 181.91 },
|
||||
{ eodSearchCode: 'MSFT.US', date: '2024-01-02T22:00:00-05:00', close: 370.6 },
|
||||
// missingId (null doc, non-string id, blank id)
|
||||
null,
|
||||
{ eodSearchCode: 123, date: '2024-01-02', close: 10 },
|
||||
{ eodSearchCode: ' ', date: '2024-01-02', close: 10 },
|
||||
// unrequestedId
|
||||
{ eodSearchCode: 'OTHER.US', date: '2024-01-02', close: 50 },
|
||||
// invalidDate (bad string, invalid Date, timezone-less timestamp)
|
||||
{ eodSearchCode: 'AAPL.US', date: '2023-02-29', close: 100 },
|
||||
{ eodSearchCode: 'AAPL.US', date: new Date('invalid'), close: 100 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02T16:00:00', close: 100 },
|
||||
// unrequestedDate (valid date outside sampleDates)
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-05', close: 181.18 },
|
||||
{ eodSearchCode: 'AAPL.US', date: new Date('2024-01-06T00:00:00Z'), close: 181.18 },
|
||||
// invalidClose (NaN, Infinity, -Infinity, 0, negative, string)
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.NaN },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.POSITIVE_INFINITY },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.NEGATIVE_INFINITY },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 0 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: -12.5 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: '185.64' },
|
||||
],
|
||||
qmPrices: [],
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(fake.reader, {
|
||||
sampleDates: ['2024-01-02', '2024-01-03', '2024-01-04'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US', 'MSFT.US'], qm: [] },
|
||||
includeFx: false,
|
||||
});
|
||||
|
||||
expect(result.closes).toEqual([
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 185.64 },
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-03', close: 184.25 },
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-04', close: 181.91 },
|
||||
{ source: 'eod', sourceId: 'MSFT.US', date: '2024-01-03', close: 370.6 },
|
||||
]);
|
||||
|
||||
expect(result.stats.eod.docsRead).toBe(19);
|
||||
expect(result.stats.eod.emitted).toBe(4);
|
||||
expect(result.stats.eod.skipped).toEqual({
|
||||
missingId: 3,
|
||||
unrequestedId: 1,
|
||||
invalidDate: 3,
|
||||
unrequestedDate: 2,
|
||||
invalidClose: 6,
|
||||
});
|
||||
assertStatsReconcile(result.stats.eod);
|
||||
expect(result.stats.qm.findsRun).toBe(0);
|
||||
expect(result.stats.fx.findsRun).toBe(0);
|
||||
});
|
||||
|
||||
test('does not trim source IDs (T-49): surrounded-space IDs match only identical requested IDs', async () => {
|
||||
const fake = createFakeReader({
|
||||
eodPrices: [
|
||||
{ eodSearchCode: ' AAPL.US ', date: '2024-01-02', close: 185.64 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 },
|
||||
],
|
||||
qmPrices: [
|
||||
{ qmSearchCode: ' AAPL ', date: '2024-01-02', unadjustedclose: 185.64 },
|
||||
{ qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.64 },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(fake.reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: {
|
||||
eod: [' AAPL.US '],
|
||||
qm: ['AAPL'],
|
||||
},
|
||||
includeFx: false,
|
||||
});
|
||||
|
||||
expect(result.closes).toEqual([
|
||||
{ source: 'eod', sourceId: ' AAPL.US ', date: '2024-01-02', close: 185.64 },
|
||||
{ source: 'qm', sourceId: 'AAPL', date: '2024-01-02', close: 185.64 },
|
||||
]);
|
||||
expect(result.stats.eod.skipped.unrequestedId).toBe(1);
|
||||
expect(result.stats.qm.skipped.unrequestedId).toBe(1);
|
||||
assertStatsReconcile(result.stats.eod);
|
||||
assertStatsReconcile(result.stats.qm);
|
||||
});
|
||||
|
||||
test('produces deterministic deep-equal output regardless of cursor or input order', async () => {
|
||||
const eodDocs = [
|
||||
{ eodSearchCode: 'MSFT.US', date: '2024-01-03', close: 371.0 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 186.0 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.0 },
|
||||
{ eodSearchCode: 'AAPL.US', date: '2024-01-03', close: 184.0 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-03', close: 1.335 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.331 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.329 },
|
||||
];
|
||||
const qmDocs = [
|
||||
{ qmSearchCode: 'MSFT', date: '2024-01-02', unadjustedclose: 370.0 },
|
||||
{ qmSearchCode: 'AAPL', date: '2024-01-03', unadjustedclose: 184.0 },
|
||||
{ qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.0 },
|
||||
];
|
||||
|
||||
const fakeA = createFakeReader({ eodPrices: eodDocs, qmPrices: qmDocs });
|
||||
const fakeB = createFakeReader({
|
||||
eodPrices: [...eodDocs].reverse(),
|
||||
qmPrices: [...qmDocs].reverse(),
|
||||
});
|
||||
|
||||
const resultA = await readSampleCloses(fakeA.reader, {
|
||||
sampleDates: ['2024-01-03', '2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['MSFT.US', 'AAPL.US'], qm: ['MSFT', 'AAPL'] },
|
||||
});
|
||||
const resultB = await readSampleCloses(fakeB.reader, {
|
||||
sampleDates: ['2024-01-02', '2024-01-03'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US', 'MSFT.US'], qm: ['AAPL', 'MSFT'] },
|
||||
});
|
||||
|
||||
expect(resultA).toEqual(resultB);
|
||||
expect(resultA.closes).toEqual([
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 185.0 },
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 186.0 },
|
||||
{ source: 'eod', sourceId: 'AAPL.US', date: '2024-01-03', close: 184.0 },
|
||||
{ source: 'eod', sourceId: 'MSFT.US', date: '2024-01-03', close: 371.0 },
|
||||
{ source: 'qm', sourceId: 'AAPL', date: '2024-01-02', close: 185.0 },
|
||||
{ source: 'qm', sourceId: 'AAPL', date: '2024-01-03', close: 184.0 },
|
||||
{ source: 'qm', sourceId: 'MSFT', date: '2024-01-02', close: 370.0 },
|
||||
]);
|
||||
expect(resultA.fxRates).toEqual([
|
||||
{ date: '2024-01-02', usdCad: 1.329 },
|
||||
{ date: '2024-01-02', usdCad: 1.331 },
|
||||
{ date: '2024-01-03', usdCad: 1.335 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('chunks large id sets by idChunkSize with date-first filters and skips empty sources', async () => {
|
||||
const eodIds = ['A.US', 'B.US', 'C.US', 'D.US', 'E.US'];
|
||||
const fake = createFakeReader(
|
||||
{
|
||||
eodPrices: eodIds.map((id, i) => ({
|
||||
eodSearchCode: id,
|
||||
date: '2024-02-01',
|
||||
close: 10 + i,
|
||||
})),
|
||||
qmPrices: [],
|
||||
},
|
||||
{ applyFilter: true }
|
||||
);
|
||||
|
||||
const result = await readSampleCloses(fake.reader, {
|
||||
sampleDates: ['2024-02-01'],
|
||||
sourceIdsBySource: { eod: eodIds, qm: [] },
|
||||
idChunkSize: 2,
|
||||
includeFx: false,
|
||||
});
|
||||
|
||||
expect(DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE).toBe(10_000);
|
||||
expect(fake.calls).toHaveLength(3);
|
||||
expect(result.stats.eod.findsRun).toBe(3);
|
||||
expect(result.stats.qm.findsRun).toBe(0);
|
||||
expect(result.stats.fx.findsRun).toBe(0);
|
||||
expect(result.closes).toHaveLength(5);
|
||||
|
||||
for (const call of fake.calls) {
|
||||
expect(call.collectionName).toBe('eodPrices');
|
||||
expect(Object.keys(call.filter ?? {})).toEqual(['date', 'eodSearchCode']);
|
||||
expect(call.filter?.date).toEqual({ $in: ['2024-02-01'] });
|
||||
}
|
||||
expect(fake.calls[0]?.filter?.eodSearchCode).toEqual({ $in: ['A.US', 'B.US'] });
|
||||
expect(fake.calls[1]?.filter?.eodSearchCode).toEqual({ $in: ['C.US', 'D.US'] });
|
||||
expect(fake.calls[2]?.filter?.eodSearchCode).toEqual({ $in: ['E.US'] });
|
||||
});
|
||||
|
||||
test('rejects non-read-only reader and invalid options before issuing any find', async () => {
|
||||
const writableFake = createFakeReader({}, { readOnly: false });
|
||||
await expect(
|
||||
readSampleCloses(writableFake.reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
})
|
||||
).rejects.toThrow(/isReadOnly/);
|
||||
expect(writableFake.calls).toHaveLength(0);
|
||||
|
||||
const validFake = createFakeReader({});
|
||||
const badDateInputs: string[][] = [
|
||||
[],
|
||||
['2024-1-2'],
|
||||
['2023-02-29'],
|
||||
[' 2024-01-02 '],
|
||||
['2024-01-02T00:00:00Z'],
|
||||
makeSampleDates(MAX_SAMPLE_DATES + 1),
|
||||
];
|
||||
|
||||
for (const badDates of badDateInputs) {
|
||||
await expect(
|
||||
readSampleCloses(validFake.reader, {
|
||||
sampleDates: badDates,
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
})
|
||||
).rejects.toThrow(RangeError);
|
||||
}
|
||||
|
||||
await expect(
|
||||
readSampleCloses(validFake.reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
batchSize: 0,
|
||||
})
|
||||
).rejects.toThrow(RangeError);
|
||||
|
||||
await expect(
|
||||
readSampleCloses(validFake.reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
idChunkSize: -5,
|
||||
})
|
||||
).rejects.toThrow(RangeError);
|
||||
|
||||
expect(validFake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('rejects buffered array results with TypeError and closes cursors on errors while preserving collection name', async () => {
|
||||
const bufferedReader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find: () => [] as unknown as AsyncIterable<Record<string, unknown>>,
|
||||
};
|
||||
|
||||
await expect(
|
||||
readSampleCloses(bufferedReader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
})
|
||||
).rejects.toThrow(TypeError);
|
||||
|
||||
// Cursor error on qmPrices (call index 1) with close() also failing: primary error + collection name preserved.
|
||||
const failingFake = createFakeReader(
|
||||
{
|
||||
eodPrices: [{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }],
|
||||
qmPrices: [
|
||||
{ qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.64 },
|
||||
{ qmSearchCode: 'MSFT', date: '2024-01-02', unadjustedclose: 370.0 },
|
||||
],
|
||||
},
|
||||
{
|
||||
failOnCallIndex: 1,
|
||||
failAfterDocs: 1,
|
||||
failMessage: 'socket reset',
|
||||
failCloseOnCallIndex: 1,
|
||||
}
|
||||
);
|
||||
|
||||
await expect(
|
||||
readSampleCloses(failingFake.reader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: ['AAPL', 'MSFT'] },
|
||||
})
|
||||
).rejects.toThrow(/qmPrices.*socket reset/);
|
||||
|
||||
// Both call 0 (eodPrices) and call 1 (qmPrices) must have had close() invoked.
|
||||
expect(failingFake.closedCount()).toBe(2);
|
||||
});
|
||||
|
||||
test('wraps TypeError thrown during iteration or close with collection name and original cause while closing cursor', async () => {
|
||||
const iterationCause = new TypeError('cannot decode malformed BSON field');
|
||||
let iterationCloseCalls = 0;
|
||||
|
||||
const iterationTypeErrorReader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
if (collectionName === 'qmPrices') {
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
yield {
|
||||
qmSearchCode: 'AAPL',
|
||||
date: '2024-01-02',
|
||||
unadjustedclose: 185.64,
|
||||
} as unknown as T;
|
||||
throw iterationCause;
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
iterationCloseCalls += 1;
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
// empty
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
// noop
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
let caughtIterationError: unknown;
|
||||
try {
|
||||
await readSampleCloses(iterationTypeErrorReader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: [], qm: ['AAPL'] },
|
||||
includeFx: false,
|
||||
});
|
||||
} catch (error) {
|
||||
caughtIterationError = error;
|
||||
}
|
||||
|
||||
expect(caughtIterationError).toBeInstanceOf(Error);
|
||||
expect((caughtIterationError as Error).message).toContain('qmPrices');
|
||||
expect((caughtIterationError as Error).message).toContain('cannot decode malformed BSON field');
|
||||
expect((caughtIterationError as Error).cause).toBe(iterationCause);
|
||||
expect(iterationCloseCalls).toBe(1);
|
||||
|
||||
const closeCause = new TypeError('cursor close internal TypeError');
|
||||
const closeTypeErrorReader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
// empty
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
throw closeCause;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
let caughtCloseError: unknown;
|
||||
try {
|
||||
await readSampleCloses(closeTypeErrorReader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
includeFx: false,
|
||||
});
|
||||
} catch (error) {
|
||||
caughtCloseError = error;
|
||||
}
|
||||
|
||||
expect(caughtCloseError).toBeInstanceOf(Error);
|
||||
expect((caughtCloseError as Error).message).toContain('eodPrices');
|
||||
expect((caughtCloseError as Error).message).toContain('cursor close internal TypeError');
|
||||
expect((caughtCloseError as Error).cause).toBe(closeCause);
|
||||
});
|
||||
|
||||
test('rejects an invalid closable handle with TypeError and still releases it via close()', async () => {
|
||||
let invalidHandleClosed = 0;
|
||||
const invalidClosableReader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find: () =>
|
||||
({
|
||||
async close(): Promise<void> {
|
||||
invalidHandleClosed += 1;
|
||||
},
|
||||
}) as unknown as AsyncIterable<Record<string, unknown>>,
|
||||
};
|
||||
|
||||
await expect(
|
||||
readSampleCloses(invalidClosableReader, {
|
||||
sampleDates: ['2024-01-02'],
|
||||
sourceIdsBySource: { eod: ['AAPL.US'], qm: [] },
|
||||
includeFx: false,
|
||||
})
|
||||
).rejects.toThrow(TypeError);
|
||||
|
||||
expect(invalidHandleClosed).toBe(1);
|
||||
});
|
||||
|
||||
test('integrates end to end with crossCheckPrices for USD/USD and CAD/USD pairs (confirmed and conflict)', async () => {
|
||||
const dates = [
|
||||
'2024-01-02',
|
||||
'2024-02-01',
|
||||
'2024-03-01',
|
||||
'2024-04-01',
|
||||
'2024-05-01',
|
||||
'2024-06-03',
|
||||
];
|
||||
const usdPrices = [100, 108, 102, 115, 121, 118];
|
||||
const fxRatesByIdx = [1.33, 1.35, 1.36, 1.37, 1.38, 1.36];
|
||||
|
||||
const eodDocs: Record<string, unknown>[] = [];
|
||||
const qmDocs: Record<string, unknown>[] = [];
|
||||
|
||||
for (let i = 0; i < dates.length; i++) {
|
||||
const date = dates[i]!;
|
||||
const p = usdPrices[i]!;
|
||||
const fx = fxRatesByIdx[i]!;
|
||||
|
||||
// FX series
|
||||
eodDocs.push({ eodSearchCode: FX_USD_CAD_SOURCE_ID, date, close: fx });
|
||||
|
||||
// USD/USD consistent pair (AAPL.US vs AAPL)
|
||||
eodDocs.push({ eodSearchCode: 'AAPL.US', date, close: p });
|
||||
qmDocs.push({ qmSearchCode: 'AAPL', date, unadjustedclose: p * 1.002 });
|
||||
|
||||
// CAD/USD consistent cross-listed pair (SHOP.TO in CAD vs SHOP in USD)
|
||||
eodDocs.push({ eodSearchCode: 'SHOP.TO', date, close: p * fx });
|
||||
qmDocs.push({ qmSearchCode: 'SHOP', date, unadjustedclose: p });
|
||||
|
||||
// Mismatched USD/USD pair (ratio off by 15%)
|
||||
eodDocs.push({ eodSearchCode: 'BAD.US', date, close: p * 1.15 });
|
||||
qmDocs.push({ qmSearchCode: 'BAD', date, unadjustedclose: p });
|
||||
|
||||
// Low-correlation USD/USD pair (same scale near 1.0 ratio, opposite daily moves)
|
||||
const inverted = usdPrices[dates.length - 1 - i]!;
|
||||
eodDocs.push({ eodSearchCode: 'UNCORR.US', date, close: p });
|
||||
qmDocs.push({ qmSearchCode: 'UNCORR', date, unadjustedclose: inverted });
|
||||
}
|
||||
|
||||
const fake = createFakeReader({ eodPrices: eodDocs, qmPrices: qmDocs }, { applyFilter: true });
|
||||
const sample = await readSampleCloses(fake.reader, {
|
||||
sampleDates: dates,
|
||||
sourceIdsBySource: {
|
||||
eod: ['AAPL.US', 'SHOP.TO', 'BAD.US', 'UNCORR.US'],
|
||||
qm: ['AAPL', 'SHOP', 'BAD', 'UNCORR'],
|
||||
},
|
||||
});
|
||||
|
||||
const check = crossCheckPrices({
|
||||
pairs: [
|
||||
{
|
||||
left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' },
|
||||
right: { source: 'qm', sourceId: 'AAPL', currency: 'USD' },
|
||||
},
|
||||
{
|
||||
left: { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD' },
|
||||
right: { source: 'qm', sourceId: 'SHOP', currency: 'USD' },
|
||||
},
|
||||
{
|
||||
left: { source: 'eod', sourceId: 'BAD.US', currency: 'USD' },
|
||||
right: { source: 'qm', sourceId: 'BAD', currency: 'USD' },
|
||||
},
|
||||
{
|
||||
left: { source: 'eod', sourceId: 'UNCORR.US', currency: 'USD' },
|
||||
right: { source: 'qm', sourceId: 'UNCORR', currency: 'USD' },
|
||||
},
|
||||
],
|
||||
closes: sample.closes,
|
||||
usdCadByDate: sample.fxRates,
|
||||
});
|
||||
|
||||
const byLeftId = new Map(check.results.map(r => [r.left.sourceId, r]));
|
||||
expect(byLeftId.get('AAPL.US')?.verdict).toBe('confirmed');
|
||||
expect(byLeftId.get('SHOP.TO')?.verdict).toBe('confirmed');
|
||||
expect(byLeftId.get('BAD.US')?.verdict).toBe('ratio_mismatch');
|
||||
expect(byLeftId.get('UNCORR.US')?.verdict).toBe('low_correlation');
|
||||
expect(check.conflicts).toHaveLength(2);
|
||||
expect(check.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([
|
||||
['BAD.US', 'price_ratio_mismatch'],
|
||||
['UNCORR.US', 'price_low_correlation'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('reconciles skip counts on FX scan for malformed, unrequested, and invalid FX docs', async () => {
|
||||
const fake = createFakeReader({
|
||||
eodPrices: [
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.335 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: new Date('2024-01-03T12:00:00Z'), close: 1.34 },
|
||||
null,
|
||||
{ eodSearchCode: '', date: '2024-01-02', close: 1.33 },
|
||||
{ eodSearchCode: 'EUR.FOREX', date: '2024-01-02', close: 1.09 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: 'bad-date', close: 1.33 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-09', close: 1.33 },
|
||||
{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: -1.33 },
|
||||
],
|
||||
qmPrices: [],
|
||||
});
|
||||
|
||||
const result = await readSampleCloses(fake.reader, {
|
||||
sampleDates: ['2024-01-02', '2024-01-03'],
|
||||
sourceIdsBySource: { eod: [], qm: [] },
|
||||
});
|
||||
|
||||
expect(result.fxRates).toEqual([
|
||||
{ date: '2024-01-02', usdCad: 1.335 },
|
||||
{ date: '2024-01-03', usdCad: 1.34 },
|
||||
]);
|
||||
expect(result.stats.eod.findsRun).toBe(0);
|
||||
expect(result.stats.qm.findsRun).toBe(0);
|
||||
expect(result.stats.fx.findsRun).toBe(1);
|
||||
expect(result.stats.fx.docsRead).toBe(8);
|
||||
expect(result.stats.fx.emitted).toBe(2);
|
||||
expect(result.stats.fx.skipped).toEqual({
|
||||
missingId: 2,
|
||||
unrequestedId: 1,
|
||||
invalidDate: 1,
|
||||
unrequestedDate: 1,
|
||||
invalidClose: 1,
|
||||
});
|
||||
assertStatsReconcile(result.stats.fx);
|
||||
});
|
||||
});
|
||||
364
apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts
Normal file
364
apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
MAX_EXAMPLES_CAP,
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
runSourceFieldShapesProbe,
|
||||
summarizeFieldShapes,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
// QA coverage for T-108 beyond the programmer's suite: real BSON wire decoding,
|
||||
// option pass-through via the production read-only adapter, fail-fast safety,
|
||||
// and CLI/runner failure paths. No MongoDB connection is opened anywhere here.
|
||||
|
||||
const OBJECT_ID_HEX = '507f1f77bcf86cd799439011';
|
||||
|
||||
function serializeRealBsonDoc(): Uint8Array {
|
||||
return BSON.serialize({
|
||||
_id: new BSON.ObjectId(OBJECT_ID_HEX),
|
||||
i32: new BSON.Int32(7),
|
||||
dbl: new BSON.Double(1.0),
|
||||
lng: BSON.Long.fromString('9007199254740993'),
|
||||
dec: BSON.Decimal128.fromString('12.34'),
|
||||
flag: true,
|
||||
text: '2025-01-02',
|
||||
when: new Date('2025-01-02T00:00:00.000Z'),
|
||||
nothing: null,
|
||||
list: [1, 2],
|
||||
nested: { px: new BSON.Double(2.5), qty: new BSON.Int32(3) },
|
||||
bin: new BSON.Binary(new Uint8Array([1, 2, 3])),
|
||||
ts: new BSON.Timestamp({ t: 1, i: 1 }),
|
||||
min: new BSON.MinKey(),
|
||||
});
|
||||
}
|
||||
|
||||
function nonZeroTypes(counts: Record<string, number>): Record<string, number> {
|
||||
return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0));
|
||||
}
|
||||
|
||||
function asyncCursor<T>(
|
||||
docs: readonly T[],
|
||||
onClose?: () => void
|
||||
): { [Symbol.asyncIterator](): AsyncIterator<T>; close(): Promise<void> } {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
async close() {
|
||||
onClose?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('summarizeFieldShapes with real BSON wire documents', () => {
|
||||
test('promoteValues:false decoding keeps int/double/long/objectId distinct and maps other BSON types to other', () => {
|
||||
const doc = BSON.deserialize(serializeRealBsonDoc(), {
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
|
||||
const summary = summarizeFieldShapes([doc]);
|
||||
const types = Object.fromEntries(summary.fields.map(f => [f.field, nonZeroTypes(f.typeCounts)]));
|
||||
|
||||
expect(types).toEqual({
|
||||
_id: { objectId: 1 },
|
||||
bin: { other: 1 },
|
||||
dbl: { double: 1 },
|
||||
dec: { other: 1 },
|
||||
flag: { bool: 1 },
|
||||
i32: { int: 1 },
|
||||
list: { array: 1 },
|
||||
lng: { int: 1 },
|
||||
min: { other: 1 },
|
||||
nested: { object: 1 },
|
||||
'nested.px': { double: 1 },
|
||||
'nested.qty': { int: 1 },
|
||||
nothing: { null: 1 },
|
||||
text: { string: 1 },
|
||||
ts: { other: 1 },
|
||||
when: { date: 1 },
|
||||
});
|
||||
|
||||
const examples = Object.fromEntries(summary.fields.map(f => [f.field, f.examples]));
|
||||
expect(examples._id).toEqual([]);
|
||||
expect(examples.dbl).toEqual(['1']);
|
||||
expect(examples.lng).toEqual(['9007199254740993']);
|
||||
expect(examples.dec).toEqual(['12.34']);
|
||||
expect(examples.when).toEqual(['2025-01-02T00:00:00.000Z']);
|
||||
expect(examples.bin).toEqual([]);
|
||||
});
|
||||
|
||||
test('default driver promotion collapses Double(1.0) into int, which is why the probe disables promotion', () => {
|
||||
const promoted = BSON.deserialize(serializeRealBsonDoc());
|
||||
const summary = summarizeFieldShapes([promoted]);
|
||||
const dbl = summary.fields.find(f => f.field === 'dbl')!;
|
||||
expect(nonZeroTypes(dbl.typeCounts)).toEqual({ int: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('readFieldShapes through the production read-only Mongo adapter', () => {
|
||||
test('forwards limit/promoteValues/promoteLongs verbatim to collection.find and classifies decoded BSON', async () => {
|
||||
const findCalls: Array<{ name: string; filter: unknown; options: unknown }> = [];
|
||||
const closed: string[] = [];
|
||||
const wireDoc = BSON.deserialize(serializeRealBsonDoc(), {
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection(name: string) {
|
||||
return {
|
||||
find(filter?: Record<string, unknown>, options?: SourceSymbolFindOptions) {
|
||||
findCalls.push({ name, filter, options });
|
||||
return asyncCursor(name === 'qmDividends' ? [wireDoc] : [], () => closed.push(name));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const reader = createReadOnlyMongoSourceSymbolReader(client);
|
||||
const result = await readFieldShapes(reader, {
|
||||
collections: ['qmDividends', 'qmSplits'],
|
||||
limit: 25,
|
||||
});
|
||||
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
name: 'qmDividends',
|
||||
filter: {},
|
||||
options: { limit: 25, promoteValues: false, promoteLongs: false },
|
||||
},
|
||||
{
|
||||
name: 'qmSplits',
|
||||
filter: {},
|
||||
options: { limit: 25, promoteValues: false, promoteLongs: false },
|
||||
},
|
||||
]);
|
||||
expect(closed).toEqual(['qmDividends', 'qmSplits']);
|
||||
expect(result.totalDocsSampled).toBe(1);
|
||||
const dbl = result.collections[0]!.fields.find(f => f.field === 'dbl')!;
|
||||
expect(dbl.typeCounts.double).toBe(1);
|
||||
});
|
||||
|
||||
test('re-checks read-only before every collection and stops if the reader stops being read-only', async () => {
|
||||
let readOnly = true;
|
||||
const findCalls: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => readOnly,
|
||||
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls.push(name);
|
||||
readOnly = false; // simulate a reader that flips after its first query
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
readFieldShapes(reader, { collections: ['ceoShorts', 'qmSplits'] })
|
||||
).rejects.toThrow(/read-only/i);
|
||||
expect(findCalls).toEqual(['ceoShorts']);
|
||||
});
|
||||
|
||||
test('fails fast: an error on one collection prevents queries on later collections', async () => {
|
||||
const findCalls: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls.push(name);
|
||||
if (name === 'eodPrices') {
|
||||
throw new Error('not authorized on stock');
|
||||
}
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await readFieldShapes(reader, { collections: ['qmSplits', 'eodPrices', 'ceoShorts'] });
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
// Collections are ASCII-sorted: ceoShorts, eodPrices, qmSplits.
|
||||
expect(findCalls).toEqual(['ceoShorts', 'eodPrices']);
|
||||
expect((caught as Error).message).toContain('eodPrices');
|
||||
expect((caught as Error).message).toContain('not authorized on stock');
|
||||
expect(((caught as Error).cause as Error).message).toBe('not authorized on stock');
|
||||
});
|
||||
|
||||
test('rejects non-integer limit and invalid batchSize before any query', async () => {
|
||||
let findCalls = 0;
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls += 1;
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
await expect(readFieldShapes(reader, { limit: 1.5 })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { limit: Number.NaN })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { batchSize: 0 })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { collections: [] })).rejects.toThrow(RangeError);
|
||||
expect(findCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeFieldShapes edge cases', () => {
|
||||
test('non-object documents count toward docCount and keep presence invariants', () => {
|
||||
const docs = [{ a: 1 }, null, 'oops', { a: 'x' }] as unknown as Record<string, unknown>[];
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(4);
|
||||
const a = summary.fields.find(f => f.field === 'a')!;
|
||||
expect(a.presentCount).toBe(2);
|
||||
expect(a.missingCount).toBe(2);
|
||||
});
|
||||
|
||||
test('undefined values are treated as missing, not as a present type', () => {
|
||||
const summary = summarizeFieldShapes([{ a: undefined }, { a: 1 }]);
|
||||
const a = summary.fields.find(f => f.field === 'a')!;
|
||||
expect(a.presentCount).toBe(1);
|
||||
expect(a.missingCount).toBe(1);
|
||||
});
|
||||
|
||||
test('rejects near-miss dates and times as ymd/isoDatetime', () => {
|
||||
const values = [
|
||||
'2024-13-01', // month 13
|
||||
'2024-04-31', // April has 30 days
|
||||
'2025-01-01T24:00:00Z', // hour 24
|
||||
'2025-01-01T10:60:00Z', // minute 60
|
||||
'2025-01-01 10:00:00', // space separator
|
||||
'20250101', // compact date is numeric, not ymd
|
||||
];
|
||||
const summary = summarizeFieldShapes(values.map(s => ({ s })));
|
||||
const s = summary.fields.find(f => f.field === 's')!;
|
||||
expect(s.stringStats!.patterns).toEqual({
|
||||
ymd: 0,
|
||||
isoDatetime: 0,
|
||||
numeric: 1,
|
||||
emptyOrWhitespace: 0,
|
||||
other: 5,
|
||||
});
|
||||
});
|
||||
|
||||
test('examples are distinct, strip control characters, and honour maxExamples 0 and the cap', () => {
|
||||
const docs = [{ s: 'dup' }, { s: 'dup' }, { s: '\u0000\u001bbell\u0007' }];
|
||||
|
||||
expect(summarizeFieldShapes(docs).fields[0]!.examples).toEqual(['bell', 'dup']);
|
||||
expect(summarizeFieldShapes(docs, { maxExamples: 0 }).fields[0]!.examples).toEqual([]);
|
||||
|
||||
const many = Array.from({ length: 50 }, (_, i) => ({ s: `v${String(i).padStart(2, '0')}` }));
|
||||
const capped = summarizeFieldShapes(many, { maxExamples: MAX_EXAMPLES_CAP }).fields[0]!;
|
||||
expect(capped.examples.length).toBe(MAX_EXAMPLES_CAP);
|
||||
expect(capped.examples[0]).toBe('v00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderFieldShapesMarkdown privacy and header', () => {
|
||||
test('never renders _id values and states the bounded sample in the header', async () => {
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
return asyncCursor<T>([
|
||||
{ _id: new BSON.ObjectId(OBJECT_ID_HEX), symbol: 'ABC' },
|
||||
{ _id: { ticker: 'SECRET-COMPOSITE' }, symbol: 'DEF' },
|
||||
] as unknown as T[]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
const result = await readFieldShapes(reader, { collections: ['ceoShorts'], limit: 7 });
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
|
||||
expect(markdown).not.toContain(OBJECT_ID_HEX);
|
||||
expect(markdown).not.toContain('SECRET-COMPOSITE');
|
||||
expect(markdown).toContain('bounded sample, not a full scan');
|
||||
expect(markdown).toContain('**Sample limit per collection:** 7');
|
||||
expect(markdown).toContain('**Total documents sampled:** 2');
|
||||
expect(markdown).toContain('| `_id.ticker` | 50.0% (1/2) |');
|
||||
expect(markdown).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); // no wall-clock stamp
|
||||
});
|
||||
});
|
||||
|
||||
describe('probe CLI parsing and runner failure paths', () => {
|
||||
test('rejects a flag in place of a value and empty inline values', () => {
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out', '--limit', '5'])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit'])).toThrow(/--limit/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections='])).toThrow(
|
||||
/--collections/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections', ' , '])).toThrow(
|
||||
/--collections/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1e3'])).toThrow(/--limit/);
|
||||
});
|
||||
|
||||
test('merges repeated --collections, accepts boundary limits, and lets --help win', () => {
|
||||
expect(
|
||||
parseProbeSourceFieldShapesArgs([
|
||||
'--out=x.md',
|
||||
'--collections=qmSplits',
|
||||
'--collections',
|
||||
'ceoShorts,qmSplits',
|
||||
'--limit=10000',
|
||||
])
|
||||
).toEqual({ help: false, outPath: 'x.md', limit: 10_000, collections: ['ceoShorts', 'qmSplits'] });
|
||||
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1'])).toMatchObject({ limit: 1 });
|
||||
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--help'])).toEqual({ help: true });
|
||||
});
|
||||
|
||||
test('closes Mongo and surfaces the write error when the report cannot be written', async () => {
|
||||
let closeCalls = 0;
|
||||
const stdout: string[] = [];
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection() {
|
||||
return { find: () => asyncCursor([{ a: 1 }]) };
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: client,
|
||||
closeMongo: () => {
|
||||
closeCalls += 1;
|
||||
},
|
||||
writeFile: () => {
|
||||
throw new Error('EACCES: permission denied');
|
||||
},
|
||||
writeStdout: text => stdout.push(text),
|
||||
},
|
||||
{ outPath: './tmp/out.md', collections: ['qmSplits'] }
|
||||
)
|
||||
).rejects.toThrow('EACCES');
|
||||
expect(closeCalls).toBe(1);
|
||||
expect(stdout).toEqual([]);
|
||||
});
|
||||
|
||||
test('blank outPath is rejected before any collection is opened', async () => {
|
||||
let getCollectionCalls = 0;
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection() {
|
||||
getCollectionCalls += 1;
|
||||
return { find: () => asyncCursor([]) };
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{ mongoCollectionClient: client, writeFile: () => {}, writeStdout: () => {} },
|
||||
{ outPath: ' ' }
|
||||
)
|
||||
).rejects.toThrow(/outPath/);
|
||||
expect(getCollectionCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
812
apps/stock/data-pipeline/test/source-field-shapes.test.ts
Normal file
812
apps/stock/data-pipeline/test/source-field-shapes.test.ts
Normal file
|
|
@ -0,0 +1,812 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import type { ParserOptions } from 'prettier';
|
||||
import * as markdownPlugin from 'prettier/plugins/markdown';
|
||||
import {
|
||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
DEFAULT_MAX_EXAMPLE_LENGTH,
|
||||
DEFAULT_MAX_EXAMPLES,
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
FIELD_VALUE_TYPES,
|
||||
MAX_EXAMPLE_LENGTH_CAP,
|
||||
MAX_EXAMPLES_CAP,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
runSourceFieldShapesProbe,
|
||||
STRING_PATTERN_CLASSES,
|
||||
summarizeFieldShapes,
|
||||
UnknownProbeCollectionError,
|
||||
type FieldShapeSummary,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
interface RecordedFindCall {
|
||||
collectionName: string;
|
||||
filter: Record<string, unknown> | undefined;
|
||||
options: SourceSymbolFindOptions | undefined;
|
||||
}
|
||||
|
||||
interface FakeBsonWrapper {
|
||||
_bsontype: string;
|
||||
valueOf?: () => unknown;
|
||||
toString: () => string;
|
||||
}
|
||||
|
||||
function fakeInt32(value: number): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Int32',
|
||||
valueOf: () => value,
|
||||
toString: () => String(value),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDouble(value: number): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Double',
|
||||
valueOf: () => value,
|
||||
toString: () => String(value),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeLong(value: string): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Long',
|
||||
toString: () => value,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeObjectId(hex: string): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'ObjectId',
|
||||
toString: () => hex,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDecimal128(value: string): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Decimal128',
|
||||
toString: () => value,
|
||||
};
|
||||
}
|
||||
|
||||
function sumTypeCounts(summary: FieldShapeSummary): number {
|
||||
let total = 0;
|
||||
for (const typeName of FIELD_VALUE_TYPES) {
|
||||
total += summary.typeCounts[typeName];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function sumPatternCounts(summary: FieldShapeSummary): number {
|
||||
if (summary.stringStats === null) {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const pattern of STRING_PATTERN_CLASSES) {
|
||||
total += summary.stringStats.patterns[pattern];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function createFakeReader(
|
||||
docsByCollection: Record<string, readonly Record<string, unknown>[]>,
|
||||
opts?: {
|
||||
readOnly?: boolean;
|
||||
failFindOnCollection?: string;
|
||||
failIterOnCollection?: string;
|
||||
failIterAtIndex?: number;
|
||||
failCloseOnCollection?: string;
|
||||
returnBufferedArrayOnCollection?: string;
|
||||
ignoreLimit?: boolean;
|
||||
}
|
||||
): {
|
||||
reader: ReadOnlySourceSymbolReader;
|
||||
calls: RecordedFindCall[];
|
||||
closedCollections: string[];
|
||||
pullsByCollection: Record<string, number>;
|
||||
} {
|
||||
const calls: RecordedFindCall[] = [];
|
||||
const closedCollections: string[] = [];
|
||||
const pullsByCollection: Record<string, number> = {};
|
||||
const readOnly = opts?.readOnly ?? true;
|
||||
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly(): boolean {
|
||||
return readOnly;
|
||||
},
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
filter?: Record<string, unknown>,
|
||||
options?: SourceSymbolFindOptions
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
calls.push({ collectionName, filter, options });
|
||||
|
||||
if (opts?.failFindOnCollection === collectionName) {
|
||||
throw new Error('simulated find failure');
|
||||
}
|
||||
if (opts?.returnBufferedArrayOnCollection === collectionName) {
|
||||
return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
}
|
||||
|
||||
const sourceDocs = docsByCollection[collectionName] ?? [];
|
||||
const maxToYield =
|
||||
opts?.ignoreLimit === true || options?.limit === undefined
|
||||
? sourceDocs.length
|
||||
: Math.min(sourceDocs.length, options.limit);
|
||||
const failAt = opts?.failIterAtIndex ?? 1;
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (let i = 0; i < maxToYield; i++) {
|
||||
pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1;
|
||||
if (opts?.failIterOnCollection === collectionName && i === failAt) {
|
||||
throw new Error('simulated cursor iteration failure');
|
||||
}
|
||||
yield sourceDocs[i] as T;
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
closedCollections.push(collectionName);
|
||||
if (opts?.failCloseOnCollection === collectionName) {
|
||||
throw new Error('simulated cursor close failure');
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return { reader, calls, closedCollections, pullsByCollection };
|
||||
}
|
||||
|
||||
describe('source-field-shapes static purity', () => {
|
||||
test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => {
|
||||
const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts');
|
||||
const source = readFileSync(filePath, 'utf8');
|
||||
const runtimeImportLines = source
|
||||
.split('\n')
|
||||
.filter(line => /^\s*import\s+(?!type\b)/.test(line));
|
||||
|
||||
for (const line of runtimeImportLines) {
|
||||
expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i);
|
||||
}
|
||||
expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeFieldShapes', () => {
|
||||
test('classifies mixed JS and BSON value types on one field and reconciles counts', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{ mixed: 'hello' },
|
||||
{ mixed: 42 },
|
||||
{ mixed: 3.14 },
|
||||
{ mixed: fakeInt32(7) },
|
||||
{ mixed: fakeLong('9007199254740993') },
|
||||
{ mixed: fakeDouble(1.0) },
|
||||
{ mixed: true },
|
||||
{ mixed: new Date('2025-01-15T12:00:00.000Z') },
|
||||
{ mixed: null },
|
||||
{ mixed: fakeObjectId('507f1f77bcf86cd799439011') },
|
||||
{ mixed: [1, 2, 3] },
|
||||
{ mixed: { nested: 'a' } },
|
||||
{ mixed: fakeDecimal128('12.34') },
|
||||
{ mixed: new Uint8Array([1, 2]) },
|
||||
{}, // missing
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(docs.length);
|
||||
|
||||
const mixed = summary.fields.find(f => f.field === 'mixed');
|
||||
expect(mixed).toBeDefined();
|
||||
expect(mixed!.presentCount).toBe(14);
|
||||
expect(mixed!.missingCount).toBe(1);
|
||||
expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount);
|
||||
expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount);
|
||||
|
||||
expect(mixed!.typeCounts).toEqual({
|
||||
string: 1,
|
||||
int: 3, // 42, Int32(7), Long(...)
|
||||
double: 2, // 3.14, Double(1.0)
|
||||
bool: 1,
|
||||
date: 1,
|
||||
null: 1,
|
||||
objectId: 1,
|
||||
array: 1,
|
||||
object: 1,
|
||||
other: 2, // Decimal128, Uint8Array
|
||||
});
|
||||
});
|
||||
|
||||
test('tracks one level of nested parent.child keys and stops at depth 1', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
meta: {
|
||||
exchange: 'TSX',
|
||||
deep: { level2: 'ignored' },
|
||||
recordedAt: new Date('2025-02-01T00:00:00Z'),
|
||||
},
|
||||
arr: [{ insideArray: 1 }],
|
||||
bsonObj: fakeObjectId('507f1f77bcf86cd799439012'),
|
||||
},
|
||||
{
|
||||
meta: {
|
||||
exchange: 'NYSE',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
const fieldNames = summary.fields.map(f => f.field);
|
||||
|
||||
expect(fieldNames).toEqual([
|
||||
'arr',
|
||||
'bsonObj',
|
||||
'meta',
|
||||
'meta.deep',
|
||||
'meta.exchange',
|
||||
'meta.recordedAt',
|
||||
]);
|
||||
expect(fieldNames).not.toContain('meta.deep.level2');
|
||||
expect(fieldNames).not.toContain('bsonObj._bsontype');
|
||||
|
||||
const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!;
|
||||
expect(metaExchange.presentCount).toBe(2);
|
||||
expect(metaExchange.missingCount).toBe(0);
|
||||
expect(metaExchange.typeCounts.string).toBe(2);
|
||||
|
||||
const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!;
|
||||
expect(metaDeep.presentCount).toBe(1);
|
||||
expect(metaDeep.missingCount).toBe(1);
|
||||
expect(metaDeep.typeCounts.object).toBe(1);
|
||||
});
|
||||
|
||||
test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
'meta.exchange': 'LITERAL_EXCHANGE',
|
||||
meta: {
|
||||
exchange: 42,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(1);
|
||||
|
||||
const literalField = summary.fields.find(f => f.field === 'meta\\.exchange');
|
||||
const nestedField = summary.fields.find(f => f.field === 'meta.exchange');
|
||||
expect(literalField).toBeDefined();
|
||||
expect(nestedField).toBeDefined();
|
||||
|
||||
expect(literalField!.presentCount).toBe(1);
|
||||
expect(literalField!.missingCount).toBe(0);
|
||||
expect(literalField!.typeCounts.string).toBe(1);
|
||||
expect(literalField!.typeCounts.int).toBe(0);
|
||||
expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']);
|
||||
|
||||
expect(nestedField!.presentCount).toBe(1);
|
||||
expect(nestedField!.missingCount).toBe(0);
|
||||
expect(nestedField!.typeCounts.int).toBe(1);
|
||||
expect(nestedField!.typeCounts.string).toBe(0);
|
||||
expect(nestedField!.examples).toEqual(['42']);
|
||||
});
|
||||
|
||||
test('classifies all five string pattern classes and tracks min/max string length', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{ s: '2024-02-29' }, // valid leap-year ymd (len 10)
|
||||
{ s: '2023-02-29' }, // invalid calendar date -> other (len 10)
|
||||
{ s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20)
|
||||
{ s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29)
|
||||
{ s: '-123.45' }, // numeric (len 7)
|
||||
{ s: '1.5e-4' }, // numeric (len 6)
|
||||
{ s: '' }, // emptyOrWhitespace (len 0)
|
||||
{ s: ' \t ' }, // emptyOrWhitespace (len 5)
|
||||
{ s: 'AAPL.US' }, // other (len 7)
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
const field = summary.fields.find(f => f.field === 's')!;
|
||||
|
||||
expect(field.typeCounts.string).toBe(9);
|
||||
expect(field.stringStats).toEqual({
|
||||
minLength: 0,
|
||||
maxLength: 29,
|
||||
patterns: {
|
||||
ymd: 1,
|
||||
isoDatetime: 2,
|
||||
numeric: 2,
|
||||
emptyOrWhitespace: 2,
|
||||
other: 2,
|
||||
},
|
||||
});
|
||||
expect(sumPatternCounts(field)).toBe(field.typeCounts.string);
|
||||
});
|
||||
|
||||
test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
_id: fakeObjectId('507f1f77bcf86cd799439011'),
|
||||
symbol: 'ZZZZ',
|
||||
note: 'line1\nline2\twith a very long description that must be truncated',
|
||||
},
|
||||
{
|
||||
_id: { key: 'secret-composite-id' },
|
||||
symbol: 'AAAA',
|
||||
note: 'short',
|
||||
},
|
||||
{
|
||||
_id: 'string-id-should-never-appear',
|
||||
symbol: 'MMMM',
|
||||
},
|
||||
{
|
||||
symbol: 'BBBB',
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 });
|
||||
const idField = summary.fields.find(f => f.field === '_id')!;
|
||||
const idChildField = summary.fields.find(f => f.field === '_id.key')!;
|
||||
const symbolField = summary.fields.find(f => f.field === 'symbol')!;
|
||||
const noteField = summary.fields.find(f => f.field === 'note')!;
|
||||
|
||||
expect(idField.examples).toEqual([]);
|
||||
expect(idChildField.examples).toEqual([]);
|
||||
expect(symbolField.examples).toEqual(['AAAA', 'BBBB']);
|
||||
expect(noteField.examples.length).toBe(2);
|
||||
expect(noteField.examples[0]).toBe('line1 line2 w...');
|
||||
expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16);
|
||||
expect(noteField.examples[1]).toBe('short');
|
||||
|
||||
expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError);
|
||||
expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow(
|
||||
RangeError
|
||||
);
|
||||
expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError);
|
||||
expect(() =>
|
||||
summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 })
|
||||
).toThrow(RangeError);
|
||||
});
|
||||
|
||||
test('produces deep-equal output for shuffled input order and handles empty iterable', () => {
|
||||
expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] });
|
||||
|
||||
const original: Record<string, unknown>[] = [
|
||||
{ _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } },
|
||||
{ _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } },
|
||||
{ _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } },
|
||||
{ _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } },
|
||||
];
|
||||
const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!];
|
||||
|
||||
const a = summarizeFieldShapes(original, { maxExamples: 2 });
|
||||
const b = summarizeFieldShapes(shuffled, { maxExamples: 2 });
|
||||
|
||||
expect(b).toEqual(a);
|
||||
expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readFieldShapes', () => {
|
||||
test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => {
|
||||
const docsByCollection: Record<string, Record<string, unknown>[]> = {
|
||||
qmDividends: [
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' },
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' },
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' },
|
||||
],
|
||||
ceoShorts: [
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) },
|
||||
],
|
||||
};
|
||||
|
||||
const { reader, calls, closedCollections, pullsByCollection } = createFakeReader(
|
||||
docsByCollection,
|
||||
{
|
||||
ignoreLimit: true,
|
||||
failIterOnCollection: 'qmDividends',
|
||||
failIterAtIndex: 2,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await readFieldShapes(reader, {
|
||||
collections: ['qmDividends', 'ceoShorts', 'qmDividends'],
|
||||
limit: 2,
|
||||
batchSize: 500,
|
||||
});
|
||||
|
||||
expect(calls.length).toBe(2);
|
||||
expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']);
|
||||
for (const call of calls) {
|
||||
expect(call.filter).toEqual({});
|
||||
expect(call.options).toEqual({
|
||||
limit: 2,
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
batchSize: 500,
|
||||
});
|
||||
}
|
||||
expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']);
|
||||
// Breaks immediately after recording the limit-th doc without pulling a 3rd item
|
||||
expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 });
|
||||
|
||||
// Defensively capped at limit=2 even though fake reader ignored limit
|
||||
expect(result.limit).toBe(2);
|
||||
expect(result.totalDocsSampled).toBe(3);
|
||||
const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!;
|
||||
expect(qmDiv.docCount).toBe(2);
|
||||
const amountField = qmDiv.fields.find(f => f.field === 'amount')!;
|
||||
expect(amountField.typeCounts.double).toBe(2);
|
||||
});
|
||||
|
||||
test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => {
|
||||
const { reader, calls } = createFakeReader({});
|
||||
const result = await readFieldShapes(reader);
|
||||
|
||||
expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT);
|
||||
expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES);
|
||||
expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH);
|
||||
expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length);
|
||||
for (const call of calls) {
|
||||
expect(call.options).toEqual({
|
||||
limit: DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => {
|
||||
const nonRo = createFakeReader({}, { readOnly: false });
|
||||
await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i);
|
||||
expect(nonRo.calls.length).toBe(0);
|
||||
|
||||
const badLimitHigh = createFakeReader({});
|
||||
await expect(
|
||||
readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 })
|
||||
).rejects.toThrow(RangeError);
|
||||
expect(badLimitHigh.calls.length).toBe(0);
|
||||
|
||||
const badLimitZero = createFakeReader({});
|
||||
await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError);
|
||||
expect(badLimitZero.calls.length).toBe(0);
|
||||
|
||||
const unknownCol = createFakeReader({});
|
||||
let caught: unknown;
|
||||
try {
|
||||
await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
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 () => {
|
||||
const buffered = createFakeReader(
|
||||
{ eodPrices: [{ date: '2025-01-02' }] },
|
||||
{ returnBufferedArrayOnCollection: 'eodPrices' }
|
||||
);
|
||||
await expect(
|
||||
readFieldShapes(buffered.reader, { collections: ['eodPrices'] })
|
||||
).rejects.toThrow(TypeError);
|
||||
|
||||
const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' });
|
||||
let caughtFind: unknown;
|
||||
try {
|
||||
await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] });
|
||||
} catch (err) {
|
||||
caughtFind = err;
|
||||
}
|
||||
expect(caughtFind).toBeInstanceOf(Error);
|
||||
expect((caughtFind as Error).message).toContain('qmFilings');
|
||||
expect((caughtFind as Error).cause).toBeInstanceOf(Error);
|
||||
|
||||
const iterErr = createFakeReader(
|
||||
{ qmEarnings: [{ a: 1 }, { a: 2 }] },
|
||||
{ failIterOnCollection: 'qmEarnings' }
|
||||
);
|
||||
let caughtIter: unknown;
|
||||
try {
|
||||
await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] });
|
||||
} catch (err) {
|
||||
caughtIter = err;
|
||||
}
|
||||
expect(caughtIter).toBeInstanceOf(Error);
|
||||
expect((caughtIter as Error).message).toContain('qmEarnings');
|
||||
expect((caughtIter as Error).cause).toBeInstanceOf(Error);
|
||||
expect(iterErr.closedCollections).toEqual(['qmEarnings']);
|
||||
|
||||
const closeErr = createFakeReader(
|
||||
{ teMarketData: [{ country: 'US' }] },
|
||||
{ failCloseOnCollection: 'teMarketData' }
|
||||
);
|
||||
let caughtClose: unknown;
|
||||
try {
|
||||
await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] });
|
||||
} catch (err) {
|
||||
caughtClose = err;
|
||||
}
|
||||
expect(caughtClose).toBeInstanceOf(Error);
|
||||
expect((caughtClose as Error).message).toContain('teMarketData');
|
||||
expect((caughtClose as Error).cause).toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
|
||||
interface MdastNode {
|
||||
type: string;
|
||||
value?: string;
|
||||
children?: MdastNode[];
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(text: string): string {
|
||||
return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => {
|
||||
if (code !== undefined) {
|
||||
return String.fromCharCode(Number(code));
|
||||
}
|
||||
switch (entity) {
|
||||
case 'amp':
|
||||
return '&';
|
||||
case 'lt':
|
||||
return '<';
|
||||
case 'gt':
|
||||
return '>';
|
||||
default:
|
||||
return `&${entity};`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function parseGfmTables(markdown: string): MdastNode[][] {
|
||||
const ast = markdownPlugin.parsers.markdown.parse(
|
||||
markdown,
|
||||
{} as ParserOptions
|
||||
) as unknown as MdastNode;
|
||||
const rows: MdastNode[][] = [];
|
||||
for (const node of ast.children ?? []) {
|
||||
if (node.type !== 'table') {
|
||||
continue;
|
||||
}
|
||||
const tableRows = node.children ?? [];
|
||||
for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) {
|
||||
rows.push(tableRows[rowIndex]?.children ?? []);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function extractGfmCodeCellValues(cell: MdastNode): string[] {
|
||||
const nodes = cell.children ?? [];
|
||||
if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
let i = 0;
|
||||
while (i < nodes.length) {
|
||||
const node = nodes[i]!;
|
||||
if (node.type === 'inlineCode') {
|
||||
values.push(node.value ?? '');
|
||||
i += 1;
|
||||
} else if (node.type === 'html' && node.value === '<code>') {
|
||||
let inner = '';
|
||||
i += 1;
|
||||
let closed = false;
|
||||
while (i < nodes.length) {
|
||||
const innerNode = nodes[i]!;
|
||||
if (innerNode.type === 'html' && innerNode.value === '</code>') {
|
||||
closed = true;
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if (innerNode.type !== 'text') {
|
||||
throw new Error(
|
||||
`Unexpected Markdown node "${innerNode.type}" inside <code> element: ${JSON.stringify(innerNode)}`
|
||||
);
|
||||
}
|
||||
inner += decodeHtmlEntities(innerNode.value ?? '');
|
||||
i += 1;
|
||||
}
|
||||
if (!closed) {
|
||||
throw new Error('Unclosed <code> HTML element in GFM table cell');
|
||||
}
|
||||
values.push(inner);
|
||||
} else if (node.type === 'text' && node.value === ', ') {
|
||||
i += 1;
|
||||
} else {
|
||||
throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
describe('renderFieldShapesMarkdown', () => {
|
||||
test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => {
|
||||
const docsA = [
|
||||
{
|
||||
_id: fakeObjectId('000000000000000000000001'),
|
||||
'pipe|col': 'val|with`ticks\\slash',
|
||||
'slash\\|field': 'slash\\|pipe*em*_u_<tag>&',
|
||||
'tick`field\nname': '`leading`',
|
||||
edge: 'double``ticks',
|
||||
dt: '2025-01-02',
|
||||
},
|
||||
{
|
||||
_id: fakeObjectId('000000000000000000000002'),
|
||||
'pipe|col': 'slash\\|pipe',
|
||||
'slash\\|field': 'slash\\\\|pipe',
|
||||
'tick`field\nname': ' spaced ',
|
||||
edge: '',
|
||||
dt: '2025-01-03',
|
||||
},
|
||||
];
|
||||
const docsB = [docsA[1]!, docsA[0]!];
|
||||
|
||||
const run1 = await readFieldShapes(
|
||||
createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader,
|
||||
{ collections: ['eodPrices', 'qmSplits'], limit: 500 }
|
||||
);
|
||||
const run2 = await readFieldShapes(
|
||||
createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader,
|
||||
{ collections: ['qmSplits', 'eodPrices'], limit: 500 }
|
||||
);
|
||||
|
||||
const md1 = renderFieldShapesMarkdown(run1);
|
||||
const md2 = renderFieldShapesMarkdown(run2);
|
||||
|
||||
expect(md1).toBe(md2);
|
||||
expect(md1).toContain('bounded sample');
|
||||
expect(md1).toContain('Sample limit per collection:** 500');
|
||||
expect(md1).toContain('Total documents sampled:** 2');
|
||||
expect(md1).toContain('_No documents sampled._');
|
||||
|
||||
const tableRows = parseGfmTables(md1);
|
||||
expect(tableRows.length).toBe(6);
|
||||
|
||||
const visibleByField = new Map<string, string[]>();
|
||||
for (const cells of tableRows) {
|
||||
expect(cells.length).toBe(5);
|
||||
const parsedField = extractGfmCodeCellValues(cells[0]!);
|
||||
expect(parsedField.length).toBe(1);
|
||||
const parsedExamples = extractGfmCodeCellValues(cells[4]!);
|
||||
visibleByField.set(parsedField[0]!, parsedExamples);
|
||||
}
|
||||
|
||||
expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']);
|
||||
expect(visibleByField.get('slash\\\\|field')).toEqual([
|
||||
'slash\\\\|pipe',
|
||||
'slash\\|pipe*em*_u_<tag>&',
|
||||
]);
|
||||
expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']);
|
||||
expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']);
|
||||
expect(visibleByField.get('_id')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CLI arg parsing and headless probe runner', () => {
|
||||
test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => {
|
||||
expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true });
|
||||
expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() =>
|
||||
parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)])
|
||||
).toThrow(/--limit/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow(
|
||||
/Unknown argument/
|
||||
);
|
||||
expect(() =>
|
||||
parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol'])
|
||||
).toThrow(UnknownProbeCollectionError);
|
||||
|
||||
const parsed = parseProbeSourceFieldShapesArgs([
|
||||
'--out',
|
||||
'./tmp/report.md',
|
||||
'--limit',
|
||||
'250',
|
||||
'--collections',
|
||||
'qmDividends,ceoShorts,qmDividends',
|
||||
]);
|
||||
expect(parsed).toEqual({
|
||||
help: false,
|
||||
outPath: './tmp/report.md',
|
||||
limit: 250,
|
||||
collections: ['ceoShorts', 'qmDividends'],
|
||||
});
|
||||
});
|
||||
|
||||
test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => {
|
||||
let getCollectionCalls = 0;
|
||||
let closeCalls = 0;
|
||||
|
||||
const writableClient: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => false,
|
||||
getCollection() {
|
||||
getCollectionCalls += 1;
|
||||
throw new Error('should never be called');
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: writableClient,
|
||||
closeMongo: () => {
|
||||
closeCalls += 1;
|
||||
},
|
||||
writeFile: () => {},
|
||||
writeStdout: () => {},
|
||||
},
|
||||
{ outPath: './tmp/should-not-write.md' }
|
||||
)
|
||||
).rejects.toThrow(/read-only/i);
|
||||
expect(getCollectionCalls).toBe(0);
|
||||
expect(closeCalls).toBe(1);
|
||||
|
||||
const writtenFiles: Array<{ filePath: string; content: string }> = [];
|
||||
const stdoutChunks: string[] = [];
|
||||
let roCloseCalls = 0;
|
||||
|
||||
const roClient: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection(name: string) {
|
||||
return {
|
||||
find() {
|
||||
const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : [];
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const output = await runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: roClient,
|
||||
closeMongo: () => {
|
||||
roCloseCalls += 1;
|
||||
},
|
||||
writeFile: (filePath, content) => {
|
||||
writtenFiles.push({ filePath, content });
|
||||
},
|
||||
writeStdout: text => {
|
||||
stdoutChunks.push(text);
|
||||
},
|
||||
},
|
||||
{
|
||||
outPath: './tmp/field-shapes.md',
|
||||
limit: 10,
|
||||
collections: ['ceoShorts'],
|
||||
}
|
||||
);
|
||||
|
||||
expect(roCloseCalls).toBe(1);
|
||||
expect(writtenFiles.length).toBe(1);
|
||||
expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md');
|
||||
expect(writtenFiles[0]!.content).toBe(output.markdown);
|
||||
expect(stdoutChunks.join('')).toContain('Documents sampled: 1');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`.
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, and the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`).
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -453,7 +453,29 @@ Rules:
|
|||
- `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`).
|
||||
- `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`.
|
||||
5. **Deferred out of `M1.2o`:**
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`).
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`).
|
||||
|
||||
## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`)
|
||||
|
||||
`decode_qm_split_doc`, `decode_qm_split_bytes`, `decode_qm_split_buffer`, `decode_qm_dividend_doc`, `decode_qm_dividend_bytes`, and `decode_qm_dividend_buffer` (`src/bson_qm_actions.rs`) decode raw MongoDB `qmSplits` and `qmDividends` BSON documents in a single forward pass over `RawDocument::iter_elements()` into borrowed `RawQmSplit<'a>` and `RawQmDividend<'a>` views without allocating a `String` or `bson::Document` per row, reusing `bson_eod_prices::iter_raw_bson_docs` for concatenated length-prefixed buffers.
|
||||
|
||||
1. **Field contract & cited in-repo sources:**
|
||||
- `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`.
|
||||
- `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `splitratio` (`FIELD_SPLIT_RATIO`): BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `splitratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding.
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below.
|
||||
- `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below.
|
||||
2. **Zero-allocation key mapping & builder conversions:**
|
||||
- `RawQmSplit::to_split_event` → `SplitEvent`, `to_split_action_event` → `SplitActionEvent`; `RawQmDividend::to_dividend_event` → `DividendEvent`, `to_dividend_action_event` → `DividendActionEvent`.
|
||||
- `try_map_key(|code, ex_date| ...)` and `try_into_*` helpers mirror `RawEodDailyBar::try_into_eod_daily_bar` so callers can resolve `("qm", qmSearchCode, ex_date)` through `ProviderMappingTable` before allocating `currency` on dividends.
|
||||
3. **Typed errors & stream accounting policy:**
|
||||
- Never panics on untrusted input. `BsonQmActionError` names the offending field on every field-level error (`MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, plus framing variants `TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`).
|
||||
- Buffer decoders report and skip per-document errors without aborting the stream, always reconciling `decoded + rejected_total() == docs_in`.
|
||||
4. **Unverified field names:**
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`) and `currency` (`FIELD_DIVIDEND_CURRENCY`) could not be proven from any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped and `design/DATA-CONTRACTS.md` names only `date`, `declared`, and `usdFxRate` for `qmDividends`). Both are isolated in single `pub const` constants so the live MongoDB cursor task can confirm or adjust them in one place before touching QA data.
|
||||
- Numeric strings (e.g. `"10.0"`, `"1.42"`) are currently rejected as `WrongType` because no in-repo source proves QuoteMedia sends `splitratio` or dividend cash as strings; live schema inspection should confirm whether string coercion is needed.
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
|
|
@ -669,6 +691,54 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d27
|
|||
- Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3`
|
||||
- Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`).
|
||||
|
||||
### `bench-bson-qm-actions`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic QuoteMedia corporate-action documents (~4% `qmSplits`, ~96% `qmDividends`, with extra metadata `_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) pre-encoded into two contiguous length-prefixed buffers up front, timing decode-only via `decode_qm_split_buffer` and `decode_qm_dividend_buffer`:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-qm-actions [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59e46dc9dc`): `cargo run --release -p curate-etl --offline -- bench-bson-qm-actions`
|
||||
|
||||
- Input: `rows=1000000`, `splits=40146`, `dividends=959854`, `bytes=236043886` (~225.1 MiB, ~236.0 bytes/doc)
|
||||
- Splits: `decoded=39937`, `noop_ratio_one=616`, `rejected=209` (`missing=93`, `empty=0`, `wrong_type=45`, `malformed_date=38`, `invalid_number=33`, `corrupt=0`)
|
||||
- Dividends: `decoded=954952`, `rejected=4902` (`missing=1952`, `empty=0`, `wrong_type=1009`, `malformed_date=946`, `invalid_number=995`, `corrupt=0`)
|
||||
- Run 1: `elapsed=275.12 ms`, `throughput=3634828 docs/s`, `scan=818.23 MB/s`, `latency=275.12 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
- Run 2: `elapsed=282.92 ms`, `throughput=3534598 docs/s`, `scan=795.67 MB/s`, `latency=282.92 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
|
||||
## Raw BSON Streaming Reader (`bson_stream`, `M1.2y`)
|
||||
|
||||
`RawBsonChunkReader<R: std::io::Read>` (`src/bson_stream.rs`) frames arbitrary concatenated length-prefixed raw BSON streams (files, stdin pipes, or future cursor adapters) into whole-document [`RawBsonChunk`] slices using a single reused buffer, feeding the existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, `decode_qm_dividend_buffer`) unchanged without requiring the full dataset to fit in memory.
|
||||
|
||||
1. **Bounded memory & exact growth:**
|
||||
- Defaults: `DEFAULT_CHUNK_CAPACITY_BYTES = 8 MiB`, `DEFAULT_MAX_DOC_BYTES = 16 MiB + 16 KiB` (MongoDB max document size plus headroom). `BsonStreamOptions::validate` rejects `chunk_capacity_bytes == 0` (`InvalidChunkCapacity`) and `max_doc_bytes < 5` (`InvalidMaxDocBytes`).
|
||||
- Reuses one internal `Vec<u8>` buffer across chunks, compacting any trailing partial document to the front via `copy_within`. Grows only via `reserve_exact` + `resize` when a single document exceeds the current buffer length (or to 4 bytes when `chunk_capacity_bytes < 4`), and never beyond `max_doc_bytes`. `buffer_capacity()` exposes the current allocation ceiling.
|
||||
- Retries `ErrorKind::Interrupted` transparently and handles arbitrary short reads down to 1 byte at a time.
|
||||
2. **Error semantics & sticky terminal state:**
|
||||
- Complete prefix documents already buffered are always yielded before surfacing a trailing framing or I/O error.
|
||||
- Terminal errors carry the absolute byte `offset: u64` of the offending document: declared length `< 5` or `> max_doc_bytes` → `CorruptDocumentLength`; EOF mid-header or mid-document → `TruncatedDocument`; underlying read error → `Io`. After any terminal error, subsequent `next_chunk()` calls keep returning an error without panicking, looping, or re-reading the underlying source.
|
||||
3. **Streaming decode helpers (`for<'a>` callbacks):**
|
||||
- `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result<BsonEodDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream.
|
||||
|
||||
### `bench-bson-stream`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) streaming vs in-memory buffer decode benchmark over `2,000,000` synthetic `eodPrices` documents (reusing the exact `bench-bson-eod-prices` generator), decoding once via `decode_eod_price_buffer` and once via `RawBsonChunkReader` + `decode_eod_price_chunks` over an irregular short-read adapter (`257 B`..`128 KiB` prime steps straddling document and 4-byte header boundaries), asserting identical stats and checksum:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-stream [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-bson-stream`
|
||||
|
||||
- Input: `rows=2000000`, `bytes=571280190` (~544.8 MiB)
|
||||
- Decode: `decoded=1989987`, `rejected=10013` (`missing=3964`, `empty=0`, `wrong_type=2033`, `malformed_date=2027`, `invalid_number=1989`, `corrupt=0`), `checksum=0x94f87c60c9d3fbc6`
|
||||
- Buffer baseline: `elapsed=524.54 ms`, `throughput=3812856 rows/s`, `scan=1038.65 MiB/s`
|
||||
- Streamed short-read: `elapsed=544.59 ms`, `throughput=3672494 rows/s`, `scan=1000.42 MiB/s`, `ratio=0.963x`, `peak_buffer_capacity=8388608 bytes` (8 MiB)
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add:
|
||||
|
|
@ -842,6 +912,61 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows]
|
|||
- Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s`
|
||||
- Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000`
|
||||
|
||||
## `adj_factors` Curation Stage (`M1.2v`)
|
||||
|
||||
`curate_adj_factors`, `curate_adj_factors_as_of`, `curate_and_write_adj_factors`, `curate_and_write_adj_factors_as_of`, `read_adj_factors_dataset`, `read_adj_factors_dataset_as_of`, and `adj_factors_for_bar` (`src/curate_adj.rs`) join `ProviderMappingTable`, `build_adj_factors`, `session_close::et_session_close_utc_micros`, and `write_adj_factors_dataset` into contract `AdjFactorsParquetRow` records sorted and unique by `(listing_id, ex_date)`.
|
||||
|
||||
1. **Map-before-build rule:**
|
||||
- Resolves every source-keyed `qmSplits` and `qmDividends` event via `(mapping_source, source_key, ex_date) -> listing_id: i32` (using a cached per-key `ProviderMappingCursor`) *before* invoking `build_adj_factors::<i32, _, _>` unchanged.
|
||||
- Cumulative factors (`cum_split_factor`, `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker renames (two adjacent source-key ranges mapping to one `listing_id`), while ticker reuse across distinct `listing_id`s (e.g. `FB` 2012–2022 vs `FB` 2025+) produces two independent chains with no cross-listing bleed.
|
||||
- Unmapped splits and dividends are dropped and counted separately (`splits_dropped_unmapped`, `dividends_dropped_unmapped`).
|
||||
2. **Collision policy (fail closed on cross-key conflict):**
|
||||
- Single-source-key groups on `(listing_id, ex_date)` pass through unchanged to `build_adj_factors` (preserving same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and zero-cash dividend drops).
|
||||
- Multi-source-key groups with bitwise-identical split ratios (or bitwise-identical dividend `cash`/`currency`/`prev_close`/`prev_close_currency`) collapse to one event and are counted in `splits_collision_collapsed`, `dividends_collision_collapsed`, and `listing_collision_collapsed`.
|
||||
- Multi-source-key groups with conflicting split ratios or differing dividend payloads fail closed with `CurateAdjError::ConflictingCrossKeySplit` / `CurateAdjError::ConflictingCrossKeyDividend` (silently dropping or doubling an event would corrupt every earlier cumulative factor).
|
||||
3. **Conservative `known_at` & point-in-time / vault-fence policy:**
|
||||
- Stamps every curated row with `known_at_micros = session_close::et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / `America/Toronto`: `21:00 UTC` in EST, `20:00 UTC` in EDT) because `qmSplits` / `qmDividends` adj builder inputs carry no announcement timestamp.
|
||||
- Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns `CurateAdjError::ExDateOutOfRange` naming `(listing_id, ex_date)` without panicking (dropping a row would break the cumulative chain).
|
||||
- **Retrospective vs. Point-in-Time snapshots:** because `cum_split_factor` and `cum_total_factor` are right-to-left suffix products, later splits and dividends are embedded in earlier rows. `curate_adj_factors` / `curate_and_write_adj_factors` explicitly tag their output as `AdjSnapshotKind::RetrospectiveSnapshot` — slicing a retrospective snapshot with a bare `known_at <= as_of` filter would still leak future or held-out vault actions into earlier bars.
|
||||
- **Point-in-time & Vault fencing:** `curate_adj_factors_as_of` / `curate_and_write_adj_factors_as_of` accept an `AdjPointInTimeFence { as_of_micros, vault_cutoff_micros }` (`known_at <= as_of_micros` inclusive and `known_at < vault_cutoff_micros` strictly exclusive, matching `design/DATA-CONTRACTS.md` §4) and fence mapped source events *before* compaction and compounding, tagging the output as `AdjSnapshotKind::PointInTimeFenced(fence)`. Appending any future or vault-held action leaves earlier rows and `adj_factors_for_bar` reads bitwise identical.
|
||||
- **Persisted Parquet footer metadata & verified readers:** `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` publish `<out_dir>/adj_factors/part.parquet` in a single atomic file commit (one dataset lock, exclusive staging, live-preserving backup, single `rename`) embedding `stock_bot.adj_factors.{format_version, snapshot_kind, as_of_micros, vault_cutoff_micros, rows_written, snapshot_checksum}` directly in the Parquet footer `key_value_metadata` (where `snapshot_checksum` binds `format_version`, `snapshot_kind` / exact fence, row count, and all 8 columns of every row). When a run produces 0 rows (e.g. a fence excludes every event), an explicit 0-row Zstd Parquet file with the contract schema and embedded footer metadata is atomically published so any previous `part.parquet` is superseded rather than left stale. `read_adj_factors_dataset_as_of` requires a non-retrospective fence, fails closed on missing/corrupt/unsupported footer metadata, rejects retrospective snapshots (`RetrospectiveSnapshotRejected`) or any mismatched fence (`IncompatibleFence`), checks every row's `known_at` against the fence (`RowOutsideFence`), verifies per-listing `cum_split_factor` reverse suffix products, and verifies the bound `snapshot_checksum` (`SnapshotIntegrityMismatch`).
|
||||
4. **Accounting & error handling:**
|
||||
- Exact conservation invariants in `CurateAdjFactorsStats`:
|
||||
- `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in`
|
||||
- `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in`
|
||||
- `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed`
|
||||
- `rows_out == builder.rows_out` and `listings_out == builder.keys_out`
|
||||
- For `AdjSnapshotKind::RetrospectiveSnapshot`, `splits_dropped_fenced == 0` and `dividends_dropped_fenced == 0`.
|
||||
- `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` run curation before touching `out_dir`, so any `CurateAdjError` leaves `out_dir` untouched and publishes no `adj_factors/part.parquet` (surfacing via `CurateAdjWriteError::{Curate, Parquet}`).
|
||||
5. **Deferred items:**
|
||||
- Live MongoDB cursor streaming and BSON decoders for `qmSplits` / `qmDividends`
|
||||
- PostgreSQL `provider_mapping` preload
|
||||
- Sourcing `DividendEvent.prev_close` from `bars_1d` (currently supplied by the caller)
|
||||
- `rayon` parallel sharding and end-to-end `curate` CLI command
|
||||
|
||||
### `bench-curate-adj`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `1,000,000` (default) or `[events]` source-keyed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys spanning `1990..=2025` (single-range keys, ticker-rename pairs, ticker-reuse keys with an H2-2018 gap, unmapped keys, and explicit bitwise-identical alias keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet `write_adj_factors_dataset` into a temp directory with footer row-count verification and cleanup:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-curate-adj [events]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a1afe7e6b`): `cargo run --release -p curate-etl --offline -- bench-curate-adj`
|
||||
|
||||
- Input: `events=1000000`, `splits=40221`, `dividends=959779`, `keys=20000`
|
||||
- Builder: `rows_out=946414`, `keys_out=19500`, `split_noops=1938`, `zero_div=9234`, `missing_prev_close=18458`, `currency_mismatch=18461`, `not_below_prev_close=9193`
|
||||
- Output: `rows_out=946414` (`94.64%` retained), `listings_out=19500`, `files=1`, `row_groups=1`, `bytes=11872037`, `read_back_rows=946414`
|
||||
- Curation stats: `splits_unmapped=1486`, `divs_unmapped=34220`, `splits_coll_collapsed=213`, `divs_coll_collapsed=4717`, `coll_collapsed=4930`
|
||||
- Run 1:
|
||||
- Stage (in-memory): `elapsed=930.92 ms`, `throughput=1074206 events/s`, `latency=930.92 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.42 ms`, `throughput=3606439 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1193.34 ms`, `throughput=837982 events/s`
|
||||
- Run 2:
|
||||
- Stage (in-memory): `elapsed=933.02 ms`, `throughput=1071785 events/s`, `latency=933.02 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s`
|
||||
|
||||
## `corporate_actions` Curation Stage (`M1.2u`)
|
||||
|
||||
`curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -42,7 +42,7 @@ use bson::spec::ElementType;
|
|||
use crate::bars::EodDailyBar;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
pub(crate) const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
const MIN_BSON_DOC_LEN: i32 = 5;
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `eodPrices` BSON document.
|
||||
|
|
@ -235,6 +235,26 @@ impl BsonEodDecodeStats {
|
|||
| BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonEodDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -250,22 +270,20 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option<u32> {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
pub(crate) fn parse_ymd_strict_days(s: &str) -> Option<i32> {
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
return None;
|
||||
}
|
||||
let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })
|
||||
let year_u32 = parse_ascii_digits_u32(&bytes[0..4])?;
|
||||
let month = parse_ascii_digits_u32(&bytes[5..7])?;
|
||||
let day = parse_ascii_digits_u32(&bytes[8..10])?;
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
parse_ymd_strict_days(s).ok_or(BsonEodPriceError::MalformedDate { field: "date" })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -438,11 +456,7 @@ pub fn decode_eod_price_doc<'a>(
|
|||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
|
|
@ -471,10 +485,18 @@ pub fn decode_eod_price_bytes<'a>(
|
|||
declared_len,
|
||||
});
|
||||
}
|
||||
let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
let doc = parse_single_raw_doc(bytes)?;
|
||||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
|
|
|
|||
813
tools/curate-etl/src/bson_qm_actions.rs
Normal file
813
tools/curate-etl/src/bson_qm_actions.rs
Normal file
|
|
@ -0,0 +1,813 @@
|
|||
//! Zero-copy raw BSON decoders for MongoDB `qmSplits` and `qmDividends` documents (`M1.2w`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawQmSplit`] and [`RawQmDividend`] views without allocating a `String` or
|
||||
//! `bson::Document` per row. Callers convert borrowed views into [`SplitEvent`], [`DividendEvent`],
|
||||
//! [`SplitActionEvent`], or [`DividendActionEvent`], optionally resolving `("qm", qmSearchCode, ex_date)`
|
||||
//! through a caller-supplied key mapper (such as [`crate::provider_mapping::ProviderMappingTable::resolve`]).
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! - `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:92-124`: writes
|
||||
//! `qmSearchCode`, `symbol`, `exchange`, `reportDate: new Date(x.date)` plus the spread
|
||||
//! QuoteMedia API payload into `qmDividends` and `qmSplits`.
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 25): documents `date`, `declared`, `splitratio`
|
||||
//! (`258` rows have `splitratio == 1`), and `usdFxRate` (bogus `usdFxRate: 1` on CAD dividend
|
||||
//! rows; contract rule: ignore `usdFxRate`).
|
||||
//! - **Unverified field names:** the raw MongoDB dividend cash and currency field names are not
|
||||
//! proven by any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped).
|
||||
//! They are isolated in [`FIELD_DIVIDEND_CASH`] (`"amount"`) and [`FIELD_DIVIDEND_CURRENCY`]
|
||||
//! (`"currency"`) and explicitly listed under "Unverified field names" in `tools/curate-etl/README.md`.
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `qmSearchCode`, `currency`: BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only
|
||||
//! is rejected).
|
||||
//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via
|
||||
//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via
|
||||
//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check).
|
||||
//! - `declared` (optional): absent, BSON `Null`, or empty/whitespace `String` maps to `None`;
|
||||
//! otherwise strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`.
|
||||
//! - `splitratio`: BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `ratio == 1.0`
|
||||
//! no-ops are **decoded, not dropped** (downstream builders drop them) and counted in
|
||||
//! [`BsonQmActionDecodeStats::split_noop_ratio_one`].
|
||||
//! - `amount` (dividend cash): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0`
|
||||
//! (`-0.0` is normalized to `+0.0`).
|
||||
//! - `usdFxRate` and all unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`,
|
||||
//! `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without calling
|
||||
//! `elem.value()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::adj::DividendEvent;
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
MILLIS_PER_DAY,
|
||||
};
|
||||
use crate::corporate_actions::{DividendActionEvent, SplitActionEvent};
|
||||
use crate::split::SplitEvent;
|
||||
|
||||
/// MongoDB field name for the QuoteMedia security key (`events.action.ts:98,118`).
|
||||
pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode";
|
||||
/// MongoDB field name for the ex-split / ex-dividend date (`events.action.ts:99,119`, `DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DATE: &str = "date";
|
||||
/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DECLARED: &str = "declared";
|
||||
/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_SPLIT_RATIO: &str = "splitratio";
|
||||
/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_USD_FX_RATE: &str = "usdFxRate";
|
||||
/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CASH: &str = "amount";
|
||||
/// MongoDB field name for dividend currency code (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CURRENCY: &str = "currency";
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmSplits` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `ratio == 1.0` no-op rows are preserved here so downstream builders (`SplitTable`,
|
||||
/// `build_adj_factors`, `build_corporate_actions`) apply their own filtering and accounting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmSplit<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-split date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// `new_shares / old_shares` (finite and `> 0.0`).
|
||||
pub ratio: f64,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmSplit<'a> {
|
||||
/// Converts this borrowed split into a [`SplitEvent`] for [`crate::split::SplitTable`] or
|
||||
/// [`crate::adj::build_adj_factors`].
|
||||
#[inline]
|
||||
pub fn to_split_event(self) -> SplitEvent {
|
||||
SplitEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed split into a [`SplitActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_split_action_event(self) -> SplitActionEvent {
|
||||
SplitActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_event<K, F>(self, map_key: F) -> Option<(K, SplitEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_event()))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_action_event<K, F>(self, map_key: F) -> Option<(K, SplitActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmDividends` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` and `currency` directly from the underlying `&RawDocument` byte slice.
|
||||
/// Deliberately omits `usdFxRate` per `design/DATA-CONTRACTS.md` §1.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmDividend<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-dividend date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// Cash dividend amount per share (finite and `>= 0.0`, with `-0.0` normalized to `+0.0`).
|
||||
pub cash: f64,
|
||||
/// Local dividend currency code (e.g. `"USD"`, `"CAD"`).
|
||||
pub currency: &'a str,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmDividend<'a> {
|
||||
/// Converts this borrowed dividend into a [`DividendEvent`] for
|
||||
/// [`crate::adj::build_adj_factors`], attaching caller-supplied `prev_close` context.
|
||||
#[inline]
|
||||
pub fn to_dividend_event(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
) -> DividendEvent {
|
||||
DividendEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
prev_close,
|
||||
prev_close_currency,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed dividend into a [`DividendActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_dividend_action_event(self) -> DividendActionEvent {
|
||||
DividendActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with [`DividendEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_event<K, F>(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_event(prev_close, prev_close_currency)))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with
|
||||
/// [`DividendActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_action_event<K, F>(
|
||||
self,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `qmSplits` or `qmDividends` BSON documents or
|
||||
/// length-prefixed buffers.
|
||||
///
|
||||
/// Every field-level error names the offending BSON field in both its structure and `Display`
|
||||
/// output; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonQmActionError {
|
||||
/// A required field was absent from the document.
|
||||
MissingField { field: &'static str },
|
||||
/// A required string field was empty or contained only whitespace.
|
||||
EmptyField { field: &'static str },
|
||||
/// A decoded field had an unexpected BSON element type.
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A date field was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime`
|
||||
/// overflowed `i32` epoch days.
|
||||
MalformedDate { field: &'static str },
|
||||
/// A numeric field was non-finite (`NaN`, `±inf`) or violated its domain bound (`> 0` for
|
||||
/// `splitratio`, `>= 0` for dividend cash).
|
||||
InvalidNumber { field: &'static str, value: f64 },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonQmActionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "qm action BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(f, "qm action BSON field '{field}' must not be empty or blank")
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime"
|
||||
)
|
||||
}
|
||||
Self::InvalidNumber { field, value } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has invalid numeric value {value}"
|
||||
)
|
||||
}
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonQmActionError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonQmActionError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmActionError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonQmActionError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonQmActionError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonQmActionError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonQmActionError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => BsonQmActionError::MalformedDate { field },
|
||||
BsonEodPriceError::InvalidNumber { field, value } => {
|
||||
BsonQmActionError::InvalidNumber { field, value }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_qm_split_buffer`] and
|
||||
/// [`decode_qm_dividend_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
/// `split_noop_ratio_one` counts decoded `qmSplits` documents with `ratio == 1.0` (a subset of
|
||||
/// `decoded`, never added to `rejected_total()`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonQmActionDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub decoded: usize,
|
||||
/// Decoded `qmSplits` rows with `splitratio == 1.0` (subset of `decoded`).
|
||||
pub split_noop_ratio_one: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_malformed_date: usize,
|
||||
pub rejected_invalid_number: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonQmActionDecodeStats {
|
||||
/// Total number of rejected documents across all error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_missing_field
|
||||
+ self.rejected_empty_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_malformed_date
|
||||
+ self.rejected_invalid_number
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonQmActionError) {
|
||||
match err {
|
||||
BsonQmActionError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonQmActionError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonQmActionError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonQmActionError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonQmActionError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
|
||||
BsonQmActionError::TruncatedDocument { .. }
|
||||
| BsonQmActionError::CorruptDocumentLength { .. }
|
||||
| BsonQmActionError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.split_noop_ratio_one += other.split_noop_ratio_one;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonQmActionDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonQmActionError> {
|
||||
elem.value().map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_empty_str<'a>(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'a>,
|
||||
) -> Result<&'a str, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonQmActionError::EmptyField { field });
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_required_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<i32, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
parse_ymd_strict_days(s).ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days).map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_optional_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<Option<i32>, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Null => Ok(None),
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
parse_ymd_strict_days(s)
|
||||
.map(Some)
|
||||
.ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days)
|
||||
.map(Some)
|
||||
.map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_positive_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v <= 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_negative_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v < 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
if v == 0.0 {
|
||||
Ok(0.0)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_qm_split_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut ratio: Option<f64> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_SPLIT_RATIO {
|
||||
let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?;
|
||||
ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(ratio) = ratio else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmSplit {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
ratio,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_qm_dividend_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut cash: Option<f64> = None;
|
||||
let mut currency: Option<&'a str> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CASH {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CASH, elem, offset)?;
|
||||
cash = Some(decode_non_negative_number(FIELD_DIVIDEND_CASH, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CURRENCY {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CURRENCY, elem, offset)?;
|
||||
currency = Some(decode_non_empty_str(FIELD_DIVIDEND_CURRENCY, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(cash) = cash else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
});
|
||||
};
|
||||
let Some(currency) = currency else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmDividend {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
cash,
|
||||
currency,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmSplits` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_split_doc<'a>(doc: &'a RawDocument) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmSplit`].
|
||||
pub fn decode_qm_split_bytes<'a>(bytes: &'a [u8]) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmDividends` MongoDB document in one forward
|
||||
/// pass without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_dividend_doc<'a>(
|
||||
doc: &'a RawDocument,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawQmDividend`].
|
||||
pub fn decode_qm_dividend_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_split_doc`], invoking
|
||||
/// `on_split` for every valid document (including `splitratio == 1.0`, counted in
|
||||
/// `stats.split_noop_ratio_one`) and `on_error(byte_offset, err)` for every rejected document
|
||||
/// without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_split_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_split: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_split_doc_at(doc, doc_offset) {
|
||||
Ok(split) => {
|
||||
stats.decoded += 1;
|
||||
if split.ratio == 1.0 {
|
||||
stats.split_noop_ratio_one += 1;
|
||||
}
|
||||
on_split(split);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_dividend_doc`], invoking
|
||||
/// `on_dividend` for every valid document and `on_error(byte_offset, err)` for every rejected
|
||||
/// document without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_dividend_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_dividend: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_dividend_doc_at(doc, doc_offset) {
|
||||
Ok(dividend) => {
|
||||
stats.decoded += 1;
|
||||
on_dividend(dividend);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_qm_actions_tests.rs"]
|
||||
mod tests;
|
||||
883
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
883
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::corporate_actions::{build_corporate_actions, CorporateActionKind, KnownAtSource};
|
||||
use crate::curate_adj::curate_adj_factors;
|
||||
use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::split::{ymd_to_epoch_days, SplitTable};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn make_dividend_doc(
|
||||
code: &str,
|
||||
date: &str,
|
||||
cash: f64,
|
||||
currency: &str,
|
||||
declared: Option<&str>,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rate() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "quotemedia");
|
||||
nested.append(cstr!("version"), 1_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("ca");
|
||||
tags.push("equity");
|
||||
|
||||
// Realistic qmSplits document with extra metadata and bogus usdFxRate.
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
split_doc.append(cstr!("symbol"), "NVDA");
|
||||
split_doc.append(cstr!("exchange"), "NASDAQ");
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("splitratio"), 10.0_f64);
|
||||
split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type");
|
||||
split_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY),
|
||||
);
|
||||
split_doc.append(cstr!("created_at"), DateTime::from_millis(1_718_000_000_000));
|
||||
split_doc.append(cstr!("updated_at"), DateTime::from_millis(1_718_000_060_000));
|
||||
split_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
split_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio.to_bits(), 10.0_f64.to_bits());
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
|
||||
// Realistic qmDividends document with bogus usdFxRate: 1 on CAD row.
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]),
|
||||
);
|
||||
div_doc.append(cstr!("symbol"), "RY");
|
||||
div_doc.append(cstr!("exchange"), "TSX");
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(cstr!("date"), "2024-11-15");
|
||||
div_doc.append(cstr!("declared"), "2024-10-30");
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * MILLIS_PER_DAY),
|
||||
);
|
||||
div_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
div_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash.to_bits(), 1.42_f64.to_bits());
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_day() {
|
||||
// Pre-1970 mid-day: 1969-12-31T12:34:56.789Z must floor to epoch day -1 (not 0).
|
||||
let pre_1970_ex_ms: i64 = -MILLIS_PER_DAY + (12 * 3600 + 34 * 60 + 56) * 1000 + 789;
|
||||
let pre_1970_decl_ms: i64 = -10 * MILLIS_PER_DAY + 43_200_000;
|
||||
|
||||
let mut split_dt = RawDocumentBuf::new();
|
||||
split_dt.append(cstr!("qmSearchCode"), "IBM");
|
||||
split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms));
|
||||
split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms));
|
||||
split_dt.append(cstr!("splitratio"), 2_i32);
|
||||
|
||||
let split = decode_qm_split_doc(&split_dt).unwrap();
|
||||
assert_eq!(split.ex_date, -1);
|
||||
assert_eq!(split.declared_date, Some(-10));
|
||||
assert_eq!(split.ratio, 2.0);
|
||||
|
||||
// Leap day string + DateTime declared.
|
||||
let mut div_leap = RawDocumentBuf::new();
|
||||
div_leap.append(cstr!("qmSearchCode"), "TD:CA");
|
||||
div_leap.append(cstr!("date"), "2024-02-29");
|
||||
div_leap.append(
|
||||
cstr!("declared"),
|
||||
DateTime::from_millis(i64::from(day(2024, 2, 1)) * MILLIS_PER_DAY + 36_000_000),
|
||||
);
|
||||
div_leap.append(cstr!("amount"), 1.02_f64);
|
||||
div_leap.append(cstr!("currency"), "CAD");
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_leap).unwrap();
|
||||
assert_eq!(div.ex_date, day(2024, 2, 29));
|
||||
assert_eq!(div.declared_date, Some(day(2024, 2, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() {
|
||||
// Splits: Double, Int32, Int64.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.05), 0.05_f64),
|
||||
(RawBsonRef::Int32(4), 4.0_f64),
|
||||
(RawBsonRef::Int64(10), 10.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
let decoded = decode_qm_split_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.ratio.to_bits(), expected.to_bits());
|
||||
}
|
||||
|
||||
// Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.25), 0.25_f64),
|
||||
(RawBsonRef::Double(-0.0), 0.0_f64),
|
||||
(RawBsonRef::Double(0.0), 0.0_f64),
|
||||
(RawBsonRef::Int32(0), 0.0_f64),
|
||||
(RawBsonRef::Int32(2), 2.0_f64),
|
||||
(RawBsonRef::Int64(0), 0.0_f64),
|
||||
(RawBsonRef::Int64(5), 5.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), val);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let decoded = decode_qm_dividend_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.cash.to_bits(), expected.to_bits());
|
||||
assert!(!decoded.cash.is_sign_negative());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_optional_declared_missing_null_empty_malformed_and_wrong_type() {
|
||||
// Missing declared -> None.
|
||||
let s_missing = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
assert_eq!(decode_qm_split_doc(&s_missing).unwrap().declared_date, None);
|
||||
|
||||
// Null declared -> None.
|
||||
let mut s_null = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
s_null.append(cstr!("declared"), RawBsonRef::Null);
|
||||
assert_eq!(decode_qm_split_doc(&s_null).unwrap().declared_date, None);
|
||||
|
||||
// Empty and whitespace-only declared -> None.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let d_blank = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", Some(blank));
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&d_blank).unwrap().declared_date,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// Malformed declared -> MalformedDate naming "declared".
|
||||
let s_bad = make_split_doc("AAPL", "2020-08-31", 4.0, Some("2023-02-29"));
|
||||
let err = decode_qm_split_doc(&s_bad).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
|
||||
// Wrong type on declared -> WrongType naming "declared".
|
||||
let mut d_wrong = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
d_wrong.append(cstr!("declared"), 20240801_i32);
|
||||
let err = decode_qm_dividend_doc(&d_wrong).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DECLARED,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() {
|
||||
let mut buf = Vec::new();
|
||||
for val in [
|
||||
RawBsonRef::Double(1.0),
|
||||
RawBsonRef::Int32(1),
|
||||
RawBsonRef::Int64(1),
|
||||
RawBsonRef::Double(2.0),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NOOP");
|
||||
doc.append(cstr!("date"), "2024-03-15");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
|
||||
let mut decoded_ratios = Vec::new();
|
||||
let stats = decode_qm_split_buffer(
|
||||
&buf,
|
||||
|s| decoded_ratios.push(s.ratio),
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_ratios, vec![1.0, 1.0, 1.0, 2.0]);
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.decoded, 4);
|
||||
assert_eq!(stats.split_noop_ratio_one, 3);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_every_error_variant_and_names_offending_field() {
|
||||
// 1. Missing required fields on splits.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 2. Missing required fields on dividends.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 3. Empty / whitespace-only string fields.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let s = make_split_doc(blank, "2024-06-10", 2.0, None);
|
||||
let err = decode_qm_split_doc(&s).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
|
||||
let d = make_dividend_doc("RY:CA", "2024-06-10", 0.5, blank, None);
|
||||
let err = decode_qm_dividend_doc(&d).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 4. Wrong BSON types (including string-encoded numerics).
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), 123_i32);
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), 20240610_i32);
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), "10.0");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), "1.42");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 1.42_f64);
|
||||
doc.append(cstr!("currency"), true);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
actual: ElementType::Boolean,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 5. Malformed dates (bad calendar date, bad format, and DateTime overflowing i32 days).
|
||||
for bad_date in ["2023-02-29", "2024/06/10", "2024-6-10", "not-a-date"] {
|
||||
let doc = make_split_doc("NVDA", bad_date, 2.0, None);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), DateTime::from_millis(i64::MAX));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("declared"), DateTime::from_millis(i64::MIN));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 6. Invalid numeric values for splitratio (<= 0 or non-finite).
|
||||
for bad_ratio in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Double(-2.0),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(0),
|
||||
RawBsonRef::Int64(-5),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), bad_ratio);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_ratio:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 7. Invalid numeric values for dividend cash (< 0 or non-finite).
|
||||
for bad_cash in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(-0.01),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-10),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), bad_cash);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_cash:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
|
||||
// 8. Truncated and corrupt documents (zero panics).
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&[]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 0,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_dividend_bytes(&[1, 2, 3]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 3,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&4_i32.to_le_bytes()),
|
||||
Err(BsonQmActionError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
})
|
||||
));
|
||||
let valid_bytes = make_split_doc("NVDA", "2024-06-10", 10.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&valid_bytes[..valid_bytes.len() - 1]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
})
|
||||
));
|
||||
let mut with_trailing = valid_bytes.clone();
|
||||
with_trailing.push(0);
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&with_trailing),
|
||||
Err(BsonQmActionError::CorruptDocumentLength { offset: 0, .. })
|
||||
));
|
||||
let mut bad_terminator = valid_bytes;
|
||||
*bad_terminator.last_mut().unwrap() = 0xFF;
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&bad_terminator),
|
||||
Err(BsonQmActionError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Invalid UTF-8 inside a known string field (`qmSearchCode`).
|
||||
let mut invalid_utf8_doc: Vec<u8> = Vec::new();
|
||||
// Placeholder 4-byte length.
|
||||
invalid_utf8_doc.extend_from_slice(&0_i32.to_le_bytes());
|
||||
invalid_utf8_doc.push(0x02); // UTF-8 String element
|
||||
invalid_utf8_doc.extend_from_slice(b"qmSearchCode\0");
|
||||
invalid_utf8_doc.extend_from_slice(&3_i32.to_le_bytes()); // 2 bytes + NUL
|
||||
invalid_utf8_doc.extend_from_slice(&[0xFF, 0xFE, 0x00]);
|
||||
invalid_utf8_doc.push(0x00); // doc terminator
|
||||
let total_len = invalid_utf8_doc.len() as i32;
|
||||
invalid_utf8_doc[0..4].copy_from_slice(&total_len.to_le_bytes());
|
||||
let err = decode_qm_split_bytes(&invalid_utf8_doc).unwrap_err();
|
||||
assert!(matches!(err, BsonQmActionError::CorruptBson { offset: 0, .. }));
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_decoders_survive_per_doc_errors_and_reconcile_stats_for_both_collections() {
|
||||
// 1. qmSplits mixed valid/invalid buffer.
|
||||
let s1 = make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22"));
|
||||
let s_noop = make_split_doc("NOOP", "2024-06-11", 1.0, None);
|
||||
let mut s_missing = RawDocumentBuf::new();
|
||||
s_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
s_missing.append(cstr!("date"), "2024-06-12");
|
||||
let s_empty = make_split_doc(" ", "2024-06-13", 2.0, None);
|
||||
let mut s_wrong = RawDocumentBuf::new();
|
||||
s_wrong.append(cstr!("qmSearchCode"), "WRNG");
|
||||
s_wrong.append(cstr!("date"), "2024-06-14");
|
||||
s_wrong.append(cstr!("splitratio"), "2.0");
|
||||
let s_bad_date = make_split_doc("DATE", "2023-02-29", 2.0, None);
|
||||
let s_bad_num = make_split_doc("NUM", "2024-06-15", 0.0, None);
|
||||
let mut s_corrupt = make_split_doc("CORR", "2024-06-16", 2.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
*s_corrupt.last_mut().unwrap() = 0xAA;
|
||||
let s2 = make_split_doc("NEXM:CA", "2025-06-18", 0.05, None);
|
||||
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(s1.as_bytes());
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
split_buf.extend_from_slice(s_missing.as_bytes());
|
||||
split_buf.extend_from_slice(s_empty.as_bytes());
|
||||
split_buf.extend_from_slice(s_wrong.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_date.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_num.as_bytes());
|
||||
split_buf.extend_from_slice(&s_corrupt);
|
||||
split_buf.extend_from_slice(s2.as_bytes());
|
||||
|
||||
let mut split_codes = Vec::new();
|
||||
let mut split_errors = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| split_codes.push(s.qm_search_code.to_owned()),
|
||||
|off, err| split_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(split_codes, vec!["NVDA", "NOOP", "NEXM:CA"]);
|
||||
assert_eq!(split_errors.len(), 6);
|
||||
assert_eq!(split_stats.docs_in, 9);
|
||||
assert_eq!(split_stats.decoded, 3);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_missing_field, 1);
|
||||
assert_eq!(split_stats.rejected_empty_field, 1);
|
||||
assert_eq!(split_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(split_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(split_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
|
||||
// 2. qmDividends mixed valid/invalid buffer ending with a corrupt length prefix.
|
||||
let d1 = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
let mut d_missing = RawDocumentBuf::new();
|
||||
d_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
d_missing.append(cstr!("date"), "2024-11-15");
|
||||
d_missing.append(cstr!("amount"), 0.5_f64);
|
||||
let d_empty = make_dividend_doc("RY:CA", "2024-11-15", 0.5, " ", None);
|
||||
let mut d_wrong = RawDocumentBuf::new();
|
||||
d_wrong.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_wrong.append(cstr!("date"), "2024-11-15");
|
||||
d_wrong.append(cstr!("amount"), "0.5");
|
||||
d_wrong.append(cstr!("currency"), "CAD");
|
||||
let d_bad_date = make_dividend_doc("RY:CA", "2024-11-15", 0.5, "CAD", Some("bad"));
|
||||
let d_bad_num = make_dividend_doc("RY:CA", "2024-11-15", -0.1, "CAD", None);
|
||||
let d2 = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
div_buf.extend_from_slice(d1.as_bytes());
|
||||
div_buf.extend_from_slice(d_missing.as_bytes());
|
||||
div_buf.extend_from_slice(d_empty.as_bytes());
|
||||
div_buf.extend_from_slice(d_wrong.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_date.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_num.as_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
// Trailing corrupt length < 5 stops cleanly.
|
||||
div_buf.extend_from_slice(&2_i32.to_le_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
|
||||
let mut div_codes = Vec::new();
|
||||
let mut div_errors = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| div_codes.push(d.qm_search_code.to_owned()),
|
||||
|off, err| div_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(div_codes, vec!["RY:CA", "AAPL"]);
|
||||
assert_eq!(div_errors.len(), 6);
|
||||
assert_eq!(div_stats.docs_in, 8);
|
||||
assert_eq!(div_stats.decoded, 2);
|
||||
assert_eq!(div_stats.split_noop_ratio_one, 0);
|
||||
assert_eq!(div_stats.rejected_missing_field, 1);
|
||||
assert_eq!(div_stats.rejected_empty_field, 1);
|
||||
assert_eq!(div_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(div_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(div_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_events_feed_split_table_curate_adj_factors_and_corporate_actions_unchanged() {
|
||||
// 1. SplitTable interoperability (NVDA 10:1 forward, NEXM:CA 1:20 reverse, 1:1 no-op).
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(
|
||||
make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")).as_bytes(),
|
||||
);
|
||||
split_buf.extend_from_slice(make_split_doc("NVDA", "2024-07-01", 1.0, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("NEXM:CA", "2025-06-18", 0.05, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("UNMAPPED", "2024-06-10", 2.0, None).as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
let mut ry_div = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
ry_div.append(cstr!("usdFxRate"), 1_i32); // bogus usdFxRate must have zero effect
|
||||
div_buf.extend_from_slice(ry_div.as_bytes());
|
||||
let mut unmapped_div = make_dividend_doc("UNMAPPED", "2024-11-15", 0.50, "USD", None);
|
||||
unmapped_div.append(cstr!("usdFxRate"), 999.0_f64);
|
||||
div_buf.extend_from_slice(unmapped_div.as_bytes());
|
||||
|
||||
let mut source_splits = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| source_splits.push((s.qm_search_code.to_owned(), s.to_split_event())),
|
||||
|_, err| panic!("unexpected split decode error: {err}"),
|
||||
);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
|
||||
let table = SplitTable::from_events(source_splits.iter().cloned()).unwrap();
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 10)), 1.0);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 17)), 0.05);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 18)), 1.0);
|
||||
|
||||
// 2. ProviderMappingTable + curate_adj_factors interoperability.
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NEXM:CA".to_string(),
|
||||
listing_id: 202,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut source_divs = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
source_divs.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
},
|
||||
|_, err| panic!("unexpected dividend decode error: {err}"),
|
||||
);
|
||||
|
||||
let curated = curate_adj_factors(&mapping, "qm", source_splits, source_divs).unwrap();
|
||||
// 1:1 NVDA split dropped by builder; UNMAPPED split & dividend dropped by mapping.
|
||||
assert_eq!(curated.rows.len(), 3);
|
||||
assert_eq!(curated.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(curated.stats.splits_dropped_unmapped, 1);
|
||||
assert_eq!(curated.stats.dividends_dropped_unmapped, 1);
|
||||
|
||||
// Row 0: listing 101 (NVDA) 10:1 split
|
||||
assert_eq!(curated.rows[0].listing_id, 101);
|
||||
assert_eq!(curated.rows[0].ex_date, day(2024, 6, 10));
|
||||
assert_eq!(curated.rows[0].split_factor, 10.0);
|
||||
assert_eq!(curated.rows[0].cum_split_factor, 10.0);
|
||||
|
||||
// Row 1: listing 202 (NEXM:CA) 1:20 reverse split
|
||||
assert_eq!(curated.rows[1].listing_id, 202);
|
||||
assert_eq!(curated.rows[1].ex_date, day(2025, 6, 18));
|
||||
assert_eq!(curated.rows[1].split_factor, 0.05);
|
||||
|
||||
// Row 2: listing 303 (RY:CA) CAD dividend with usdFxRate ignored
|
||||
assert_eq!(curated.rows[2].listing_id, 303);
|
||||
assert_eq!(curated.rows[2].ex_date, day(2024, 11, 15));
|
||||
assert_eq!(curated.rows[2].div_cash, 1.42);
|
||||
assert_eq!(curated.rows[2].div_currency.as_deref(), Some("CAD"));
|
||||
let expected_div_factor = 142.0 / (142.0 - 1.42);
|
||||
assert!((curated.rows[2].cum_total_factor - expected_div_factor).abs() < 1e-12);
|
||||
|
||||
// 3. try_map_key / try_into_*_action_event -> build_corporate_actions.
|
||||
let mut mapped_split_actions = Vec::new();
|
||||
decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
let mut mapped_div_actions = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
// Also verify try_into_split_event & try_into_dividend_event filter unmapped keys.
|
||||
let unmapped_split_doc = make_split_doc("UNMAPPED", "2024-06-10", 2.0, None);
|
||||
let unmapped_split = decode_qm_split_doc(&unmapped_split_doc).unwrap();
|
||||
assert_eq!(
|
||||
unmapped_split.try_into_split_event(|code, date| mapping.resolve("qm", code, date)),
|
||||
None
|
||||
);
|
||||
let mapped_div = decode_qm_dividend_doc(&ry_div).unwrap();
|
||||
let (lid, div_ev) = mapped_div
|
||||
.try_into_dividend_event(Some(142.0), Some("CAD".to_string()), |code, date| {
|
||||
mapping.resolve("qm", code, date)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(lid, 303);
|
||||
assert_eq!(div_ev.currency, "CAD");
|
||||
|
||||
let ca = build_corporate_actions(
|
||||
mapped_split_actions,
|
||||
mapped_div_actions,
|
||||
std::iter::empty(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ca.rows.len(), 3);
|
||||
assert_eq!(ca.stats.split_noops_dropped, 1);
|
||||
|
||||
// NVDA split has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[0].key, 101);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
|
||||
// NEXM split has no declared_date -> ExDateFallback.
|
||||
assert_eq!(ca.rows[1].key, 202);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[1].declared_date, None);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::ExDateFallback);
|
||||
|
||||
// RY:CA dividend has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[2].key, 303);
|
||||
assert_eq!(ca.rows[2].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[2].cash_amount, Some(1.42));
|
||||
assert_eq!(ca.rows[2].currency.as_deref(), Some("CAD"));
|
||||
assert_eq!(ca.rows[2].declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(ca.rows[2].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
661
tools/curate-etl/src/bson_stream.rs
Normal file
661
tools/curate-etl/src/bson_stream.rs
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
//! Bounded-memory streaming reader for concatenated raw BSON (`M1.2y`).
|
||||
//!
|
||||
//! Reads length-prefixed raw BSON documents from any [`std::io::Read`] source (files, stdin pipes,
|
||||
//! or future cursor adapters) into a single reused byte buffer with a fixed memory ceiling,
|
||||
//! framing only complete documents into [`RawBsonChunk`] slices that can be passed directly to the
|
||||
//! existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`,
|
||||
//! `decode_qm_dividend_buffer`).
|
||||
//!
|
||||
//! # Callback Lifetime Bound (`for<'a>`)
|
||||
//!
|
||||
//! Because [`RawBsonChunkReader`] reuses one internal byte buffer across chunks, borrowed zero-copy
|
||||
//! document views ([`RawEodDailyBar<'a>`], [`RawQmSplit<'a>`], [`RawQmDividend<'a>`]) only remain
|
||||
//! valid for the duration of the chunk in which they were decoded. The streaming decode helpers
|
||||
//! ([`decode_eod_price_stream`], [`decode_qm_split_stream`], [`decode_qm_dividend_stream`], and
|
||||
//! their `*_chunks` counterparts) therefore require higher-ranked callbacks
|
||||
//! (`F: for<'a> FnMut(RawEodDailyBar<'a>)`, etc.) so closures cannot escape borrowed slices past a
|
||||
//! chunk boundary. Callers should map or intern borrowed keys (e.g. via
|
||||
//! `ProviderMappingTable::resolve`) or copy only the retained fields inside the callback.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
use crate::bson_eod_prices::{
|
||||
decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar,
|
||||
};
|
||||
use crate::bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError,
|
||||
RawQmDividend, RawQmSplit,
|
||||
};
|
||||
|
||||
/// Default chunk buffer capacity: 8 MiB.
|
||||
pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024;
|
||||
/// Default maximum allowed BSON document size: 16 MiB (MongoDB limit) + 16 KiB headroom.
|
||||
pub const DEFAULT_MAX_DOC_BYTES: usize = 16 * 1024 * 1024 + 16 * 1024;
|
||||
/// Minimum valid length-prefixed BSON document size (4-byte length prefix + trailing `0x00`).
|
||||
pub const MIN_BSON_DOC_BYTES: usize = 5;
|
||||
|
||||
/// Configuration options for [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BsonStreamOptions {
|
||||
/// Initial reusable buffer size in bytes (capped at `max_doc_bytes`). Must be `> 0`.
|
||||
pub chunk_capacity_bytes: usize,
|
||||
/// Hard upper bound on any single BSON document's declared byte length. Must be `>= 5`.
|
||||
pub max_doc_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for BsonStreamOptions {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BsonStreamOptions {
|
||||
/// Validates option invariants, rejecting `chunk_capacity_bytes == 0` and `max_doc_bytes < 5`.
|
||||
#[inline]
|
||||
pub fn validate(&self) -> Result<(), BsonStreamError> {
|
||||
if self.chunk_capacity_bytes == 0 {
|
||||
return Err(BsonStreamError::InvalidChunkCapacity);
|
||||
}
|
||||
if self.max_doc_bytes < MIN_BSON_DOC_BYTES {
|
||||
return Err(BsonStreamError::InvalidMaxDocBytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Terminal errors returned by [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
|
||||
///
|
||||
/// Every stream-level framing or I/O error carries the absolute byte `offset` of the offending
|
||||
/// document in the underlying stream.
|
||||
#[derive(Debug)]
|
||||
pub enum BsonStreamError {
|
||||
/// `BsonStreamOptions::chunk_capacity_bytes` was `0`.
|
||||
InvalidChunkCapacity,
|
||||
/// `BsonStreamOptions::max_doc_bytes` was `< 5`.
|
||||
InvalidMaxDocBytes,
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` or `> max_doc_bytes`.
|
||||
CorruptDocumentLength {
|
||||
offset: u64,
|
||||
declared_len: i32,
|
||||
max_doc_bytes: usize,
|
||||
},
|
||||
/// Stream reached EOF mid-header (`declared_len == None`) or mid-document (`Some(len)`).
|
||||
TruncatedDocument {
|
||||
offset: u64,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Underlying [`std::io::Read`] failed with a non-`Interrupted` error.
|
||||
Io { offset: u64, source: io::Error },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonStreamError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidChunkCapacity => {
|
||||
write!(f, "invalid BSON stream chunk_capacity_bytes: must be > 0")
|
||||
}
|
||||
Self::InvalidMaxDocBytes => {
|
||||
write!(
|
||||
f,
|
||||
"invalid BSON stream max_doc_bytes: must be >= {MIN_BSON_DOC_BYTES}"
|
||||
)
|
||||
}
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
max_doc_bytes,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at stream offset {offset} (valid range: {MIN_BSON_DOC_BYTES}..={max_doc_bytes})"
|
||||
),
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at stream offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at stream offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::Io { offset, source } => {
|
||||
write!(
|
||||
f,
|
||||
"I/O error reading BSON stream at offset {offset}: {source}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonStreamError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Io { source, .. } => Some(source),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed chunk of complete, length-prefixed raw BSON documents from [`RawBsonChunkReader`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RawBsonChunk<'a> {
|
||||
/// Contiguous bytes containing one or more complete length-prefixed BSON documents.
|
||||
pub bytes: &'a [u8],
|
||||
/// Absolute byte offset of `bytes[0]` from the start of the underlying stream.
|
||||
pub start_offset: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum StickyError {
|
||||
CorruptDocumentLength {
|
||||
offset: u64,
|
||||
declared_len: i32,
|
||||
max_doc_bytes: usize,
|
||||
},
|
||||
TruncatedDocument {
|
||||
offset: u64,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
Io {
|
||||
offset: u64,
|
||||
kind: io::ErrorKind,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl StickyError {
|
||||
fn to_error(&self) -> BsonStreamError {
|
||||
match self {
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
max_doc_bytes,
|
||||
} => BsonStreamError::CorruptDocumentLength {
|
||||
offset: *offset,
|
||||
declared_len: *declared_len,
|
||||
max_doc_bytes: *max_doc_bytes,
|
||||
},
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonStreamError::TruncatedDocument {
|
||||
offset: *offset,
|
||||
remaining: *remaining,
|
||||
declared_len: *declared_len,
|
||||
},
|
||||
Self::Io {
|
||||
offset,
|
||||
kind,
|
||||
message,
|
||||
} => BsonStreamError::Io {
|
||||
offset: *offset,
|
||||
source: io::Error::new(*kind, message.clone()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TerminalState {
|
||||
Active,
|
||||
Eof,
|
||||
Failed(StickyError),
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_i32_le(bytes: &[u8]) -> i32 {
|
||||
i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
/// Bounded-memory chunked reader for concatenated length-prefixed raw BSON documents.
|
||||
///
|
||||
/// Reuses a single internal byte buffer across all calls to [`Self::next_chunk`], carrying any
|
||||
/// trailing partial document to the front of the buffer before the next fill. The initial
|
||||
/// allocation is capped at `min(options.chunk_capacity_bytes, options.max_doc_bytes)`; the buffer
|
||||
/// grows only when a single document exceeds the current buffer length (or to 4 bytes when
|
||||
/// `chunk_capacity_bytes < 4`), and never beyond `options.max_doc_bytes`.
|
||||
pub struct RawBsonChunkReader<R: io::Read> {
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
buf: Vec<u8>,
|
||||
filled: usize,
|
||||
consumed: usize,
|
||||
buf_start_offset: u64,
|
||||
bytes_read: u64,
|
||||
docs_framed: u64,
|
||||
eof_reached: bool,
|
||||
pending_io_err: Option<io::Error>,
|
||||
terminal: TerminalState,
|
||||
}
|
||||
|
||||
impl<R: io::Read> RawBsonChunkReader<R> {
|
||||
/// Creates a new chunk reader with [`BsonStreamOptions::default`].
|
||||
pub fn new(reader: R) -> Self {
|
||||
let options = BsonStreamOptions::default();
|
||||
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
|
||||
Self {
|
||||
reader,
|
||||
options,
|
||||
buf: vec![0u8; initial_cap],
|
||||
filled: 0,
|
||||
consumed: 0,
|
||||
buf_start_offset: 0,
|
||||
bytes_read: 0,
|
||||
docs_framed: 0,
|
||||
eof_reached: false,
|
||||
pending_io_err: None,
|
||||
terminal: TerminalState::Active,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new chunk reader with explicit [`BsonStreamOptions`], validating them up front.
|
||||
pub fn with_options(reader: R, options: BsonStreamOptions) -> Result<Self, BsonStreamError> {
|
||||
options.validate()?;
|
||||
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
|
||||
Ok(Self {
|
||||
reader,
|
||||
options,
|
||||
buf: vec![0u8; initial_cap],
|
||||
filled: 0,
|
||||
consumed: 0,
|
||||
buf_start_offset: 0,
|
||||
bytes_read: 0,
|
||||
docs_framed: 0,
|
||||
eof_reached: false,
|
||||
pending_io_err: None,
|
||||
terminal: TerminalState::Active,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the configured stream options.
|
||||
#[inline]
|
||||
pub fn options(&self) -> BsonStreamOptions {
|
||||
self.options
|
||||
}
|
||||
|
||||
/// Returns the current allocated capacity of the reusable internal buffer in bytes.
|
||||
#[inline]
|
||||
pub fn buffer_capacity(&self) -> usize {
|
||||
self.buf.capacity()
|
||||
}
|
||||
|
||||
/// Returns the total number of bytes read from the underlying reader so far.
|
||||
#[inline]
|
||||
pub fn bytes_read(&self) -> u64 {
|
||||
self.bytes_read
|
||||
}
|
||||
|
||||
/// Returns the total number of complete length-prefixed documents framed and yielded so far.
|
||||
#[inline]
|
||||
pub fn docs_framed(&self) -> u64 {
|
||||
self.docs_framed
|
||||
}
|
||||
|
||||
/// Consumes the chunk reader, returning the underlying [`std::io::Read`] source.
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> R {
|
||||
self.reader
|
||||
}
|
||||
|
||||
/// Grows `self.buf` to exactly `target_len` without doubling past `max_doc_bytes`.
|
||||
fn grow_buf_exact(&mut self, target_len: usize) {
|
||||
debug_assert!(target_len <= self.options.max_doc_bytes);
|
||||
if target_len > self.buf.len() {
|
||||
if target_len > self.buf.capacity() {
|
||||
self.buf.reserve_exact(target_len - self.buf.len());
|
||||
}
|
||||
self.buf.resize(target_len, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and frames the next chunk of complete length-prefixed BSON documents.
|
||||
///
|
||||
/// Returns `Ok(None)` at clean EOF. Any terminal framing or I/O error locks the reader into a
|
||||
/// failed state so subsequent calls continue returning an error without panicking or looping.
|
||||
pub fn next_chunk(&mut self) -> Result<Option<RawBsonChunk<'_>>, BsonStreamError> {
|
||||
match &self.terminal {
|
||||
TerminalState::Active => {}
|
||||
TerminalState::Eof => return Ok(None),
|
||||
TerminalState::Failed(err) => return Err(err.to_error()),
|
||||
}
|
||||
|
||||
// Compact bytes already yielded by the previous chunk.
|
||||
if self.consumed > 0 {
|
||||
if self.consumed < self.filled {
|
||||
self.buf.copy_within(self.consumed..self.filled, 0);
|
||||
}
|
||||
self.filled -= self.consumed;
|
||||
self.buf_start_offset += self.consumed as u64;
|
||||
self.consumed = 0;
|
||||
}
|
||||
|
||||
let mut chunk_end = 0usize;
|
||||
let mut chunk_docs = 0u64;
|
||||
loop {
|
||||
// Incrementally frame complete documents as bytes arrive so a corrupt length prefix
|
||||
// stops the fill loop immediately without issuing further reads.
|
||||
let mut saw_corrupt_len = false;
|
||||
while self.filled - chunk_end >= 4 {
|
||||
let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]);
|
||||
if declared_len < MIN_BSON_DOC_BYTES as i32
|
||||
|| (declared_len as usize) > self.options.max_doc_bytes
|
||||
{
|
||||
if chunk_end == 0 {
|
||||
let err = StickyError::CorruptDocumentLength {
|
||||
offset: self.buf_start_offset,
|
||||
declared_len,
|
||||
max_doc_bytes: self.options.max_doc_bytes,
|
||||
};
|
||||
self.terminal = TerminalState::Failed(err.clone());
|
||||
return Err(err.to_error());
|
||||
}
|
||||
// Yield any complete preceding documents first; the next call will compact
|
||||
// this corrupt header to index 0 and surface `CorruptDocumentLength`.
|
||||
saw_corrupt_len = true;
|
||||
break;
|
||||
}
|
||||
let doc_len = declared_len as usize;
|
||||
if chunk_end == 0
|
||||
&& doc_len > self.buf.len()
|
||||
&& !self.eof_reached
|
||||
&& self.pending_io_err.is_none()
|
||||
{
|
||||
self.grow_buf_exact(doc_len);
|
||||
}
|
||||
if doc_len > self.filled - chunk_end {
|
||||
break;
|
||||
}
|
||||
chunk_end += doc_len;
|
||||
chunk_docs += 1;
|
||||
}
|
||||
|
||||
if saw_corrupt_len || self.eof_reached || self.pending_io_err.is_some() {
|
||||
break;
|
||||
}
|
||||
|
||||
if self.filled == self.buf.len() {
|
||||
if self.filled < 4 {
|
||||
// `chunk_capacity_bytes` was in `1..=3`; grow to 4 bytes (always <= max_doc_bytes).
|
||||
self.grow_buf_exact(4);
|
||||
} else {
|
||||
// Buffer is full and the leading document fit in `self.buf.len()`, so at least
|
||||
// one complete document is ready to yield.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
match self.reader.read(&mut self.buf[self.filled..]) {
|
||||
Ok(0) => {
|
||||
self.eof_reached = true;
|
||||
break;
|
||||
}
|
||||
Ok(n) => {
|
||||
self.filled += n;
|
||||
self.bytes_read += n as u64;
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => {
|
||||
self.pending_io_err = Some(err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if chunk_end > 0 {
|
||||
self.consumed = chunk_end;
|
||||
self.docs_framed += chunk_docs;
|
||||
return Ok(Some(RawBsonChunk {
|
||||
bytes: &self.buf[..chunk_end],
|
||||
start_offset: self.buf_start_offset,
|
||||
}));
|
||||
}
|
||||
|
||||
// No complete document could be framed; surface pending I/O error, clean EOF, or truncation.
|
||||
if let Some(source) = self.pending_io_err.take() {
|
||||
let offset = self.buf_start_offset;
|
||||
self.terminal = TerminalState::Failed(StickyError::Io {
|
||||
offset,
|
||||
kind: source.kind(),
|
||||
message: source.to_string(),
|
||||
});
|
||||
return Err(BsonStreamError::Io { offset, source });
|
||||
}
|
||||
|
||||
if self.filled == 0 {
|
||||
self.terminal = TerminalState::Eof;
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let declared_len = if self.filled >= 4 {
|
||||
Some(read_i32_le(&self.buf[0..4]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let err = StickyError::TruncatedDocument {
|
||||
offset: self.buf_start_offset,
|
||||
remaining: self.filled,
|
||||
declared_len,
|
||||
};
|
||||
self.terminal = TerminalState::Failed(err.clone());
|
||||
Err(err.to_error())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_offset(base: u64, local: usize) -> usize {
|
||||
let abs = base.saturating_add(local as u64);
|
||||
usize::try_from(abs).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_eod_error(base: u64, err: BsonEodPriceError) -> BsonEodPriceError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonEodPriceError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => BsonEodPriceError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError {
|
||||
match err {
|
||||
BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmActionError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonQmActionError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmActionError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonQmActionError::CorruptBson { offset, detail } => BsonQmActionError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`],
|
||||
/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream
|
||||
/// byte offsets.
|
||||
pub fn decode_eod_price_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonEodDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawEodDailyBar<'a>),
|
||||
E: FnMut(u64, BsonEodPriceError),
|
||||
{
|
||||
let mut total = BsonEodDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_eod_price_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_bar,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_eod_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `eodPrices` [`std::io::Read`] source through
|
||||
/// [`decode_eod_price_buffer`] with bounded memory.
|
||||
///
|
||||
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
|
||||
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
|
||||
pub fn decode_eod_price_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_bar: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonEodDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawEodDailyBar<'a>),
|
||||
E: FnMut(u64, BsonEodPriceError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_eod_price_chunks(&mut chunk_reader, on_bar, on_error)
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_split_buffer`],
|
||||
/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute
|
||||
/// stream byte offsets.
|
||||
pub fn decode_qm_split_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_split: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut total = BsonQmActionDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_qm_split_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_split,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_qm_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `qmSplits` [`std::io::Read`] source through
|
||||
/// [`decode_qm_split_buffer`] with bounded memory.
|
||||
pub fn decode_qm_split_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_split: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_qm_split_chunks(&mut chunk_reader, on_split, on_error)
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_dividend_buffer`],
|
||||
/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute
|
||||
/// stream byte offsets.
|
||||
pub fn decode_qm_dividend_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_dividend: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut total = BsonQmActionDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_qm_dividend_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_dividend,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_qm_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `qmDividends` [`std::io::Read`] source through
|
||||
/// [`decode_qm_dividend_buffer`] with bounded memory.
|
||||
pub fn decode_qm_dividend_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_dividend: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_stream_tests.rs"]
|
||||
mod tests;
|
||||
1724
tools/curate-etl/src/bson_stream_tests.rs
Normal file
1724
tools/curate-etl/src/bson_stream_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -5,10 +5,11 @@
|
|||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_EVENTS_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS,
|
||||
DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
|
|
@ -35,10 +36,13 @@ pub enum CliAction {
|
|||
BenchParquetAdj(usize),
|
||||
BenchParquetCorporateActions(usize),
|
||||
BenchBsonEodPrices(usize),
|
||||
BenchBsonQmActions(usize),
|
||||
BenchBsonStream(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
BenchCurateEvents(usize),
|
||||
BenchCurateFx(usize),
|
||||
BenchCurateAdj(usize),
|
||||
BenchCurateCorporateActions(usize),
|
||||
}
|
||||
|
||||
|
|
@ -65,10 +69,13 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\
|
||||
{name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
|
||||
{name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})"
|
||||
)
|
||||
}
|
||||
|
|
@ -94,10 +101,13 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-parquet-adj [rows]\n\
|
||||
{name} bench-parquet-corporate-actions [rows]\n\
|
||||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-bson-qm-actions [rows]\n\
|
||||
{name} bench-bson-stream [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]\n\
|
||||
{name} bench-curate-events [rows]\n\
|
||||
{name} bench-curate-fx [rows]\n\
|
||||
{name} bench-curate-adj [events]\n\
|
||||
{name} bench-curate-corporate-actions [events]"
|
||||
)
|
||||
}
|
||||
|
|
@ -263,6 +273,28 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-bson-eod-prices", _, ..] => {
|
||||
Err("too many arguments for bench-bson-eod-prices".to_string())
|
||||
}
|
||||
["bench-bson-qm-actions"] => Ok(CliAction::BenchBsonQmActions(
|
||||
DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
)),
|
||||
["bench-bson-qm-actions", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBsonQmActions(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bson-qm-actions", _, ..] => {
|
||||
Err("too many arguments for bench-bson-qm-actions".to_string())
|
||||
}
|
||||
["bench-bson-stream"] => Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS)),
|
||||
["bench-bson-stream", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBsonStream(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bson-stream", _, ..] => {
|
||||
Err("too many arguments for bench-bson-stream".to_string())
|
||||
}
|
||||
["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)),
|
||||
["bench-curate-bars", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)),
|
||||
|
|
@ -305,6 +337,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()),
|
||||
["bench-curate-adj"] => Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)),
|
||||
["bench-curate-adj", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdj(n)),
|
||||
_ => Err(format!(
|
||||
"invalid event count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-adj", _, ..] => Err("too many arguments for bench-curate-adj".to_string()),
|
||||
["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions(
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
)),
|
||||
|
|
@ -604,6 +644,40 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bson_qm_actions_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-qm-actions"])),
|
||||
Ok(CliAction::BenchBsonQmActions(
|
||||
DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-qm-actions", "250000"])),
|
||||
Ok(CliAction::BenchBsonQmActions(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bson_stream_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-stream"])),
|
||||
Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-stream", "250000"])),
|
||||
Ok(CliAction::BenchBsonStream(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -622,10 +696,13 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-adj"));
|
||||
assert!(full.contains("bench-parquet-corporate-actions"));
|
||||
assert!(full.contains("bench-bson-eod-prices"));
|
||||
assert!(full.contains("bench-bson-qm-actions"));
|
||||
assert!(full.contains("bench-bson-stream"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
assert!(full.contains("bench-curate-events"));
|
||||
assert!(full.contains("bench-curate-fx"));
|
||||
assert!(full.contains("bench-curate-adj"));
|
||||
assert!(full.contains("bench-curate-corporate-actions"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
|
|
@ -644,10 +721,13 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-adj"));
|
||||
assert!(short.contains("bench-parquet-corporate-actions"));
|
||||
assert!(short.contains("bench-bson-eod-prices"));
|
||||
assert!(short.contains("bench-bson-qm-actions"));
|
||||
assert!(short.contains("bench-bson-stream"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
assert!(short.contains("bench-curate-events"));
|
||||
assert!(short.contains("bench-curate-fx"));
|
||||
assert!(short.contains("bench-curate-adj"));
|
||||
assert!(short.contains("bench-curate-corporate-actions"));
|
||||
}
|
||||
|
||||
|
|
@ -719,6 +799,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_adj_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-adj"])),
|
||||
Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-adj", "100000"])),
|
||||
Ok(CliAction::BenchCurateAdj(100_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_corporate_actions_args() {
|
||||
assert_eq!(
|
||||
|
|
|
|||
1944
tools/curate-etl/src/curate_adj.rs
Normal file
1944
tools/curate-etl/src/curate_adj.rs
Normal file
File diff suppressed because it is too large
Load diff
2312
tools/curate-etl/src/curate_adj_tests.rs
Normal file
2312
tools/curate-etl/src/curate_adj_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -4,6 +4,8 @@ pub mod adj;
|
|||
pub mod bars;
|
||||
pub mod bench;
|
||||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod bson_stream;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
|
|
@ -32,6 +34,18 @@ pub use bson_eod_prices::{
|
|||
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
|
||||
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
|
||||
};
|
||||
pub use bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc,
|
||||
decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, BsonQmActionDecodeStats,
|
||||
BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH,
|
||||
FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
|
||||
};
|
||||
pub use bson_stream::{
|
||||
decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks,
|
||||
decode_qm_dividend_stream, decode_qm_split_chunks, decode_qm_split_stream, BsonStreamError,
|
||||
BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
pub use corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow,
|
||||
CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent,
|
||||
|
|
@ -122,6 +136,15 @@ pub use curate_fx::{
|
|||
FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START,
|
||||
};
|
||||
|
||||
pub mod curate_adj;
|
||||
pub use curate_adj::{
|
||||
adj_factors_for_bar, curate_adj_factors, curate_adj_factors_as_of,
|
||||
curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, read_adj_factors_dataset,
|
||||
read_adj_factors_dataset_as_of, AdjFactorsSnapshot, AdjPointInTimeFence, AdjSnapshotKind,
|
||||
CurateAdjError, CurateAdjFactorsOutput, CurateAdjFactorsStats, CurateAdjFactorsWriteReport,
|
||||
CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION,
|
||||
};
|
||||
|
||||
pub mod curate_corporate_actions;
|
||||
pub use curate_corporate_actions::{
|
||||
curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError,
|
||||
|
|
|
|||
|
|
@ -5,12 +5,13 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_corporate_actions_benchmark, run_curate_events_benchmark, run_curate_fx_benchmark,
|
||||
run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark,
|
||||
run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark,
|
||||
run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark,
|
||||
run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
|
||||
run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_bars_benchmark, run_curate_corporate_actions_benchmark,
|
||||
run_curate_events_benchmark, run_curate_fx_benchmark, run_curate_shorts_benchmark,
|
||||
run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -504,6 +505,82 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonQmActions(rows)) => {
|
||||
let report = run_bson_qm_actions_benchmark(rows);
|
||||
println!("curate-etl bench-bson-qm-actions");
|
||||
println!(
|
||||
" input: rows={} splits={} dividends={} bytes={}",
|
||||
report.rows, report.split_rows, report.dividend_rows, report.bytes
|
||||
);
|
||||
println!(
|
||||
" splits: decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.split_stats.decoded,
|
||||
report.split_stats.split_noop_ratio_one,
|
||||
report.split_stats.rejected_total(),
|
||||
report.split_stats.rejected_missing_field,
|
||||
report.split_stats.rejected_empty_field,
|
||||
report.split_stats.rejected_wrong_type,
|
||||
report.split_stats.rejected_malformed_date,
|
||||
report.split_stats.rejected_invalid_number,
|
||||
report.split_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" dividends: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.dividend_stats.decoded,
|
||||
report.dividend_stats.rejected_total(),
|
||||
report.dividend_stats.rejected_missing_field,
|
||||
report.dividend_stats.rejected_empty_field,
|
||||
report.dividend_stats.rejected_wrong_type,
|
||||
report.dividend_stats.rejected_malformed_date,
|
||||
report.dividend_stats.rejected_invalid_number,
|
||||
report.dividend_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s latency={:.2} ns/doc checksum=0x{:016x}",
|
||||
report.elapsed_ms,
|
||||
report.docs_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.ns_per_doc,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonStream(rows)) => {
|
||||
let report = match run_bson_stream_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: bson-stream benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-bson-stream");
|
||||
println!(" input: rows={} bytes={}", report.rows, report.bytes);
|
||||
println!(
|
||||
" decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}",
|
||||
report.stats.decoded,
|
||||
report.stats.rejected_total(),
|
||||
report.stats.rejected_missing_field,
|
||||
report.stats.rejected_empty_field,
|
||||
report.stats.rejected_wrong_type,
|
||||
report.stats.rejected_malformed_date,
|
||||
report.stats.rejected_invalid_number,
|
||||
report.stats.rejected_corrupt_document,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" buffer: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s",
|
||||
report.buffer_elapsed_ms, report.buffer_rows_per_sec, report.buffer_mib_per_sec
|
||||
);
|
||||
println!(
|
||||
" stream: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s ratio={:.3}x peak_buffer_capacity={} bytes",
|
||||
report.stream_elapsed_ms,
|
||||
report.stream_rows_per_sec,
|
||||
report.stream_mib_per_sec,
|
||||
report.stream_to_buffer_ratio,
|
||||
report.peak_buffer_capacity
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBars(rows)) => {
|
||||
let report = match run_curate_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -759,6 +836,67 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateAdj(events)) => {
|
||||
let report = match run_curate_adj_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-adj benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-adj");
|
||||
println!(
|
||||
" input: events={} splits={} dividends={} keys={}",
|
||||
report.events, report.splits_in, report.dividends_in, report.key_count
|
||||
);
|
||||
println!(
|
||||
" builder: rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}",
|
||||
report.stats.builder.rows_out,
|
||||
report.stats.builder.keys_out,
|
||||
report.stats.builder.split_noops_dropped,
|
||||
report.stats.builder.dividend_zero_cash_dropped,
|
||||
report.stats.builder.dividends_missing_prev_close,
|
||||
report.stats.builder.dividends_currency_mismatch,
|
||||
report.stats.builder.dividends_not_below_prev_close
|
||||
);
|
||||
println!(
|
||||
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.stage_elapsed_ms,
|
||||
report.stage_events_per_sec,
|
||||
report.stage_ns_per_event,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows,
|
||||
report.parquet_elapsed_ms,
|
||||
report.parquet_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s",
|
||||
report.total_elapsed_ms, report.total_events_per_sec
|
||||
);
|
||||
println!(
|
||||
" curate: splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}",
|
||||
report.stats.splits_dropped_unmapped,
|
||||
report.stats.dividends_dropped_unmapped,
|
||||
report.stats.splits_collision_collapsed,
|
||||
report.stats.dividends_collision_collapsed,
|
||||
report.stats.listing_collision_collapsed
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateCorporateActions(events)) => {
|
||||
let report = match run_curate_corporate_actions_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
205
tools/curate-etl/tests/bson_qm_actions_contract.rs
Normal file
205
tools/curate-etl/tests/bson_qm_actions_contract.rs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
//! Public-API integration contract test for `qmSplits` and `qmDividends` raw BSON decoders (`M1.2w`).
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::{
|
||||
build_corporate_actions, curate_adj_factors, decode_qm_dividend_buffer,
|
||||
decode_qm_dividend_bytes, decode_qm_dividend_doc, decode_qm_split_buffer,
|
||||
decode_qm_split_bytes, decode_qm_split_doc, ymd_to_epoch_days, BsonQmActionError,
|
||||
CorporateActionKind, KnownAtSource, ProviderMappingRow, ProviderMappingTable, SplitTable,
|
||||
FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE,
|
||||
FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
|
||||
};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_field_constants_and_single_doc_decoders_match_contract() {
|
||||
assert_eq!(FIELD_QM_SEARCH_CODE, "qmSearchCode");
|
||||
assert_eq!(FIELD_DATE, "date");
|
||||
assert_eq!(FIELD_DECLARED, "declared");
|
||||
assert_eq!(FIELD_SPLIT_RATIO, "splitratio");
|
||||
assert_eq!(FIELD_USD_FX_RATE, "usdFxRate");
|
||||
assert_eq!(FIELD_DIVIDEND_CASH, "amount");
|
||||
assert_eq!(FIELD_DIVIDEND_CURRENCY, "currency");
|
||||
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("splitratio"), 10_i32);
|
||||
split_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio, 10.0);
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * 86_400_000),
|
||||
);
|
||||
div_doc.append(cstr!("declared"), RawBsonRef::Null);
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash, 1.42);
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_buffer_decoders_reconcile_and_feed_all_downstream_builders() {
|
||||
let mut split_buf = Vec::new();
|
||||
|
||||
let mut s_nvda = RawDocumentBuf::new();
|
||||
s_nvda.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_nvda.append(cstr!("date"), "2024-06-10");
|
||||
s_nvda.append(cstr!("declared"), "2024-05-22");
|
||||
s_nvda.append(cstr!("splitratio"), 10.0_f64);
|
||||
split_buf.extend_from_slice(s_nvda.as_bytes());
|
||||
|
||||
let mut s_noop = RawDocumentBuf::new();
|
||||
s_noop.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_noop.append(cstr!("date"), "2024-07-01");
|
||||
s_noop.append(cstr!("splitratio"), 1_i64);
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
|
||||
let mut s_bad = RawDocumentBuf::new();
|
||||
s_bad.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_bad.append(cstr!("date"), "2024-07-02");
|
||||
s_bad.append(cstr!("splitratio"), -3.0_f64);
|
||||
split_buf.extend_from_slice(s_bad.as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
|
||||
let mut d_ry = RawDocumentBuf::new();
|
||||
d_ry.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_ry.append(cstr!("date"), "2024-11-15");
|
||||
d_ry.append(cstr!("declared"), "2024-10-30");
|
||||
d_ry.append(cstr!("amount"), 1.42_f64);
|
||||
d_ry.append(cstr!("currency"), "CAD");
|
||||
d_ry.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_buf.extend_from_slice(d_ry.as_bytes());
|
||||
|
||||
let mut d_bad = RawDocumentBuf::new();
|
||||
d_bad.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_bad.append(cstr!("date"), "2023-02-29");
|
||||
d_bad.append(cstr!("amount"), 1.0_f64);
|
||||
d_bad.append(cstr!("currency"), "CAD");
|
||||
div_buf.extend_from_slice(d_bad.as_bytes());
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut split_events = Vec::new();
|
||||
let mut split_actions = Vec::new();
|
||||
let mut split_errs = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
split_events.push((s.qm_search_code.to_owned(), s.to_split_event()));
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| split_errs.push(err),
|
||||
);
|
||||
|
||||
assert_eq!(split_stats.docs_in, 3);
|
||||
assert_eq!(split_stats.decoded, 2);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
assert!(matches!(
|
||||
split_errs.as_slice(),
|
||||
[BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}]
|
||||
));
|
||||
|
||||
let mut div_events = Vec::new();
|
||||
let mut div_actions = Vec::new();
|
||||
let mut div_errs = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
div_events.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| div_errs.push(err),
|
||||
);
|
||||
|
||||
assert_eq!(div_stats.docs_in, 2);
|
||||
assert_eq!(div_stats.decoded, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
assert!(matches!(
|
||||
div_errs.as_slice(),
|
||||
[BsonQmActionError::MalformedDate { field: FIELD_DATE }]
|
||||
));
|
||||
|
||||
// Feed SplitTable.
|
||||
let split_table = SplitTable::from_events(split_events.iter().cloned()).unwrap();
|
||||
assert_eq!(split_table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
|
||||
// Feed curate_adj_factors.
|
||||
let adj = curate_adj_factors(&mapping, "qm", split_events, div_events).unwrap();
|
||||
assert_eq!(adj.rows.len(), 2);
|
||||
assert_eq!(adj.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(adj.rows[0].listing_id, 101);
|
||||
assert_eq!(adj.rows[0].split_factor, 10.0);
|
||||
assert_eq!(adj.rows[1].listing_id, 303);
|
||||
assert_eq!(adj.rows[1].div_cash, 1.42);
|
||||
assert_eq!(adj.rows[1].div_currency.as_deref(), Some("CAD"));
|
||||
|
||||
// Feed build_corporate_actions.
|
||||
let ca = build_corporate_actions(split_actions, div_actions, std::iter::empty()).unwrap();
|
||||
assert_eq!(ca.rows.len(), 2);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
520
tools/curate-etl/tests/bson_qm_actions_qa_contract.rs
Normal file
520
tools/curate-etl/tests/bson_qm_actions_qa_contract.rs
Normal file
|
|
@ -0,0 +1,520 @@
|
|||
//! QA contract tests for the public `qmSplits` / `qmDividends` raw BSON decoders (T-107 / M1.2w).
|
||||
//!
|
||||
//! Covers gaps left by `src/bson_qm_actions_tests.rs` and `tests/bson_qm_actions_contract.rs`,
|
||||
//! using only the public API:
|
||||
//! - zero-copy: `qm_search_code` / `currency` borrow from the input buffer;
|
||||
//! - field-order independence, case-sensitive keys, nested look-alike keys ignored;
|
||||
//! - `usdFxRate` / unknown fields with corrupt payloads are skipped without decoding, while the
|
||||
//! same corruption inside a known field is a typed `CorruptBson` naming that field;
|
||||
//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch);
|
||||
//! - `split_noop_ratio_one` counts exactly `1.0`, not near-one ratios;
|
||||
//! - error callbacks receive the exact byte offset of the rejected document; empty buffer,
|
||||
//! truncated tail after good docs, `i32::MAX` declared length;
|
||||
//! - seeded byte-mutation fuzz for both collections: never panics, always reconciles, and every
|
||||
//! streamed row equals the single-document decode of the same bytes;
|
||||
//! - benchmark guard: synthetic docs actually decode (rejections stay near the injected ~0.5%),
|
||||
//! so a field-constant change cannot silently turn the benchmark into a rejection-path timing;
|
||||
//! - `bench-bson-qm-actions` binary: identical checksum across two runs, invalid args exit 1.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::bench::run_bson_qm_actions_benchmark;
|
||||
use curate_etl::{
|
||||
decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc,
|
||||
decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, iter_raw_bson_docs,
|
||||
ymd_to_epoch_days, BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DIVIDEND_CASH,
|
||||
FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO,
|
||||
};
|
||||
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn split_doc(code: &str, date: &str, ratio: f64) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), "ignored");
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc
|
||||
}
|
||||
|
||||
fn dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), "ignored");
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("declared"), "2024-05-01");
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc
|
||||
}
|
||||
|
||||
fn ptr_within(s: &str, buf: &[u8]) -> bool {
|
||||
let range = buf.as_ptr_range();
|
||||
let p = s.as_ptr();
|
||||
range.contains(&p) && (p as usize + s.len()) <= range.end as usize
|
||||
}
|
||||
|
||||
/// Overwrites the first occurrence of `needle` in `bytes` with `replacement` (same length).
|
||||
fn patch(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) {
|
||||
assert_eq!(needle.len(), replacement.len());
|
||||
let pos = bytes
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
.expect("needle present");
|
||||
bytes[pos..pos + needle.len()].copy_from_slice(replacement);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_strings_borrow_directly_from_the_input_buffer() {
|
||||
let s = split_doc("NVDA", "2024-06-10", 10.0);
|
||||
let split = decode_qm_split_bytes(s.as_bytes()).unwrap();
|
||||
assert!(ptr_within(split.qm_search_code, s.as_bytes()));
|
||||
|
||||
let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(d.as_bytes());
|
||||
let mut seen = Vec::new();
|
||||
decode_qm_dividend_buffer(&buf, |div| seen.push(div), |_, e| panic!("{e}"));
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert!(ptr_within(seen[0].qm_search_code, &buf));
|
||||
assert!(ptr_within(seen[0].currency, &buf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_order_is_irrelevant_keys_are_case_sensitive_and_nested_lookalikes_are_ignored() {
|
||||
// Reverse field order decodes identically.
|
||||
let mut rev = RawDocumentBuf::new();
|
||||
rev.append(cstr!("usdFxRate"), 1.0_f64);
|
||||
rev.append(cstr!("currency"), "CAD");
|
||||
rev.append(cstr!("amount"), 1.42_f64);
|
||||
rev.append(cstr!("declared"), "2024-05-01");
|
||||
rev.append(cstr!("date"), "2024-11-15");
|
||||
rev.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
let fwd = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&rev).unwrap(),
|
||||
decode_qm_dividend_doc(&fwd).unwrap()
|
||||
);
|
||||
|
||||
// Differently-cased keys are unknown fields, so the required field is missing.
|
||||
let mut cased = RawDocumentBuf::new();
|
||||
cased.append(cstr!("QmSearchCode"), "NVDA");
|
||||
cased.append(cstr!("date"), "2024-06-10");
|
||||
cased.append(cstr!("splitratio"), 10.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_split_doc(&cased).unwrap_err(),
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
let mut cased_ratio = RawDocumentBuf::new();
|
||||
cased_ratio.append(cstr!("qmSearchCode"), "NVDA");
|
||||
cased_ratio.append(cstr!("date"), "2024-06-10");
|
||||
cased_ratio.append(cstr!("splitRatio"), 10.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_split_doc(&cased_ratio).unwrap_err(),
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
|
||||
// A nested sub-document carrying look-alike keys must neither satisfy nor poison the decode.
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("splitratio"), -99.0_f64);
|
||||
nested.append(cstr!("amount"), "bad");
|
||||
nested.append(cstr!("currency"), 7_i32);
|
||||
nested.append(cstr!("date"), "not-a-date");
|
||||
let mut outer = split_doc("NVDA", "2024-06-10", 10.0);
|
||||
outer.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref()));
|
||||
let split = decode_qm_split_doc(&outer).unwrap();
|
||||
assert_eq!(split.ratio, 10.0);
|
||||
|
||||
let mut outer_div = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
outer_div.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref()));
|
||||
let div = decode_qm_dividend_doc(&outer_div).unwrap();
|
||||
assert_eq!((div.cash, div.currency), (1.42, "CAD"));
|
||||
|
||||
let mut only_nested = RawDocumentBuf::new();
|
||||
only_nested.append(cstr!("qmSearchCode"), "NVDA");
|
||||
only_nested.append(cstr!("date"), "2024-06-10");
|
||||
only_nested.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref()));
|
||||
assert_eq!(
|
||||
decode_qm_split_doc(&only_nested).unwrap_err(),
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_payload_in_ignored_field_is_skipped_but_in_known_field_names_that_field() {
|
||||
// Unknown field / `usdFxRate` with invalid UTF-8 string bytes: framing is valid, payload is
|
||||
// never decoded.
|
||||
let mut d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
d.append(cstr!("zzExtra"), "XYZW");
|
||||
let mut bytes = d.as_bytes().to_vec();
|
||||
patch(&mut bytes, b"XYZW", &[0xFF, 0xFE, 0xFD, 0xFC]);
|
||||
let div = decode_qm_dividend_bytes(&bytes).unwrap();
|
||||
assert_eq!(div.currency, "CAD");
|
||||
|
||||
let mut s = split_doc("NVDA", "2024-06-10", 10.0);
|
||||
s.append(cstr!("usdFxRate"), "QQQQ");
|
||||
let mut bytes = s.as_bytes().to_vec();
|
||||
patch(&mut bytes, b"QQQQ", &[0xC3, 0x28, 0xA0, 0xA1]);
|
||||
assert_eq!(decode_qm_split_bytes(&bytes).unwrap().ratio, 10.0);
|
||||
|
||||
// Same corruption inside `currency` is a typed CorruptBson naming the field (no panic).
|
||||
let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "QQQ");
|
||||
let mut bytes = d.as_bytes().to_vec();
|
||||
patch(&mut bytes, b"QQQ", &[0xFF, 0xFE, 0xFD]);
|
||||
match decode_qm_dividend_bytes(&bytes).unwrap_err() {
|
||||
BsonQmActionError::CorruptBson { offset, detail } => {
|
||||
assert_eq!(offset, 0);
|
||||
assert!(detail.contains(FIELD_DIVIDEND_CURRENCY), "{detail}");
|
||||
}
|
||||
other => panic!("expected CorruptBson, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datetime_dates_floor_to_utc_day_at_boundaries() {
|
||||
let cases = [
|
||||
(-1_i64, -1_i32),
|
||||
(0, 0),
|
||||
(-MILLIS_PER_DAY, -1),
|
||||
(-MILLIS_PER_DAY - 1, -2),
|
||||
(
|
||||
i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1,
|
||||
day(2024, 6, 10),
|
||||
),
|
||||
(
|
||||
i64::from(day(2024, 6, 11)) * MILLIS_PER_DAY,
|
||||
day(2024, 6, 11),
|
||||
),
|
||||
];
|
||||
for (ms, expected) in cases {
|
||||
let mut s = RawDocumentBuf::new();
|
||||
s.append(cstr!("qmSearchCode"), "IBM");
|
||||
s.append(cstr!("date"), DateTime::from_millis(ms));
|
||||
s.append(cstr!("declared"), DateTime::from_millis(ms));
|
||||
s.append(cstr!("splitratio"), 2_i64);
|
||||
let split = decode_qm_split_doc(&s).unwrap();
|
||||
assert_eq!(split.ex_date, expected, "ms={ms}");
|
||||
assert_eq!(split.declared_date, Some(expected), "ms={ms}");
|
||||
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("qmSearchCode"), "IBM");
|
||||
d.append(cstr!("date"), DateTime::from_millis(ms));
|
||||
d.append(cstr!("amount"), 1_i32);
|
||||
d.append(cstr!("currency"), "USD");
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&d).unwrap().ex_date,
|
||||
expected,
|
||||
"ms={ms}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_counter_counts_only_exact_ratio_one() {
|
||||
let mut buf = Vec::new();
|
||||
for ratio in [1.0, 1.000_000_000_1, 0.999_999_999_9, 1.0, 2.0] {
|
||||
buf.extend_from_slice(split_doc("X", "2024-03-15", ratio).as_bytes());
|
||||
}
|
||||
let mut n = 0;
|
||||
let stats = decode_qm_split_buffer(&buf, |_| n += 1, |_, e| panic!("{e}"));
|
||||
assert_eq!(n, 5);
|
||||
assert_eq!(stats.decoded, 5);
|
||||
assert_eq!(stats.split_noop_ratio_one, 2);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
|
||||
// Dividends never touch the split no-op counter.
|
||||
let d = dividend_doc("X", "2024-03-15", 1.0, "USD");
|
||||
let stats = decode_qm_dividend_buffer(d.as_bytes(), |_| {}, |_, e| panic!("{e}"));
|
||||
assert_eq!(stats.split_noop_ratio_one, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_callbacks_report_exact_offsets_and_framing_failures_stop_cleanly() {
|
||||
// Empty buffer: nothing in, nothing out.
|
||||
let stats = decode_qm_split_buffer(&[], |_| panic!(), |_, _| panic!());
|
||||
assert_eq!(stats, Default::default());
|
||||
let stats = decode_qm_dividend_buffer(&[], |_| panic!(), |_, _| panic!());
|
||||
assert_eq!(stats, Default::default());
|
||||
|
||||
let good = dividend_doc("A", "2024-06-10", 0.5, "USD");
|
||||
let bad_cash = dividend_doc("B", "2024-06-10", -0.5, "USD");
|
||||
let bad_date = dividend_doc("C", "2024-13-01", 0.5, "USD");
|
||||
let mut buf = Vec::new();
|
||||
let mut expected_err_offsets = Vec::new();
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
expected_err_offsets.push(buf.len());
|
||||
buf.extend_from_slice(bad_cash.as_bytes());
|
||||
expected_err_offsets.push(buf.len());
|
||||
buf.extend_from_slice(bad_date.as_bytes());
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
// Truncated tail: declares a full doc but only half is present.
|
||||
expected_err_offsets.push(buf.len());
|
||||
let tail_start = buf.len();
|
||||
buf.extend_from_slice(&good.as_bytes()[..good.as_bytes().len() / 2]);
|
||||
|
||||
let mut errs = Vec::new();
|
||||
let mut codes = Vec::new();
|
||||
let stats = decode_qm_dividend_buffer(
|
||||
&buf,
|
||||
|d: RawQmDividend<'_>| codes.push(d.qm_search_code),
|
||||
|off, e| errs.push((off, e)),
|
||||
);
|
||||
assert_eq!(codes, vec!["A", "A"]);
|
||||
assert_eq!(
|
||||
errs.iter().map(|(o, _)| *o).collect::<Vec<_>>(),
|
||||
expected_err_offsets
|
||||
);
|
||||
assert!(matches!(
|
||||
errs[0].1,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
errs[2].1,
|
||||
BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
} if offset == tail_start
|
||||
));
|
||||
assert_eq!(stats.docs_in, 5);
|
||||
assert_eq!(stats.decoded, 2);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
|
||||
// i32::MAX declared length after a good split doc terminates without panicking.
|
||||
let mut buf = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec();
|
||||
let bad_at = buf.len();
|
||||
buf.extend_from_slice(&i32::MAX.to_le_bytes());
|
||||
buf.extend_from_slice(&[0u8; 8]);
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_qm_split_buffer(&buf, |_| {}, |off, e| errs.push((off, e)));
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.decoded, 1);
|
||||
assert_eq!(errs.len(), 1);
|
||||
assert_eq!(errs[0].0, bad_at);
|
||||
assert!(matches!(
|
||||
errs[0].1,
|
||||
BsonQmActionError::TruncatedDocument { .. }
|
||||
));
|
||||
|
||||
// Single-doc decoder: trailing bytes are rejected as a length mismatch, not silently ignored.
|
||||
let mut trailing = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec();
|
||||
trailing.push(0);
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&trailing).unwrap_err(),
|
||||
BsonQmActionError::CorruptDocumentLength { .. }
|
||||
));
|
||||
}
|
||||
|
||||
/// `std`-only SplitMix64 so the fuzz corpus is fixed across runs.
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
fn mutate(rng: &mut SplitMix64, base: &[u8]) -> Vec<u8> {
|
||||
let mut buf = base.to_vec();
|
||||
let flips = 1 + (rng.next() % 4) as usize;
|
||||
for _ in 0..flips {
|
||||
let pos = (rng.next() as usize) % buf.len();
|
||||
buf[pos] = rng.next() as u8;
|
||||
}
|
||||
if rng.next() % 4 == 0 {
|
||||
let cut = (rng.next() as usize) % buf.len();
|
||||
buf.truncate(cut);
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
fn framed_slices(buf: &[u8]) -> Vec<(usize, usize)> {
|
||||
let mut out = Vec::new();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
if let Ok((off, doc)) = item {
|
||||
out.push((off, doc.as_bytes().len()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles_for_both_collections() {
|
||||
let mut split_base = Vec::new();
|
||||
let mut div_base = Vec::new();
|
||||
for i in 0..8 {
|
||||
let code = format!("Q{i}:CA");
|
||||
split_base.extend_from_slice(split_doc(&code, "2024-06-07", 1.0 + i as f64).as_bytes());
|
||||
div_base
|
||||
.extend_from_slice(dividend_doc(&code, "2024-06-07", 0.1 * i as f64, "CAD").as_bytes());
|
||||
}
|
||||
|
||||
let split_key = |s: &RawQmSplit<'_>| {
|
||||
(
|
||||
s.qm_search_code.to_string(),
|
||||
s.ex_date,
|
||||
s.ratio.to_bits(),
|
||||
s.declared_date,
|
||||
)
|
||||
};
|
||||
let div_key = |d: &RawQmDividend<'_>| {
|
||||
(
|
||||
d.qm_search_code.to_string(),
|
||||
d.ex_date,
|
||||
d.cash.to_bits(),
|
||||
d.currency.to_string(),
|
||||
d.declared_date,
|
||||
)
|
||||
};
|
||||
|
||||
let mut rng = SplitMix64(0x0B50_7E57_0A11_0107);
|
||||
for _ in 0..2_000 {
|
||||
let buf = mutate(&mut rng, &split_base);
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_qm_split_buffer(&buf, |s| rows.push(s), |_, _| {});
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(stats.decoded, rows.len());
|
||||
assert_eq!(
|
||||
stats.split_noop_ratio_one,
|
||||
rows.iter().filter(|s| s.ratio == 1.0).count()
|
||||
);
|
||||
let expected: Vec<_> = framed_slices(&buf)
|
||||
.into_iter()
|
||||
.filter_map(|(o, l)| decode_qm_split_bytes(&buf[o..o + l]).ok())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows.iter().map(split_key).collect::<Vec<_>>(),
|
||||
expected.iter().map(split_key).collect::<Vec<_>>()
|
||||
);
|
||||
for s in &rows {
|
||||
assert!(s.ratio.is_finite() && s.ratio > 0.0);
|
||||
assert!(!s.qm_search_code.trim().is_empty());
|
||||
}
|
||||
|
||||
let buf = mutate(&mut rng, &div_base);
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_qm_dividend_buffer(&buf, |d| rows.push(d), |_, _| {});
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(stats.decoded, rows.len());
|
||||
assert_eq!(stats.split_noop_ratio_one, 0);
|
||||
let expected: Vec<_> = framed_slices(&buf)
|
||||
.into_iter()
|
||||
.filter_map(|(o, l)| decode_qm_dividend_bytes(&buf[o..o + l]).ok())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows.iter().map(div_key).collect::<Vec<_>>(),
|
||||
expected.iter().map(div_key).collect::<Vec<_>>()
|
||||
);
|
||||
for d in &rows {
|
||||
assert!(d.cash.is_finite() && d.cash >= 0.0 && !d.cash.is_sign_negative());
|
||||
assert!(!d.currency.trim().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn benchmark_corpus_mostly_decodes_so_it_times_the_happy_path() {
|
||||
let report = run_bson_qm_actions_benchmark(20_000);
|
||||
let s = report.split_stats;
|
||||
let d = report.dividend_stats;
|
||||
assert_eq!(s.docs_in + d.docs_in, 20_000);
|
||||
// Injected errors are ~0.5% per collection; allow generous headroom but fail if a renamed
|
||||
// field constant makes the corpus reject en masse.
|
||||
assert!(
|
||||
s.rejected_total() * 50 < s.docs_in,
|
||||
"split rejections too high: {s:?}"
|
||||
);
|
||||
assert!(
|
||||
d.rejected_total() * 50 < d.docs_in,
|
||||
"dividend rejections too high: {d:?}"
|
||||
);
|
||||
assert_eq!(s.rejected_corrupt_document + d.rejected_corrupt_document, 0);
|
||||
}
|
||||
|
||||
fn run_bin(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("spawn curate-etl binary")
|
||||
}
|
||||
|
||||
fn stable_output(out: &Output) -> String {
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let checksum = text
|
||||
.split_whitespace()
|
||||
.find(|t| t.starts_with("checksum=0x"))
|
||||
.unwrap_or_else(|| panic!("no checksum in output: {text}"));
|
||||
let stats: Vec<&str> = text
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.filter(|l| {
|
||||
l.starts_with("input:") || l.starts_with("splits:") || l.starts_with("dividends:")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(stats.len(), 3, "missing stats lines: {text}");
|
||||
format!("{checksum} {}", stats.join(" | "))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_binary_prints_identical_checksum_and_stats_across_runs() {
|
||||
let a = run_bin(&["bench-bson-qm-actions", "5000"]);
|
||||
let b = run_bin(&["bench-bson-qm-actions", "5000"]);
|
||||
assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr));
|
||||
assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr));
|
||||
|
||||
let text = String::from_utf8_lossy(&a.stdout);
|
||||
assert!(text.contains("rows=5000"), "{text}");
|
||||
for needle in [
|
||||
"elapsed=",
|
||||
"docs/s",
|
||||
"MB/s",
|
||||
"noop_ratio_one=",
|
||||
"checksum=0x",
|
||||
] {
|
||||
assert!(text.contains(needle), "missing {needle}: {text}");
|
||||
}
|
||||
assert_eq!(stable_output(&a), stable_output(&b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_binary_rejects_invalid_row_counts_and_is_listed_in_usage() {
|
||||
for args in [
|
||||
&["bench-bson-qm-actions", "0"][..],
|
||||
&["bench-bson-qm-actions", "-5"][..],
|
||||
&["bench-bson-qm-actions", "abc"][..],
|
||||
&["bench-bson-qm-actions", "10", "20"][..],
|
||||
] {
|
||||
let out = run_bin(args);
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}");
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(err.contains("error:"), "{args:?}: {err}");
|
||||
assert!(out.stdout.is_empty(), "{args:?} wrote to stdout");
|
||||
}
|
||||
|
||||
let out = run_bin(&["--help"]);
|
||||
assert!(out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("bench-bson-qm-actions"));
|
||||
}
|
||||
273
tools/curate-etl/tests/bson_stream_qa_contract.rs
Normal file
273
tools/curate-etl/tests/bson_stream_qa_contract.rs
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
//! QA contract tests for the public `bson_stream` API (T-109 / M1.2y).
|
||||
//!
|
||||
//! Covers gaps left by `src/bson_stream_tests.rs`, using only the public crate API:
|
||||
//! - seeded byte-mutation fuzz: for every mutated `eodPrices` stream the streamed decode never
|
||||
//! panics, yields exactly the buffer decoder's rows and per-document errors in order, and a
|
||||
//! buffer framing error maps to a stream `Err` at the same absolute offset;
|
||||
//! - `RawBsonChunkReader::new` (default options) frames a multi-document stream end to end;
|
||||
//! - `decode_*_chunks` resumed on a reader that already failed returns the sticky error at once;
|
||||
//! - `BsonStreamError` `Display` names the offset and `source()` exposes the original I/O error;
|
||||
//! - `bench-bson-stream` binary: completes on a small row count with a ratio and peak buffer
|
||||
//! line, identical checksum across two runs, invalid args exit non-zero.
|
||||
|
||||
use std::error::Error as _;
|
||||
use std::io::{self, Cursor, Read};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use curate_etl::{
|
||||
decode_eod_price_buffer, decode_eod_price_chunks, decode_eod_price_stream,
|
||||
decode_qm_split_chunks, BsonEodPriceError, BsonStreamError, BsonStreamOptions,
|
||||
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
};
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reader returning seeded pseudo-random short reads of 1..=97 bytes.
|
||||
struct JitterReader<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl Read for JitterReader<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let remaining = self.data.len() - self.pos;
|
||||
if remaining == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let step = (self.rng.next_u64() % 97) as usize + 1;
|
||||
let take = remaining.min(step).min(buf.len());
|
||||
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
|
||||
self.pos += take;
|
||||
Ok(take)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reader that yields its data once and then fails every subsequent read.
|
||||
struct FailAfterData {
|
||||
data: Vec<u8>,
|
||||
pos: usize,
|
||||
reads_after_fail: usize,
|
||||
}
|
||||
|
||||
impl Read for FailAfterData {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.pos == self.data.len() {
|
||||
self.reads_after_fail += 1;
|
||||
return Err(io::Error::new(io::ErrorKind::ConnectionReset, "cursor dropped"));
|
||||
}
|
||||
let take = (self.data.len() - self.pos).min(buf.len());
|
||||
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
|
||||
self.pos += take;
|
||||
Ok(take)
|
||||
}
|
||||
}
|
||||
|
||||
fn eod_doc(code: &str, day: u32, close: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), format!("2024-06-{day:02}"));
|
||||
doc.append(cstr!("open"), close - 0.5);
|
||||
doc.append(cstr!("high"), close + 1.0);
|
||||
doc.append(cstr!("low"), close - 1.0);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), 1_000_i64 + day as i64);
|
||||
doc.append(cstr!("exchange"), "TSX");
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn eod_fixture(count: usize) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for i in 0..count {
|
||||
out.extend_from_slice(&eod_doc(&format!("Q{i:03}.TO"), 1 + (i % 28) as u32, 10.0 + i as f64));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
type Row = (String, i32, u64, u64);
|
||||
|
||||
fn buffer_decode(bytes: &[u8]) -> (Vec<Row>, Vec<(u64, String)>) {
|
||||
let mut rows = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
decode_eod_price_buffer(
|
||||
bytes,
|
||||
|b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())),
|
||||
|off, e| errs.push((off as u64, format!("{e:?}"))),
|
||||
);
|
||||
(rows, errs)
|
||||
}
|
||||
|
||||
fn is_framing_error(debug: &str) -> bool {
|
||||
debug.starts_with("CorruptDocumentLength") || debug.starts_with("TruncatedDocument")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_mutation_fuzz_stream_matches_buffer_rows_errors_and_framing_offset() {
|
||||
let clean = eod_fixture(24);
|
||||
let mut rng = SplitMix64(0x5EED_B50E);
|
||||
let mut framing_cases = 0usize;
|
||||
let mut ok_cases = 0usize;
|
||||
|
||||
for case in 0..400u64 {
|
||||
let mut bytes = clean.clone();
|
||||
let flips = 1 + (rng.next_u64() % 4) as usize;
|
||||
for _ in 0..flips {
|
||||
let idx = (rng.next_u64() as usize) % bytes.len();
|
||||
bytes[idx] = rng.next_u64() as u8;
|
||||
}
|
||||
if rng.next_u64() % 5 == 0 {
|
||||
let cut = (rng.next_u64() as usize) % bytes.len();
|
||||
bytes.truncate(cut);
|
||||
}
|
||||
|
||||
let (exp_rows, mut exp_errs) = buffer_decode(&bytes);
|
||||
let exp_framing = match exp_errs.last() {
|
||||
Some((off, dbg)) if is_framing_error(dbg) => {
|
||||
let off = *off;
|
||||
exp_errs.pop();
|
||||
Some(off)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let cap = [1usize, 4, 37, 256, 4096][(case % 5) as usize];
|
||||
let mut rows = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let result = decode_eod_price_stream(
|
||||
JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) },
|
||||
BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 },
|
||||
|b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())),
|
||||
|off, e: BsonEodPriceError| errs.push((off, format!("{e:?}"))),
|
||||
);
|
||||
|
||||
assert_eq!(rows, exp_rows, "case={case} cap={cap}: rows diverge");
|
||||
assert_eq!(errs, exp_errs, "case={case} cap={cap}: per-doc errors diverge");
|
||||
match (exp_framing, result) {
|
||||
(None, Ok(stats)) => {
|
||||
ok_cases += 1;
|
||||
assert_eq!(stats.decoded, exp_rows.len(), "case={case}");
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in, "case={case}");
|
||||
}
|
||||
(Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. }))
|
||||
| (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => {
|
||||
framing_cases += 1;
|
||||
assert_eq!(offset, off, "case={case} cap={cap}: framing offset");
|
||||
}
|
||||
(exp, got) => panic!("case={case} cap={cap}: expected framing={exp:?}, got {got:?}"),
|
||||
}
|
||||
}
|
||||
// The sweep must exercise both outcomes, or it proves nothing.
|
||||
assert!(framing_cases >= 20, "framing_cases={framing_cases}");
|
||||
assert!(ok_cases >= 20, "ok_cases={ok_cases}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_reader_frames_whole_stream_with_default_capacity() {
|
||||
let input = eod_fixture(50);
|
||||
let mut reader = RawBsonChunkReader::new(JitterReader { data: &input, pos: 0, rng: SplitMix64(7) });
|
||||
let mut joined = Vec::new();
|
||||
while let Some(chunk) = reader.next_chunk().expect("valid stream") {
|
||||
assert_eq!(chunk.start_offset, joined.len() as u64);
|
||||
joined.extend_from_slice(chunk.bytes);
|
||||
}
|
||||
assert_eq!(joined, input);
|
||||
assert_eq!(reader.docs_framed(), 50);
|
||||
assert_eq!(reader.bytes_read(), input.len() as u64);
|
||||
assert_eq!(reader.buffer_capacity(), DEFAULT_CHUNK_CAPACITY_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_helpers_on_failed_reader_return_sticky_error_without_rereading() {
|
||||
let input = eod_fixture(3);
|
||||
let len = input.len() as u64;
|
||||
let mut reader = RawBsonChunkReader::with_options(
|
||||
FailAfterData { data: input, pos: 0, reads_after_fail: 0 },
|
||||
BsonStreamOptions { chunk_capacity_bytes: 64, max_doc_bytes: 4096 },
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut bars = 0usize;
|
||||
let err = decode_eod_price_chunks(&mut reader, |_| bars += 1, |_, _| panic!("no per-doc errors"))
|
||||
.expect_err("I/O failure must surface");
|
||||
assert_eq!(bars, 3, "all complete docs delivered before the I/O error");
|
||||
let BsonStreamError::Io { offset, ref source } = err else { panic!("expected Io, got {err:?}") };
|
||||
assert_eq!(offset, len);
|
||||
assert_eq!(source.kind(), io::ErrorKind::ConnectionReset);
|
||||
|
||||
// A different helper resumed on the same failed reader must fail immediately.
|
||||
let again = decode_qm_split_chunks(&mut reader, |_| panic!("no rows"), |_, _| panic!("no errors"))
|
||||
.expect_err("sticky error");
|
||||
assert!(matches!(again, BsonStreamError::Io { offset, .. } if offset == len));
|
||||
assert_eq!(reader.into_inner().reads_after_fail, 1, "source read exactly once after data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_display_names_offset_and_io_source_is_exposed() {
|
||||
let mut bytes = eod_doc("A.TO", 3, 5.0);
|
||||
let first_len = bytes.len();
|
||||
bytes.extend_from_slice(&2_i32.to_le_bytes());
|
||||
let err = decode_eod_price_stream(Cursor::new(bytes), BsonStreamOptions::default(), |_| {}, |_, _| {})
|
||||
.expect_err("corrupt length");
|
||||
assert!(err.source().is_none());
|
||||
let text = err.to_string();
|
||||
assert!(text.contains(&format!("offset {first_len}")), "{text}");
|
||||
assert!(text.contains("length 2"), "{text}");
|
||||
|
||||
let io_err = decode_eod_price_stream(
|
||||
FailAfterData { data: Vec::new(), pos: 0, reads_after_fail: 0 },
|
||||
BsonStreamOptions::default(),
|
||||
|_| {},
|
||||
|_, _| {},
|
||||
)
|
||||
.expect_err("io");
|
||||
let src = io_err.source().expect("Io exposes source");
|
||||
assert!(src.to_string().contains("cursor dropped"), "{src}");
|
||||
assert!(io_err.to_string().contains("offset 0"), "{io_err}");
|
||||
|
||||
assert!(BsonStreamError::InvalidChunkCapacity.to_string().contains("chunk_capacity_bytes"));
|
||||
assert!(BsonStreamError::InvalidMaxDocBytes.to_string().contains("max_doc_bytes"));
|
||||
}
|
||||
|
||||
fn run_bin(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("spawn curate-etl binary")
|
||||
}
|
||||
|
||||
fn checksum_of(out: &Output) -> String {
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.split_whitespace()
|
||||
.find(|t| t.starts_with("checksum=0x"))
|
||||
.unwrap_or_else(|| panic!("no checksum in output: {text}"))
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_bson_stream_binary_is_deterministic_and_rejects_bad_args() {
|
||||
let a = run_bin(&["bench-bson-stream", "5000"]);
|
||||
let b = run_bin(&["bench-bson-stream", "5000"]);
|
||||
assert!(a.status.success(), "stderr: {}", String::from_utf8_lossy(&a.stderr));
|
||||
assert!(b.status.success());
|
||||
assert_eq!(checksum_of(&a), checksum_of(&b));
|
||||
let text = String::from_utf8_lossy(&a.stdout).to_lowercase();
|
||||
assert!(text.contains("rows=5000"), "{text}");
|
||||
assert!(text.contains("ratio"), "{text}");
|
||||
assert!(text.contains("peak_buffer_capacity"), "{text}");
|
||||
|
||||
for bad in [&["bench-bson-stream", "abc"][..], &["bench-bson-stream", "1", "2"][..]] {
|
||||
let out = run_bin(bad);
|
||||
assert!(!out.status.success(), "args {bad:?} must fail");
|
||||
}
|
||||
}
|
||||
418
tools/curate-etl/tests/curate_adj_qa_contract.rs
Normal file
418
tools/curate-etl/tests/curate_adj_qa_contract.rs
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
//! QA contract tests for the public `adj_factors` curation stage (T-106 / M1.2v).
|
||||
//!
|
||||
//! Complements the in-crate `curate_adj_tests.rs` with checks against independent references
|
||||
//! built only from the public API:
|
||||
//! - seeded differential test: per-bar split factors across ticker renames, ticker reuse and
|
||||
//! unmapped gaps equal a naive per-listing product of later split ratios;
|
||||
//! - fenced publish → separate reopen equals the naive reference over only the events whose
|
||||
//! conservative `16:00 ET` known_at is `<= as_of`, and every reopened row honours the fence;
|
||||
//! - re-publishing a smaller fenced snapshot over a larger retrospective one leaves exactly one
|
||||
//! `part.parquet` whose footer carries the `stock_bot.adj_factors.*` keys and contract schema;
|
||||
//! - `bench-curate-adj` binary run: checksum/bytes/rows pinned to the README values, temp dir
|
||||
//! cleaned.
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::fs::{self, File};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use curate_etl::{
|
||||
adj_factors_for_bar, adj_factors_parquet_schema, curate_adj_factors,
|
||||
curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, et_session_close_utc_micros,
|
||||
read_adj_factors_dataset, read_adj_factors_dataset_as_of, ymd_to_epoch_days,
|
||||
AdjFactorsWriteOptions, AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError,
|
||||
DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent,
|
||||
};
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-etl-curate-adj-qa-{tag}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn map_row(key: &str, from: i32, to: Option<i32>, listing_id: i32) -> ProviderMappingRow {
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.to_string(),
|
||||
valid_from: from,
|
||||
valid_to: to,
|
||||
listing_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exactly representable ratios so the naive product is order-independent.
|
||||
const RATIOS: [f64; 6] = [2.0, 0.5, 4.0, 0.25, 3.0, 1.0];
|
||||
|
||||
struct Fixture {
|
||||
mapping: ProviderMappingTable,
|
||||
splits: Vec<(String, SplitEvent)>,
|
||||
/// Naive reference: listing_id -> (ex_date -> ratio) for every mapped split (incl. 1:1).
|
||||
reference: BTreeMap<i32, BTreeMap<i32, f64>>,
|
||||
min: i32,
|
||||
max: i32,
|
||||
}
|
||||
|
||||
/// Layout per listing group `g` (deterministic):
|
||||
/// - listing `3g+1`: single key `S{g}` for the whole span;
|
||||
/// - listing `3g+2`: key `OLD{g}` until 2012-12-31, renamed to `NEW{g}` from 2013-01-01;
|
||||
/// - key `RE{g}` maps to listing `3g+3` until 2015-06-30, unmapped through 2015, then to listing
|
||||
/// `100_000 + g` from 2016-01-01 (ticker reuse with a gap).
|
||||
fn seeded_fixture(seed: u64, groups: i32, events: usize) -> Fixture {
|
||||
let min = day(2000, 1, 1);
|
||||
let max = day(2025, 12, 31);
|
||||
let rename = day(2012, 12, 31);
|
||||
let reuse_old_end = day(2015, 6, 30);
|
||||
let reuse_new_start = day(2016, 1, 1);
|
||||
|
||||
let mut rows = Vec::new();
|
||||
for g in 0..groups {
|
||||
rows.push(map_row(&format!("S{g}"), min, None, 3 * g + 1));
|
||||
rows.push(map_row(&format!("OLD{g}"), min, Some(rename), 3 * g + 2));
|
||||
rows.push(map_row(&format!("NEW{g}"), rename + 1, None, 3 * g + 2));
|
||||
rows.push(map_row(
|
||||
&format!("RE{g}"),
|
||||
min,
|
||||
Some(reuse_old_end),
|
||||
3 * g + 3,
|
||||
));
|
||||
rows.push(map_row(
|
||||
&format!("RE{g}"),
|
||||
reuse_new_start,
|
||||
None,
|
||||
100_000 + g,
|
||||
));
|
||||
}
|
||||
let mapping = ProviderMappingTable::from_rows(rows).expect("valid mapping");
|
||||
|
||||
let mut rng = SplitMix64(seed);
|
||||
let mut seen: HashSet<(String, i32)> = HashSet::new();
|
||||
let mut splits = Vec::new();
|
||||
let mut reference: BTreeMap<i32, BTreeMap<i32, f64>> = BTreeMap::new();
|
||||
while splits.len() < events {
|
||||
let g = rng.below(groups as u64) as i32;
|
||||
let ex_date = min + rng.below((max - min + 1) as u64) as i32;
|
||||
let (key, listing) = match rng.below(4) {
|
||||
0 => (format!("S{g}"), Some(3 * g + 1)),
|
||||
1 if ex_date <= rename => (format!("OLD{g}"), Some(3 * g + 2)),
|
||||
1 => (format!("NEW{g}"), Some(3 * g + 2)),
|
||||
2 if ex_date <= reuse_old_end => (format!("RE{g}"), Some(3 * g + 3)),
|
||||
2 if ex_date < reuse_new_start => (format!("RE{g}"), None),
|
||||
2 => (format!("RE{g}"), Some(100_000 + g)),
|
||||
_ => (format!("UNMAPPED{g}"), None),
|
||||
};
|
||||
// One event per (key, ex_date): same-key same-day multiplication is the builder's own
|
||||
// contract and is covered in-crate.
|
||||
if !seen.insert((key.clone(), ex_date)) {
|
||||
continue;
|
||||
}
|
||||
let ratio = RATIOS[rng.below(RATIOS.len() as u64) as usize];
|
||||
if let Some(listing_id) = listing {
|
||||
reference
|
||||
.entry(listing_id)
|
||||
.or_default()
|
||||
.insert(ex_date, ratio);
|
||||
}
|
||||
splits.push((key, SplitEvent { ex_date, ratio }));
|
||||
}
|
||||
Fixture {
|
||||
mapping,
|
||||
splits,
|
||||
reference,
|
||||
min,
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
/// Product of every reference split ratio with `ex_date > bar_date` for `listing_id`.
|
||||
fn naive_factor(
|
||||
reference: &BTreeMap<i32, BTreeMap<i32, f64>>,
|
||||
listing_id: i32,
|
||||
bar_date: i32,
|
||||
admit: impl Fn(i32) -> bool,
|
||||
) -> f64 {
|
||||
reference.get(&listing_id).map_or(1.0, |events| {
|
||||
events
|
||||
.range(bar_date + 1..)
|
||||
.filter(|(ex, _)| admit(**ex))
|
||||
.map(|(_, r)| *r)
|
||||
.product()
|
||||
})
|
||||
}
|
||||
|
||||
const NO_DIVIDENDS: [(String, DividendEvent); 0] = [];
|
||||
|
||||
#[test]
|
||||
fn seeded_split_factors_match_naive_per_listing_reference_across_rename_reuse_and_gaps() {
|
||||
let fx = seeded_fixture(0xAD0A_115E_ED00, 40, 3_000);
|
||||
let out =
|
||||
curate_adj_factors(&fx.mapping, "qm", fx.splits.clone(), NO_DIVIDENDS).expect("curate");
|
||||
|
||||
assert_eq!(out.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot);
|
||||
let mapped: usize = fx.reference.values().map(BTreeMap::len).sum();
|
||||
assert_eq!(out.stats.splits_in, fx.splits.len());
|
||||
assert_eq!(
|
||||
out.stats.splits_dropped_unmapped,
|
||||
fx.splits.len() - mapped,
|
||||
"unmapped count must equal events with no covering range"
|
||||
);
|
||||
assert_eq!(out.stats.splits_collision_collapsed, 0);
|
||||
assert_eq!(out.stats.builder.split_events_in, mapped);
|
||||
let noops = fx
|
||||
.reference
|
||||
.values()
|
||||
.flat_map(BTreeMap::values)
|
||||
.filter(|r| **r == 1.0)
|
||||
.count();
|
||||
assert_eq!(out.stats.builder.split_noops_dropped, noops);
|
||||
assert_eq!(out.stats.rows_out, mapped - noops);
|
||||
assert!(out.stats.splits_dropped_unmapped > 0 && noops > 0);
|
||||
|
||||
let mut rng = SplitMix64(0x0B5E_55ED);
|
||||
let listings: Vec<i32> = fx.reference.keys().copied().collect();
|
||||
for _ in 0..5_000 {
|
||||
let listing_id = listings[rng.below(listings.len() as u64) as usize];
|
||||
let bar = fx.min - 5 + rng.below((fx.max - fx.min + 10) as u64) as i32;
|
||||
let expected = naive_factor(&fx.reference, listing_id, bar, |_| true);
|
||||
let (split, _total) = adj_factors_for_bar(&out.rows, listing_id, bar);
|
||||
assert_eq!(
|
||||
split.to_bits(),
|
||||
expected.to_bits(),
|
||||
"listing {listing_id} bar {bar}: got {split}, expected {expected}"
|
||||
);
|
||||
}
|
||||
// Unknown listing never picks up another listing's chain.
|
||||
assert_eq!(adj_factors_for_bar(&out.rows, 99_999, fx.min), (1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_publish_then_separate_reopen_matches_naive_filtered_reference() {
|
||||
let fx = seeded_fixture(0xFE11_CE00, 25, 2_000);
|
||||
let tmp = TempDir::new("fenced-reopen");
|
||||
// As of 2018-03-14 12:00 UTC: an ex-date of 2018-03-14 (close 20:00 UTC) is still unknown.
|
||||
let as_of = et_session_close_utc_micros(day(2018, 3, 14)).unwrap() - 8 * 3_600_000_000;
|
||||
let fence = AdjPointInTimeFence::as_of(as_of);
|
||||
|
||||
let report = curate_and_write_adj_factors_as_of(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
fence,
|
||||
AdjFactorsWriteOptions {
|
||||
row_group_rows: 11,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("fenced publish");
|
||||
assert_eq!(
|
||||
report.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert!(report.curate_stats.splits_dropped_fenced > 0);
|
||||
|
||||
// Separate read step: only the published artifact is consulted.
|
||||
let snap = read_adj_factors_dataset_as_of(&tmp.0, fence).expect("reopen");
|
||||
assert_eq!(
|
||||
snap.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert_eq!(snap.rows.len(), report.write_stats.rows_written);
|
||||
for row in &snap.rows {
|
||||
assert!(row.known_at_micros <= as_of, "row beyond as_of: {row:?}");
|
||||
}
|
||||
for w in snap.rows.windows(2) {
|
||||
assert!((w[0].listing_id, w[0].ex_date) < (w[1].listing_id, w[1].ex_date));
|
||||
}
|
||||
|
||||
let admitted = |ex: i32| et_session_close_utc_micros(ex).unwrap() <= as_of;
|
||||
let mut rng = SplitMix64(0xA5_0F);
|
||||
let listings: Vec<i32> = fx.reference.keys().copied().collect();
|
||||
for _ in 0..3_000 {
|
||||
let listing_id = listings[rng.below(listings.len() as u64) as usize];
|
||||
let bar = fx.min + rng.below((day(2018, 3, 14) - fx.min) as u64) as i32;
|
||||
let expected = naive_factor(&fx.reference, listing_id, bar, admitted);
|
||||
let (split, _) = snap.factors_for_bar(listing_id, bar);
|
||||
assert_eq!(
|
||||
split.to_bits(),
|
||||
expected.to_bits(),
|
||||
"listing {listing_id} bar {bar} as_of {as_of}"
|
||||
);
|
||||
}
|
||||
|
||||
// A neighbouring fence one microsecond later is a different artifact and must be refused.
|
||||
let other = AdjPointInTimeFence::as_of(as_of + 1);
|
||||
assert!(matches!(
|
||||
read_adj_factors_dataset_as_of(&tmp.0, other),
|
||||
Err(CurateAdjReadError::IncompatibleFence { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smaller_fenced_republish_supersedes_larger_retrospective_snapshot_in_one_file() {
|
||||
let fx = seeded_fixture(0x5_0BE5, 30, 2_500);
|
||||
let tmp = TempDir::new("republish");
|
||||
|
||||
let retro = curate_and_write_adj_factors(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.expect("retrospective publish");
|
||||
let fence = AdjPointInTimeFence::as_of_with_vault_cutoff(
|
||||
et_session_close_utc_micros(day(2024, 6, 28)).unwrap(),
|
||||
et_session_close_utc_micros(day(2005, 1, 3)).unwrap(),
|
||||
);
|
||||
assert!(matches!(
|
||||
read_adj_factors_dataset_as_of(&tmp.0, fence),
|
||||
Err(CurateAdjReadError::RetrospectiveSnapshotRejected { .. })
|
||||
));
|
||||
|
||||
let fenced = curate_and_write_adj_factors_as_of(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
fence,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.expect("fenced publish");
|
||||
assert!(fenced.write_stats.rows_written < retro.write_stats.rows_written);
|
||||
|
||||
let names: Vec<String> = fs::read_dir(tmp.0.join("adj_factors"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["part.parquet".to_string()]);
|
||||
|
||||
// Vault cutoff wins over the later as_of: every row is strictly before the vault boundary.
|
||||
let snap = read_adj_factors_dataset(&tmp.0).expect("reopen");
|
||||
assert_eq!(
|
||||
snap.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert_eq!(snap.rows.len(), fenced.write_stats.rows_written);
|
||||
let vault = fence.vault_cutoff_micros.unwrap();
|
||||
assert!(snap.rows.iter().all(|r| r.known_at_micros < vault));
|
||||
|
||||
// A generic Parquet reader sees the contract schema and the bound footer keys.
|
||||
let path = tmp.0.join("adj_factors").join("part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
let file_meta = reader.metadata().file_metadata();
|
||||
assert_eq!(
|
||||
file_meta.schema(),
|
||||
adj_factors_parquet_schema().unwrap().as_ref()
|
||||
);
|
||||
assert_eq!(file_meta.num_rows() as usize, snap.rows.len());
|
||||
let kv: BTreeMap<String, Option<String>> = file_meta
|
||||
.key_value_metadata()
|
||||
.expect("footer key_value_metadata")
|
||||
.iter()
|
||||
.map(|kv| (kv.key.clone(), kv.value.clone()))
|
||||
.filter(|(k, _)| k.starts_with("stock_bot.adj_factors."))
|
||||
.collect();
|
||||
let get = |k: &str| kv[&format!("stock_bot.adj_factors.{k}")].as_deref();
|
||||
assert_eq!(kv.len(), 6, "{kv:?}");
|
||||
assert_eq!(get("format_version"), Some("1"));
|
||||
assert_eq!(get("snapshot_kind"), Some("point_in_time_fenced"));
|
||||
assert_eq!(
|
||||
get("as_of_micros"),
|
||||
Some(fence.as_of_micros.unwrap().to_string().as_str())
|
||||
);
|
||||
assert_eq!(get("vault_cutoff_micros"), Some(vault.to_string().as_str()));
|
||||
assert_eq!(
|
||||
get("rows_written"),
|
||||
Some(snap.rows.len().to_string().as_str())
|
||||
);
|
||||
}
|
||||
|
||||
fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
|
||||
text.split_whitespace()
|
||||
.find(|t| t.starts_with(prefix))
|
||||
.map(|t| &t[prefix.len()..])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_adj_default_run_matches_readme_values_and_cleans_temp_dir() {
|
||||
let tmp = TempDir::new("bench-tmpdir");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.arg("bench-curate-adj")
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("run curate-etl");
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
// Values recorded in tools/curate-etl/README.md (`bench-curate-adj`, default 1,000,000).
|
||||
assert_eq!(field(&stdout, "events="), Some("1000000"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "splits="), Some("40221"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "dividends="), Some("959779"), "{stdout}");
|
||||
assert_eq!(
|
||||
field(&stdout, "checksum="),
|
||||
Some("0x024ec73a1afe7e6b"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert_eq!(field(&stdout, "bytes="), Some("11872037"), "{stdout}");
|
||||
assert_eq!(
|
||||
field(&stdout, "read_back_rows="),
|
||||
Some("946414"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert_eq!(field(&stdout, "rows_out="), Some("946414"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "coll_collapsed="), Some("4930"), "{stdout}");
|
||||
|
||||
let leftovers: Vec<_> = fs::read_dir(&tmp.0)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert!(
|
||||
leftovers.is_empty(),
|
||||
"bench left temp entries: {leftovers:?}"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue