stock-bot/tools/curate-etl/README.md

1729 lines
211 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# `curate-etl`
Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) 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`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`).
## Scope & Sign Conventions
Aligned with `design/DATA-CONTRACTS.md` (§1 `qmSplits`, `eodPrices`, `eodIntraday1M`):
- **Split ratio**: `ratio = new_shares / old_shares`.
- Forward split `10:1` (e.g., NVDA on `2024-06-10`) → `ratio = 10.0`.
- Reverse split `1:20` (e.g., NEXM.V on `2025-06-18`) → `ratio = 0.05`.
- No-op rows (`ratio == 1.0`) are dropped during `SplitTable::from_events`.
- Duplicate events on the same `ex_date` are multiplied (and dropped if reciprocal pairs cancel to `1.0`).
- Non-finite or `<= 0.0` ratios and compounding overflow/underflow return a typed `SplitError` rather than panicking.
- **Ex-date boundary (strict `>`):** `cum_factor_after(key, bar_date)` returns the product of all split ratios with `ex_date > bar_date`. A bar dated on an ex-date excludes that day's split (it is already post-split for that event) while still including any later splits (for example, NVDA on its `2021-07-20` 4:1 ex-date still has `factor = 10.0` from the later `2024-06-10` 10:1 split). Unknown keys and dates with no later splits return `1.0`.
- **`eodPrices` (daily bars):** OHLC is raw and only volume is retroactively split-adjusted:
- `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor`
- **`eodIntraday1M` (1m bars, reused in M2):** both OHLC and volume are retroactively split-adjusted:
- `raw_price = unadjust_price(adj_price, factor) = adj_price * factor`
- `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor`
- `unadjust_ohlcv(bar, factor)` applies both so dollar volume (`raw_close * raw_volume == adj_close * adj_volume`) is invariant.
## `adj_factors` Builder (`M1.2b`)
`build_adj_factors` (`src/adj.rs`) turns split (`qmSplits`) and cash-dividend (`qmDividends`) event streams into sorted, unique per-`(key, ex_date)` rows matching the `adj_factors/part.parquet` columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, split_factor, div_cash, div_currency, cum_split_factor, cum_total_factor`), omitting `usdFxRate` per contract.
> **Contract interpretation note:** `design/DATA-CONTRACTS.md` names `split_factor`, `div_cash`, `div_currency`, `cum_split_factor`, and `cum_total_factor` without writing formulas. Rules 3–5 below document this crate's back-adjustment divisor definitions so downstream consumers and reviewers can verify parity with `SplitTable::cum_factor_after`.
Rules:
1. **Split normalization:** Drop `ratio == 1.0` no-ops (counted in `stats.split_noops_dropped`). Multiply same-day splits in `f64::total_cmp` order; if they cancel back to `1.0` (e.g. `2.0 * 0.5`), drop the split component (and omit the row if no dividend is present on that date).
2. **Dividend normalization:** Drop `cash == 0.0` events (counted in `stats.dividend_zero_cash_dropped`). Sum same-day same-currency cash dividends in `f64::total_cmp` order into `div_cash`. Split-only rows carry `div_cash = 0.0` and `div_currency = None`; dividend-only rows carry `split_factor = 1.0`. Two different dividend currencies on the same `(key, ex_date)` return `AdjError::ConflictingDividendCurrency`.
3. **`cum_split_factor` (back-adjustment divisor):** Product of `split_factor` over this row and all later rows of the same key (inclusive of the row's own `ex_date`). For any bar dated `d`, the first row with `ex_date > d` (`adj_factors_after(rows, key, d).0`) matches `SplitTable::cum_factor_after(key, d)` bitwise.
4. **Per-row dividend factor:** `prev_close / (prev_close - div_cash)` when `prev_close` (the raw close of the last session strictly before `ex_date`) is present, finite, `> div_cash > 0.0`, and `prev_close_currency == div_currency`. Otherwise falls back to `1.0` in strict priority order while preserving `div_cash` and `div_currency` on the row and incrementing the matching counter:
- `dividends_missing_prev_close` (`prev_close` is `None` or non-finite)
- `dividends_currency_mismatch` (`prev_close_currency != Some(div_currency)`)
- `dividends_not_below_prev_close` (`prev_close <= div_cash`)
5. **`cum_total_factor`:** `cum_split_factor` multiplied by the product of per-row dividend factors over this row and all later rows of the same key (inclusive of the row's own `ex_date`).
6. **Validation & overflow guards:** Non-finite or `<= 0.0` split ratios (`InvalidSplitRatio`), non-finite or `< 0.0` dividend cash (`InvalidDividendCash`), empty/whitespace currency on positive cash (`EmptyDividendCurrency`), conflicting same-day dividend currencies (`ConflictingDividendCurrency`), and overflow/underflow of any combined or cumulative factor (`FactorOverflow`) return a typed `AdjError` without panicking.
Deferred out of `src/adj.rs`: cross-currency dividend FX conversion (waits for `fx_1d`). Point-in-time `known_at` clamping and delisting / Shumway rows live in `src/corporate_actions.rs`.
## `corporate_actions` Builder (`M1.2c`)
`build_corporate_actions` (`src/corporate_actions.rs`) turns split (`qmSplits`), cash-dividend (`qmDividends`), and Pass 6 delisting outcome streams into a deterministically sorted event log matching the `corporate_actions/part.parquet` columns in `design/DATA-CONTRACTS.md` (`listing_id, ex_date, declared_date, kind, ratio, cash_amount, currency, successor_listing_id, terminal_return, known_at, known_at_source`).
Rules:
1. **Splits (`kind = "split"`):** Same `ratio = new_shares / old_shares` convention as `src/split.rs`. `ratio == 1.0` no-ops are dropped and counted in `stats.split_noops_dropped`. Non-finite or `<= 0.0` ratios return `CorporateActionError::InvalidSplitRatio`.
2. **Dividends (`kind = "dividend"`):** Local `currency` and `cash` are preserved unchanged (deliberately omitting `usdFxRate`). `cash == 0.0` events are dropped and counted in `stats.dividend_zero_cash_dropped`. Multiple dividends on the same `(key, ex_date)` remain separate event-log rows. Non-finite or `< 0.0` cash returns `InvalidDividendCash`; empty/whitespace currency on positive cash returns `EmptyDividendCurrency`.
3. **Point-in-time `known_at` clamping:** Uses `declared_date` when present and `<= ex_date` (`known_at_source = "declared_date"`). Otherwise falls back to `ex_date` (`known_at_source = "ex_date_fallback"`), preserving the raw `declared_date` on the row and counting `declared_date > ex_date` in `stats.declared_after_ex_date` so `known_at_date <= ex_date` always holds.
4. **Delistings (Pass 6):**
- `successor_key = Some(s), terminal_return = None` → one `otc_delist_transfer` row (`ex_date = known_at_date = delist_date`, `known_at_source = "delist_date"`). Callers must pass the Pass 6 continuity `effectiveDate` (the successor's first observed OTC trading date) as `delist_date`, not the primary listing's last exchange print / halt date.
- `successor_key = None, terminal_return = Some(r)` → one `delisting` row (`r` must be finite and in `[-1.0, 0.0]`, normalizing `-0.0` to `0.0`, else `InvalidTerminalReturn`).
- Both `None` → dropped and counted in `stats.delist_without_outcome`.
- Both `Some` → `CorporateActionError::ConflictingDelistingOutcome`.
5. **Determinism & accounting:** Output rows are sorted by `(key, ex_date, kind, declared_date, ratio_bits, cash_bits, currency, successor_key, terminal_return_bits, known_at_date, known_at_source)` so any input permutation yields byte-identical output, and `stats` satisfies `in == out + dropped` per kind and `known_at_declared_date + known_at_ex_date_fallback + known_at_delist_date == rows_out`.
## `bars_1d` Builder (`M1.2d`)
`build_bars_1d` (`src/bars.rs`) turns raw `eodPrices` daily bars (`EodDailyBar<K>`) into sorted, unique per-`(key, session_date)` `Bar1dRow<K>` rows matching the contract sort `(listing_id, session_date)` in `design/DATA-CONTRACTS.md`, un-adjusting share volume via `&SplitTable<K>` and cross-checking against optional `qmPrices.sharevolume` observations (`QmRawVolume<K>`).
Rules:
1. **Raw OHLC & un-adjusted volume:** `eodPrices` OHLC is passed through bit-for-bit; `volume = unadjust_volume(adj_volume, factor)` where `factor = splits.cum_factor_after(&key, session_date)` (computed via a per-key monotonic cursor over `splits.splits_for(&key)` that matches `cum_factor_after` bitwise under the strict `ex_date > session_date` boundary).
2. **Bad-row resilience (never aborts on single-row errors):** Invalid bars are dropped and counted in strict priority order:
- `dropped_invalid_ohlc`: any OHLC field non-finite or `<= 0.0`.
- `dropped_inconsistent_ohlc`: `high < low`, or `open`/`close` outside `[low, high]`.
- `dropped_invalid_volume`: `adj_volume` non-finite or `< 0.0`, or post-unadjustment `volume` non-finite or `< 0.0` (e.g. extreme reverse-split overflow). Zero volume (`0.0` / `-0.0` normalized to `0.0`) is valid and kept.
3. **Deduplication:** After filtering bad bars, bitwise-identical duplicate `(key, session_date)` rows collapse to one (`duplicate_collapsed += n - 1`). Conflicting duplicates for the same `(key, session_date)` drop the entire group (`duplicate_conflict_dropped += n`).
4. **Caller errors (`BarsError`):** Reserved strictly for caller configuration errors (`BarsError::InvalidTolerance` when `rel_tolerance` is non-finite or `< 0.0`). Invalid/duplicate/conflicting `qmPrices` rows are filtered and compacted into `qm_invalid_volume_dropped`, `qm_duplicate_collapsed`, and `qm_duplicate_conflict_dropped` without aborting.
5. **`qmPrices.sharevolume` cross-check (read-only):** Never modifies emitted bars; EOD remains the row source. For each output row with a unique QM partner on `(key, session_date)`:
- Both `0.0` → `rel = 0.0` (match); `share_volume == 0.0` with `volume > 0.0` → `rel = INFINITY` (mismatch); otherwise `rel = |volume - share_volume| / share_volume` (within iff `rel <= rel_tolerance`).
- Retains up to `MAX_MISMATCH_SAMPLES` (`100`) worst mismatches sorted deterministically by `(rel DESC, key ASC, session_date ASC)`.
6. **Determinism & accounting invariants:** Any permutation of `bars` or `qm_volumes` produces bitwise-identical `rows`, `stats`, and `mismatch_samples`, and:
- `bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + duplicate_collapsed + duplicate_conflict_dropped`
- `volume_checked + volume_unchecked == rows_out` and `volume_within_tolerance + volume_mismatched == volume_checked`
- `qm_rows_in == qm_unique_partners + qm_invalid_volume_dropped + qm_duplicate_collapsed + qm_duplicate_conflict_dropped`
## `fx_1d` Builder (`M1.2e`)
`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) matching the `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (the `M1.2l` Parquet writer takes caller-supplied `ts`/`known_at` timestamps; timestamp derivation policy belongs to the Mongo-streaming wiring task).
Rules:
1. **Quote convention:** Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (`CADUSD.FOREX` inversion is out of scope).
2. **Per-source filtering (strict priority, never panics or aborts):**
- `dropped_invalid_ohlc`: any OHLC field non-finite or `<= 0.0`.
- `dropped_inconsistent_ohlc`: `high < low`, or `open`/`close` outside `[low, high]`.
3. **Per-source deduplication on `session_date`:** Bitwise-identical duplicates collapse to one (`duplicate_collapsed += n - 1`); conflicting duplicate groups drop entirely (`duplicate_conflict_dropped += n`).
4. **Merge precedence:** `EodCadForex` wins on overlapping dates (`te_superseded_by_eod += 1`); `TeUsdCad` fills interior gaps and all dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting group).
5. **Read-only overlap cross-check:** On every date where both sources survive, evaluates `|eod.close - te.close| / eod.close <= FX_OVERLAP_REL_TOLERANCE` (`0.01`, 1% inclusive with a small IEEE-754 rounding slack so exact decimal 1% pairs like `1.4000` vs. `1.4140` are not falsely flagged), counts `overlap_checked`, `overlap_within_tolerance`, and `overlap_mismatched`, and tracks raw `max_overlap_rel` without modifying emitted rows.
6. **No-look-ahead lookup (`fx_rate_on_or_before`):** Binary-searches sorted `Fx1dRow` slices for the latest row with `session_date <= date` and `date - session_date <= max_stale_days`. Carries forward across weekends/holidays within `max_stale_days`, returns `None` before the first row or when stale, and never returns a later date.
7. **Determinism & accounting invariants:** Any permutation of `eod` or `te` yields bitwise-identical `rows` and `stats`, and:
- Per source: `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped`
- Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out`
- Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod`
Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation policy (the `M1.2l` Parquet writer accepts caller-supplied timestamps; derivation belongs to the Mongo-streaming wiring task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends.
## `shorts` Builder (`M1.2f`)
`build_shorts` (`src/shorts.rs`) turns raw `ceoShorts` semi-monthly short-interest report rows (`CeoShortReport<K>`) into sorted, unique per-`(key, report_date)` point-in-time `ShortRow<K>` rows matching `shorts/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, report_date, known_at, shares_short, net_change, pct_float, source`).
Rules:
1. **Canadian TSX business-day calendar (`2008-01-01..=2030-12-31`):**
- `is_canadian_business_day(epoch_day)` and `add_canadian_business_days(epoch_day, n)` cover `MIN_SUPPORTED_YEAR = 2008` through `MAX_SUPPORTED_YEAR = 2030` (`MIN_SUPPORTED_DATE = 13_879` ..= `MAX_SUPPORTED_DATE = 22_279`), strictly covering the `2017-01-01..=2027-12-31` dataset window plus year-end `+4` business-day rollovers. Dates outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (or stepping past `MAX_SUPPORTED_DATE`) return `ShortsError::DateOutOfRange` rather than guessing or panicking.
- Non-business days: Saturdays, Sundays, and the 9 TSX market holidays:
1. **New Year's Day** (Jan 1; Sat → Mon Jan 3, Sun → Mon Jan 2)
2. **Family Day** (3rd Monday of February, TSX holiday since 2008)
3. **Good Friday** (computed Gregorian Easter Sunday − 2 days)
4. **Victoria Day** (Monday strictly before May 25)
5. **Canada Day** (Jul 1; Sat → Mon Jul 3, Sun → Mon Jul 2)
6. **Civic Holiday** (1st Monday of August)
7. **Labour Day** (1st Monday of September)
8. **Thanksgiving** (2nd Monday of October)
9. **Christmas Day & Boxing Day** (Mon–Thu → Dec 25/26; Fri → Dec 25 & Mon Dec 28; Sat → Mon Dec 27 & Tue Dec 28; Sun → Mon Dec 26 & Tue Dec 27)
- Federal holidays where TSX remains open (National Day for Truth and Reconciliation on Sept 30 and Remembrance Day on Nov 11) are treated as normal TSX business days.
- When `report_date` itself falls on a non-business day (e.g. a Saturday month-end), `add_canadian_business_days(report_date, 4)` counts strictly forward so `known_at_date` is the 4th TSX business day strictly after `report_date` (`known_at_date > report_date` always holds).
2. **`America/Toronto` ET → UTC DST conversion (`et_to_utc_micros`):**
- Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November 02:00 = EDT `UTC-4`, otherwise EST `UTC-5`).
- `known_at_utc_micros` is `17:00:00 America/Toronto` on `known_at_date` (`21:00:00 UTC` in EDT, `22:00:00 UTC` in EST).
- Rejects out-of-range dates (`DateOutOfRange`), invalid wall-clock components (`InvalidLocalTime`), spring-forward nonexistent times `02:00..03:00` (`NonexistentLocalTime`), and fall-back ambiguous times `01:00..02:00` (`AmbiguousLocalTime`).
- Exposed publicly alongside `epoch_days_to_ymd` so the upcoming `events` builder (`16:05 ET` lag) can reuse it directly.
3. **Bad-row resilience, sanitization, and deduplication:**
- Every input row's `report_date + 4` business days is validated first so out-of-range dates fail deterministically with `ShortsError::DateOutOfRange` regardless of row order or bad numeric fields.
- Non-finite or negative `shares_short` rows are dropped and counted in `dropped_invalid_shares_short` (without incrementing optional-field null counters); `-0.0` is normalized to `0.0`.
- Non-finite `net_change` and `pct_float` values are sanitized to `None` and counted in `nulled_invalid_net_change` and `nulled_invalid_pct_float`; `-0.0` is normalized to `0.0`.
- Bitwise-identical duplicates on `(key, report_date)` collapse (`duplicate_collapsed += n - 1`); conflicting duplicate groups drop entirely (`duplicate_conflict_dropped += n`).
- Every emitted row carries `source = "ceo_shorts"`, `known_at_date > report_date`, and is strictly sorted by `(key, report_date)`.
4. **Determinism & accounting invariants:**
- Any input permutation yields bitwise-identical `rows` and `stats`.
- `rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped`.
5. **CIRO publication-lag note:** The `+4` Canadian business-day `17:00 ET` rule is the locked contract proxy from `design/DATA-CONTRACTS.md` (not an observed CIRO scrape timestamp). Downstream signal studies should still run `+1` business-day lag stress tests around holidays and month-end boundaries.
Deferred out of `src/shorts.rs`: MongoDB `ceoShorts` BSON streaming, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, `rayon` sharding, and deriving `pct_float` from shares outstanding (values are passed through as supplied by the caller).
## `posts` Builder (`M2.2b`)
`build_posts` (`src/posts.rs`) turns already-decoded `ceoPosts` rows (`CeoPost<K>`) into two disjoint, deterministically sorted point-in-time `PostRow<K>` streams (`newswire` and `retail`) aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row).
Rules:
1. **Newswire vs. retail split:** `is_bot` is `true` iff `bot` is `"1"` after trimming whitespace; only `is_bot == true` rows route to `newswire`, and all other values (`None`, `"0"`, `""`, etc.) route to `retail`.
2. **Point-in-time `known_at` guard:** `posted_at = timestamp_ms * 1_000` (UTC microseconds) and `known_at = max(timestamp_ms, edited_ms) * 1_000` (`COALESCE(edited, timestamp)` clamped so `known_at >= posted_at` always holds). Any text-based feature MUST join on `known_at`, never `posted_at`. Rows with `edited_ms < timestamp_ms` clamp `known_at` to `posted_at` and increment `stats.edited_before_posted`. Both `stats.edited` and `stats.edited_before_posted` are counted on valid input rows before deduplication. Because `ceoPosts` overwrites `spiel` in place without version history, the builder retains one supplied version per `spiel_id` and cannot recover earlier pre-edit text.
3. **Validation & overflow:** Empty `spiel_id` or `timestamp_ms <= 0` rows are rejected before conversion and counted in `stats.rejected_invalid`. Overflow converting `timestamp_ms` or the selected `known_at` millisecond value to UTC microseconds returns `PostsError::TimestampOverflow`.
4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`.
5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`.
Deferred out of `src/posts.rs`: `curate-posts` CLI subcommand, benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, chunked streaming in `src/bson_stream.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`, and the file-to-file runner in `src/run_curate_posts.rs`).
### `run_curate_posts` File-to-File Runner (`M2.2i`)
`run_curate_posts` / `run_curate_posts_with_reader` (`src/run_curate_posts.rs`) connects a concatenated raw BSON `ceoPosts` dump file and a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) through `decode_ceo_posts_chunks` (`src/bson_stream.rs`) and `curate_and_write_posts` into `<out_dir>/events/year=YYYY/part.parquet` (Zstd Parquet):
- **Explicit timestamp unit (no default):** `CuratePostsArgs::timestamp_unit` requires callers to pass `CeoPostsTimestampUnit::Seconds` or `CeoPostsTimestampUnit::Millis` explicitly (the live MongoDB numeric unit is unverified in the repo; BSON `DateTime` values are always epoch milliseconds).
- **Dedicated output directory & clobber guard:** Because `write_events_dataset` replaces whole `events/year=YYYY/part.parquet` files and `run_curate_events` (filings + earnings) writes to the same `<out_dir>/events` path, `run_curate_posts` requires a dedicated `--out` directory and fails closed with `RunCuratePostsError::EventsDatasetExists` before any write whenever `<out_dir>/events` already contains any `year=*` entry. Combining filings, earnings, and posts into a single `events` dataset is a separate follow-up.
- **Zero-row & fail-closed behavior:** Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/events`. Validation, clobber checks, TSV loading, full BSON decoding, and curation complete before `out_dir` is touched.
- **In-memory accumulation:** `RawBsonChunkReader` bounds only the raw BSON chunk buffer (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before `curate_and_write_posts` runs (as `curate_posts` requires).
## `events` Builder (`M1.2g`)
`build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling<K>`) and `qmEarnings` (`QmEarning<K>`) streams into deterministically sorted point-in-time `EventRow<K>` records matching `events/year=YYYY/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, payload_json`), plus `partition_year_utc` / `EventRow::partition_year` for UTC `year=YYYY` partitioning.
Rules:
1. **Filing timestamps (`kind = "filing"`):**
- `parse_filing_timefiled` strictly parses `YYYY-MM-DDTHH:MM:SS EST` (`UTC-5`) and `YYYY-MM-DDTHH:MM:SS EDT` (`UTC-4`). Using the explicit abbreviation's fixed offset avoids DST calendar range limits so pre-2008 filings convert cleanly.
- Emits `ts_micros = known_at_micros = UTC(timefiled)` and `known_at_source = "filing_timestamp"`.
- Malformed strings (`filings_skipped_malformed_timestamp`), missing/unknown zones such as `PST`/`UTC`/`Z` (`filings_skipped_unknown_zone`), and invalid calendar dates or wall-clock times (`filings_skipped_invalid_date_time`) are skipped and counted without panicking.
- *Provenance caveat:* EDGAR filings accepted after `17:30 ET` are converted directly to UTC without next-business-day shifting (per the M1.2g contract); downstream intraday studies should apply exchange-session routing and post-`17:30 ET` visibility rules on top of `known_at_micros`.
2. **Table-driven form groups & periodic-report predicate (`classify_form_type`, `is_periodic_financial_report`):**
- Exact EDGAR codes (checked after stripping optional `/A` and standalone `Amended` markers such as `10-K (Amended)` so `"4"` never matches `"40-F"`, `"424B5"`, or `"45-106F1"`): `10-K` (`"10-k"`), `10-Q` (`"10-q"`), `8-K` (`"8-k"`), `4` (`"4"`), `144` (`"144"`), `40-F` (`"40-f"`).
- SEDAR+ substring rules in fixed priority order: `Interim financial statements/report` (`"interim_financial_statements"`), `Annual financial statements` (`"annual_financial_statements"`), `MD&A` (`"mda"`), `52-109` (`"52-109"`), `NI 43-101` (`"ni_43_101"`), `45-106F1` (`"45-106f1"`), `News release` (`"news_release"`). Everything else maps to `"other"`.
- Amendments (`/A` or standalone `"amended"`) map to the same group with `is_amendment: true` and the raw `form_type` preserved in `payload_json`.
- `is_periodic_financial_report` is `true` only for `10-K`, `10-Q`, `40-F`, `Interim financial statements`, and `Annual financial statements` (for the M2 `fundamentals_pit` filing join).
3. **Earnings linking & conservative `16:05 ET` lag (`kind = "earnings"`):**
- Precedence:
1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments) whose local ET calendar date matches `report_date` (including late-evening ET filings whose UTC date is the next day), `known_at_micros` = earliest such filing's UTC timestamp (`known_at_source = "filing_timestamp"`, deterministic tie-break on `(filing_id, form_type, url)`).
2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via `shorts::et_to_utc_micros` (`known_at_source = "statutory_lag_estimate"`). This fallback is intended for T+1 open use (not same-day intraday cutoffs, since a later same-date `8-K` or `News release` filing supersedes the fallback with its actual filing timestamp). It applies to `N/A`, `BTO`, and `AMC` alike whenever no linked filing provides a real timestamp—unlinked `BTO`/`AMC` rows are never stamped earlier than `16:05 ET`.
3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`) are skipped and counted in `earnings_skipped_out_of_range` (pre-2008 dates with a linked same-day filing still succeed).
- `ts_micros = known_at_micros`; `subtype` = normalized announce time (`"bto"` / `"amc"` / `"unknown"`).
- Post-hoc overwritten `consensusEps` is deliberately omitted from `QmEarning` and `payload_json` per `design/DATA-CONTRACTS.md` §1.
4. **Payload JSON, deduplication, sorting & accounting:**
- Hand-written `std`-only RFC 8259 JSON encoder with strict string escaping, non-ASCII UTF-8 passthrough, stable key order, `-0.0` normalized to `0`, and non-finite `f64` (`NaN`/`±inf`) emitted as `null`.
- Exact duplicate filings collapse (`filings_duplicate_collapsed`); identical normalized `(key, report_date)` earnings collapse (`earnings_duplicate_collapsed`) and conflicting `(key, report_date)` groups drop entirely (`earnings_duplicate_conflict_dropped`).
- Output rows are sorted deterministically by `(key, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)` and `EventsStats` reconciles exactly per kind (`filings_in == filings_out + skips + dup`, `earnings_in == earnings_out + oor + dup + conflict`, `earnings_out == linked + lagged`, `rows_out == filings_out + earnings_out`).
Deferred out of `src/events.rs`: live MongoDB `qmFilings` / `qmEarnings` cursors and M2 `fundamentals_pit` joins (concatenated-BSON decoding, `provider_mapping` resolution, and Zstd Parquet publishing are wired in `src/bson_qm_events.rs` + `src/run_curate_events.rs`).
## `provider_mapping` Table (`M1.2h`)
`ProviderMappingTable` (`src/provider_mapping.rs`) is a pure, zero-allocation in-RAM lookup table resolving `(source, source_id, bar_date)` to a permanent `listing_id: i32` over inclusive date ranges, mirroring `provider_mapping` in `database/postgres/init/34-security-master.sql`.
Rules:
1. **Inclusive date ranges & open-ended active spans:** `valid_from` and `valid_to` are UTC Gregorian epoch days (`split::ymd_to_epoch_days`). `valid_to = Some(d)` is inclusive (`valid_from <= bar_date <= d`); `valid_to = None` is open-ended (`bar_date >= valid_from`). Unknown keys, dates before the first range, interior gap dates (e.g., ticker reuse `FB.US` `2012-05-18..=2022-06-08` → `2025-01-02..`), and dates after a closed last range return `None`.
2. **Verbatim key storage (no trimming):** Empty or whitespace-only `source` / `source_id` strings return `EmptySource` / `EmptySourceId`, but non-empty strings with leading or trailing whitespace are stored and matched verbatim (never trimmed or merged with unspaced IDs).
3. **Strict PostgreSQL PK & overlap validation (`from_rows`):**
- Rejects `listing_id <= 0` (`InvalidListingId`) and `valid_to < valid_from` (`InvalidRange`).
- **Exact-duplicate policy:** Every duplicate `(source, source_id, valid_from)`—including bitwise-identical duplicate rows—is rejected with `DuplicateValidFrom`, matching the PostgreSQL `PRIMARY KEY (source, source_id, valid_from)` constraint.
- Rejects intersecting inclusive ranges (including touching endpoints `prev.valid_to == curr.valid_from` and any open-ended range followed by a later range) with `OverlappingRanges`. Adjacent ranges (`prev.valid_to = d`, `curr.valid_from = d + 1`) are accepted, and boundary checks avoid `valid_to + 1` overflow at `i32::MAX`.
- Deterministic for any input row permutation.
4. **Zero-allocation lookups & sorted-stream cursor:**
- `resolve(source, source_id, bar_date)` and `ranges_for(source, source_id)` perform zero heap allocations: all `MappingRange`s live in a single contiguous `Vec<MappingRange>` arena indexed by a sorted per-source `HashMap<String, (usize, usize)>` (linear scan for `<= 8` sources, binary search otherwise) plus binary search over the key's ranges.
- `ProviderMappingCursor` (via `cursor_for(source, source_id)` or `ProviderMappingCursor::new(ranges)`) resolves ascending `bar_date` streams for a single key in amortised O(1), automatically falling back to binary search on out-of-order probes so its output always matches `ProviderMappingTable::resolve` identically.
## `bars_1d` Parquet Writer (`M1.2i`)
`write_bars_1d_dataset` (`src/parquet_bars.rs`) streams strictly ascending `(listing_id, session_date)` `Bars1dParquetRow` records into Zstd-compressed, year-partitioned Parquet files matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 12-column contract schema (`bars_1d_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `session_date` (`INT32`, `REQUIRED`, `DATE`)
- `open`, `high`, `low`, `close`, `volume` (`DOUBLE`, `REQUIRED`)
- `vwap` (`DOUBLE`, `OPTIONAL`)
- `currency`, `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
2. **Partition layout & compression:**
- Writes `<out_dir>/bars_1d/year=YYYY/part.parquet` lazily per observed `session_date` calendar year (`1900..=2200`); empty input and empty years create no directories or files.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`).
- Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary.
- **Year-sharded `rayon` parallel write (`M1.2ai`):** configurable via `Bars1dWriteOptions::threads` (`DEFAULT_WRITE_THREADS = 1` in `Bars1dWriteOptions::default()` to keep bounded streaming memory for library callers; `default_parallel_threads()` returns `std::thread::available_parallelism()`, falling back to `1`). When `threads == 1`, runs the unchanged single-pass streaming path. When `threads > 1`, runs one sequential validation + order-preserving year-bucketing pass, encodes and Zstd-compresses each `year=YYYY` staging file on a local `rayon::ThreadPool` sized to `threads.min(years).max(1)` (never the global pool), catches worker panics (`WorkerPanicked`), sorts outcomes by ascending year (returning the lowest failing year's error deterministically on failure after unlinking only this run's staging files), and publishes sequentially in ascending year order.
- **Byte-identical determinism guarantee:** identical inputs produce byte-for-byte identical `bars_1d/year=YYYY/part.parquet` files regardless of `threads` (same row order per year, same `row_group_rows` flush boundaries, same schema, dictionary interning order, and `created_by` metadata).
3. **Sort, concurrency & atomicity rules:**
- Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order.
- Concurrent writers targeting the same `<out_dir>/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked.
4. **Typed errors (`ParquetBarsError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `InvalidThreads` (`threads == 0`)
- `ThreadPoolBuild { threads, detail }`
- `WorkerPanicked { year, detail }`
- `UnsortedInput { prev_listing_id, prev_session_date, listing_id, session_date }`
- `DuplicateKey { listing_id, session_date }`
- `SessionYearOutOfRange { listing_id, session_date, year, min_year, max_year }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-bars`
- Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` (20 years `2006..=2025`)
- Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000`
- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
## `shorts` Parquet Writer (`M1.2j`)
`write_shorts_dataset` (`src/parquet_shorts.rs`) streams strictly ascending `(listing_id, report_date)` `ShortsParquetRow` records (with `From<&ShortRow<i32>>` / `From<ShortRow<i32>>` conversions from `build_shorts`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 7-column contract schema (`shorts_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `report_date` (`INT32`, `REQUIRED`, `DATE`)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `shares_short` (`DOUBLE`, `REQUIRED`)
- `net_change` (`DOUBLE`, `OPTIONAL`)
- `pct_float` (`DOUBLE`, `OPTIONAL`)
- `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
2. **Layout, compression & streaming:**
- Writes `<out_dir>/shorts/part.parquet` (unpartitioned).
- Empty input returns `Ok(ShortsWriteStats::default())` without creating `<out_dir>/shorts` and without modifying or removing any pre-existing `part.parquet`.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `ShortsWriteOptions::zstd_level`).
- Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `ShortsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with string interning for `source`), flushing and clearing on every row-group boundary.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Validation, concurrency & atomic publish rules:**
- Input must be strictly ascending by `(listing_id, report_date)` (rejecting duplicates and out-of-order rows).
- `shares_short` must be finite and `>= 0.0`; `net_change` and `pct_float` must be finite when `Some`; `known_at_micros` must be strictly after `report_date` `00:00:00 UTC` (compared in `i128` to avoid overflow on extreme `i32` epoch days); `source` must be non-empty after trimming.
- Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `<out_dir>/shorts` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`.
4. **Typed errors (`ParquetShortsError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { prev_listing_id, prev_report_date, listing_id, report_date }`
- `DuplicateKey { listing_id, report_date }`
- `InvalidSharesShort { listing_id, report_date, value }`
- `InvalidNetChange { listing_id, report_date, value }`
- `InvalidPctFloat { listing_id, report_date, value }`
- `KnownAtNotAfterReportDate { listing_id, report_date, known_at_micros }`
- `EmptySource { listing_id, report_date }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-shorts`
- Input: `rows=1000000`, `listings=12500`, `raw_row_bytes=50` (semi-monthly dates `2017-04-15..=2026-04-30`)
- Output: `files=1`, `row_groups=1`, `bytes=6741816`, `read_back_rows=1000000`
- Perf: `elapsed=106.79 ms`, `throughput=9364116 rows/s`, `write=60.21 MB/s`, `size=6.74 bytes/row`, `compression=7.42x`
## `events` Parquet Writer (`M1.2k`)
`write_events_dataset` (`src/parquet_events.rs`) streams strictly ascending `EventsParquetRow` records (with `From<&EventRow<i32>>` / `From<EventRow<i32>>` conversions from `build_events`) into Zstd-compressed, UTC-year-partitioned Parquet files matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 7-column contract schema (`events_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `subtype` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary disabled)
- `payload_json` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary disabled)
2. **Partition layout, compression & streaming:**
- Writes `<out_dir>/events/year=YYYY/part.parquet` lazily per observed UTC year `partition_year_utc(ts_micros)` (`1900..=2200`).
- Empty input returns `Ok(EventsWriteStats::default())` without creating `<out_dir>/events` and without modifying or removing any pre-existing partitions.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `EventsWriteOptions::zstd_level`).
- Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `EventsWriteOptions::row_group_rows`): buffers at most one row group per active year; low-cardinality `known_at_source`/`kind` use string interning while high-cardinality `subtype`/`payload_json` write directly as batched plain byte arrays without unbounded interning.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Validation, concurrency & atomic publish rules:**
- Input must be strictly ascending by the `build_events` sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`; out-of-order and exact-duplicate rows are rejected with the offending `row_index`.
- `known_at_micros >= ts_micros` is enforced (`KnownAtBeforeTs` rejects look-ahead `known_at < ts`); partition year must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`; `known_at_source`, `kind`, `subtype`, and `payload_json` must be non-empty after trimming.
- Reuses the shared `parquet_publish` locking, exclusive per-run staging (`part.parquet.<run>.tmp`), `File::sync_all()`, live-preserving backup (`part.parquet.<run>.bak`), atomic `rename`, and multi-partition rollback (`rollback_published` / `RollbackFailed`) path so partial or failing runs never leave corrupt partitions or transient files behind.
4. **Typed errors (`ParquetEventsError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { row_index, prev_listing_id, prev_ts_micros, listing_id, ts_micros }`
- `DuplicateRow { row_index, listing_id, ts_micros }`
- `KnownAtBeforeTs { row_index, listing_id, ts_micros, known_at_micros }`
- `PartitionYearOutOfRange { row_index, listing_id, ts_micros, year, min_year, max_year }`
- `EmptyKnownAtSource { row_index, listing_id, ts_micros }`
- `EmptyKind { row_index, listing_id, ts_micros }`
- `EmptySubtype { row_index, listing_id, ts_micros }`
- `EmptyPayloadJson { row_index, listing_id, ts_micros }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-events`
- Input: `rows=500000`, `listings=5000`, `avg_raw_row_bytes=243.6` (11 UTC years `2015..=2025`, ~98.5% filings / ~1.5% linked & lagged earnings)
- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000`
- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x`
## `fx_1d` Parquet Writer (`M1.2l`)
`write_fx_1d_dataset` (`src/parquet_fx.rs`) streams strictly ascending `(pair, session_date)` `Fx1dParquetRow` records (with zero-allocation `Fx1dParquetRow::from_fx_row(&Fx1dRow, ts_micros, known_at_micros)` construction from `build_fx_1d`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 9-column contract schema (`fx_1d_parquet_schema`):**
- `pair` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `session_date` (`INT32`, `REQUIRED`, `DATE`)
- `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `open`, `high`, `low`, `close` (`DOUBLE`, `REQUIRED`)
- `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
2. **Layout, compression & streaming:**
- Writes `<out_dir>/fx_1d/part.parquet` (unpartitioned).
- Empty input returns `Ok(Fx1dWriteStats::default())` without creating `<out_dir>/fx_1d` and without modifying or removing any pre-existing `part.parquet`.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Fx1dWriteOptions::zstd_level`).
- Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Fx1dWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with string interning for `pair` and `source` and reused buffers across row groups), flushing and clearing on every row-group boundary.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Validation, concurrency & atomic publish rules:**
- Caller supplies `ts_micros` and `known_at_micros` (FX timestamp derivation policy belongs to the Mongo-streaming wiring task).
- Every streamed row is validated before publication: `pair` and `source` must be non-empty after trimming; every OHLC value must be finite and `> 0.0` with `high >= low` and `open`, `close` inside `[low, high]`; `ts_micros` must fall inside the UTC day `[session_date * 86_400_000_000, +1 day)` (computed in `i128` to avoid overflow on pre-1970 or extreme `i32` dates); `known_at_micros >= ts_micros` is enforced; and input must be strictly ascending and unique by `(pair, session_date)`.
- Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `<out_dir>/fx_1d` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`.
4. **Typed errors (`ParquetFxError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { prev_pair, prev_session_date, pair, session_date }`
- `DuplicateKey { pair, session_date }`
- `EmptyPair { session_date }`
- `EmptySource { pair, session_date }`
- `InvalidOhlc { pair, session_date, open, high, low, close }`
- `InconsistentOhlc { pair, session_date, open, high, low, close }`
- `TsOutsideSessionDate { pair, session_date, ts_micros }`
- `KnownAtBeforeTs { pair, session_date, ts_micros, known_at_micros }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-fx`
- Input: `rows=1000000`, `pairs=80`, `raw_row_bytes=70` (weekday dates `1971..=2026`, mixing `eod_cad_forex` and `te_usdcad`)
- Output: `files=1`, `row_groups=1`, `bytes=22102946`, `read_back_rows=1000000`
- Perf: `elapsed=228.82 ms`, `throughput=4370208 rows/s`, `write=92.12 MB/s`, `size=22.10 bytes/row`, `compression=3.17x`
## `adj_factors` Parquet Writer (`M1.2m`)
`write_adj_factors_dataset` (`src/parquet_adj.rs`) streams strictly ascending `(listing_id, ex_date)` `AdjFactorsParquetRow` records (with `AdjFactorsParquetRow::from_adj_row(&AdjFactorRow<i32>, known_at_micros)` construction from `build_adj_factors`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 8-column contract schema (`adj_factors_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `ex_date` (`INT32`, `REQUIRED`, `DATE`)
- `split_factor` (`DOUBLE`, `REQUIRED`)
- `div_cash` (`DOUBLE`, `REQUIRED`)
- `div_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`, dictionary-encoded; `None` on split-only rows)
- `cum_split_factor` (`DOUBLE`, `REQUIRED`)
- `cum_total_factor` (`DOUBLE`, `REQUIRED`)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
2. **Layout, compression & streaming:**
- Writes `<out_dir>/adj_factors/part.parquet` (unpartitioned).
- Empty input returns `Ok(AdjFactorsWriteStats::default())` without creating `<out_dir>/adj_factors` and without modifying or removing any pre-existing `part.parquet`.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `AdjFactorsWriteOptions::zstd_level`).
- Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `AdjFactorsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with interned optional `div_currency` streamed in 4,096-row batches and reused buffers across row groups), flushing and clearing on every row-group boundary.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Validation, concurrency & atomic publish rules:**
- Caller supplies `known_at_micros` without restricting it against `ex_date` (declared dates typically precede `ex_date`, while fallbacks/late notices can fall on or after `ex_date`; timestamp derivation policy belongs to the Mongo-streaming wiring task).
- Every streamed row is validated before publication: `ex_date` calendar year must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR` (`1900..=2200`); `split_factor`, `cum_split_factor`, and `cum_total_factor` must be finite and `> 0.0`; `div_cash` must be finite and `>= 0.0`; `div_currency` must be `Some(non-empty)` whenever `div_cash > 0.0` and never empty/whitespace when `Some`; and input must be strictly ascending and unique by `(listing_id, ex_date)`.
- Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `<out_dir>/adj_factors` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`.
4. **Typed errors (`ParquetAdjError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { prev_listing_id, prev_ex_date, listing_id, ex_date }`
- `DuplicateKey { listing_id, ex_date }`
- `ExDateOutOfRange { listing_id, ex_date, year, min_year, max_year }`
- `InvalidSplitFactor { listing_id, ex_date, value }`
- `InvalidDivCash { listing_id, ex_date, value }`
- `InvalidDivCurrency { listing_id, ex_date }`
- `InvalidCumSplitFactor { listing_id, ex_date, value }`
- `InvalidCumTotalFactor { listing_id, ex_date, value }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-adj`
- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=51` (weekday dates `1990..=2025`, ~4% split-only with `None` `div_currency`, ~95% USD/CAD dividends, ~1% combined)
- Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000`
- Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x`
## `corporate_actions` Parquet Writer (`M1.2n`)
`write_corporate_actions_dataset` (`src/parquet_corporate_actions.rs`) streams non-decreasing `(listing_id, ex_date, kind)` `CorporateActionsParquetRow` records (with `CorporateActionsParquetRow::from_corporate_action_row(&CorporateActionRow<i32>, known_at_micros)` construction from `build_corporate_actions`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 11-column contract schema (`corporate_actions_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `ex_date` (`INT32`, `REQUIRED`, `DATE`)
- `declared_date` (`INT32`, `OPTIONAL`, `DATE`)
- `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"split"` | `"dividend"` | `"otc_delist_transfer"` | `"delisting"`)
- `ratio` (`DOUBLE`, `OPTIONAL`)
- `cash_amount` (`DOUBLE`, `OPTIONAL`)
- `currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`, dictionary-encoded)
- `successor_listing_id` (`INT32`, `OPTIONAL`)
- `terminal_return` (`DOUBLE`, `OPTIONAL`)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"declared_date"` | `"ex_date_fallback"` | `"delist_date"`)
2. **Layout, compression & streaming:**
- Writes `<out_dir>/corporate_actions/part.parquet` (unpartitioned).
- Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating `<out_dir>/corporate_actions` and without modifying or removing any pre-existing `part.parquet`.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `CorporateActionsWriteOptions::zstd_level`).
- Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `CorporateActionsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with interned `kind`, `currency`, and `known_at_source` streamed in 4,096-row batches and reused buffers across row groups), flushing and clearing on every row-group boundary.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Validation, ordering, concurrency & atomic publish rules:**
- Caller supplies `known_at_micros` (date→timestamp derivation policy belongs to the later Mongo-streaming wiring task).
- Input must be non-decreasing on `(listing_id, ex_date, kind)` using `CorporateActionKind`'s `Ord` (`Split < Dividend < OtcDelistTransfer < Delisting`), matching `build_corporate_actions` output without re-sorting; multiple rows may share the same key (e.g. regular + special dividend on the same ex-date).
- Every streamed row is validated before publication: `ex_date` and optional `declared_date` years must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR` (`1900..=2200`); `split` requires `ratio` finite `> 0.0`; `dividend` requires `cash_amount` finite `> 0.0` and `currency` non-empty after trimming; `otc_delist_transfer` requires `successor_listing_id != listing_id`; `delisting` requires `terminal_return` finite in `[-1.0, 0.0]`; all fields belonging to other kinds must be `None`; and `known_at_source` must match the kind (`delist_date` only for delisting kinds, `declared_date` requires `declared_date.is_some()`).
- Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `<out_dir>/corporate_actions` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`.
4. **Typed errors (`ParquetCorporateActionsError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { prev_listing_id, prev_ex_date, prev_kind, listing_id, ex_date, kind }`
- `ExDateOutOfRange { listing_id, ex_date, year, min_year, max_year }`
- `DeclaredDateOutOfRange { listing_id, ex_date, declared_date, year, min_year, max_year }`
- `InvalidRatio { listing_id, ex_date, value }`
- `InvalidCashAmount { listing_id, ex_date, value }`
- `InvalidCurrency { listing_id, ex_date }`
- `InvalidSuccessorListingId { listing_id, ex_date, successor_listing_id }`
- `InvalidTerminalReturn { listing_id, ex_date, value }`
- `ForbiddenFieldForKind { listing_id, ex_date, kind, field }`
- `InconsistentKnownAtSource { listing_id, ex_date, kind, known_at_source, declared_date }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions`
- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72` (weekday dates `1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes)
- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000`
- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x`
## `eodPrices` Raw BSON Decoder (`M1.2o`)
`decode_eod_price_doc`, `decode_eod_price_bytes`, `iter_raw_bson_docs`, and `decode_eod_price_buffer` (`src/bson_eod_prices.rs`) decode raw MongoDB `eodPrices` BSON documents in a single forward pass over `RawDocument::iter_elements()` without allocating a `String` or `bson::Document` per row.
1. **Pinned dependency & driver compatibility:**
- Adds `bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] }` (MSRV `1.81+`, tested against workspace `rustc 1.88.0`, no `serde` derive).
- Paired with the official `mongodb` `3.x` Rust driver using `features = ["bson-3"]` so the upcoming MongoDB cursor task reuses the same `bson` 3.x crate without pulling in a duplicate `bson` major version.
2. **Empirical field contract & cited sources:**
- Grounded in `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56`, `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157`, `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18`, and `design/DATA-CONTRACTS.md` §1 (line 13).
- `eodSearchCode`: BSON UTF-8 `String` (borrowed verbatim as `&str`; empty or whitespace-only is rejected).
- `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (converted to UTC epoch days via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps map accurately).
- `open`, `high`, `low`, `close`, `volume`: every BSON numeric representation MongoDB can store for a JS number (`Double`, `Int32`, `Int64`); must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). Per `design/DATA-CONTRACTS.md` §1, OHLC is raw and `volume` is retroactively split-adjusted, mapping directly to `EodDailyBar::adj_volume`.
- Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without decoding their values.
3. **Zero-allocation key mapping:**
- Decodes into borrowed `RawEodDailyBar<'a>` and converts to `EodDailyBar<K>` via `into_eod_daily_bar(|code, date| ...)` or `try_into_eod_daily_bar(|code, date| mapping.resolve("eod", code, date))`, avoiding per-row `String` allocations across 846M documents.
4. **Typed errors & stream skip/accounting policy:**
- Never panics on untrusted input. `BsonEodPriceError` names the offending field on every field-level error: `MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, `TruncatedDocument`, `CorruptDocumentLength`, and `CorruptBson`.
- `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, and decoders for remaining collections (`eodIntraday1M`). (`qmSplits`/`qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.)
## `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`), `forfactor` (`FIELD_FOR_FACTOR`), `tofactor` (`FIELD_TO_FACTOR`): BSON `Double`, `Int32`, or `Int64`; `splitratio` must be finite and `> 0.0`. Empirically across all `18,751` live `qmSplits` documents (`16,892/16,892` with numeric `forfactor`/`tofactor`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `0.1` for NVDA's `2024-06-10` 10:1 forward split; `8` for GE's `2021-08-02` 1:8 reverse split). `decode_qm_split_doc` converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1), or `1.0 / splitratio` otherwise. `ratio == 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
### `bench-split`
Fixed-seed (`std`-only SplitMix64), zero-allocation hot-loop benchmark over `20,000` symbol keys and `19,000` forward/reverse split events spanning `1990-01-01..=2025-12-31` (default `10,000,000` bar lookups + `unadjust_volume`):
```bash
cargo run --release -p curate-etl --offline -- bench-split [rows]
```
Command: `cargo run --release -p curate-etl --offline -- bench-split`
- Table: `keys=20000`, `keys_with_splits=12153`, `events=18999`, `build=1.73 ms`
- Run: `rows=10000000`, `elapsed=367.40 ms`, `throughput=27218476 rows/s`, `latency=36.74 ns/row`, `checksum=259124314244145.531`
### `bench-adj`
Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` `i32` `listing_id` keys spanning `1990-01-01..=2025-12-31` with ~4% splits and ~96% dividends (default `1,000,000` mixed events), timing only `build_adj_factors`:
```bash
cargo run --release -p curate-etl --offline -- bench-adj [events]
```
Command: `cargo run --release -p curate-etl --offline -- bench-adj`
- Input: `events=1000000`, `splits=39861`, `dividends=960139`, `keys=20000`
- Build: `rows_out=986702`, `keys_out=20000`, `elapsed=242.94 ms`, `throughput=4116183 events/s`, `latency=242.94 ns/event`, `checksum=17888280.062 (0x41710f4180ff5d60)` (bitwise identical across back-to-back runs)
- Stats: `split_noops=1988`, `zero_div=9527`, `missing_prev_close=19089`, `currency_mismatch=19147`, `not_below_prev_close=9693`
### `bench-corporate-actions`
Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` `i32` `listing_id` keys spanning `1990-01-01..=2025-12-31` with ~4% splits, ~92% USD/CAD dividends, and ~4% delisting outcomes (default `1,000,000` mixed events), timing only `build_corporate_actions`:
```bash
cargo run --release -p curate-etl --offline -- bench-corporate-actions [events]
```
Command: `cargo run --release -p curate-etl --offline -- bench-corporate-actions`
- Input: `events=1000000`, `splits=39872`, `dividends=920134`, `delistings=39994`, `keys=20000`
- Build: `rows_out=980694`, `keys_out=20000`, `elapsed=107.48 ms`, `throughput=9303979 events/s`, `latency=107.48 ns/event`, `checksum=0xbfd2ceda373762f5` (identical across back-to-back runs)
- Stats: `split_noops=1963`, `zero_div=9302`, `delist_no_outcome=8041`, `otc_transfers=11942`, `delistings=20011`, `declared=758098`, `ex_fallback=190643`, `declared_after_ex=19108`, `delist_date=31953`
### `bench-bars`
Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` `i32` `listing_id` keys and `19,000` splits spanning `1990-01-01..=2025-12-31` (default `10,000,000` daily bars with a small share of invalid/duplicate rows and ~50% `qmPrices.sharevolume` partners), timing only `build_bars_1d`:
```bash
cargo run --release -p curate-etl --offline -- bench-bars [rows]
```
Command: `cargo run --release -p curate-etl --offline -- bench-bars`
- Input: `rows=10000000`, `qm_rows=4912050`, `splits=18998`, `keys=20000`
- Build: `rows_out=9488072`, `keys_out=20000`, `elapsed=842.38 ms`, `throughput=11871057 rows/s`, `latency=84.24 ns/row`, `checksum=0x25fae7ad0816891b` (identical across back-to-back runs)
- Stats: `invalid_ohlc=20006`, `inconsistent_ohlc=19818`, `invalid_vol=19812`, `dup_collapsed=47627`, `dup_conflict=404665`, `checked=4721305`, `within_tol=4673885`, `mismatched=47420`, `unchecked=4766767`, `max_rel_diff=0.130435`, `samples=100`
### `bench-fx`
Fixed-seed (`std`-only SplitMix64) benchmark over ~20,000 daily USD/CAD rows (~80% `CAD.FOREX`, ~20% `teMarketData.USDCAD` with an overlap window, interior gaps, post-EOD tail, injected bad/duplicate rows, and ~5% overlap mismatches), timing `build_fx_1d` plus `1,000,000` zero-allocation `fx_rate_on_or_before` lookups:
```bash
cargo run --release -p curate-etl --offline -- bench-fx [rows]
```
Command: `cargo run --release -p curate-etl --offline -- bench-fx`
- Input: `rows=20000`, `eod_rows=16000`, `te_rows=4000`
- Build: `rows_out=17172`, `eod_out=15336`, `te_out=1836`, `elapsed=0.741 ms`, `throughput=26993285 rows/s`, `latency=37.05 ns/row`
- Lookup: `lookups=1000000`, `hits=999224`, `elapsed=25.68 ms`, `throughput=38946650 lookups/s`, `latency=25.68 ns/lookup`, `checksum=0x21e746bd53f3e7ff` (identical across back-to-back runs)
- Stats: `eod_invalid=164`, `eod_inconsistent=170`, `eod_dup_collapsed=165`, `eod_dup_conflict=165`, `te_invalid=21`, `te_inconsistent=23`, `te_dup_collapsed=21`, `te_dup_conflict=34`, `te_superseded=2065`, `overlap_checked=2065`, `within_tol=1954`, `mismatched=111`, `max_overlap_rel=0.025000`
### `bench-shorts`
Fixed-seed (`std`-only SplitMix64) benchmark over `700,000` synthetic `ceoShorts` report rows across `12,500` `i32` `listing_id` keys on semi-monthly (15th and month-end) dates spanning `2017-04-15..=2026-04-30` with injected negative/NaN `shares_short`, non-finite optional fields, identical duplicates, and conflicting duplicates, timing only `build_shorts`:
```bash
cargo run --release -p curate-etl --offline -- bench-shorts [rows]
```
Command: `cargo run --release -p curate-etl --offline -- bench-shorts`
- Input: `rows=700000`, `keys=12500`
- Build: `rows_out=528426`, `keys_out=12500`, `elapsed=49.76 ms`, `throughput=14068555 rows/s`, `latency=71.08 ns/row`, `checksum=0x1a99126eaa1a519b` (identical across back-to-back runs)
- Stats: `invalid_shares=6915`, `nulled_net_change=3673`, `nulled_pct_float=3500`, `dup_collapsed=5352`, `dup_conflict=159307`
### `bench-events`
Fixed-seed (`std`-only SplitMix64) benchmark over `500,000` synthetic rows (~98.5% `qmFilings`, ~1.5% `qmEarnings`, mirroring `30.52M` filings / `444.9k` earnings) across `20,000` `i32` `listing_id` keys with EST/EDT/pre-2008/late-evening timestamps, all EDGAR/SEDAR+ form groups, linked + unlinked earnings, and injected malformed/skipped/duplicate/conflicting rows, timing only `build_events`:
```bash
cargo run --release -p curate-etl --offline -- bench-events [rows]
```
Command: `cargo run --release -p curate-etl --offline -- bench-events`
- Input: `rows=500000`, `filings=492500`, `earnings=7500`, `keys=20000`
- Build: `rows_out=491190`, `filings_out=484531`, `earnings_out=6659`, `keys_out=20000`, `elapsed=268.55 ms`, `throughput=1861871 rows/s`, `latency=537.09 ns/row`, `checksum=0xbf74cd745a2646c6` (identical across back-to-back runs)
- Stats: `malformed_ts=1525`, `unknown_zone=1496`, `invalid_dt=2476`, `filing_dup=2472`, `linked=2569`, `lagged_1605=4090`, `earnings_oor=37`, `earnings_dup=98`, `earnings_conflict=706`
- Extrapolation to full `30.52M` `qmFilings` + `444.9k` `qmEarnings` (`30,964,900` rows): ~`16.6 s` single-threaded CPU time (excluding MongoDB BSON streaming and Zstd Parquet I/O).
### `bench-provider-mapping`
Fixed-seed (`std`-only SplitMix64), zero-allocation lookup benchmark over `60,000` `(source, source_id)` keys across 4 sources (`eod`, `qm`, `ib`, `ceo`) with 10% multi-range keys (`6,000` keys with 2–3 date ranges and interior gaps modeling ticker reuse), shuffling `68,000` input rows before timing `ProviderMappingTable::from_rows` and running `10,000,000` `resolve` lookups (~5% misses across unknown key/source, pre-first, interior gap, and post-last):
```bash
cargo run --release -p curate-etl --offline -- bench-provider-mapping [lookups]
```
Command: `cargo run --release -p curate-etl --offline -- bench-provider-mapping`
- Table: `keys=60000`, `ranges=68000`, `multi_range_keys=6000`, `build=17.45 ms`, `throughput=3896541 rows/s`
- Lookup: `lookups=10000000`, `hits=9443294`, `misses=556706`, `elapsed=447.14 ms`, `throughput=22364140 lookups/s`, `latency=44.71 ns/lookup`, `checksum=0xad8536129cafb697` (identical across back-to-back runs)
### `bench-parquet-bars`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `5,000,000` sorted `Bars1dParquetRow` rows across `2,000` listings and 20 years (`2006..=2025`), writing `bars_1d/year=YYYY/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying Parquet footer row counts across all 20 files, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-bars [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-bars`
- Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84`
- Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000`
- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
### `bench-parquet-shorts`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `ShortsParquetRow` rows across `12,500` listings on semi-monthly dates (`2017-04-15..=2026-04-30`) with CIRO `+4` business-day `17:00 ET` `known_at` timestamps, writing `shorts/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-shorts [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-shorts`
- Input: `rows=1000000`, `listings=12500`, `raw_row_bytes=50`
- Output: `files=1`, `row_groups=1`, `bytes=6741816`, `read_back_rows=1000000`
- Perf: `elapsed=106.79 ms`, `throughput=9364116 rows/s`, `write=60.21 MB/s`, `size=6.74 bytes/row`, `compression=7.42x`
### `bench-parquet-events`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `500,000` sorted `EventsParquetRow` rows (~98.5% filings, ~1.5% linked/lagged earnings with ~150–300 byte `payload_json`) across `5,000` listings and 11 UTC years (`2015..=2025`), writing `events/year=YYYY/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying Parquet footer row counts across all 11 files, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-events [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-events`
- Input: `rows=500000`, `listings=5000`, `avg_raw_row_bytes=243.6`
- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000`
- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x`
### `bench-parquet-fx`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `Fx1dParquetRow` rows across `80` currency pairs on weekday dates (`1971..=2026`, mixing `eod_cad_forex` and `te_usdcad`), writing `fx_1d/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-fx [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-fx`
- Input: `rows=1000000`, `pairs=80`, `raw_row_bytes=70`
- Output: `files=1`, `row_groups=1`, `bytes=22102946`, `read_back_rows=1000000`
- Perf: `elapsed=228.82 ms`, `throughput=4370208 rows/s`, `write=92.12 MB/s`, `size=22.10 bytes/row`, `compression=3.17x`
### `bench-parquet-adj`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `AdjFactorsParquetRow` rows across `20,000` listings on weekday dates (`1990..=2025`, ~4% split-only with `None` `div_currency`, ~95% USD/CAD dividends, ~1% combined), writing `adj_factors/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-adj [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-adj`
- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=51`
- Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000`
- Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x`
### `bench-parquet-corporate-actions`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `CorporateActionsParquetRow` rows across `20,000` listings on weekday dates (`1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes), writing `corporate_actions/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions`
- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72`
- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000`
- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x`
### `bench-bson-eod-prices`
Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic `eodPrices` documents (including `_id`, `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON `DateTime` dates, and ~0.5% deterministic rejected rows) pre-encoded into one contiguous length-prefixed buffer up front, timing decode-only via `decode_eod_price_buffer`:
```bash
cargo run --release -p curate-etl --offline -- bench-bson-eod-prices [rows]
```
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d2746d1b5e3`): `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices`
- Input: `rows=1000000`, `bytes=285639152` (~272.4 MiB, ~285.6 bytes/doc)
- Decode: `decoded=995008`, `rejected=4992` (`missing=1985`, `empty=0`, `wrong_type=986`, `malformed_date=1027`, `invalid_number=994`, `corrupt=0`)
- Run 1: `elapsed=221.82 ms`, `throughput=4508210 rows/s`, `scan=1228.07 MB/s`, `latency=221.82 ns/row`, `checksum=0x05af9d2746d1b5e3`
- 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>`
- `decode_te_data_stream` / `decode_te_data_chunks` → `Result<BsonTeDataDecodeStats, BsonStreamError>` (borrowed historical `TeDataPoint<'a>` points only — `forecast` unread — with absolute `u64` error offsets)
- 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:
- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
- `qmPrices` OHLC cross-check
- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`)
- PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32`
- `rayon` parallel sharding across symbol/date partitions
- QuestDB ILP v2 writer for time-series ingestion
## `bars_1d` Curation Stage (`M1.2p` / `M1.2q`)
`curate_bars_1d` and `curate_and_write_bars_1d` (`src/curate_bars.rs`) join `build_bars_1d`, `ProviderMappingTable`, listing currency metadata, `session_close::et_session_close_utc_micros`, and `write_bars_1d_dataset` into contract `Bars1dParquetRow` records sorted and unique by `(listing_id, session_date)`.
1. **Field rules:**
- Calls `build_bars_1d` unchanged (raw OHLC passed through bit-for-bit, `volume = adj_volume / factor` via `SplitTable`, read-only `qmPrices.sharevolume` cross-check with `Bars1dStats` and `mismatch_samples` carried through untouched).
- Resolves `(mapping_source, source_id, session_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, caching the last `(listing_id, currency)` lookup per run).
- Stamps `ts_micros = known_at_micros = 16:00:00 America/New_York` (`16:00 ET`) converted to UTC microseconds via `session_close::et_session_close_utc_micros` (`21:00 UTC` in EST, `20:00 UTC` in EDT). Across `1976-01-01..=2030-12-31`, `America/New_York` and `America/Toronto` share identical DST rules across all three eras:
- `1976..=1986`: last Sunday of April → last Sunday of October.
- `1987..=2006`: first Sunday of April → last Sunday of October.
- `2007..=2030`: second Sunday of March → first Sunday of November.
Early-close half days still use `16:00 ET` (strictly later than the real close, so never look-ahead).
- Sets `vwap = None` and `source = "eod_unadj"` (`BARS_1D_SOURCE_EOD`).
2. **Drop & collision policy (never panics or aborts on bad rows):**
- Strict drop priority per built row:
1. `dropped_unmapped`: no `provider_mapping` range covers `(mapping_source, source_id, session_date)`.
2. `dropped_missing_currency`: `listing_id` absent from `listing_currencies` or maps to a blank string.
3. `dropped_ts_out_of_range`: `session_date` falls outside `session_close::et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window. The lower bound is deliberately `1976-01-01` because US emergency DST in `1974–1975` diverged from Toronto, so earlier dates drop here rather than guessing.
- After re-sorting in place by `(listing_id, session_date)`, cross-`source_id` collisions on the same `(listing_id, session_date)` collapse to one row when OHLCV is bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any OHLCV field differs (`listing_collision_dropped += g`).
- Exact conservation invariant in `CurateBars1dStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped`.
- Typed caller errors: `CurateBarsError` (`Bars(BarsError)`, `EmptyMappingSource`) and `CurateBarsWriteError` (`Curate(CurateBarsError)`, `Parquet(ParquetBarsError)`).
### `bench-curate-bars`
Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `eodPrices` bars across `2,000` `String` keys per `2,000,000`-row block (`2008..=2025` with unique per-key coprime-stride `(source_id, session_date)` pairs guarded against cursor wrap, plus in-range `1990..=2007`, pre-1976 out-of-range, explicitly injected builder duplicates, date-ranged ticker-reuse/unmapped, missing-currency, and cross-`source_id` collision slices, `2,000` splits per block, and ~50% `qmPrices` partners), separately timing in-memory `curate_bars_1d` and Zstd Parquet `write_bars_1d_dataset` into a temp directory with footer row-count verification and cleanup:
```bash
cargo run --release -p curate-etl --offline -- bench-curate-bars [rows]
```
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x098ac03b74d9899a`): `cargo run --release -p curate-etl --offline -- bench-curate-bars`
- Input: `rows=2000000`, `qm_rows=995681`, `splits=2000`, `keys=2000`
- Builder: `rows_out=1994014`, `invalid_ohlc=0`, `inconsistent_ohlc=0`, `invalid_vol=0`, `dup_collapsed=1930`, `dup_conflict_dropped=4056`
- Output: `rows_out=1947916` (`97.40%` retained), `listings_out=2000`, `files=36`, `row_groups=36`, `bytes=53241768`, `read_back_rows=1947916`
- Curation stats: `unmapped=17873`, `missing_curr=15129`, `ts_oor=3946`, `pre_2008_rows=39257`, `coll_collapsed=3066`, `coll_dropped=6084`, `mismatch_samples=100`
- Note: 846M-row single-core figures below are linear projections from the measured `2,000,000`-row batch at `97.40%` retention.
- Run 1:
- Stage (in-memory): `elapsed=1164.89 ms`, `throughput=1716906 rows/s`, `latency=582.44 ns/row`, single-core 846M projection `492.7 s` (`8.21 min`), `checksum=0x098ac03b74d9899a`
- Parquet write: `elapsed=698.34 ms`, `throughput=2789371 rows/s`
- Combined (stage → Parquet): `elapsed=1863.22 ms`, `throughput=1073410 rows/s`, single-core 846M projection `788.1 s` (`13.14 min`, projected at batch=`2000000` and `97.40%` retention)
- Run 2:
- Stage (in-memory): `elapsed=1181.40 ms`, `throughput=1692903 rows/s`, `latency=590.70 ns/row`, single-core 846M projection `499.7 s` (`8.33 min`), `checksum=0x098ac03b74d9899a`
- Parquet write: `elapsed=708.69 ms`, `throughput=2748627 rows/s`
- Combined (stage → Parquet): `elapsed=1890.09 ms`, `throughput=1058151 rows/s`, single-core 846M projection `799.5 s` (`13.33 min`, projected at batch=`2000000` and `97.40%` retention)
## `shorts` Curation Stage (`M1.2r`)
`curate_shorts` and `curate_and_write_shorts` (`src/curate_shorts.rs`) join `build_shorts`, `ProviderMappingTable`, and `write_shorts_dataset` into contract `ShortsParquetRow` records sorted and unique by `(listing_id, report_date)`.
1. **Field rules:**
- Calls `build_shorts` unchanged (finite `>= 0.0` `shares_short` validation, non-finite optional `net_change`/`pct_float` sanitization to `None`, `-0.0` normalization, same-`(key, report_date)` deduplication, `+4` Canadian TSX business-day CIRO lag, and `known_at_micros = 17:00:00 America/Toronto` UTC microseconds).
- Resolves `(mapping_source, key, report_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by `(key, report_date)`).
- **Point-in-time mapping boundary:** `provider_mapping` is resolved strictly on `report_date` (the reporting period the short position describes), not on `known_at_date` (`+4` TSX business days later).
- Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO = "ceo_shorts"`) as `Cow::Borrowed`.
2. **Drop & collision policy (never panics or aborts on bad rows):**
- Rows whose `(mapping_source, key, report_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`.
- After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`, `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any of those fields differ (`listing_collision_dropped += g`).
- Exact conservation invariant in `CurateShortsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped`.
- Typed caller errors: `CurateShortsError` (`Shorts(ShortsError)`, `EmptyMappingSource`) and `CurateShortsWriteError` (`Curate(CurateShortsError)`, `Parquet(ParquetShortsError)`). A curate error in `curate_and_write_shorts` returns before invoking `write_shorts_dataset`, leaving `out_dir` untouched.
### `bench-curate-shorts`
Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `ceoShorts` reports across `12,500` `String` keys per `1,000,000`-row block (`25,000` keys at `2,000,000` rows over the `218` semi-monthly dates `2017-04-15..=2026-04-30`, with per-key coprime-stride cursors guarded against exhaustion, date-ranged ticker reuse with an interior gap, unmapped keys, explicit builder duplicates, invalid `shares_short`/non-finite optional field slices, and identical/conflicting cross-key collisions), separately timing in-memory `curate_shorts` and Zstd Parquet `write_shorts_dataset` into a temp directory with footer row-count verification and cleanup:
```bash
cargo run --release -p curate-etl --offline -- bench-curate-shorts [rows]
```
Command (`2026-11-28`, two back-to-back runs with identical checksum `0xde3b3bd654c65ebe`): `cargo run --release -p curate-etl --offline -- bench-curate-shorts`
- Input: `rows=2000000`, `keys=25000`
- Builder: `rows_out=1990174`, `invalid_shares=4005`, `nulled_net_change=1953`, `nulled_pct_float=1956`, `dup_collapsed=1937`, `dup_conflict_dropped=3884`
- Output: `rows_out=1936876` (`96.84%` retained), `listings_out=25000`, `files=1`, `row_groups=2`, `bytes=17721340`, `read_back_rows=1936876`
- Curation stats: `unmapped=43484`, `coll_collapsed=3410`, `coll_dropped=6404`
- Run 1:
- Stage (in-memory): `elapsed=1091.40 ms`, `throughput=1832514 rows/s`, `latency=545.70 ns/row`, `checksum=0xde3b3bd654c65ebe`
- Parquet write: `elapsed=224.75 ms`, `throughput=8617888 rows/s`
- Combined (stage → Parquet): `elapsed=1316.15 ms`, `throughput=1519586 rows/s`
- Run 2:
- Stage (in-memory): `elapsed=1002.51 ms`, `throughput=1994998 rows/s`, `latency=501.25 ns/row`, `checksum=0xde3b3bd654c65ebe`
- Parquet write: `elapsed=228.03 ms`, `throughput=8494083 rows/s`
- Combined (stage → Parquet): `elapsed=1230.53 ms`, `throughput=1625311 rows/s`
## `events` Curation Stage (`M1.2s`)
`curate_events` and `curate_and_write_events` (`src/curate_events.rs`) join `build_events`, `ProviderMappingTable`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`.
1. **Field & Point-in-Time rules:**
- Runs `build_events` unchanged on source keys so same-day earnings↔filing linking (`8-K` / `News release`), form classification, timestamp parsing, conservative `16:05 ET` fallback, and per-key deduplication happen before `provider_mapping` resolution.
- Internally uses the crate-private `build_events_with_dates` helper (zero overhead on public `build_events`, unchanged `EventsParquetRow` schema) to carry each row's already-parsed Eastern local calendar date (`ParsedFilingTime::et_date` for filings; `QmEarning::report_date` for earnings) alongside the row.
- Resolves `(mapping_source, key, event_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) strictly on that Eastern local calendar date—covering pre-2008 historical filings and late-evening EST/EDT filings whose UTC date has rolled over—never on UTC date or `known_at` date.
- Moves `subtype` and `payload_json` without cloning, keeps `known_at_source` and `kind` as `Cow::Borrowed`, and frees builder rows before re-sorting.
2. **Drop & collapse policy (never panics or aborts on bad rows):**
- Rows whose `(mapping_source, key, event_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`.
- After re-sorting in place by the 7-field writer key, cross-`key` rows mapping to the same `listing_id` that are identical on all seven fields collapse to one row (`listing_duplicate_collapsed`), while rows differing in any single field are all kept.
- Exact conservation invariants in `CurateEventsStats`: `rows_in == builder.rows_out`, `rows_in == rows_out + dropped_unmapped + listing_duplicate_collapsed`, and `rows_out == filings_out + earnings_out`.
- Typed caller errors: `CurateEventsError::EmptyMappingSource` and `CurateEventsWriteError` (`Curate(CurateEventsError)`, `Parquet(ParquetEventsError)`). A curate error in `curate_and_write_events` returns before invoking `write_events_dataset`, leaving `out_dir` untouched.
### `bench-curate-events`
Fixed-seed (`std`-only SplitMix64) benchmark over `500,000` source-keyed rows (~98.5% `qmFilings`, ~1.5% `qmEarnings`) across `20,000` `String` source keys (`2003-01-01..=2026-04-30`, covering single-range keys, multi-range ticker reuse with an H2-2021 gap, alias keys for cross-key duplicates, unmapped keys, pre-2008 filings, late-evening ET rollovers, linked/unlinked earnings, and builder skips/duplicates), separately timing in-memory `curate_events` and Zstd Parquet `write_events_dataset` into a temp directory with footer row-count verification across all year partitions and cleanup:
```bash
cargo run --release -p curate-etl --offline -- bench-curate-events [rows]
```
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace6344e408`): `cargo run --release -p curate-etl --offline -- bench-curate-events`
- Input: `rows=500000`, `filings=492500`, `earnings=7500`, `keys=20000`
- Builder: `rows_out=493755`, `filings_out=487053`, `earnings_out=6702`, `malformed_ts=1011`, `unknown_zone=960`, `invalid_dt=1466`, `filing_dup=2010`, `linked=2556`, `lagged_1605=4146`, `earnings_oor=38`, `earnings_dup=102`, `earnings_conflict=658`
- Output: `rows_out=484402` (`96.88%` retained), `filings_out=477818`, `earnings_out=6584`, `listings_out=19997`, `files=24`, `row_groups=24`, `bytes=16057718`, `read_back_rows=484402`
- Curation stats: `unmapped=7713`, `dup_collapsed=1640`
- Run 1:
- Stage (in-memory): `elapsed=551.10 ms`, `throughput=907273 rows/s`, `latency=1102.20 ns/row`, `checksum=0x0a1b7ace6344e408`
- Parquet write: `elapsed=752.90 ms`, `throughput=643382 rows/s`
- Combined (stage → Parquet): `elapsed=1304.00 ms`, `throughput=383435 rows/s`
- Run 2:
- Stage (in-memory): `elapsed=589.24 ms`, `throughput=848550 rows/s`, `latency=1178.48 ns/row`, `checksum=0x0a1b7ace6344e408`
- Parquet write: `elapsed=682.82 ms`, `throughput=709419 rows/s`
- Combined (stage → Parquet): `elapsed=1272.06 ms`, `throughput=393065 rows/s`
## `posts` Curation Stage (`M2.2h`)
`curate_posts` and `curate_and_write_posts` (`src/curate_posts.rs`) join `build_posts`, `ProviderMappingTable`, `parquet_posts`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`.
1. **Contract & Eastern-posting-date mapping rules:**
- Validates that `mapping_source` is non-blank before consuming the input iterator (`CuratePostsError::EmptyMappingSource`), then runs `build_posts` unchanged on source keys so global `spiel_id` deduplication, `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard execute before listing resolution.
- **Mapping date (`posted_at` in `America/Toronto`):** resolves `(mapping_source, key, et_date) -> listing_id` where `et_date` is the Eastern local calendar date of `posted_at` computed via `session_close::utc_micros_to_et_local` (supported Eastern calendar range `1976-01-01..=2030-12-31`, i.e. `1976-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z`). Never uses the UTC date and never uses the `known_at` date, so a post edited days later stays on the listing active when it was posted while its text remains guarded by `known_at`.
- Uses one `ProviderMappingTable::cursor_for` per contiguous `key` run in each builder stream (`newswire`, then `retail`); because `build_posts` sorts by `(key, known_at, spiel_id)` rather than `posted_at`, backward `et_date` steps use `ProviderMappingCursor::resolve`'s binary-search fallback automatically.
- Converts each mapped `PostRow<i32>` via `EventsParquetRow::from` (reusing `parquet_posts` labels `kind = "post"`, `subtype = "newswire" | "retail"`, `known_at_source = "post_timestamp" | "post_edited"`, and its RFC 8259 `payload_json` encoder), then sorts in place by the 7-field writer key and collapses exact 7-field duplicates into `listing_duplicate_collapsed`.
- `curate_and_write_posts` publishes Zstd Parquet partitions to `<out_dir>/events/year=YYYY/part.parquet` (partitioned by UTC calendar year of `ts_micros`). Any `CuratePostsError` returns before `write_events_dataset` is called, leaving `out_dir` untouched.
2. **Drop policy & stats conservation invariants (`CuratePostsStats`):**
- Posts whose `posted_at` falls outside `utc_micros_to_et_local`'s supported range are dropped and counted in `dropped_unsupported_date` (checked before mapping coverage) without aborting or panicking.
- Posts whose `(mapping_source, key, et_date)` has no covering `provider_mapping` range are dropped into `dropped_unmapped`.
- Exact conservation invariants:
- `rows_in == builder.newswire + builder.retail`
- `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed`
- `rows_out == newswire_out + retail_out`
- Typed errors: `CuratePostsError` (`Posts(PostsError)`, `EmptyMappingSource`) and `CuratePostsWriteError` (`Curate(CuratePostsError)`, `Parquet(ParquetEventsError)`).
3. **Known limits & deferred work:**
- **Global `spiel_id` deduplication & `listing_duplicate_collapsed`:** because `build_posts` deduplicates globally on `spiel_id` (keeping the greatest `known_at` and breaking ties by the maximum `(posted_at, is_edited, is_bot, key, user_id, text)` tuple) and `payload_json` carries `spiel_id`, `listing_duplicate_collapsed` is expected to be `0` for real input and exists only as a defensive writer-key uniqueness guard; when the same `spiel_id` appears under two source keys, the surviving key is chosen by `build_posts`'s existing tie-break.
- **In-memory buffering:** both `build_posts` and the final 7-field sort buffer all rows in RAM; full-corpus memory and throughput over the 14.8M-row `ceoPosts` dataset remain unverified.
- **Separate output root (no co-publishing with `curate-events`):** `write_events_dataset` writes and replaces `<out_dir>/events/year=YYYY/part.parquet` partitions, so publishing curated posts alongside `curate-events` filings/earnings in the same `events/` directory is not handled here; pass a dedicated `out_dir` until a unified publisher exists.
- **Not done / deferred:** the `curate-posts` CLI subcommand, benchmark, live `ceoPosts` run/verification, and co-publishing posts with `curate-events` output remain deferred to follow-up tasks.
## `fx_1d` Curation Stage (`M1.2t`)
`curate_fx_1d` and `curate_and_write_fx_1d` (`src/curate_fx.rs`) join `build_fx_1d` and `write_fx_1d_dataset` into contract `Fx1dParquetRow` records sorted and unique by `session_date` (no `provider_mapping` lookup is needed because FX rows are keyed by `pair = "USDCAD"`, not `listing_id`).
1. **Field & timestamp rules:**
- Calls `build_fx_1d` unchanged (`CAD.FOREX` takes precedence on overlapping dates, `teMarketData.USDCAD` fills interior gaps and the post-EOD tail, the read-only 1% overlap cross-check runs untouched, and all `Fx1dStats` counters are carried through unchanged).
- Maps every `Fx1dRow` via `Fx1dParquetRow::from_fx_row` with zero per-row heap allocation (`pair = "USDCAD"` and `source` ∈ `{"eod_cad_forex", "te_usdcad"}` stay `Cow::Borrowed`), preserving the strictly ascending, unique `session_date` order.
- **Conservative no-look-ahead timestamp rule:** stamps every row with `ts_micros = known_at_micros = (session_date + 1) * FX_1D_MICROS_PER_DAY - 1` (`23:59:59.999999 UTC` of `session_date`, offset `FX_1D_TS_OFFSET_MICROS_FROM_DAY_START = 86_399_999_999` from UTC midnight) via `fx_1d_utc_day_end_micros`. Neither `CAD.FOREX` nor `teMarketData.USDCAD` documents its daily FX cutoff, so the last microsecond of the UTC day is the conservative no-look-ahead choice (same-day `16:00 ET` equity close signals resolve to the prior UTC day's bar), satisfies `parquet_fx`'s `TsOutsideSessionDate` and `KnownAtBeforeTs` checks, and requires no DST table for `1971–1975` (outside `session_close.rs`'s `1976–2030` window).
2. **Accounting & error handling:**
- Exact conservation invariant in `CurateFx1dStats`: `rows_in == builder.rows_out == rows_out`, with `stats.builder` bit-identical to calling `build_fx_1d` directly.
- Checked `i64` arithmetic: any `session_date` whose UTC day-end microsecond timestamp overflows `i64` (`session_date >= 106_751_991` or `session_date <= -106_751_993`, including `i32::MAX` / `i32::MIN`) returns `CurateFxError::SessionDateOutOfRange { session_date }` without panicking or wrapping.
- `curate_and_write_fx_1d` runs `curate_fx_1d` before invoking `write_fx_1d_dataset`, so any `CurateFxError` leaves `out_dir` untouched (and surfaces via `CurateFxWriteError::{Curate, Parquet}`).
3. **Still out of scope:**
- Live MongoDB cursor / BSON decoders for `CAD.FOREX` and `teMarketData.USDCAD` documents
- Intraday `fx_1m` curation
### `bench-curate-fx`
Fixed-seed (`std`-only SplitMix64) benchmark over `20,000` (default; real dataset is ~15k rows) or `[rows]` daily USD/CAD bars (~80% `CAD.FOREX`, ~20% `teMarketData.USDCAD` with overlap window, interior EOD gaps, post-EOD TE tail, and injected invalid/inconsistent/duplicate rows), separately timing in-memory `curate_fx_1d` and Zstd Parquet `write_fx_1d_dataset` into a temp directory with footer row-count verification and cleanup:
```bash
cargo run --release -p curate-etl --offline -- bench-curate-fx [rows]
```
1. Default run (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-curate-fx`
- Input: `rows=20000`, `eod_rows=16000`, `te_rows=4000`
- Builder: `rows_out=17180` (`eod_out=15341`, `te_out=1839`, `eod_invalid=164`, `eod_inconsistent=178`, `eod_dup_collapsed=145`, `eod_dup_conflict=172`, `te_invalid=18`, `te_inconsistent=26`, `te_dup_collapsed=27`, `te_dup_conflict=14`)
- Stage (in-memory): `rows_out=17180` (`85.90%` retained), `elapsed=1.070 ms`, `throughput=18683801 rows/s`, `latency=53.52 ns/row`, `checksum=0x298f47e68cdf7022`
- Parquet write: `files=1`, `row_groups=1`, `bytes=714498`, `read_back_rows=17180`, `elapsed=16.691 ms`, `throughput=1029303 rows/s`
- Combined (stage → Parquet): `elapsed=17.761 ms`, `throughput=1126041 rows/s`
- Overlap: `te_superseded=2076`, `checked=2076`, `within_tol=1979`, `mismatched=97`, `max_overlap_rel=0.025000`
2. 1M-row run (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-curate-fx 1000000`
- Input: `rows=1000000`, `eod_rows=800000`, `te_rows=200000`
- Builder: `rows_out=859916` (`eod_out=767923`, `te_out=91993`, `eod_invalid=8245`, `eod_inconsistent=8035`, `eod_dup_collapsed=7794`, `eod_dup_conflict=8003`, `te_invalid=1214`, `te_inconsistent=1198`, `te_dup_collapsed=1213`, `te_dup_conflict=1213`)
- Stage (in-memory): `rows_out=859916` (`85.99%` retained), `elapsed=59.652 ms`, `throughput=16763900 rows/s`, `latency=59.65 ns/row`, `checksum=0x2a2f2665b32d8ae0`
- Parquet write: `files=1`, `row_groups=1`, `bytes=27440094`, `read_back_rows=859916`, `elapsed=215.804 ms`, `throughput=3984706 rows/s`
- 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)`.
1. **Field & timestamp rules:**
- Calls `build_corporate_actions` unchanged (`1:1` split no-ops, `0.0` cash dividends, and delistings without an outcome drop inside the builder; same-key multi-dividends stay separate; late declarations clamp to `ex_date` with `KnownAtSource::ExDateFallback`; local `currency` is preserved).
- Resolves `(mapping_source, key, ex_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) for `split`, `dividend`, and terminal `delisting` rows.
- For `otc_delist_transfer` rows, Pass 6 anchors `ex_date` (and `known_at`) to `effectiveDate` (the successor's first OTC trading date), which normally falls after the outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` starts `2023-03-28`) and may coincide with ticker reuse. `otc_delist_transfer` therefore requires Pass 6's outgoing listing identity via `CurateDelistingInput::from_listing_id` (`Some(id)`): curation selects only a `provider_mapping` range for `(mapping_source, key)` with `valid_from <= ex_date` and `listing_id == id` (never attaching to an unrelated ticker occupant), and any identity-less `otc_delist_transfer` (`from_listing_id = None`) drops into `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to `successor_listing_id`. Never emits an `otc_delist_transfer` with `successor_listing_id = None` or `successor_listing_id == listing_id`.
- Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source corporate-action records carry no intraday announcement time) and carries `known_at_source` through unchanged.
- Carries `ex_date`, `declared_date`, `kind`, `ratio`, `cash_amount`, `currency`, and `terminal_return` through bit-exactly (`"USD"`/`"CAD"` interned as `Cow::Borrowed`).
2. **Drop & collision policy (never panics or aborts on bad rows):**
- Strict drop priority per built row:
1. `dropped_unmapped`: no covering `provider_mapping` range for `(mapping_source, key, ex_date)` (or, for `otc_delist_transfer`, missing `from_listing_id = None` or no range with `valid_from <= ex_date` matching `from_listing_id = Some(id)`; or, for terminal `delisting` with `from_listing_id = Some(id)`, active occupant does not match `id`).
2. `dropped_unmapped_successor`: `otc_delist_transfer` whose `successor_key` has no covering range on `ex_date`.
3. `dropped_self_successor`: `otc_delist_transfer` whose `successor_key` resolves to the row's own `listing_id`.
4. `dropped_known_at_out_of_range`: `known_at_date` falls outside `et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window.
- After re-sorting deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`):
- Cross-key conflicting `split` ratios on the same `(listing_id, ex_date)` (`> 1` source key and `> 1` distinct `ratio` bit pattern) drop the entire group (`listing_collision_dropped`).
- Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount same-day regular + special dividends) while collapsing cross-key aliases.
- Exact conservation invariant in `CurateCorporateActionsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`.
- Typed caller errors: `CurateCorporateActionsError` (`CorporateAction(CorporateActionError)`, `EmptyMappingSource`) and `CurateCorporateActionsWriteError` (`Curate(CurateCorporateActionsError)`, `Parquet(ParquetCorporateActionsError)`). A curate error in `curate_and_write_corporate_actions` returns before invoking `write_corporate_actions_dataset`, leaving `out_dir` untouched.
### `bench-curate-corporate-actions`
Fixed-seed (`std`-only SplitMix64) benchmark over `520,000` source-keyed corporate-action events (~3.6% splits ≈20.3k incl. `1:1` no-ops and alias collisions, ~95.4% USD/CAD dividends ≈494.6k incl. `0.0` drops and same-day multi-dividends, ~1.0% delisting outcomes ≈5.1k incl. OTC transfers and `-0.3`/`-1.0`/no-outcome) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps, aliases, unmapped/self successors, and pre-1976 dates, separately timing in-memory `curate_corporate_actions` and Zstd Parquet `write_corporate_actions_dataset` into a temp directory with footer row-count verification and cleanup:
```bash
cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions [events]
```
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1ab7caad4`): `cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions`
- Input: `events=520000`, `splits=20262`, `dividends=494624`, `delistings=5114`, `keys=20000`
- Builder: `rows_out=514224`, `splits_out=19938`, `split_noops=324`, `divs_out=489671`, `zero_div=4953`, `otc_out=2856`, `delist_out=1759`, `delist_no_outcome=499`
- Output: `rows_out=494518` (`95.10%` retained), `listings_out=19996`, `files=1`, `row_groups=1`, `bytes=3802001`, `read_back_rows=494518`
- Curation stats: `unmapped=12886`, `unmapped_succ=511`, `self_succ=531`, `known_at_oor=2526`, `coll_collapsed=1398`, `coll_dropped=1854`
- Run 1:
- Stage (in-memory): `elapsed=278.66 ms`, `throughput=1866040 events/s`, `latency=535.89 ns/event`, `checksum=0x0c22a1a1ab7caad4`
- Parquet write: `elapsed=84.14 ms`, `throughput=5877527 rows/s`
- Combined (stage → Parquet): `elapsed=362.80 ms`, `throughput=1433288 events/s`
- Run 2:
- Stage (in-memory): `elapsed=284.33 ms`, `throughput=1828877 events/s`, `latency=546.78 ns/event`, `checksum=0x0c22a1a1ab7caad4`
- Parquet write: `elapsed=87.57 ms`, `throughput=5647404 rows/s`
- Combined (stage → Parquet): `elapsed=371.89 ms`, `throughput=1398252 events/s`
## `curate-bars-1d` Command (`M1.2z` / `M1.2ah` / `M1.2ai`)
End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, optional `decode_qm_price_chunks` (`src/bson_qm_prices.rs`), `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` (with `rayon` year-sharded parallel Zstd Parquet encoding) into `<out>/bars_1d/year=YYYY/part.parquet` with no database connections.
### Invocation
```bash
curate-etl curate-bars-1d \
--eod-prices <path> # concatenated raw BSON (mongodump eodPrices.bson)
--qm-splits <path> # concatenated raw BSON (mongodump qmSplits.bson)
[--qm-prices <path>] # optional concatenated raw BSON (qmPrices.bson) for read-only sharevolume cross-check
--curate-inputs <dir> # exporter output dir (pins <dir>/current once before opening TSVs)
--out <dir> # dataset root -> bars_1d/year=YYYY/part.parquet
[--rel-tolerance <f64>] # default: 0.01
[--threads <N>] # default: available_parallelism() (1 = bounded-RAM sequential write)
```
Instead of `--curate-inputs <dir>`, standalone TSV files may be passed directly with `--provider-mapping <path> --listing-currencies <path>` (mutually exclusive with `--curate-inputs`). When reading from a live exporter output directory, always prefer `--curate-inputs <dir>` so `curate-bars-1d` pins `<dir>/current` once before opening either TSV and cannot mix generations across a concurrent refresh.
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`. Volume cross-check mismatches never fail the run (exit code `0`) and never modify emitted Parquet bytes.
### `qmPrices` Raw BSON Decoder (`src/bson_qm_prices.rs`)
- **Documented field names & raw-volume semantics** (`prices.action.ts:97-109`, `bar-spans.ts:19-24`, `sample-closes.ts:300-303`, `design/DATA-CONTRACTS.md` §1): `qmPrices` stores QuoteMedia daily bars keyed by `qmSearchCode` with provider date field `date` (and a separate BSON `Date` in `dateTime`) and unadjusted share volume in `sharevolume`.
- **Accepted BSON types (live `qmPrices` date format and numeric type distribution remain unverified against QA MongoDB):**
- `qmSearchCode`: BSON UTF-8 `String` borrowed verbatim (never trimmed; empty/whitespace-only rejected as `EmptyField`).
- `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via `parse_ymd_strict_days` (non-string `date` — including BSON `DateTime` — is rejected as `WrongType` and counted in `qm_bson.rejected`; bad format/calendar strings are rejected as `MalformedDate`).
- `sharevolume`: BSON `Double`, `Int32`, or `Int64` converted to `f64`. Numeric domain validity (negative / non-finite) is passed through to `build_bars_1d` (`qm_invalid_volume_dropped`); missing, `Null`, or non-numeric types are rejected with counted reasons.
- All extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, nested docs/arrays) are skipped without calling `elem.value()`.
- **Accounting invariant:** `docs_in == decoded + rejected_total()` (`rejected_missing_field + rejected_empty_field + rejected_wrong_type + rejected_malformed_date + rejected_corrupt_document`).
### TSV Formats (strict, headerless, `\t`-separated)
- `provider_mapping`: `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
- `source` and `source_id` are preserved verbatim (never trimmed); blank/whitespace-only values are rejected.
- Dates are parsed strictly with `YYYY-MM-DD` Gregorian validation; `listing_id` must be a strict positive ASCII integer.
- `listing_currencies`: `listing_id \t currency`
- Unique positive `listing_id` per row; non-blank currency code (`"USD"` and `"CAD"` are interned).
- Both files accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number.
### Split Re-Keying, `qmPrices` Re-Keying, Early Filter & Missing-Currency Policy
1. **Split re-keying (`qmSearchCode` → `eodSearchCode`):** Each decoded `qmSplits` row with `ratio != 1.0` resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable`. Before fanning out to `"eod"` partners, mapped splits are compacted by `(listing_id, ex_date)` using the same cross-key policy as `curate_adj_factors`: single-QM-key same-day groups pass through unchanged, multi-QM-key alias groups with bitwise-identical ratios collapse to one event (`splits_collision_collapsed`), and multi-QM-key groups with conflicting ratios fail closed (`ConflictingCrossKeySplit`). Surviving events are attached to every deduplicated `"eod"` `source_id` pointing at that `listing_id` (preventing ratio squaring when one `(listing_id, eod_source_id)` spans multiple date ranges). No ticker-text guessing is performed.
2. **Date-aware `qmPrices` volume re-keying (optional `--qm-prices`):** Each decoded `qmPrices` row resolves `("qm", qmSearchCode, session_date) -> listing_id` via `ProviderMappingTable`, then fans out only to `"eod"` `source_id`s whose mapping range covers `session_date` (reusing interned `Arc<str>` EOD keys; no ticker-text guessing, so reused EOD tickers never receive volumes from another occupant). Unmapped QM keys and QM rows whose `listing_id` has no date-covering `"eod"` partner are early-filtered before buffering into `qm_unmapped_qm` and `qm_no_eod_partner`. When `--qm-prices` is omitted, no reverse range index is built and `qm_volumes` stays empty.
3. **Early filter & key interning:** While streaming `eodPrices`, bars whose `eodSearchCode` has no `"eod"` range in `provider_mapping` are dropped before buffering (`bars_unmapped_source_dropped`). Retained bars share interned `Arc<str>` keys rather than allocating a `String` per bar.
4. **Missing-currency behavior:** Delegated unchanged to `curate_bars_1d` — mapped listings absent from `--listing-currencies` (or blank) are dropped into `dropped_missing_currency` without failing the run.
### Report Counters & Conservation Invariants
On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, `qm_check: qm_prices=absent` when `--qm-prices` is omitted or `qm_bson` / `qm_rekey` / `qm_check` + up to `100` `qm_mismatch` lines when supplied, `config: threads=<N>`, and `timing`):
- `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_bson.rejected`
- `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
- `eod_bson.decoded == write.rows_written + bars_unmapped_source_dropped + builder.(invalid_ohlc + inconsistent_ohlc + invalid_vol + dup_collapsed + dup_conflict_dropped) + curate.(dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped)`
- When `--qm-prices` is provided:
- `qm_bson.docs_framed == qm_bson.docs_in == qm_bson.decoded + qm_bson.rejected`
- `qm_rekey.qm_in == qm_rekey.qm_attached + qm_rekey.qm_unmapped_qm + qm_rekey.qm_no_eod_partner + qm_bson.rejected`
- `qm_rekey.qm_volumes_attached == qm_check.qm_rows_in`
- `qm_check.volume_checked + qm_check.volume_unchecked == builder.rows_out`
- `qm_check.volume_within_tolerance + qm_check.volume_mismatched == qm_check.volume_checked`
### `bench-curate-bars-cmd`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `qmPrices.bson` (matching `Double`/`Int32`/`Int64` `sharevolume` partners, unmapped QM keys, QM keys with no EOD partner, wrong-typed `sharevolume` rejects, and exact injected >1% divergences), `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / qm decode+rekey / curate / sequential (`threads=1`, `write_1`) vs parallel (`threads=available_parallelism()`, `write` + `speedup`) Parquet writes on the exact same curated rows, verifying Parquet footer row counts for both outputs, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows]
```
Single-threaded baseline measured locally (`2026-11-29`, prior to `rayon` parallel write; multi-thread `write_1` vs `write` numbers pending first unsandboxed release run after `rayon = "=1.12.0"` is fetched):
1. **1,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000`):
- Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `qm_docs=227439`, `qm_bytes=20815907` (19.9 MiB), `keys=2000`
- Decode (all inputs): `elapsed=234.63 ms`, `throughput=4262081 rows/s`, `scan=742.58 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`)
- QM decode + rekey: `elapsed=31.93 ms`, `throughput=7123258 docs/s`, `scan=621.74 MB/s`, `attached=224939`, `unmapped=1000`, `no_eod_partner=1000`, `rejected=500`, `checked=224939`, `within_tol=222689`, `mismatched=2250 (injected=2250)`, `unchecked=755021`, `samples=100`
- Curate: `elapsed=208.07 ms`, `throughput=4709887 rows/s`, `rows_out=938023` (`93.80%` retained), `listings_out=1941`, `unmapped=595`, `missing_curr=9500`, `ts_oor=1842`, `coll_collapsed=10000`, `coll_dropped=20000`
- Write: `elapsed=456.39 ms`, `throughput=2055293 rows/s`, `write=53.70 MB/s`, `files=36`, `row_groups=36`, `bytes=25699104`, `read_back_rows=938023`
- Total: `elapsed=899.09 ms`, `throughput=1112231 rows/s`, `throughput_mb=193.78 MB/s`, `splits_applied=1699`, `splits_coll_collapsed=40`, `splits_unmapped_qm=101`, `splits_no_eod_partner=100`, `splits_noop=100`
2. **5,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000`):
- Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4080`, `splits_bytes=376160`, `qm_docs=1138361`, `qm_bytes=104186437` (99.4 MiB), `keys=6000`
- Decode (all inputs): `elapsed=1167.06 ms`, `throughput=4284272 rows/s`, `scan=746.08 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`)
- QM decode + rekey: `elapsed=171.72 ms`, `throughput=6629277 docs/s`, `scan=578.63 MB/s`, `attached=1125861`, `unmapped=5000`, `no_eod_partner=5000`, `rejected=2500`, `checked=1125861`, `within_tol=1114602`, `mismatched=11259 (injected=11259)`, `unchecked=3773805`, `samples=100`
- Curate: `elapsed=1119.70 ms`, `throughput=4376207 rows/s`, `rows_out=4691865` (`93.84%` retained), `listings_out=5822`, `unmapped=2879`, `missing_curr=48328`, `ts_oor=9132`, `coll_collapsed=49206`, `coll_dropped=98256`
- Write: `elapsed=1238.26 ms`, `throughput=3789066 rows/s`, `write=79.75 MB/s`, `files=36`, `row_groups=36`, `bytes=103552480`, `read_back_rows=4691865`
- Total: `elapsed=3525.02 ms`, `throughput=1418430 rows/s`, `throughput_mb=247.01 MB/s`, `splits_applied=3399`, `splits_coll_collapsed=80`, `splits_unmapped_qm=201`, `splits_no_eod_partner=200`, `splits_noop=200`
### Known Limits
- **Full in-RAM buffering of mapped bars (and optional QM volumes) + parallel year-bucketing RAM:** `curate-bars-1d` buffers every mapped bar in `Vec<EodDailyBar<Arc<str>>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume<Arc<str>>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). When `--threads > 1`, Pass 1 of `write_bars_1d_dataset` buckets validated `Bars1dParquetRow`s by year (`~136 B/row` struct size plus `Vec` growth slack, `~180–200 B/row` transient overhead before the caller's `curated.rows` vector drops) and holds up to `min(threads, years)` concurrent `RowGroupBuffer`s during parallel Zstd encoding (each year's bucket drops as soon as its worker finishes). Pass `--threads 1` to use the bounded-RAM single-pass streaming writer. For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB.
- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism currently covers the `curate-bars-1d` Parquet write stage (`--threads`); parallel BSON decode, parallel curate/sort, other `curate-*` commands, and direct MongoDB cursors remain deferred to follow-up tasks.
- **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable<K>` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`.
- **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild.
## `curate-adj-factors` Command (`M1.2aa`)
End-to-end file-to-Parquet CLI command (`src/run_curate_adj.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a column-projected `bars_1d` Parquet reader for strict pre-ex-date `prev_close`, and `curate_and_write_adj_factors` into an atomically published `<out>/adj_factors/part.parquet` retrospective snapshot with zero extra crates and no database connections.
### Invocation
```bash
curate-etl curate-adj-factors \
--qm-splits qmSplits.bson \
--qm-dividends qmDividends.bson \
--provider-mapping provider_mapping.tsv \
--bars-1d ./out/bars_1d \
--out ./out
```
Inputs and output:
- `--qm-splits <path>`: concatenated raw BSON (`mongodump` `qmSplits.bson`).
- `--qm-dividends <path>`: concatenated raw BSON (`mongodump` `qmDividends.bson`).
- `--provider-mapping <path>`: headerless 5-column TSV (same format as `curate-bars-1d`).
- `--bars-1d <dir>`: `bars_1d` directory containing `year=YYYY/part.parquet` (or parent root containing `bars_1d/`).
- `--out <dir>`: dataset root where `adj_factors/part.parquet` is atomically published.
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate, or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, missing/invalid `--bars-1d` directory, missing/wrong-schema/corrupt `part.parquet`, duplicate `(listing_id, session_date)` in `bars_1d`, malformed `provider_mapping.tsv` reporting 1-based line number, truncated/oversized BSON stream, or cross-key split/dividend curation conflict) prints a single-line stderr message naming the offending path, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/adj_factors/part.parquet` byte-identical).
### `prev_close` Lookup & Contract Rules
- **Column-projected `bars_1d` reader:** validates every discovered `year=YYYY/part.parquet` against `bars_1d_parquet_schema()` and reads only 4 of the 12 columns (`listing_id`, `session_date`, `close`, `currency`) in bounded `65,536`-row batches into a compact in-RAM index (`16 bytes/bar`, currency strings interned to `u16`).
- **Strict pre-ex-date boundary:** for each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable` and attaches the raw `close` and `currency` of the last `bars_1d` session strictly before `ex_date` (`session_date < ex_date`; a bar on `ex_date` itself is never used). When no earlier bar exists (or the dividend is unmapped), `prev_close` and `prev_close_currency` are `None`.
- **`usdFxRate` & `splitratio == 1`:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op handling and cross-key collision rules stay delegated unchanged to `curate_and_write_adj_factors`. Per-document BSON decode rejects are counted without aborting the run.
### Report Counters & Conservation Invariants
On success, `curate-adj-factors` prints deterministic `key=value` lines to stdout (`bars_1d`, `splits_bson`, `dividends_bson`, `prev_close`, `builder`, `curate`, `write`, and `timing`):
- **Splits:** `splits_bson.docs_framed == splits_bson.docs_in == splits_bson.rejected + curate.splits_unmapped + curate.splits_fenced + curate.splits_coll_collapsed + builder.splits_in`
- **Dividends:** `dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.rejected + curate.divs_unmapped + curate.divs_fenced + curate.divs_coll_collapsed + builder.dividends_in`
- **Dividend `prev_close` partition:** `dividends_bson.decoded == prev_close.with_prev_close + prev_close.without_prev_close + curate.divs_unmapped`
### `bench-curate-adj-cmd`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv`, a 16-year `bars_1d` Parquet dataset (`2010..=2025`, `62,720` bars across `3,920` mapped listings), `qmSplits.bson` (~4% of events incl. `1:1` no-ops, unmapped, identical cross-key aliases, and ~0.5% malformed decode rejects), and `qmDividends.bson` (~96% of events incl. USD/CAD with bogus `usdFxRate: 1`, `cash == 0.0`, unmapped, identical cross-key aliases, pre-first-bar dates for missing `prev_close`, currency mismatches, and ~0.5% malformed decode rejects) into a temp dir, timing `bars_load` / `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd [events]
```
Measured locally (`2026-11-29`):
1. **100,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd 100000`):
- Input: `events=100000`, `splits_docs=4000` (`422,398 B`), `dividends_docs=96000` (`11,592,112 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000`
- `bars_load`: `elapsed=3.69 ms`, `throughput=17006461 bars/s` (`listings=3920`)
- `decode`: `elapsed=31.13 ms`, `throughput=3211920 events/s`, `scan=368.02 MB/s`, `splits_rejected=20`, `divs_rejected=453`, `with_prev_close=89914`, `without_prev_close=2792`
- `curate`: `elapsed=36.62 ms`, `throughput=2717561 events/s`, `rows_out=88215` (`88.22%` retained), `listings_out=3920`, `checksum=0xdacf704be0642aff`
- `write`: `elapsed=24.36 ms`, `throughput=3621493 rows/s`, `write=49.47 MB/s`, `files=1`, `row_groups=1`, `bytes=1263546`, `read_back_rows=88215`
- `total`: `elapsed=95.80 ms`, `throughput=1043793 events/s`, `checksum=0xdacf704be0642aff`
2. **500,000 events** (default; two back-to-back runs with identical checksum `0x16b8d07222f35849`): `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd`
- Input: `events=500000`, `splits_docs=20000` (`2,112,208 B`), `dividends_docs=480000` (`57,960,382 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000`
- Output: `rows_out=431459` (`86.29%` retained), `listings_out=3920`, `files=1`, `row_groups=1`, `bytes=5539481`, `read_back_rows=431459`
- Run 1: `bars_load=3.76 ms` (`16,702,636 bars/s`), `decode=129.61 ms` (`3,857,829 events/s`, `442.03 MB/s`), `curate=283.10 ms` (`1,758,001 events/s`), `write=84.42 ms` (`5,111,126 rows/s`, `62.58 MB/s`), `total=500.88 ms` (`998,252 events/s`), `checksum=0x16b8d07222f35849`
- Run 2: `bars_load=3.73 ms` (`16,832,966 bars/s`), `decode=125.40 ms` (`3,987,232 events/s`, `456.85 MB/s`), `curate=228.61 ms` (`2,177,036 events/s`), `write=79.17 ms` (`5,449,842 rows/s`, `66.73 MB/s`), `total=436.90 ms` (`1,144,419 events/s`), `checksum=0x16b8d07222f35849`
### Known Limits
- **Retrospective snapshot only:** `curate-adj-factors` publishes an unfenced `AdjSnapshotKind::RetrospectiveSnapshot` whose earlier cumulative factors embed later splits/dividends. Point-in-time readers (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically; use `curate_and_write_adj_factors_as_of` when a point-in-time or vault-fenced snapshot is required.
- **In-RAM `bars_1d` close index:** loading `bars_1d` into `PrevCloseIndex` takes `16 bytes/bar` (plus `Vec` growth slack, ~1.6–2.5 GiB for 100M bars).
- **Single-threaded file-to-file execution:** no `rayon` sharding or direct MongoDB/PostgreSQL connections yet.
## `curate-corporate-actions` Command (`M1.2ab`)
End-to-end file-to-Parquet CLI command (`src/run_curate_corporate_actions.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a strict Pass 6 `delistings.tsv` loader (`load_delistings_tsv`), and `curate_and_write_corporate_actions` into an atomically published `<out>/corporate_actions/part.parquet` dataset with zero extra crates and no database connections.
### Invocation
```bash
curate-etl curate-corporate-actions \
--qm-splits qmSplits.bson \
--qm-dividends qmDividends.bson \
--curate-inputs ./tmp/curate-inputs \
--out ./out
```
Inputs and output:
- `--qm-splits <path>`: concatenated raw BSON (`mongodump` `qmSplits.bson`).
- `--qm-dividends <path>`: concatenated raw BSON (`mongodump` `qmDividends.bson`).
- `--curate-inputs <dir>`: exporter output directory containing a committed `current` link. Requires `<dir>/current` and resolves it once via `canonicalize` before opening `provider_mapping.tsv` and `delistings.tsv` so both files always come from the same atomic PostgreSQL snapshot even if an export refreshes `current` concurrently. Fails closed if `current` is absent (use `--provider-mapping` / `--delistings` for standalone files or direct generation paths). Mutually exclusive with `--provider-mapping` and `--delistings`.
- `--provider-mapping <path>` / `--delistings <path>` *(alternative to `--curate-inputs`)*: standalone headerless 5-column TSVs (`--delistings` is optional when using explicit TSV paths; when omitted, zero delisting rows are loaded).
- `--out <dir>`: dataset root where `corporate_actions/part.parquet` is atomically published.
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--delistings`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, malformed `provider_mapping.tsv` or `delistings.tsv` reporting path + 1-based line number, overlapping mapping ranges, truncated/corrupt/oversized BSON stream carrying byte offset, or unwritable `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/corporate_actions/part.parquet` byte-identical).
### TSV Formats (strict, headerless, `\t`-separated)
- `provider_mapping` (5 columns; identical to `curate-bars-1d`):
`source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
- `delistings` (optional file; 5 columns when supplied):
`source_id \t delist_date(YYYY-MM-DD) \t from_listing_id(int or empty) \t successor_source_id(or empty) \t terminal_return(float or empty)`
- `source_id` is preserved verbatim (never trimmed) and must not be empty or whitespace-only.
- `delist_date` is parsed strictly with `YYYY-MM-DD` Gregorian validation.
- `from_listing_id` is empty (`None`) or a strict positive ASCII base-10 `i32`.
- `successor_source_id` is empty (`None`) or a non-blank string preserved verbatim.
- `terminal_return` is empty (`None`) or a finite `f64` in `[-1.0, 0.0]` with no leading/trailing whitespace (`-0.0` is normalized to `0.0`).
- Exactly one of `successor_source_id` or `terminal_return` must be set on every row.
- Any row with `successor_source_id` set (OTC transfer) requires `from_listing_id` to be set.
- Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number.
### `declared_date` / `known_at`, `usdFxRate` & Empty-Input Rules
- **`declared_date` & `known_at`:** `RawQmSplit::to_split_action_event` and `RawQmDividend::to_dividend_action_event` carry `declared_date` from the raw BSON `declared` field when present. Downstream `build_corporate_actions` clamps late declarations (`declared_date > ex_date`) to `ex_date` with `KnownAtSource::ExDateFallback`, and `curate_corporate_actions` stamps `known_at = 16:00:00 ET` of `known_at_date` (`1976-01-01..=2030-12-31`).
- **`usdFxRate` & no-ops:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1.0` no-op drops, `cash == 0.0` dividend drops, and cross-key collision rules stay delegated unchanged to `curate_and_write_corporate_actions`. Per-document BSON decode rejects are counted without aborting the run.
- **Empty-input behavior:** delegated unchanged to `curate_and_write_corporate_actions` / `write_corporate_actions_dataset`, which returns `Ok` with `rows_written == 0` and `files_written == 0` without creating `<out>/corporate_actions` or modifying any pre-existing `part.parquet` (matching `curate-bars-1d`).
### Report Counters & Conservation Invariants
On success, `curate-corporate-actions` prints deterministic `key=value` lines to stdout (`splits_bson`, `dividends_bson`, `delistings_tsv`, `builder`, `curate`, `write`, and `timing`):
- **Splits:**
`splits_bson.docs_framed == splits_bson.docs_in == splits_bson.decoded + splits_bson.rejected`
`splits_bson.decoded == builder.splits_in == builder.splits_out + builder.split_noops`
- **Dividends:**
`dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.decoded + dividends_bson.rejected`
`dividends_bson.decoded == builder.dividends_in == builder.dividends_out + builder.zero_div`
- **Delistings:**
`delistings_tsv.rows_loaded == builder.delistings_in == builder.otc_out + builder.delistings_out` (`builder.delist_no_outcome == 0` under strict TSV validation)
- **Stage & Write:**
`curate.rows_in == builder.rows_out == curate.rows_out + curate.unmapped + curate.unmapped_succ + curate.self_succ + curate.known_at_oor + curate.coll_collapsed + curate.coll_dropped`
`write.rows_written == curate.rows_out`
### `bench-curate-corporate-actions-cmd`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (20,000 keys with single-range, ended primary-venue listings for OTC transfer testing, ticker-reuse gaps, aliases, unmapped keys, and 500 OTC successors), `qmSplits.bson` (~3.6% incl. forward/reverse splits, `declared` variants, `1:1` no-ops, unmapped, identical + conflicting alias collisions, and ~0.5% malformed rejects), `qmDividends.bson` (~95.4% incl. USD/CAD with bogus `usdFxRate: 1`, `declared` variants, `0.0` cash, same-day multi-dividends, identical alias duplicates, unmapped, and ~0.5% malformed rejects), and `delistings.tsv` (~1.0% incl. valid OTC transfers with `from_listing_id`, unmapped/self successors, and `-0.3`/`-1.0` terminal delistings) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd [events]
```
Measured locally (`2026-11-29`):
1. **200,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 200000`):
- Input: `events=200000`, `splits_docs=7986` (`1,014,335 B`), `dividends_docs=190038` (`26,806,832 B`), `delistings_rows=1976` (`72,436 B`), `keys=20000`
- `decode`: `elapsed=50.15 ms`, `throughput=3987987 events/s`, `scan=530.43 MB/s`, `splits_rejected=38`, `divs_rejected=921`
- `curate`: `elapsed=65.24 ms`, `throughput=3051003 events/s`, `rows_out=188558` (`94.28%` retained), `listings_out=19850`, `unmapped=5809`, `unmapped_succ=193`, `self_succ=189`, `known_at_oor=967`, `coll_collapsed=542`, `coll_dropped=720`, `split_noops=154`, `zero_div=1909`, `checksum=0x29f0c9ec1451e7c5`
- `write`: `elapsed=40.53 ms`, `throughput=4652522 rows/s`, `write=39.23 MB/s`, `files=1`, `row_groups=1`, `bytes=1667357`, `read_back_rows=188558`
- `total`: `elapsed=155.92 ms`, `throughput=1282737 events/s`, `checksum=0x29f0c9ec1451e7c5`
2. **1,000,000 events** (two back-to-back runs with identical checksum `0xa0fb2bf8e2710d67`): `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000`
- Input: `events=1000000`, `splits_docs=39186` (`4,979,926 B`), `dividends_docs=950896` (`134,135,512 B`), `delistings_rows=9918` (`364,087 B`), `keys=20000`
- Output: `rows_out=944029` (`94.40%` retained), `listings_out=20000`, `files=1`, `row_groups=1`, `bytes=6890801`, `read_back_rows=944029`
- Curation stats: `unmapped=28446`, `unmapped_succ=986`, `self_succ=977`, `known_at_oor=4736`, `coll_collapsed=2555`, `coll_dropped=3392`, `split_noops=738`, `zero_div=9233`
- Run 1: `decode=222.11 ms` (`4,502,250 events/s`, `598.88 MB/s`), `curate=406.07 ms` (`2,450,553 events/s`), `write=147.49 ms` (`6,400,505 rows/s`, `44.56 MB/s`), `total=775.67 ms` (`1,289,204 events/s`), `checksum=0xa0fb2bf8e2710d67`
- Run 2: `decode=211.87 ms` (`4,719,887 events/s`, `627.83 MB/s`), `curate=396.55 ms` (`2,509,369 events/s`), `write=144.29 ms` (`6,542,758 rows/s`, `45.55 MB/s`), `total=752.71 ms` (`1,328,540 events/s`), `checksum=0xa0fb2bf8e2710d67`
### Known Limits
- **Unverified MongoDB `qmDividends` field names:** `bson_qm_actions::FIELD_DIVIDEND_CASH` (`"amount"`) and `FIELD_DIVIDEND_CURRENCY` (`"currency"`) remain isolated constants pending verification against live `mongodump` `qmDividends` exports.
- **In-RAM buffering of decoded events:** the single-threaded runner buffers decoded splits, dividends, and delistings in RAM (with `Arc<str>` key interning) before curation — small for real `qmSplits` (~19k) + `qmDividends` (~500k) + Pass 6 delistings, unlike `eodPrices`.
- **Single-threaded file-to-file execution:** no `rayon` sharding and no direct MongoDB/PostgreSQL connections. The TypeScript read-only PostgreSQL → TSV exporter (`apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts`) generates `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` for all `curate-etl` commands.
## `curate-fx-1d` Command (`M1.2ac`)
End-to-end file-to-Parquet CLI command (`src/run_curate_fx.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, the zero-copy `teMarketData` decoder (`src/bson_te_market_data.rs`, `decode_te_market_data_chunks`), and `curate_and_write_fx_1d` into an atomically published `<out>/fx_1d/part.parquet` dataset with zero extra crates and no database connections.
### Invocation
```bash
curate-etl curate-fx-1d \
--eod-prices eodPrices.bson \
--te-market-data teMarketData.bson \
[--te-symbol USDCAD] \
--out ./out
```
Inputs and output:
- `--eod-prices <path>`: concatenated raw BSON (`mongodump` `eodPrices.bson`). Streams through `decode_eod_price_chunks` and keeps only documents whose `eodSearchCode` is **exact** `"CAD.FOREX"` (other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when mapping to `FxDailyBar`).
- `--te-market-data <path>`: concatenated raw BSON (`mongodump` `teMarketData.bson`). Streams through `decode_te_market_data_chunks` and keeps only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive, default `USDCAD`).
- `--te-symbol <sym>` *(optional)*: target `teMarketData.teSymbol` to match (default: `USDCAD`; must match the USD/CAD allowlist `ALLOWED_TE_SYMBOLS` = `["USDCAD"]` ASCII case-insensitively so non-USD/CAD instruments cannot enter `fx_1d`).
- `--out <dir>`: dataset root where `fx_1d/part.parquet` is atomically published.
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--te-symbol`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, invalid `--out`, unsupported/blank `--te-symbol`, truncated/corrupt/oversized BSON framing or element bytes in either input, zero decoded bars across both inputs, or zero publishable rows after FX curation) prints a single-line stderr message, exits non-zero, and leaves any pre-existing `<out>/fx_1d/part.parquet` byte-identical.
### `teMarketData` Input Contract & `t` Epoch Unit Rule
- Document shape (derived from `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`; field names isolated as `pub const FIELD_*` in `src/bson_te_market_data.rs`):
- Top-level `teSymbol: string` and `daily: [{ t, o, h, l, c, pc, ac }]`.
- `monthly`, `pc`, `ac`, and all unknown fields are skipped without decoding their values.
- `daily` is captured lazily as a raw element and only decoded after `teSymbol` matches `--te-symbol`, so field ordering (`daily` before `teSymbol`) never causes false rejects on non-target symbols.
- Numeric fields `t`, `o`, `h`, `l`, `c` accept BSON `Int32`, `Int64`, or `Double`. Malformed points (non-document element, missing field, wrong type, `NaN`/`±Inf`, out-of-`i32`-range date) are counted under per-reason reject counters and skipped without panicking.
- **`t` epoch unit rule** (`TE_EPOCH_MILLIS_THRESHOLD = 100_000_000_000`):
- `|t| >= 100_000_000_000` → treated as Unix **milliseconds** (`session_date = floor(t / 86_400_000)` UTC).
- `|t| < 100_000_000_000` → treated as Unix **seconds** (`session_date = floor(t / 86_400)` UTC).
- Uses `unsigned_abs()` + `div_euclid` (flooring pre-1970 negative timestamps to the earlier UTC day) and checked `i32::try_from` bounds checking.
- Merge precedence (`CAD.FOREX` wins on overlap, `teMarketData` fills interior gaps and post-EOD tail), read-only 1% overlap cross-check, and conservative `23:59:59.999999 UTC` `ts`/`known_at` stamping stay delegated unchanged to `curate_and_write_fx_1d`.
### Report Counters & Conservation Invariants
On success, `curate-fx-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `te_bson`, `builder`, `curate`, `write`, and `timing`):
- **EOD BSON:**
`eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
`eod_bson.decoded == eod_bson.cad_forex_kept + eod_bson.other_symbol_skipped`
`eod_bson.cad_forex_kept == builder.eod_in`
- **TE BSON:**
`te_bson.docs_framed == te_bson.docs_in == te_bson.matched + te_bson.other_symbol + te_bson.docs_rejected`
`te_bson.points_in == te_bson.points_decoded + te_bson.points_rejected`
`te_bson.points_decoded == builder.te_in`
- **Stage & Write:**
`curate.rows_in == curate.rows_out == write.rows_written`
### `bench-curate-fx-cmd`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson` (`CAD.FOREX` with interior gaps, invalid/inconsistent/duplicate bars, skipped other symbols, and malformed docs) and `teMarketData.bson` (`USDCAD` with overlap including >1% cross-check mismatches, interior gap fills, post-EOD tail, mixed seconds/ms `t` across `Int32`/`Int64`/`Double`, malformed points, ignored `monthly`, and skipped other symbols) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd [rows]
```
Measured locally (`2026-11-29`, post-fix `curate-fx-1d` with full-document corruption scanning, default `20,000` rows; two back-to-back runs with identical checksum `0x45ac34f4ddf4407c`):
- Input: `rows=20000`, `eod_docs=18936` (`2,706,485 B`), `te_docs=3`, `te_points=5000` (`443,498 B`)
- Decode counts: `eod_kept=14918`, `eod_other=3936`, `eod_rejected=82`, `te_matched=1`, `te_other=2`, `te_decoded=4925`, `te_rejected=75`
- Output: `rows_out=17524` (`eod_out=14569`, `te_out=2955`, `te_superseded=1970`), `files=1`, `row_groups=1`, `bytes=733752`, `read_back_rows=17524`, `overlap: checked=1970 within_tol=1870 mismatched=100 max_rel=0.025000`
- Run 1: `decode=4.33 ms` (`4,614,470 rows/s`, `693.11 MB/s`), `curate=0.64 ms` (`30,806,515 rows/s`), `write=24.99 ms` (`701,274 rows/s`, `28.00 MB/s`), `total=29.97 ms` (`667,398 rows/s`), `checksum=0x45ac34f4ddf4407c`
- Run 2: `decode=4.26 ms` (`4,694,381 rows/s`, `705.11 MB/s`), `curate=0.67 ms` (`29,800,156 rows/s`), `write=15.27 ms` (`1,147,886 rows/s`, `45.84 MB/s`), `total=20.19 ms` (`990,462 rows/s`), `checksum=0x45ac34f4ddf4407c`
### Known Limits
- **Unverified live `teMarketData` schema & `t` unit:** `bson_te_market_data::FIELD_*` constants and the `|t| >= 100_000_000_000` ms/s threshold are derived from `market-data-fetch.action.ts` and have not yet been verified against a live `mongodump` export.
- **`eodPrices` `volume` field:** `decode_eod_price_chunks` still requires a non-negative `volume` field on `CAD.FOREX` documents (ignored when mapping to `FxDailyBar`); if a live `CAD.FOREX` dump omits `volume`, those docs will surface in `eod_bson.rejected (missing=...)`.
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB connection, and `fx_1m` is out of scope.
## `curate-shorts` Command (`M1.2ad`)
End-to-end file-to-Parquet CLI command (`src/run_curate_shorts.rs`) wiring `RawBsonChunkReader`, the zero-copy `ceoShorts` decoder (`src/bson_ceo_shorts.rs`, `decode_ceo_shorts_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_shorts` into an atomically published `<out>/shorts/part.parquet` dataset (`+4` Canadian TSX business days at `17:00 America/Toronto`, `source = "ceo_shorts"`) with zero extra crates and no database connections.
### Invocation
```bash
curate-etl curate-shorts \
--ceo-shorts ceoShorts.bson \
--provider-mapping provider_mapping.tsv \
--out ./out \
--shares-short-field <name> \
[--key-field symbol] \
[--report-date-field timestamp] \
[--net-change-field <name>] \
[--pct-float-field <name>] \
[--mapping-source ceo]
```
Inputs and output:
- `--ceo-shorts <path>` *(required)*: concatenated raw BSON (`mongodump` `ceoShorts.bson`).
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
- `--out <dir>` *(required)*: dataset root where `shorts/part.parquet` is atomically published.
- `--shares-short-field <name>` *(required, no default)*: BSON field name holding the short-share count (intentionally has no default because live `ceoShorts` value field names are unverified in the repo).
- `--key-field <name>` *(optional, default `symbol`)*: BSON field name holding the security key (passed verbatim to `provider_mapping` without trimming or suffix stripping).
- `--report-date-field <name>` *(optional, default `timestamp`)*: BSON field name holding the report period date.
- `--net-change-field <name>` *(optional)*: BSON field name holding optional net change vs. prior report.
- `--pct-float-field <name>` *(optional)*: BSON field name holding optional percent-of-float short.
- `--mapping-source <name>` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, report_date) -> listing_id`.
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Missing required flags (including `--shares-short-field`), duplicate flags, unknown flags, empty/blank field names or `--mapping-source`, positional arguments, and any two configured roles resolving to the same BSON field name (checked after applying defaults) exit non-zero with usage on stderr. Any runtime error (missing input file, malformed or overlapping `provider_mapping.tsv`, truncated/corrupt/oversized BSON framing or element bytes, out-of-range `report_date`, or obstructed `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/shorts/part.parquet` byte-identical).
### `ceoShorts` Decoder Rules
- Scans and validates every element and nested raw value (including unused strings, embedded documents, and arrays) of each `RawDocument` to completion before applying semantic skip priority (`key` → `report_date` → `shares_short`) so structural BSON corruption always fails closed with a typed error carrying the absolute byte offset.
- `key`: BSON UTF-8 `String` passed through verbatim (empty/whitespace-only, missing, or wrong type skipped and counted).
- `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)` checked to `i32`), or `Int32` / `Int64` / integral finite `Double` via `te_epoch_i64_to_session_date` (seconds vs. milliseconds UTC). Non-finite or fractional `Double`s skip under `invalid_date`; values overflowing `i64`/`i32` skip under `date_oor`.
- `shares_short`: strict BSON `Double`, `Int32`, or `Int64` (numeric strings are rejected as `wrong_shares_type`). Sign and finiteness validation remains in `build_shorts`.
- `net_change` / `pct_float`: unconfigured, absent, or BSON `Null` → `None`; wrong BSON type → `None` and counted in `nulled_wrong_type` (only on emitted rows).
- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0`, leaving any pre-existing `shorts/part.parquet` untouched.
### Report Counters & Conservation Invariants
On success, `curate-shorts` prints deterministic `key=value` lines to stdout (`ceo_bson`, `builder`, `curate`, `write`, and `timing`):
- **BSON Decode:** `ceo_bson.docs_framed == ceo_bson.docs_in == ceo_bson.rows_out + ceo_bson.skipped`
- **Builder:** `ceo_bson.rows_out == builder.rows_in == builder.rows_out + builder.invalid_shares + builder.dup_collapsed + builder.dup_conflict`
- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.coll_collapsed + curate.coll_dropped`, and `write.rows_written == curate.rows_out`
### `bench-curate-shorts-command`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing a concatenated-BSON `ceoShorts` file (default `700,000` docs, `12,500` keys distributed across all 218 semi-monthly dates `2017-04-15..=2026-04-30`, mixing `DateTime`/`Int32`/`Int64`/`Double` dates, optional fields with nulls and wrong types, ~0.5% semantically skipped docs, invalid `shares_short`, explicit identical/conflicting same-key duplicates, explicit identical/conflicting primary+alias collisions, ticker-reuse gap dates, and unmapped keys) plus `provider_mapping.tsv` into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-shorts-command [rows]
```
Measured locally (`2026-11-29`, Linux `6.8.0-151-generic`, AMD Ryzen 9 9950X3D 16-Core Processor, default `700,000` rows; two back-to-back runs with identical checksum `0xa759372dd4476f50`):
- Input: `rows=700000`, `docs_framed=700000`, `bytes_read=67925127` (`64.78 MiB`), `keys=12500`, `peak_chunk_bytes=8388608` (`8 MiB`)
- Decode counts: `rows_out=696570`, `skipped=3430`, `nulled_net_change=6860`, `nulled_pct_float=5717`
- Output: `rows_out=656911` (`93.84%` retained), `listings_out=12345`, `dropped_unmapped=15229`, `dup_collapsed=3500`, `dup_conflict=7000`, `coll_collapsed=3500`, `coll_dropped=7000`, `invalid_shares=3430`, `files=1`, `row_groups=1`, `bytes=5791000`, `read_back_rows=656911`
- Run 1: `decode=141.29 ms` (`4,954,433 rows/s`, `458.49 MB/s`), `curate=130.95 ms` (`5,319,222 rows/s`), `write=93.49 ms` (`7,026,896 rows/s`, `59.08 MB/s`), `total=365.73 ms` (`1,914,000 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xa759372dd4476f50`
- Run 2: `decode=152.15 ms` (`4,600,763 rows/s`, `425.76 MB/s`), `curate=130.95 ms` (`5,319,464 rows/s`), `write=86.38 ms` (`7,604,711 rows/s`, `63.93 MB/s`), `total=369.48 ms` (`1,894,564 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xa759372dd4476f50`
### Known Limitations
- **Unverified live `ceoShorts` field names and `timestamp` unit/timezone:** `ceoShorts` value field names (`--shares-short-field`, `--net-change-field`, `--pct-float-field`, `--key-field`) and `timestamp` unit/timezone are unverified against live QA MongoDB data. Confirm them before the first real run with the read-only field-shape probe:
```bash
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections ceoShorts --out <path>
```
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connection, and `pct_float` is passed through as supplied rather than derived from shares outstanding.
## `curate-events` Command (`M1.2ae`)
End-to-end file-to-Parquet CLI command (`src/run_curate_events.rs`) wiring `RawBsonChunkReader`, the zero-copy `qmFilings` + `qmEarnings` decoders (`src/bson_qm_events.rs`, `decode_qm_filings_chunks`, `decode_qm_earnings_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_events` into atomically published `<out>/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections.
### Invocation
```bash
curate-etl curate-events \
--qm-filings qmFilings.bson \
--qm-earnings qmEarnings.bson \
--provider-mapping provider_mapping.tsv \
--out ./out \
--filings-form-type-field <name> \
[--filings-key-field symbol] \
[--filings-timefiled-field timefiled] \
[--filings-filing-id-field <name>] \
[--filings-url-field <name>] \
[--earnings-key-field qmSearchCode] \
[--earnings-report-date-field reportDate] \
[--earnings-announce-time-field announceTime] \
[--earnings-fiscal-period-end-field <name>] \
[--earnings-actual-eps-field <name>] \
[--earnings-revenue-field <name>] \
[--mapping-source qm]
```
Inputs and verified vs. configured field names:
- `--qm-filings <path>` *(required)*: concatenated raw BSON (`mongodump` `qmFilings.bson`).
- `--qm-earnings <path>` *(required)*: concatenated raw BSON (`mongodump` `qmEarnings.bson`).
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
- `--out <dir>` *(required)*: dataset root where `events/year=YYYY/part.parquet` is atomically published. Upfront path validation rejects `--out` or `<out>/events` being a regular file, or any input path resolving to `--out` or inside `<out>/events/...` (preventing input clobbering).
- **Verified defaults** (grounded in `apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts`, `events.action.ts`, and `design/DATA-CONTRACTS.md` §1):
- `qmFilings`: `--filings-key-field` (`symbol`; note `filings.action.ts` does **not** add `qmSearchCode` to stored docs despite the upsert key), `--filings-timefiled-field` (`timefiled`).
- `qmEarnings`: `--earnings-key-field` (`qmSearchCode`), `--earnings-report-date-field` (`reportDate`), `--earnings-announce-time-field` (`announceTime`).
- **Caller-configured fields (no defaults):**
- `--filings-form-type-field <name>` *(required, no default)*: BSON field holding the EDGAR/SEDAR+ form type string.
- Optional: `--filings-filing-id-field`, `--filings-url-field`, `--earnings-fiscal-period-end-field`, `--earnings-actual-eps-field`, `--earnings-revenue-field`.
- `--mapping-source <name>` *(optional, default `qm`)*: `provider_mapping` source name used to resolve `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern local calendar date.
- **`consensusEps` exclusion:** `consensusEps` is structurally omitted from `RawQmEarning` / `QmEarning` and explicitly rejected (case-insensitively as `consensusEps` / `consensus_eps`) on any earnings field flag per `design/DATA-CONTRACTS.md` §1.
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags (including `--filings-form-type-field`), duplicate flags, unknown flags, blank field names or `--mapping-source`, colliding role mappings within a collection, or any `consensusEps` mapping exit non-zero with usage on stderr. Any runtime error (missing input file, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON in either stream, or obstructed/overlapping `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/events/` partitions byte-identical).
### `qmFilings` & `qmEarnings` Decoder Rules
- Scans and structurally validates every element and nested document/array/JS-with-scope (depth limit `128`) of each `RawDocument` before applying semantic skip rules so structural corruption always fails closed with a typed error carrying the absolute byte offset.
- `qmFilings` deterministic skip priority: `key` → `timefiled` → `form_type` (all required non-blank UTF-8 `String`s passed verbatim; timestamp syntax remains in `events::build_events`). Optional `filing_id` / `url`: unconfigured, absent, `Null`, or blank string → `None`; wrong BSON type → `None` + `nulled_wrong_type_*` (emitted rows only).
- `qmEarnings` deterministic skip priority: `key` → `report_date` → `announce_time`. `report_date` accepts BSON `DateTime` (UTC epoch day checked to `i32`) or strict `YYYY-MM-DD` `String`. Optional `fiscal_period_end` accepts absent/`Null`/blank (`None`), `DateTime` or strict `YYYY-MM-DD` (`Some(i32)`), wrong BSON type (`nulled_wrong_type_fiscal_period_end`), or malformed/out-of-range (`nulled_invalid_fiscal_period_end`, emitted rows only). Optional `actual_eps` / `revenue` accept absent/`Null` (`None`), `Double`/`Int32`/`Int64` (`Some(f64)`), or wrong BSON type (`nulled_wrong_type_*`, emitted rows only).
- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0` without creating `<out>/events` or modifying any pre-existing partitions.
### Report Counters & Conservation Invariants
On success, `curate-events` prints deterministic `key=value` lines to stdout (`filings_bson`, `earnings_bson`, `builder`, `curate`, `write`, ascending `years`, and `timing`):
- **Filings BSON:** `filings_bson.docs_framed == filings_bson.docs_in == filings_bson.rows_out + filings_bson.skipped`, and `filings_bson.rows_out == builder.filings_in`.
- **Earnings BSON:** `earnings_bson.docs_framed == earnings_bson.docs_in == earnings_bson.rows_out + earnings_bson.skipped`, and `earnings_bson.rows_out == builder.earnings_in`.
- **Builder:** `builder.filings_in == builder.filings_out + malformed_ts + unknown_zone + invalid_dt + filing_dup`, `builder.earnings_in == builder.earnings_out + earnings_oor + earnings_dup + earnings_conflict`, `builder.earnings_out == linked + lagged_1605`, and `builder.rows_out == builder.filings_out + builder.earnings_out`.
- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.listing_dup_collapsed`, and `write.rows_written == curate.rows_out`.
### `bench-curate-events-cmd`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (`5,000` keys with ~2% unmapped), `qmFilings.bson` (~98.5% of `rows`, mixed EST/EDT `2015..=2025`, EDGAR + SEDAR+ form types, ~0.5% skips/wrong-type optionals), and `qmEarnings.bson` (~1.5% of `rows`, mixed `DateTime`/`YYYY-MM-DD`, linked & unlinked rows, `consensusEps` present and ignored, ~0.5% skips/wrong-type optionals) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row counts across all UTC year partitions, extrapolating to the full `30.52M + 444.9k` (`30,964,900` rows) QA MongoDB dataset, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-events-cmd [rows]
```
Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs with identical checksum `0x2076c3a54dc2403e`):
- Input: `rows=500000`, `filings_docs=492500` (`71,019,899 B`), `earnings_docs=7500` (`1,233,791 B`), `keys=5000`, `peak_chunk_bytes=8388608` (`8 MiB`)
- Decode counts: `filings_out=490021`, `filings_skipped=2479`, `earnings_out=7462`, `earnings_skipped=38`
- Output: `rows_out=487589` (`97.52%` retained; `filings_out=480258`, `earnings_out=7331`), `listings_out=4900`, `linked=3008`, `lagged_1605=4452`, `unmapped=9892`, `files=12`, `row_groups=12`, `bytes=14125012`, `read_back_rows=487589`
- Run 1: `decode=136.07 ms` (`3,674,605 rows/s`, `506.41 MB/s`), `curate=278.55 ms` (`1,786,003 rows/s`), `write=446.48 ms` (`1,092,064 rows/s`, `30.17 MB/s`), `total=861.10 ms` (`580,654 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `53.3 s` (`0.89 min`) single-core**, `checksum=0x2076c3a54dc2403e`
- Run 2: `decode=136.68 ms` (`3,658,115 rows/s`, `504.14 MB/s`), `curate=264.16 ms` (`1,883,251 rows/s`), `write=437.86 ms` (`1,113,564 rows/s`, `30.76 MB/s`), `total=838.71 ms` (`596,155 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `51.9 s` (`0.87 min`) single-core**, `checksum=0x2076c3a54dc2403e`
### Known Limitations
- **Unverified live `qmFilings` / `qmEarnings` field names:** `--filings-form-type-field`, optional filings fields (`filing_id`, `url`), optional earnings fields (`fiscal_period_end`, `actual_eps`, `revenue`), and whether live `qmFilings` documents carry `qmSearchCode` vs. `symbol` are unverified against live QA MongoDB. Confirm them before the first real run with the read-only field-shape probe:
```bash
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections qmFilings,qmEarnings --out <path>
```
- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers.
- **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc<str>` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope.
## Read-Only MongoDB URI Safety Guard (`M1.2ak`)
Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection.
### Public API
- `parse_mongo_target(uri: &str) -> Result<MongoTarget, MongoSafetyError>` — parses `mongodb://` and `mongodb+srv://` URIs, splits authority at `/` or `?` (never `#`), percent-decodes usernames (strict UTF-8, without converting `+` to space), iteratively percent-decodes seed hosts up to `8` passes (handling bracketed IPv6 with zone IDs and `mongodb://` `.sock` Unix domain sockets), and rejects control characters, Unicode whitespace, unencoded `#` or multiple `@` in authority, `@` in path/query when authority has no credentials, invalid percent-encoding, and forbidden decoded host characters.
- `is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool` — returns `true` when any seed host is loopback (`localhost`, trailing-dot/case variants, `0.0.0.0`, `127.0.0.0/8` in dotted, shorthand `127.1`, decimal `2130706433`, hex `0x7f000001`, octal `0177.0.0.1`, leading-zero decimal `0127.0.0.1`, IPv6 `::` / `::1` with optional zone ID, and IPv4-mapped `::ffff:127.0.0.0/8` / `::ffff:0.0.0.0`) or matches an injected `LocalHosts` entry on port `27017` (or omitted/default port), regardless of database path.
- `LocalHosts` — deterministic injected set (`LocalHosts::empty()`, `new(...)`, `from_hostname_and_ips(...)`, `with_host(...)`, `contains(...)`) plus `LocalHosts::detect()`, which is **best-effort** and `std`-only (reads `HOSTNAME` and `/etc/hostname` without NIC enumeration or DNS lookups; multi-homed callers should inject LAN IPs via `LocalHosts::from_hostname_and_ips`).
- `assert_read_only_mongo_uri(uri, policy: &ReadOnlyPolicy, local_hosts) -> Result<ValidatedReadOnlyMongoUri, MongoSafetyError>` — fail-closed guard returning a `ValidatedReadOnlyMongoUri` proof token whose fields are private and whose only public constructor is `assert_read_only_mongo_uri`.
- **Password redaction:** `ValidatedReadOnlyMongoUri`'s `Display`, `Debug`, and `redacted()` always replace the password between the first `:` and `@` in userinfo with `[REDACTED]`. `MongoSafetyError` variants never store raw URIs, raw authorities, or passwords.
- **No URI query-option parsing:** beyond authority/remainder splitting and the no-credentials remainder-`@` check, URI query options are intentionally not parsed or validated (matching `apps/stock/config/src/env-safety.ts`).
- **Unix domain sockets:** `.sock` Unix-socket hosts (e.g. `%2Ftmp%2Fmongodb-27017.sock`) are never classified as QA targets (same as `env-safety.ts`).
### Intentional Stricter-than-`env-safety.ts` Differences
Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all five `test/unit/environment-safety*.test.ts` suites (including the 42-case `hostSpellings × ports` matrix, the 3,000-iteration seeded percent-encoding sweep, and all 30,000 cases per authority-split fuzz seed `0x7e28` / `0x28e7`) with identical QA / not-QA / rejected outcomes **except for the intentional stricter rules listed below**. `parse_mongo_target`, `is_qa_mongo_target`, and `assert_read_only_mongo_uri` are deliberately stricter than `env-safety.ts` in eight ways for read-only ETL safety:
1. **Global case-insensitive `trading_admin` ban:** rejects percent-decoded `trading_admin` (ASCII case-insensitive) on **any** host (QA, dev, or remote), even if a caller adds it to `ReadOnlyPolicy::allowed_read_users` (whereas `env-safety.ts` only checks `username === 'trading_admin'` on QA targets for dev `dataPipeline`).
2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`, exact match after percent-decoding); missing credentials and non-allowlisted users are rejected.
3. **Rejection of empty, malformed, or invalid bracketed-IPv6 host segments:** URIs like `mongodb://u:p@bad:port,localhost:27017/stock`, `mongodb://u:p@localhost:27018,,localhost:27017/stock`, or `mongodb://u:p@[fe80::g]:27017,localhost:27017/stock` still classify as QA in `parse_mongo_target` / `is_qa_mongo_target` (matching `env-safety.ts`), and are rejected fail-closed with `MalformedHostSegment` by `assert_read_only_mongo_uri` (matching `libs/core/config/src/schemas/database.schema.ts`). Single-seed malformed bracketed IPv6 literals such as `[fe80::g]:27017` are rejected with `NoValidHosts`.
4. **Strict `mongodb+srv://` seed rules:** `assert_read_only_mongo_uri` rejects `mongodb+srv://` URIs with multiple hosts or any explicit `:` port suffix (`InvalidSrvTarget`), matching `database.schema.ts`.
5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`), and rejects invalid percent-encoding in the username (e.g. `%ff`, failing closed with `InvalidUsernameEncoding` instead of falling back to the raw username string).
6. **No silent trimming of leading/trailing whitespace:** `env-safety.ts` calls `uri.trim()` before checking `/\s/`, whereas `parse_mongo_target` rejects any Unicode whitespace anywhere in the URI (including leading or trailing spaces) with `ForbiddenWhitespace`.
7. **Leading-zero decimal LAN IPs matched against `LocalHosts`:** `is_qa_mongo_target` normalizes 4-part decimal IPv4 spellings with leading zeros (e.g. `192.168.001.050:27017`) before checking `LocalHosts`, flagging them as QA even where `env-safety.ts` does not.
8. **Machine's own zoned link-local IPv6 matched against `LocalHosts`:** `is_qa_mongo_target` strips `%zone` suffixes when matching bracketed IPv6 hosts against `LocalHosts` (e.g. `[fe80::1234:5678%25eth0]:27017`), flagging the machine's own link-local IPv6 on port `27017` as QA even where `env-safety.ts` misses it.
## Driver-Independent MongoDB Raw-BSON Cursor Seam (`M1.2al`)
Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging the read-only safety model (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero new dependencies and zero CLI/command wiring yet.
### Dependencies
- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet.
### Public API & Sealing Guarantees
- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string.
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` server-side string ranges require Eastern calendar-day boundaries `YYYY-MM-DD` so neither UTC offsets nor fall-back DST local-string inversions can silently miss filings), building `bson::Document` via `Document::from_iter(...)`.
- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader<S>`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`.
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords (including passwords containing punctuation such as `,`, `;`, quotes, brackets, or `@`) to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
### `bench-mongo-stream`
Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices` documents (`285,639,152` bytes) through plain `io::Cursor<&[u8]>` → `decode_eod_price_stream` vs. `SliceRawDocumentSource` → `RawBsonCursorReader` → `decode_eod_price_stream`:
```bash
cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000
```
Measured locally (`2026-11-30`, two back-to-back offline runs on the final code with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`):
- **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`)
- **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`)
### Not Done / Not Verified
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks).
## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`)
`src/bson_eod_intraday.rs` decodes raw `eodIntraday1M` MongoDB BSON documents in a single zero-copy forward pass (`RawEodIntradayBar<'a>`, `decode_eod_intraday_doc`, `decode_eod_intraday_bytes`, `decode_eod_intraday_buffer`, `BsonEodIntradayError`, `BsonEodIntradayDecodeStats`) with bounded-memory streaming helpers in `src/bson_stream.rs` (`decode_eod_intraday_chunks`, `decode_eod_intraday_stream`):
- **Timestamp units:** `timestamp` is bar-start **UTC Unix seconds** (accepted in BSON `Int32`, `Int64`, or finite integral `Double` within `0..=i64::MAX / 1_000_000`) converted to UTC microseconds (`ts: i64`) via checked multiplication by `1_000_000`. It is bar start only (not a publication / `known_at` timestamp).
- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`.
- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar<K>`.
## Point-in-Time Fundamentals Core (`M2.2a`)
Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks.
### Public API & Field Set
- **Single field definition (`FundamentalsFields`):**
- Flow fields (4-quarter TTM-eligible): `revenue`, `net_income`, `operating_cash_flow`.
- Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`.
- **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation<K>` against periodic `events::QmFiling<K>` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap<K, StatutoryLagVenue>` (`UsTsx` vs `TsxvCse`).
- `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked.
- **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. If a dated statutory-lag estimate for `(key, period_end, fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped (`observations_dropped_stale_estimate`) so an older vintage never rolls a newer filing backward.
- **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field).
- **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`.
- **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`.
- **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):**
- Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot<K>` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order.
- Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate.
- Resolves standalone quarterly versions separately from `FY` rows (so an annual report sharing December 31 with standalone `Q4` never erases `Q4` from TTM) and computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency.
- `as_of(snapshots, key, as_of_micros)` performs an inclusive `O(log N)` binary search on `(key, effective_known_at_utc_micros)`.
### `bench-fundamentals`
Fixed-seed (`SplitMix64`), offline benchmark exercising both venue classes, linked periodic filings, statutory-lag fallback, exact duplicates, complete 4-quarter TTM histories, and late Q1 amendments across both stages (`k = 4`):
```bash
cargo run -p curate-etl --release --offline -- bench-fundamentals [rows]
```
Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0xd5f693a28da4d1f0` hashing all row fields, ordered snapshot slots, TTM flows, and provenance):
- **Run 1:** Stage 1 `47.63 ms`, Stage 2 `41.81 ms`, total `89.44 ms` (`1,118,108 rows/s`, `894.37 ns/row`)
- **Run 2:** Stage 1 `44.34 ms`, Stage 2 `39.73 ms`, total `84.07 ms` (`1,189,459 rows/s`, `840.72 ns/row`)
## Exporting Input Files (`data-pipeline`)
All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`:
- **PostgreSQL security-master TSVs (`provider_mapping.tsv`, `listing_currencies.tsv`, `delistings.tsv`):** `apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts`
- **MongoDB concatenated raw-BSON files (`<collection>.bson`):** `apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts`
See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.md#read-only-raw-bson-exporter-export-raw-bsonts) for flags, read-only safety guards, and the full M1 Step 2 execution order (`run-export-curate-inputs.ts` → `run-export-raw-bson.ts` → `curate-etl curate-*`).
## Zero-Copy `qmFinancials` BSON Decoder (`M2.2k`)
`src/bson_qm_financials.rs` (tested in `src/bson_qm_financials_tests.rs`) decodes raw `qmFinancials` / `qmFinancials-old` MongoDB BSON documents without allocating a `bson::Document`, emitting `FinancialObservation<&str>` rows (key borrowed verbatim from the input BSON slice; owned `currency` allocated only on emission) through `decode_qm_financials_doc`, `decode_qm_financials_bytes`, and `decode_qm_financials_buffer`:
- **Unverified live schema (explicit caller configuration):** Only the four repo-evidenced top-level field names have defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). Live inner field names under `BalanceSheet`, `CashFlow`, and `IncomeStatement`, the currency path, `reportPeriod` token strings, and date BSON types are **unverified against a live dump**, so `QmFinancialsFieldNames::with_verified_defaults(currency, revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding)` requires callers to explicitly supply the dotted `currency` path and an `Option<&str>` choice (`Some(path)` or intentional `None` opt-out) for all six `FundamentalsFields` metrics, alongside `QmFinancialsFiscalPeriod` (`ByTokens { quarterly, annual }` or `Fixed(FiscalPeriod)`). Empty paths, empty/blank dotted segments, blank tokens, and overlapping token lists fail closed before decoding.
- **Fail-closed dates, periods & BSON framing:** Every document is structurally validated (nested documents/arrays/JS-with-scope up to depth `128`) before semantic skips run so corrupt BSON always returns `Err(BsonQmFinancialsError::CorruptBson)` with the failing byte offset (in buffer mode, callbacks may have already fired for earlier valid documents). `periodEndDate` (required) and `reportDate` (optional) accept BSON `DateTime` (UTC epoch day) or strict `YYYY-MM-DD` strings within `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE`; only an absent or BSON `Null` `reportDate` emits `None` (present-but-invalid vintage dates skip the document rather than silently dropping the vintage). Numeric paths accept `Double`, `Int32`, `Int64`, and trimmed numeric strings (`f64`), counting missing paths, wrong types, unparsable strings, and non-finite values on emitted rows while leaving unconfigured (`None`) paths and BSON `Null` leaves uncounted.
- **Accounting invariant & ownership boundary:** `BsonQmFinancialsDecodeStats` satisfies `docs_in == rows_out + skipped_total()`. QuoteMedia owns the source statement inputs; `build_fundamentals_rows` owns filing linkage and `known_at` derivation, while this decoder preserves the supplied `report_date` vintage and `currency`. Chunked streaming (`bson_stream`), file-to-file runner, and CLI wiring are deferred to follow-up tasks.
## `run_curate_fundamentals` File-to-File Runner (`M2.2m`)
`run_curate_fundamentals` / `run_curate_fundamentals_with_readers` (`src/run_curate_fundamentals.rs`) connects concatenated raw BSON `qmFinancials` and `qmFilings` dump files, a headerless 5-column `provider_mapping.tsv`, and a headerless 2-column `listing_venues.tsv` through `decode_qm_financials_chunks` / `decode_qm_filings_chunks` (`src/bson_stream.rs`) and `curate_and_write_fundamentals` into `<out_dir>/fundamentals_pit/year=YYYY/part.parquet` (Zstd Parquet):
- **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option<String>` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`.
- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number.
- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up.
## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`)
`run_curate_bars_1m` / `run_curate_bars_1m_with_readers` (`src/run_curate_bars_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a headerless 5-column `provider_mapping.tsv` (reusing `load_provider_mapping_tsv` and the shared `qmSplits` loader from `src/run_curate_bars.rs`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`):
- **Bounded-memory chunking & listing-keyed splits:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), resolving each bar's `listing_id` on its Eastern Time `session_date` before applying `listing_id`-keyed `qmSplits` un-adjustment (preventing split leakage across reused tickers) into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard.
- **Cross-chunk semantics & reporting:** `mapping_source` must be `"eod"`. Collision collapse/drop and `(listing_id, ts)` ordering apply per chunk; the same `(listing_id, ts)` appearing in two chunks is emitted twice and relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. Aggregated `curate_stats.listings_out` and `curate_stats.builder.keys_out` are sums of per-chunk counts (not global distinct counts). `known_at_micros` is caller-supplied and supplies no evidence of earlier market availability.
- **Fail-closed publication:** Preflight scans `out_dir` for any pre-existing `bars_1m.shard-<digits>.ilp` file (regardless of `shard_count`) and rejects before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. File-mode CLI wiring is available via `curate-bars-1m` below; `--from-mongo` and live QuestDB ingestion remain follow-ups.
### `curate-bars-1m` Command (`M2.3n`)
File-mode CLI command wiring `run_curate_bars_1m` into the `curate-etl` binary:
```bash
curate-etl curate-bars-1m \
--eod-intraday eodIntraday1M.bson \
--qm-splits qmSplits.bson \
--provider-mapping provider_mapping.tsv \
--out ./out \
--shards 4 \
--known-at-micros 1750000000000000
```
- **Required flags:** `--eod-intraday <path>`, `--qm-splits <path>`, `--provider-mapping <path>`, `--out <dir>`, `--shards <N>` (positive base-10 integer, no default), and `--known-at-micros <i64>` (positive base-10 UTC microsecond timestamp, no default).
- **Optional flag:** `--mapping-source <name>` (defaults to `eod`; only `eod` is accepted by the runner).
- **Timestamp semantics:** `--known-at-micros` records the caller-supplied curation run timestamp verbatim in each ILP row's `known_at` column; it does not establish historical market availability.
- **Outputs & fail-closed publication:** writes `<out>/bars_1m.shard-<NN>.ilp` (`00`..`<shards-1>`) and prints the `format_curate_bars_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `bars_1m.shard-*.ilp` files and leaves no partial shard or staging files on error).
- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups.
## `run_curate_fx_1m` File-to-File Runner (`M2.3l`)
`run_curate_fx_1m` / `run_curate_fx_1m_with_readers` (`src/run_curate_fx_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`) via `curate_and_write_fx_1m_from_bson` (`src/curate_fx_1m.rs`):
- **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers.
- **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files.
- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-<digits>.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any error. CLI wiring, `--from-mongo`, and live QuestDB load remain follow-ups.
## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`)
`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`):
- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`).
- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-<NN>.ilp` prefix so QM and EOD (`bars_1m.shard-<NN>.ilp`) exports can share `out_dir` safely.
- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-<digits>.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups.
## Lagged Macro Regime Series Builder (`M2.2n`)
`build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation<K>` inputs and a caller-supplied `(country_iso, indicator) -> Option<MacroLagClass>` lookup into sorted, unique `MacroRow<K>` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A).
- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`).
- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`).
- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: `teData` BSON decoding, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access.
## Zero-Copy `teData` BSON Decoder (`M2.2p`)
`src/bson_te_data.rs` (tested in `src/bson_te_data_tests.rs`) decodes raw `teData` MongoDB BSON documents in a single forward pass without allocating a `bson::Document` or per-point heap memory, emitting borrowed `TeDataPoint<'a>` views through `decode_te_data_doc`, `decode_te_data_bytes`, and `decode_te_data_buffer`.
- **History-only (zero forecast leakage):** Reads only `data` (`[{ d: "YYYY-MM-DD", v: number }]`) and skips `forecast`, descriptive metadata, timestamps, and unknown fields without calling `elem.value()`.
- **Writer-derived schema & no hardcoded mappings:** Field names (`teSymbol`, `country`, `category`, `data`, `forecast`, `d`, `v`) come from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts` and are not verified against a live `mongodump`. Provider `te_symbol`, `country`, and `category` strings are preserved verbatim; downstream runners own country/indicator/lag mapping into `build_macro_rows`.
- **Fail-closed accounting:** Rejects missing/empty/non-string `teSymbol`, `country`, or `category`, and missing/non-array `data` before emitting any point; rejects malformed/non-string `d` and non-numeric `v` per point while passing finite and non-finite `Double` values through unchanged. `BsonTeDataDecodeStats` maintains `docs_in == docs_accepted + docs_rejected_total()` and `points_in == points_decoded + rejected_total()`.