# `curate-etl` Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`. ## 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`) into sorted, unique per-`(key, session_date)` `Bar1dRow` rows matching the contract sort `(listing_id, session_date)` in `design/DATA-CONTRACTS.md`, un-adjusting share volume via `&SplitTable` and cross-checking against optional `qmPrices.sharevolume` observations (`QmRawVolume`). 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`) into sorted, unique per-`(key, report_date)` point-in-time `ShortRow` 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). ## `events` Builder (`M1.2g`) `build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling`) and `qmEarnings` (`QmEarning`) streams into deterministically sorted point-in-time `EventRow` 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`: MongoDB `qmFilings` / `qmEarnings` BSON cursors, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, and M2 `fundamentals_pit` joins. ## `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` arena indexed by a sorted per-source `HashMap` (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 `/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. - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. 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 `/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..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 }` - `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>` / `From>` 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 `/shorts/part.parquet` (unpartitioned). - Empty input returns `Ok(ShortsWriteStats::default())` without creating `/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 `/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..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>` / `From>` 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 `/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 `/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..tmp`), `File::sync_all()`, live-preserving backup (`part.parquet..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 `/fx_1d/part.parquet` (unpartitioned). - Empty input returns `Ok(Fx1dWriteStats::default())` without creating `/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 `/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..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, 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 `/adj_factors/part.parquet` (unpartitioned). - Empty input returns `Ok(AdjFactorsWriteStats::default())` without creating `/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 `/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..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, 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 `/corporate_actions/part.parquet` (unpartitioned). - Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating `/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 `/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..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` 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, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). ## 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`). ## 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` ## `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`