| .. | ||
| src | ||
| tests | ||
| Cargo.toml | ||
| README.md | ||
curate-etl
Dedicated Rust crate (single direct dependency: parquet 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, and the M1.2j streaming Zstd Parquet writer for shorts.
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 on2024-06-10) →ratio = 10.0. - Reverse split
1:20(e.g., NEXM.V on2025-06-18) →ratio = 0.05. - No-op rows (
ratio == 1.0) are dropped duringSplitTable::from_events. - Duplicate events on the same
ex_dateare multiplied (and dropped if reciprocal pairs cancel to1.0). - Non-finite or
<= 0.0ratios and compounding overflow/underflow return a typedSplitErrorrather than panicking.
- Forward split
- Ex-date boundary (strict
>):cum_factor_after(key, bar_date)returns the product of all split ratios withex_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 its2021-07-204:1 ex-date still hasfactor = 10.0from the later2024-06-1010:1 split). Unknown keys and dates with no later splits return1.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 * factorraw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factorunadjust_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.mdnamessplit_factor,div_cash,div_currency,cum_split_factor, andcum_total_factorwithout writing formulas. Rules 3–5 below document this crate's back-adjustment divisor definitions so downstream consumers and reviewers can verify parity withSplitTable::cum_factor_after.
Rules:
- Split normalization: Drop
ratio == 1.0no-ops (counted instats.split_noops_dropped). Multiply same-day splits inf64::total_cmporder; if they cancel back to1.0(e.g.2.0 * 0.5), drop the split component (and omit the row if no dividend is present on that date). - Dividend normalization: Drop
cash == 0.0events (counted instats.dividend_zero_cash_dropped). Sum same-day same-currency cash dividends inf64::total_cmporder intodiv_cash. Split-only rows carrydiv_cash = 0.0anddiv_currency = None; dividend-only rows carrysplit_factor = 1.0. Two different dividend currencies on the same(key, ex_date)returnAdjError::ConflictingDividendCurrency. cum_split_factor(back-adjustment divisor): Product ofsplit_factorover this row and all later rows of the same key (inclusive of the row's ownex_date). For any bar datedd, the first row withex_date > d(adj_factors_after(rows, key, d).0) matchesSplitTable::cum_factor_after(key, d)bitwise.- Per-row dividend factor:
prev_close / (prev_close - div_cash)whenprev_close(the raw close of the last session strictly beforeex_date) is present, finite,> div_cash > 0.0, andprev_close_currency == div_currency. Otherwise falls back to1.0in strict priority order while preservingdiv_cashanddiv_currencyon the row and incrementing the matching counter:dividends_missing_prev_close(prev_closeisNoneor non-finite)dividends_currency_mismatch(prev_close_currency != Some(div_currency))dividends_not_below_prev_close(prev_close <= div_cash)
cum_total_factor:cum_split_factormultiplied by the product of per-row dividend factors over this row and all later rows of the same key (inclusive of the row's ownex_date).- Validation & overflow guards: Non-finite or
<= 0.0split ratios (InvalidSplitRatio), non-finite or< 0.0dividend 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 typedAdjErrorwithout 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:
- Splits (
kind = "split"): Sameratio = new_shares / old_sharesconvention assrc/split.rs.ratio == 1.0no-ops are dropped and counted instats.split_noops_dropped. Non-finite or<= 0.0ratios returnCorporateActionError::InvalidSplitRatio. - Dividends (
kind = "dividend"): Localcurrencyandcashare preserved unchanged (deliberately omittingusdFxRate).cash == 0.0events are dropped and counted instats.dividend_zero_cash_dropped. Multiple dividends on the same(key, ex_date)remain separate event-log rows. Non-finite or< 0.0cash returnsInvalidDividendCash; empty/whitespace currency on positive cash returnsEmptyDividendCurrency. - Point-in-time
known_atclamping: Usesdeclared_datewhen present and<= ex_date(known_at_source = "declared_date"). Otherwise falls back toex_date(known_at_source = "ex_date_fallback"), preserving the rawdeclared_dateon the row and countingdeclared_date > ex_dateinstats.declared_after_ex_datesoknown_at_date <= ex_datealways holds. - Delistings (Pass 6):
successor_key = Some(s), terminal_return = None→ oneotc_delist_transferrow (ex_date = known_at_date = delist_date,known_at_source = "delist_date"). Callers must pass the Pass 6 continuityeffectiveDate(the successor's first observed OTC trading date) asdelist_date, not the primary listing's last exchange print / halt date.successor_key = None, terminal_return = Some(r)→ onedelistingrow (rmust be finite and in[-1.0, 0.0], normalizing-0.0to0.0, elseInvalidTerminalReturn).- Both
None→ dropped and counted instats.delist_without_outcome. - Both
Some→CorporateActionError::ConflictingDelistingOutcome.
- 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, andstatssatisfiesin == out + droppedper kind andknown_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:
- Raw OHLC & un-adjusted volume:
eodPricesOHLC is passed through bit-for-bit;volume = unadjust_volume(adj_volume, factor)wherefactor = splits.cum_factor_after(&key, session_date)(computed via a per-key monotonic cursor oversplits.splits_for(&key)that matchescum_factor_afterbitwise under the strictex_date > session_dateboundary). - 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, oropen/closeoutside[low, high].dropped_invalid_volume:adj_volumenon-finite or< 0.0, or post-unadjustmentvolumenon-finite or< 0.0(e.g. extreme reverse-split overflow). Zero volume (0.0/-0.0normalized to0.0) is valid and kept.
- 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). - Caller errors (
BarsError): Reserved strictly for caller configuration errors (BarsError::InvalidTolerancewhenrel_toleranceis non-finite or< 0.0). Invalid/duplicate/conflictingqmPricesrows are filtered and compacted intoqm_invalid_volume_dropped,qm_duplicate_collapsed, andqm_duplicate_conflict_droppedwithout aborting. qmPrices.sharevolumecross-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.0withvolume > 0.0→rel = INFINITY(mismatch); otherwiserel = |volume - share_volume| / share_volume(within iffrel <= rel_tolerance). - Retains up to
MAX_MISMATCH_SAMPLES(100) worst mismatches sorted deterministically by(rel DESC, key ASC, session_date ASC).
- Both
- Determinism & accounting invariants: Any permutation of
barsorqm_volumesproduces bitwise-identicalrows,stats, andmismatch_samples, and:bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + duplicate_collapsed + duplicate_conflict_droppedvolume_checked + volume_unchecked == rows_outandvolume_within_tolerance + volume_mismatched == volume_checkedqm_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 (excluding ts/known_at timestamps, which belong to the later writer task).
Rules:
- Quote convention: Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (
CADUSD.FOREXinversion is out of scope). - 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, oropen/closeoutside[low, high].
- 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). - Merge precedence:
EodCadForexwins on overlapping dates (te_superseded_by_eod += 1);TeUsdCadfills interior gaps and all dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting group). - 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 like1.4000vs.1.4140are not falsely flagged), countsoverlap_checked,overlap_within_tolerance, andoverlap_mismatched, and tracks rawmax_overlap_relwithout modifying emitted rows. - No-look-ahead lookup (
fx_rate_on_or_before): Binary-searches sortedFx1dRowslices for the latest row withsession_date <= dateanddate - session_date <= max_stale_days. Carries forward across weekends/holidays withinmax_stale_days, returnsNonebefore the first row or when stale, and never returns a later date. - Determinism & accounting invariants: Any permutation of
eodorteyields bitwise-identicalrowsandstats, 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
- Per source:
Deferred out of src/fx.rs: ts/known_at timestamp derivation (later writer 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:
- Canadian TSX business-day calendar (
2008-01-01..=2030-12-31):is_canadian_business_day(epoch_day)andadd_canadian_business_days(epoch_day, n)coverMIN_SUPPORTED_YEAR = 2008throughMAX_SUPPORTED_YEAR = 2030(MIN_SUPPORTED_DATE = 13_879..=MAX_SUPPORTED_DATE = 22_279), strictly covering the2017-01-01..=2027-12-31dataset window plus year-end+4business-day rollovers. Dates outside[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE](or stepping pastMAX_SUPPORTED_DATE) returnShortsError::DateOutOfRangerather than guessing or panicking.- Non-business days: Saturdays, Sundays, and the 9 TSX market holidays:
- New Year's Day (Jan 1; Sat → Mon Jan 3, Sun → Mon Jan 2)
- Family Day (3rd Monday of February, TSX holiday since 2008)
- Good Friday (computed Gregorian Easter Sunday − 2 days)
- Victoria Day (Monday strictly before May 25)
- Canada Day (Jul 1; Sat → Mon Jul 3, Sun → Mon Jul 2)
- Civic Holiday (1st Monday of August)
- Labour Day (1st Monday of September)
- Thanksgiving (2nd Monday of October)
- 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_dateitself falls on a non-business day (e.g. a Saturday month-end),add_canadian_business_days(report_date, 4)counts strictly forward soknown_at_dateis the 4th TSX business day strictly afterreport_date(known_at_date > report_datealways holds).
America/TorontoET → 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 ESTUTC-5). known_at_utc_microsis17:00:00 America/Torontoonknown_at_date(21:00:00 UTCin EDT,22:00:00 UTCin EST).- Rejects out-of-range dates (
DateOutOfRange), invalid wall-clock components (InvalidLocalTime), spring-forward nonexistent times02:00..03:00(NonexistentLocalTime), and fall-back ambiguous times01:00..02:00(AmbiguousLocalTime). - Exposed publicly alongside
epoch_days_to_ymdso the upcomingeventsbuilder (16:05 ETlag) can reuse it directly.
- Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November 02:00 = EDT
- Bad-row resilience, sanitization, and deduplication:
- Every input row's
report_date + 4business days is validated first so out-of-range dates fail deterministically withShortsError::DateOutOfRangeregardless of row order or bad numeric fields. - Non-finite or negative
shares_shortrows are dropped and counted indropped_invalid_shares_short(without incrementing optional-field null counters);-0.0is normalized to0.0. - Non-finite
net_changeandpct_floatvalues are sanitized toNoneand counted innulled_invalid_net_changeandnulled_invalid_pct_float;-0.0is normalized to0.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).
- Every input row's
- Determinism & accounting invariants:
- Any input permutation yields bitwise-identical
rowsandstats. rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped.
- Any input permutation yields bitwise-identical
- CIRO publication-lag note: The
+4Canadian business-day17:00 ETrule is the locked contract proxy fromdesign/DATA-CONTRACTS.md(not an observed CIRO scrape timestamp). Downstream signal studies should still run+1business-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<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:
- Filing timestamps (
kind = "filing"):parse_filing_timefiledstrictly parsesYYYY-MM-DDTHH:MM:SS EST(UTC-5) andYYYY-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)andknown_at_source = "filing_timestamp". - Malformed strings (
filings_skipped_malformed_timestamp), missing/unknown zones such asPST/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 ETare 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 ETvisibility rules on top ofknown_at_micros.
- Table-driven form groups & periodic-report predicate (
classify_form_type,is_periodic_financial_report):- Exact EDGAR codes (checked after stripping optional
/Aand standaloneAmendedmarkers such as10-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 (
/Aor standalone"amended") map to the same group withis_amendment: trueand the rawform_typepreserved inpayload_json. is_periodic_financial_reportistrueonly for10-K,10-Q,40-F,Interim financial statements, andAnnual financial statements(for the M2fundamentals_pitfiling join).
- Exact EDGAR codes (checked after stripping optional
- Earnings linking & conservative
16:05 ETlag (kind = "earnings"):- Precedence:
- If the same
keyhas a qualifying filing (8-KorNews release, including amendments) whose local ET calendar date matchesreport_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)). - Otherwise
known_at_micros = report_date 16:05:00 America/Torontoviashorts::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-date8-KorNews releasefiling supersedes the fallback with its actual filing timestamp). It applies toN/A,BTO, andAMCalike whenever no linked filing provides a real timestamp—unlinkedBTO/AMCrows are never stamped earlier than16:05 ET. - Unlinked
report_datevalues outside[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE](2008-01-01..=2030-12-31) are skipped and counted inearnings_skipped_out_of_range(pre-2008 dates with a linked same-day filing still succeed).
- If the same
ts_micros = known_at_micros;subtype= normalized announce time ("bto"/"amc"/"unknown").- Post-hoc overwritten
consensusEpsis deliberately omitted fromQmEarningandpayload_jsonperdesign/DATA-CONTRACTS.md§1.
- Precedence:
- 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.0normalized to0, and non-finitef64(NaN/±inf) emitted asnull. - 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)andEventsStatsreconciles 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).
- Hand-written
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:
- Inclusive date ranges & open-ended active spans:
valid_fromandvalid_toare UTC Gregorian epoch days (split::ymd_to_epoch_days).valid_to = Some(d)is inclusive (valid_from <= bar_date <= d);valid_to = Noneis open-ended (bar_date >= valid_from). Unknown keys, dates before the first range, interior gap dates (e.g., ticker reuseFB.US2012-05-18..=2022-06-08→2025-01-02..), and dates after a closed last range returnNone. - Verbatim key storage (no trimming): Empty or whitespace-only
source/source_idstrings returnEmptySource/EmptySourceId, but non-empty strings with leading or trailing whitespace are stored and matched verbatim (never trimmed or merged with unspaced IDs). - Strict PostgreSQL PK & overlap validation (
from_rows):- Rejects
listing_id <= 0(InvalidListingId) andvalid_to < valid_from(InvalidRange). - Exact-duplicate policy: Every duplicate
(source, source_id, valid_from)—including bitwise-identical duplicate rows—is rejected withDuplicateValidFrom, matching the PostgreSQLPRIMARY KEY (source, source_id, valid_from)constraint. - Rejects intersecting inclusive ranges (including touching endpoints
prev.valid_to == curr.valid_fromand any open-ended range followed by a later range) withOverlappingRanges. Adjacent ranges (prev.valid_to = d,curr.valid_from = d + 1) are accepted, and boundary checks avoidvalid_to + 1overflow ati32::MAX. - Deterministic for any input row permutation.
- Rejects
- Zero-allocation lookups & sorted-stream cursor:
resolve(source, source_id, bar_date)andranges_for(source, source_id)perform zero heap allocations: allMappingRanges live in a single contiguousVec<MappingRange>arena indexed by a sorted per-sourceHashMap<String, (usize, usize)>(linear scan for<= 8sources, binary search otherwise) plus binary search over the key's ranges.ProviderMappingCursor(viacursor_for(source, source_id)orProviderMappingCursor::new(ranges)) resolves ascendingbar_datestreams for a single key in amortised O(1), automatically falling back to binary search on out-of-order probes so its output always matchesProviderMappingTable::resolveidentically.
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).
- 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))
- Partition layout & compression:
- Writes
<out_dir>/bars_1d/year=YYYY/part.parquetlazily per observedsession_datecalendar year (1900..=2200); empty input and empty years create no directories or files. - Zstd compression on every column chunk (
DEFAULT_ZSTD_LEVEL = 3, configurable viaBars1dWriteOptions::zstd_level). - Bounded streaming buffers (
DEFAULT_ROW_GROUP_ROWS = 1_000_000, configurable viaBars1dWriteOptions::row_group_rows): each active year buffers at most one row group of columnar data (with string interning forcurrency/source), flushing and clearing buffers on every row-group boundary. - Deterministic
created_bymetadata so identical inputs produce byte-identicalpart.parquetfiles.
- Writes
- 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_1ddirectory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive.write.lockfile (30 s default timeout returningParquetBarsError::LockTimeoutwith 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 callsFile::sync_all()before publication. During publication, pre-existingpart.parquetfiles are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomicrename; 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 viaRollbackFailed), and only staging files owned by the current run are unlinked.
- Input must already be sorted strictly ascending by
- 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 }
- 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 years2006..=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
- Command:
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).
- 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)
- Layout, compression & streaming:
- Writes
<out_dir>/shorts/part.parquet(unpartitioned). - Empty input returns
Ok(ShortsWriteStats::default())without creating<out_dir>/shortsand without modifying or removing any pre-existingpart.parquet. - Zstd compression on every column chunk (
DEFAULT_ZSTD_LEVEL = 3, configurable viaShortsWriteOptions::zstd_level). - Bounded streaming buffer (
DEFAULT_ROW_GROUP_ROWS = 1_000_000, configurable viaShortsWriteOptions::row_group_rows): buffers at most one row group of columnar data (with string interning forsource), flushing and clearing on every row-group boundary. - Deterministic
created_bymetadata so identical inputs produce byte-identicalpart.parquetfiles.
- Writes
- Validation, concurrency & atomic publish rules:
- Input must be strictly ascending by
(listing_id, report_date)(rejecting duplicates and out-of-order rows). shares_shortmust be finite and>= 0.0;net_changeandpct_floatmust be finite whenSome;known_at_microsmust be strictly afterreport_date00:00:00 UTC(compared ini128to avoid overflow on extremei32epoch days);sourcemust be non-empty after trimming.- Reuses the shared
parquet_publishlocking and atomic publication path: concurrent writers targeting<out_dir>/shortsare serialized via an in-process per-dataset mutex and a bounded-wait exclusive.write.lockfile (30 sdefault timeout); writes go to an exclusively created per-run staging file (part.parquet.<run>.tmp), flush, andFile::sync_all(); pre-existingpart.parquetfiles are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomicrename; on any error, the writer is dropped, any pre-existingpart.parquetremains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced viaRollbackFailed.
- Input must be strictly ascending by
- 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 }
- 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 dates2017-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
- Command:
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):
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:
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:
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:
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:
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:
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:
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.52MqmFilings+444.9kqmEarnings(30,964,900rows): ~16.6 ssingle-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):
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:
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:
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
Deferred Follow-Ups (M1.3+ / M2)
This crate currently depends only on parquet (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add:
bars_1dandfx_1dschema metadata columns (ts,known_at,currency,source,vwap) requiring exchange session/timezone and listing metadataCADUSD.FOREXinversion,fx_1mintraday FX, and wiringfx_1dintosrc/adj.rscross-currency dividends- Zstd Parquet writers for the remaining curated tables (
adj_factors,corporate_actions,fx_1d,events) andqmPricesOHLC cross-check - Read-only MongoDB
RawDocumentBufstreaming cursors (eodPrices,eodIntraday1M,qmSplits) - PostgreSQL I/O preload into
ProviderMappingTableand rewiring the builders to resolve(source, source_id, bar_date) -> listing_id: i32 rayonparallel sharding across symbol/date partitions- QuestDB ILP v2 writer for time-series ingestion