T-81: M1.2h — tools/curate-etl: pure in-RAM provider_mapping table ((source, source_id, bar_date) → listing_id, date-ranged) with local benchmark (no new crates)

This commit is contained in:
Studio 2026-11-28 01:02:32 -05:00
parent 91c8d34cdc
commit 47dbb30493
7 changed files with 1542 additions and 6 deletions

View file

@ -1,6 +1,6 @@
# `curate-etl`
Dedicated zero-dependency Rust crate 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, and the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder.
Dedicated zero-dependency Rust crate 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, and the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table.
## Scope & Sign Conventions
@ -160,6 +160,22 @@ Rules:
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<MappingRange>` arena indexed by a sorted per-source `HashMap<String, (usize, usize)>` (linear scan for `<= 8` sources, binary search otherwise) plus binary search over the key's ranges.
- `ProviderMappingCursor` (via `cursor_for(source, source_id)` or `ProviderMappingCursor::new(ranges)`) resolves ascending `bar_date` streams for a single key in amortised O(1), automatically falling back to binary search on out-of-order probes so its output always matches `ProviderMappingTable::resolve` identically.
## Local Benchmarks
### `bench-split`
@ -261,6 +277,19 @@ Command: `cargo run --release -p curate-etl --offline -- bench-events`
- 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)
## Deferred Follow-Ups (`M1.3+` / `M2`)
This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add:
@ -269,6 +298,6 @@ This crate currently uses `std` only so it builds strictly offline. Follow-up ta
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
- `year=YYYY` partitioning, Zstd-compressed Parquet writer for curated daily/intraday datasets, and `qmPrices` OHLC cross-check
- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`)
- PostgreSQL `provider_mapping` preload keyed by `listing_id: i32` (supported via generic `SplitTable<K>`)
- 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

View file

@ -11,6 +11,7 @@ use crate::corporate_actions::{
};
use crate::events::{build_events, EventsStats, QmEarning, QmFiling};
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar};
use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable};
use crate::shorts::{build_shorts, epoch_days_to_ymd, CeoShortReport, ShortsError, ShortsStats};
use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable};
@ -22,8 +23,10 @@ pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000;
pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000;
pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000;
pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000;
pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000;
pub const BENCH_KEY_COUNT: usize = 20_000;
pub const BENCH_EVENT_COUNT: usize = 19_000;
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
const SHORTS_BENCH_KEY_COUNT: usize = 12_500;
const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57;
@ -33,6 +36,7 @@ const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00;
const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE;
const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500;
const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500;
const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00;
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
/// Deterministic SplitMix64 generator (zero external dependencies).
@ -1369,6 +1373,230 @@ pub fn run_events_benchmark(rows: usize) -> EventsBenchReport {
}
}
/// Summary metrics produced by [`run_provider_mapping_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ProviderMappingBenchReport {
pub key_count: usize,
pub range_count: usize,
pub multi_range_keys: usize,
pub build_elapsed_ms: f64,
pub build_rows_per_sec: f64,
pub lookups: usize,
pub hits: usize,
pub misses: usize,
pub lookup_elapsed_ms: f64,
pub lookups_per_sec: f64,
pub ns_per_lookup: f64,
pub checksum: u64,
}
struct ProviderMappingBenchKey {
source: &'static str,
source_id: String,
first_from: i32,
gap_date: Option<i32>,
last_to: Option<i32>,
}
/// Runs the fixed-seed [`ProviderMappingTable`] build and zero-allocation `resolve` benchmark.
///
/// Generates `60_000` `(source, source_id)` keys across 4 sources (`eod`, `qm`, `ib`, `ceo`),
/// with ~10% multi-range keys (2–3 date ranges and interior gaps modeling ticker reuse such as
/// `FB` 2012–2022 -> `FB` 2025 ETF), shuffles input rows before timing `from_rows`, then runs
/// `lookups` zero-allocation `resolve` probes with ~5% misses spanning unknown key/source,
/// pre-first, interior gap, and post-last dates.
pub fn run_provider_mapping_benchmark(
lookups: usize,
) -> Result<ProviderMappingBenchReport, ProviderMappingError> {
const SOURCES: [&str; 4] = ["eod", "qm", "ib", "ceo"];
let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305);
let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453);
let mut rng = SplitMix64::new(PROVIDER_MAPPING_BENCH_SEED);
let mut rows: Vec<ProviderMappingRow> =
Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT + 8_000);
let mut bench_keys: Vec<ProviderMappingBenchKey> =
Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT);
let mut multi_range_indices: Vec<usize> =
Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT / 10 + 16);
let mut closed_last_indices: Vec<usize> =
Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT / 3);
let mut next_listing_id = 1i32;
for k in 0..PROVIDER_MAPPING_BENCH_KEY_COUNT {
let source = SOURCES[k % SOURCES.len()];
let source_id = match k % SOURCES.len() {
0 => format!("SYM{k:05}.US"),
1 => format!("QM{k:05}"),
2 => format!("{}", 100_000_000 + k),
_ => format!("CEO{k:05}"),
};
let range_count = if k % 30 == 0 {
3
} else if k % 10 == 0 {
2
} else {
1
};
let first_from = min_date + (rng.next_u64() % 3_000) as i32;
let mut cur_from = first_from;
let mut gap_date: Option<i32> = None;
let mut last_to: Option<i32> = None;
for r in 0..range_count {
let is_last = r + 1 == range_count;
let is_open_ended = is_last && (k % 4 != 0);
let span = 600 + (rng.next_u64() % 1_800) as i32;
let valid_to = if is_open_ended {
None
} else {
Some((cur_from + span).min(max_date - 30))
};
rows.push(ProviderMappingRow {
source: source.to_string(),
source_id: source_id.clone(),
valid_from: cur_from,
valid_to,
listing_id: next_listing_id,
});
next_listing_id += 1;
if let Some(to) = valid_to {
if is_last {
last_to = Some(to);
} else {
if gap_date.is_none() {
gap_date = Some(to + 1);
}
let gap_len = 60 + (rng.next_u64() % 400) as i32;
cur_from = to + 1 + gap_len;
}
}
}
if range_count > 1 {
multi_range_indices.push(k);
}
if last_to.is_some() {
closed_last_indices.push(k);
}
bench_keys.push(ProviderMappingBenchKey {
source,
source_id,
first_from,
gap_date,
last_to,
});
}
let multi_range_keys = multi_range_indices.len();
let row_count = rows.len();
shuffle_slice(&mut rows, &mut rng);
let build_start = Instant::now();
let table = ProviderMappingTable::from_rows(rows)?;
let build_elapsed_secs = build_start.elapsed().as_secs_f64();
let build_elapsed_ms = build_elapsed_secs * 1_000.0;
let (build_rows_per_sec, _) = compute_rates(row_count, build_elapsed_secs);
if lookups == 0 {
return Ok(ProviderMappingBenchReport {
key_count: table.len(),
range_count: table.range_count(),
multi_range_keys,
build_elapsed_ms,
build_rows_per_sec,
lookups: 0,
hits: 0,
misses: 0,
lookup_elapsed_ms: 0.0,
lookups_per_sec: 0.0,
ns_per_lookup: 0.0,
checksum: 0,
});
}
let key_count = bench_keys.len();
let multi_len = multi_range_indices.len();
let closed_len = closed_last_indices.len();
let mut hits = 0usize;
let mut misses = 0usize;
let mut hash = 0u64;
let lookup_start = Instant::now();
for _ in 0..lookups {
let roll = rng.next_u64() % 100;
let resolved = if roll < 5 {
match roll {
0 => {
let src = SOURCES[(rng.next_u64() as usize) % SOURCES.len()];
table.resolve(src, "UNKNOWN_999999", min_date + 5_000)
}
1 => {
let key = &bench_keys[(rng.next_u64() as usize) % key_count];
table.resolve("unknown_src", key.source_id.as_str(), key.first_from)
}
2 => {
let key = &bench_keys[(rng.next_u64() as usize) % key_count];
table.resolve(key.source, key.source_id.as_str(), key.first_from - 1)
}
3 => {
let idx = multi_range_indices[(rng.next_u64() as usize) % multi_len];
let key = &bench_keys[idx];
let probe = key.gap_date.unwrap_or(key.first_from - 1);
table.resolve(key.source, key.source_id.as_str(), probe)
}
_ => {
let idx = closed_last_indices[(rng.next_u64() as usize) % closed_len];
let key = &bench_keys[idx];
let probe = key.last_to.map_or(key.first_from - 1, |to| to + 1);
table.resolve(key.source, key.source_id.as_str(), probe)
}
}
} else {
let key = &bench_keys[(rng.next_u64() as usize) % key_count];
let hi = key.last_to.unwrap_or(max_date);
let span = (hi - key.first_from + 1).max(1) as u64;
let bar_date = key.first_from + (rng.next_u64() % span) as i32;
table.resolve(key.source, key.source_id.as_str(), bar_date)
};
match resolved {
Some(listing_id) => {
hits += 1;
hash = mix_u64(hash, listing_id as u64);
}
None => {
misses += 1;
hash = mix_u64(hash, u64::MAX);
}
}
}
let checksum = black_box(hash);
let lookup_elapsed_secs = lookup_start.elapsed().as_secs_f64();
let lookup_elapsed_ms = lookup_elapsed_secs * 1_000.0;
let (lookups_per_sec, ns_per_lookup) = compute_rates(lookups, lookup_elapsed_secs);
Ok(ProviderMappingBenchReport {
key_count: table.len(),
range_count: table.range_count(),
multi_range_keys,
build_elapsed_ms,
build_rows_per_sec,
lookups,
hits,
misses,
lookup_elapsed_ms,
lookups_per_sec,
ns_per_lookup,
checksum,
})
}
#[cfg(test)]
mod tests {
use super::*;
@ -1662,4 +1890,45 @@ mod tests {
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.ns_per_row, 0.0);
}
#[test]
fn provider_mapping_benchmark_small_run_is_deterministic() {
let a = run_provider_mapping_benchmark(50_000).unwrap();
let b = run_provider_mapping_benchmark(50_000).unwrap();
assert_eq!(a.key_count, PROVIDER_MAPPING_BENCH_KEY_COUNT);
assert_eq!(a.key_count, b.key_count);
assert_eq!(a.range_count, b.range_count);
assert!(a.range_count > a.key_count);
assert_eq!(a.multi_range_keys, b.multi_range_keys);
assert_eq!(a.multi_range_keys, PROVIDER_MAPPING_BENCH_KEY_COUNT / 10);
assert_eq!(a.lookups, 50_000);
assert_eq!(a.hits + a.misses, a.lookups);
assert_eq!(a.hits, b.hits);
assert_eq!(a.misses, b.misses);
assert!(a.hits > 0 && a.misses > 0);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert!(a.build_rows_per_sec.is_finite() && a.build_rows_per_sec >= 0.0);
assert!(a.lookups_per_sec.is_finite() && a.lookups_per_sec >= 0.0);
assert!(a.ns_per_lookup.is_finite() && a.ns_per_lookup >= 0.0);
}
#[test]
fn provider_mapping_benchmark_zero_lookups_handles_cleanly() {
let report = run_provider_mapping_benchmark(0).unwrap();
assert_eq!(report.key_count, PROVIDER_MAPPING_BENCH_KEY_COUNT);
assert!(report.range_count > report.key_count);
assert_eq!(
report.multi_range_keys,
PROVIDER_MAPPING_BENCH_KEY_COUNT / 10
);
assert_eq!(report.lookups, 0);
assert_eq!(report.hits, 0);
assert_eq!(report.misses, 0);
assert_eq!(report.lookup_elapsed_ms, 0.0);
assert_eq!(report.lookups_per_sec, 0.0);
assert_eq!(report.ns_per_lookup, 0.0);
assert_eq!(report.checksum, 0);
}
}

View file

@ -6,7 +6,7 @@
use crate::bench::{
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
DEFAULT_SHORTS_BENCH_ROWS,
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
};
/// Parsed CLI command to execute.
@ -21,6 +21,7 @@ pub enum CliAction {
BenchFx(usize),
BenchShorts(usize),
BenchEvents(usize),
BenchProviderMapping(usize),
}
/// Formats full help text including binary name and version.
@ -37,7 +38,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\
{name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\
{name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})"
{name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})"
)
}
@ -53,7 +55,8 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-bars [rows]\n\
{name} bench-fx [rows]\n\
{name} bench-shorts [rows]\n\
{name} bench-events [rows]"
{name} bench-events [rows]\n\
{name} bench-provider-mapping [lookups]"
)
}
@ -126,6 +129,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
)),
},
["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()),
["bench-provider-mapping"] => Ok(CliAction::BenchProviderMapping(
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS,
)),
["bench-provider-mapping", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchProviderMapping(n)),
_ => Err(format!(
"invalid lookup count '{raw}' (expected a positive integer)"
)),
},
["bench-provider-mapping", _, ..] => {
Err("too many arguments for bench-provider-mapping".to_string())
}
[other, ..] => Err(format!("unknown argument '{other}'")),
}
}
@ -275,6 +290,24 @@ mod tests {
assert!(parse_args(&to_args(&["bench-events", "10", "20"])).is_err());
}
#[test]
fn parses_and_validates_bench_provider_mapping_args() {
assert_eq!(
parse_args(&to_args(&["bench-provider-mapping"])),
Ok(CliAction::BenchProviderMapping(
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS
))
);
assert_eq!(
parse_args(&to_args(&["bench-provider-mapping", "250000"])),
Ok(CliAction::BenchProviderMapping(250_000))
);
assert!(parse_args(&to_args(&["bench-provider-mapping", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-provider-mapping", "-5"])).is_err());
assert!(parse_args(&to_args(&["bench-provider-mapping", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-provider-mapping", "10", "20"])).is_err());
}
#[test]
fn usage_strings_mention_all_benchmarks() {
let full = format_usage("curate-etl", "0.1.0");
@ -285,6 +318,7 @@ mod tests {
assert!(full.contains("bench-fx"));
assert!(full.contains("bench-shorts"));
assert!(full.contains("bench-events"));
assert!(full.contains("bench-provider-mapping"));
let short = format_usage_stderr("curate-etl");
assert!(short.contains("bench-split"));
@ -294,5 +328,6 @@ mod tests {
assert!(short.contains("bench-fx"));
assert!(short.contains("bench-shorts"));
assert!(short.contains("bench-events"));
assert!(short.contains("bench-provider-mapping"));
}
}

View file

@ -7,6 +7,7 @@ pub mod cli;
pub mod corporate_actions;
pub mod events;
pub mod fx;
pub mod provider_mapping;
pub mod shorts;
pub mod split;
@ -35,6 +36,10 @@ pub use fx::{
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
};
pub use provider_mapping::{
MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow,
ProviderMappingTable,
};
pub use shorts::{
add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros,
is_canadian_business_day, CeoShortReport, ShortRow, ShortsBuild, ShortsError, ShortsStats,

View file

@ -5,7 +5,7 @@ use std::process::ExitCode;
use curate_etl::bench::{
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark,
run_fx_benchmark, run_shorts_benchmark, run_split_benchmark,
run_fx_benchmark, run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
};
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
@ -265,6 +265,35 @@ fn main() -> ExitCode {
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchProviderMapping(lookups)) => {
let report = match run_provider_mapping_benchmark(lookups) {
Ok(report) => report,
Err(err) => {
eprintln!("error: provider_mapping benchmark failed: {err}");
return ExitCode::FAILURE;
}
};
println!("curate-etl bench-provider-mapping");
println!(
" table: keys={} ranges={} multi_range_keys={} build={:.2} ms throughput={:.0} rows/s",
report.key_count,
report.range_count,
report.multi_range_keys,
report.build_elapsed_ms,
report.build_rows_per_sec
);
println!(
" lookup: lookups={} hits={} misses={} elapsed={:.2} ms throughput={:.0} lookups/s latency={:.2} ns/lookup checksum=0x{:016x}",
report.lookups,
report.hits,
report.misses,
report.lookup_elapsed_ms,
report.lookups_per_sec,
report.ns_per_lookup,
report.checksum
);
ExitCode::SUCCESS
}
Err(msg) => {
eprintln!("error: {msg}");
eprintln!("{}", format_usage_stderr(NAME));

View file

@ -0,0 +1,867 @@
//! Pure in-RAM `provider_mapping` lookup table mapping `(source, source_id, bar_date)` to a
//! permanent `listing_id` over inclusive date ranges.
//!
//! Mirrors `provider_mapping` in `database/postgres/init/34-security-master.sql`:
//! - `valid_from` and `valid_to` are UTC Gregorian epoch days (same convention as
//! [`crate::split::ymd_to_epoch_days`]).
//! - `valid_to` is **inclusive**; `None` denotes an open-ended active range.
//! - Primary key is `(source, source_id, valid_from)`: every duplicate `(source, source_id,
//! valid_from)`—including bitwise-identical duplicate rows—is rejected with
//! [`ProviderMappingError::DuplicateValidFrom`].
//! - Source and `source_id` strings are stored and matched **verbatim** (never trimmed or
//! case-folded), while empty or whitespace-only strings are rejected.
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
/// A single raw `provider_mapping` row used to build a [`ProviderMappingTable`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderMappingRow {
/// Provider source identifier (e.g. `"eod"`, `"qm"`, `"ib"`, `"ceo"`).
pub source: String,
/// Provider-native security identifier (stored and matched verbatim, never trimmed).
pub source_id: String,
/// Inclusive start date as days since `1970-01-01` (UTC Gregorian).
pub valid_from: i32,
/// Inclusive end date as days since `1970-01-01`, or `None` for open-ended ranges.
pub valid_to: Option<i32>,
/// Permanent positive security master `listing_id`.
pub listing_id: i32,
}
/// A validated, non-overlapping inclusive date range in [`ProviderMappingTable`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MappingRange {
/// Inclusive start date as days since `1970-01-01`.
pub valid_from: i32,
/// Inclusive end date as days since `1970-01-01`, or `None` for open-ended ranges.
pub valid_to: Option<i32>,
/// Permanent positive security master `listing_id`.
pub listing_id: i32,
}
impl MappingRange {
/// Returns `true` if `bar_date` falls within `[valid_from, valid_to]` (or `[valid_from, +inf)`
/// when `valid_to` is `None`).
#[inline]
pub fn contains(&self, bar_date: i32) -> bool {
bar_date >= self.valid_from && self.valid_to.is_none_or(|to| bar_date <= to)
}
}
/// Typed errors returned while building a [`ProviderMappingTable`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderMappingError {
/// `source` was empty or contained only whitespace.
EmptySource,
/// `source_id` was empty or contained only whitespace.
EmptySourceId { source: String },
/// `listing_id` was `<= 0`.
InvalidListingId {
source: String,
source_id: String,
listing_id: i32,
},
/// `valid_to < valid_from`.
InvalidRange {
source: String,
source_id: String,
valid_from: i32,
valid_to: i32,
},
/// Duplicate `(source, source_id, valid_from)` primary key (including identical duplicate rows).
DuplicateValidFrom {
source: String,
source_id: String,
valid_from: i32,
},
/// Two inclusive ranges for the same `(source, source_id)` intersect, or an open-ended range
/// is followed by a later range.
OverlappingRanges {
source: String,
source_id: String,
first_valid_from: i32,
first_valid_to: Option<i32>,
second_valid_from: i32,
second_valid_to: Option<i32>,
},
}
impl fmt::Display for ProviderMappingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptySource => write!(f, "provider_mapping source must not be empty or blank"),
Self::EmptySourceId { source } => {
write!(
f,
"provider_mapping source_id for source '{source}' must not be empty or blank"
)
}
Self::InvalidListingId {
source,
source_id,
listing_id,
} => write!(
f,
"invalid listing_id {listing_id} for ({source}, {source_id}): must be > 0"
),
Self::InvalidRange {
source,
source_id,
valid_from,
valid_to,
} => write!(
f,
"invalid date range [{valid_from}, {valid_to}] for ({source}, {source_id}): valid_to < valid_from"
),
Self::DuplicateValidFrom {
source,
source_id,
valid_from,
} => write!(
f,
"duplicate primary key ({source}, {source_id}, valid_from={valid_from})"
),
Self::OverlappingRanges {
source,
source_id,
first_valid_from,
first_valid_to,
second_valid_from,
second_valid_to,
} => write!(
f,
"overlapping date ranges [{first_valid_from}, {first_valid_to:?}] and [{second_valid_from}, {second_valid_to:?}] for ({source}, {source_id})"
),
}
}
}
impl Error for ProviderMappingError {}
type SourceIndex = HashMap<String, (usize, usize)>;
type SourceGroupedRows = HashMap<String, Vec<MappingRange>>;
/// Zero-allocation in-RAM `provider_mapping` lookup table.
///
/// All [`MappingRange`] entries are packed into a single contiguous `Vec<MappingRange>` arena
/// indexed by a source-partitioned map (`by_source` sorted by `source`, each mapping `source_id`
/// to `(start, len)` in `ranges`). Lookups perform zero heap allocations: one tiny source scan
/// (or binary search for `> 8` sources), one `HashMap::get(source_id)` probe, and one binary
/// search over the key's contiguous range slice.
#[derive(Debug, Clone, Default)]
pub struct ProviderMappingTable {
ranges: Vec<MappingRange>,
by_source: Vec<(String, SourceIndex)>,
key_count: usize,
}
impl ProviderMappingTable {
/// Builds a [`ProviderMappingTable`] from an arbitrary (possibly unsorted) stream of
/// [`ProviderMappingRow`]s.
///
/// - Rejects empty or whitespace-only `source` / `source_id` without trimming stored values.
/// - Rejects `listing_id <= 0` with [`ProviderMappingError::InvalidListingId`].
/// - Rejects `valid_to < valid_from` with [`ProviderMappingError::InvalidRange`].
/// - Rejects every duplicate `(source, source_id, valid_from)`—including bitwise-identical
/// duplicate rows—with [`ProviderMappingError::DuplicateValidFrom`], matching the PostgreSQL
/// `PRIMARY KEY (source, source_id, valid_from)` constraint.
/// - Rejects intersecting inclusive ranges (including an open-ended range followed by a later
/// range) with [`ProviderMappingError::OverlappingRanges`]. Adjacent ranges (`valid_to = d`,
/// next `valid_from = d + 1`) are accepted.
/// - Deterministic for any permutation of valid input rows.
pub fn from_rows<I>(rows: I) -> Result<Self, ProviderMappingError>
where
I: IntoIterator<Item = ProviderMappingRow>,
{
let mut grouped: HashMap<String, SourceGroupedRows> = HashMap::new();
let mut total_rows = 0usize;
for row in rows {
if row.source.trim().is_empty() {
return Err(ProviderMappingError::EmptySource);
}
if row.source_id.trim().is_empty() {
return Err(ProviderMappingError::EmptySourceId { source: row.source });
}
if row.listing_id <= 0 {
return Err(ProviderMappingError::InvalidListingId {
source: row.source,
source_id: row.source_id,
listing_id: row.listing_id,
});
}
if let Some(valid_to) = row.valid_to {
if valid_to < row.valid_from {
return Err(ProviderMappingError::InvalidRange {
source: row.source,
source_id: row.source_id,
valid_from: row.valid_from,
valid_to,
});
}
}
grouped
.entry(row.source)
.or_default()
.entry(row.source_id)
.or_default()
.push(MappingRange {
valid_from: row.valid_from,
valid_to: row.valid_to,
listing_id: row.listing_id,
});
total_rows += 1;
}
let mut sources: Vec<(String, SourceGroupedRows)> = grouped.into_iter().collect();
sources.sort_unstable_by(|a, b| a.0.cmp(&b.0));
let mut ranges = Vec::with_capacity(total_rows);
let mut by_source = Vec::with_capacity(sources.len());
let mut key_count = 0usize;
for (source, source_map) in sources {
let mut entries: Vec<(String, Vec<MappingRange>)> = source_map.into_iter().collect();
entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
let mut index = HashMap::with_capacity(entries.len());
for (source_id, mut key_ranges) in entries {
key_ranges.sort_unstable_by(|a, b| {
a.valid_from
.cmp(&b.valid_from)
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
.then_with(|| a.listing_id.cmp(&b.listing_id))
});
for pair in key_ranges.windows(2) {
let prev = pair[0];
let curr = pair[1];
if prev.valid_from == curr.valid_from {
return Err(ProviderMappingError::DuplicateValidFrom {
source,
source_id,
valid_from: curr.valid_from,
});
}
let overlaps = match prev.valid_to {
None => true,
Some(prev_to) => prev_to >= curr.valid_from,
};
if overlaps {
return Err(ProviderMappingError::OverlappingRanges {
source,
source_id,
first_valid_from: prev.valid_from,
first_valid_to: prev.valid_to,
second_valid_from: curr.valid_from,
second_valid_to: curr.valid_to,
});
}
}
let start = ranges.len();
let count = key_ranges.len();
ranges.extend_from_slice(&key_ranges);
index.insert(source_id, (start, count));
key_count += 1;
}
by_source.push((source, index));
}
ranges.shrink_to_fit();
Ok(Self {
ranges,
by_source,
key_count,
})
}
/// Number of distinct `(source, source_id)` keys in the table.
#[inline]
pub fn len(&self) -> usize {
self.key_count
}
/// Returns `true` if the table contains no keys.
#[inline]
pub fn is_empty(&self) -> bool {
self.key_count == 0
}
/// Total number of [`MappingRange`] rows stored across all keys.
#[inline]
pub fn range_count(&self) -> usize {
self.ranges.len()
}
/// Returns the sorted, non-overlapping [`MappingRange`] slice for `(source, source_id)`
/// (empty slice if absent). Performs zero heap allocations.
#[inline]
pub fn ranges_for(&self, source: &str, source_id: &str) -> &[MappingRange] {
let map = if self.by_source.len() <= 8 {
self.by_source
.iter()
.find(|(s, _)| s.as_str() == source)
.map(|(_, m)| m)
} else {
self.by_source
.binary_search_by(|(s, _)| s.as_str().cmp(source))
.ok()
.and_then(|idx| self.by_source.get(idx).map(|(_, m)| m))
};
let Some(map) = map else {
return &[];
};
let Some(&(start, len)) = map.get(source_id) else {
return &[];
};
self.ranges.get(start..start + len).unwrap_or(&[])
}
/// Resolves `(source, source_id, bar_date)` to its permanent `listing_id`, or `None` if
/// `(source, source_id)` is unknown or `bar_date` does not fall inside any inclusive range.
///
/// Performs zero heap allocations.
#[inline]
pub fn resolve(&self, source: &str, source_id: &str, bar_date: i32) -> Option<i32> {
let slice = self.ranges_for(source, source_id);
let idx = slice.partition_point(|r| r.valid_from <= bar_date);
if idx == 0 {
return None;
}
let candidate = &slice[idx - 1];
candidate.contains(bar_date).then_some(candidate.listing_id)
}
/// Creates a [`ProviderMappingCursor`] positioned over the ranges for `(source, source_id)`
/// for amortised O(1) resolution of ascending `bar_date` streams.
#[inline]
pub fn cursor_for(&self, source: &str, source_id: &str) -> ProviderMappingCursor<'_> {
ProviderMappingCursor::new(self.ranges_for(source, source_id))
}
}
/// Stateful per-key cursor for resolving sorted (ascending) `bar_date` streams in amortised O(1).
///
/// If a caller probes an out-of-order (earlier) `bar_date`, the cursor automatically repositions
/// via binary search so results always match [`ProviderMappingTable::resolve`] exactly.
#[derive(Debug, Clone, Copy)]
pub struct ProviderMappingCursor<'a> {
ranges: &'a [MappingRange],
idx: usize,
last_date: i32,
}
impl<'a> ProviderMappingCursor<'a> {
/// Creates a new cursor over a sorted, non-overlapping slice of [`MappingRange`]s (such as
/// one returned by [`ProviderMappingTable::ranges_for`]).
#[inline]
pub fn new(ranges: &'a [MappingRange]) -> Self {
Self {
ranges,
idx: 0,
last_date: i32::MIN,
}
}
/// Returns the underlying [`MappingRange`] slice.
#[inline]
pub fn ranges(&self) -> &'a [MappingRange] {
self.ranges
}
/// Resets the cursor back to the beginning of its range slice.
#[inline]
pub fn reset(&mut self) {
self.idx = 0;
self.last_date = i32::MIN;
}
/// Resolves `bar_date` against the cursor's ranges.
///
/// Runs in amortised O(1) for non-decreasing `bar_date` sequences and falls back to binary
/// search if `bar_date < last_date`.
#[inline]
pub fn resolve(&mut self, bar_date: i32) -> Option<i32> {
if bar_date < self.last_date {
self.idx = self
.ranges
.partition_point(|r| matches!(r.valid_to, Some(to) if to < bar_date));
} else {
while let Some(range) = self.ranges.get(self.idx) {
match range.valid_to {
Some(to) if to < bar_date => self.idx += 1,
_ => break,
}
}
}
self.last_date = bar_date;
self.ranges
.get(self.idx)
.filter(|r| bar_date >= r.valid_from)
.map(|r| r.listing_id)
}
}
#[inline]
fn valid_to_sort_key(valid_to: Option<i32>) -> i64 {
valid_to.map_or(i64::MAX, i64::from)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::split::ymd_to_epoch_days;
fn row(
source: &str,
source_id: &str,
valid_from: i32,
valid_to: Option<i32>,
listing_id: i32,
) -> ProviderMappingRow {
ProviderMappingRow {
source: source.to_string(),
source_id: source_id.to_string(),
valid_from,
valid_to,
listing_id,
}
}
struct TestRng(u64);
impl TestRng {
fn new(seed: u64) -> Self {
Self(seed)
}
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn shuffle<T>(&mut self, items: &mut [T]) {
for i in (1..items.len()).rev() {
let j = (self.next_u64() % (i as u64 + 1)) as usize;
items.swap(i, j);
}
}
}
#[test]
fn ticker_reuse_fb_us_inclusive_boundaries_and_gap() {
let d_2012_05_17 = ymd_to_epoch_days(2012, 5, 17).unwrap();
let d_2012_05_18 = ymd_to_epoch_days(2012, 5, 18).unwrap();
let d_2018_07_01 = ymd_to_epoch_days(2018, 7, 1).unwrap();
let d_2022_06_08 = ymd_to_epoch_days(2022, 6, 8).unwrap();
let d_2022_06_09 = ymd_to_epoch_days(2022, 6, 9).unwrap();
let d_2023_06_01 = ymd_to_epoch_days(2023, 6, 1).unwrap();
let d_2025_01_01 = ymd_to_epoch_days(2025, 1, 1).unwrap();
let d_2025_01_02 = ymd_to_epoch_days(2025, 1, 2).unwrap();
let d_2026_11_28 = ymd_to_epoch_days(2026, 11, 28).unwrap();
let table = ProviderMappingTable::from_rows([
row("eod", "FB.US", d_2025_01_02, None, 2),
row("eod", "FB.US", d_2012_05_18, Some(d_2022_06_08), 1),
])
.unwrap();
assert_eq!(table.len(), 1);
assert!(!table.is_empty());
assert_eq!(table.range_count(), 2);
assert_eq!(table.resolve("eod", "FB.US", d_2012_05_17), None);
assert_eq!(table.resolve("eod", "FB.US", d_2012_05_18), Some(1));
assert_eq!(table.resolve("eod", "FB.US", d_2018_07_01), Some(1));
assert_eq!(table.resolve("eod", "FB.US", d_2022_06_08), Some(1));
assert_eq!(table.resolve("eod", "FB.US", d_2022_06_09), None);
assert_eq!(table.resolve("eod", "FB.US", d_2023_06_01), None);
assert_eq!(table.resolve("eod", "FB.US", d_2025_01_01), None);
assert_eq!(table.resolve("eod", "FB.US", d_2025_01_02), Some(2));
assert_eq!(table.resolve("eod", "FB.US", d_2026_11_28), Some(2));
assert_eq!(table.resolve("eod", "FB.US", i32::MAX), Some(2));
}
#[test]
fn unknown_keys_cross_source_isolation_and_verbatim_whitespace_ids() {
let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap();
let d2 = ymd_to_epoch_days(2024, 1, 2).unwrap();
let table = ProviderMappingTable::from_rows([
row("eod", "AAPL.US", d1, None, 10),
row("eod", " AAPL.US ", d1, None, 11),
row("qm", "AAPL", d1, None, 12),
])
.unwrap();
assert_eq!(table.len(), 3);
assert_eq!(table.range_count(), 3);
// Exact matches, including verbatim whitespace preservation (no trimming/merging).
assert_eq!(table.resolve("eod", "AAPL.US", d2), Some(10));
assert_eq!(table.resolve("eod", " AAPL.US ", d2), Some(11));
assert_eq!(table.resolve("qm", "AAPL", d2), Some(12));
// Unknown source, unknown source_id, cross-source isolation, and unspaced vs spaced.
assert_eq!(table.resolve("ib", "AAPL.US", d2), None);
assert_eq!(table.resolve("eod", "MSFT.US", d2), None);
assert_eq!(table.resolve("qm", "AAPL.US", d2), None);
assert_eq!(table.resolve("eod", "AAPL", d2), None);
assert_eq!(table.resolve("eod", " AAPL.US", d2), None);
assert_eq!(table.resolve("eod", "AAPL.US ", d2), None);
assert!(table.ranges_for("ib", "AAPL.US").is_empty());
assert!(table.ranges_for("eod", "MSFT.US").is_empty());
}
#[test]
fn more_than_eight_sources_uses_binary_search_path() {
let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap();
let sources = [
"s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10",
];
let rows: Vec<_> = sources
.iter()
.enumerate()
.map(|(i, s)| row(s, "SYM", d1, None, (i + 1) as i32))
.collect();
let table = ProviderMappingTable::from_rows(rows).unwrap();
assert_eq!(table.len(), 10);
for (i, s) in sources.iter().enumerate() {
assert_eq!(table.resolve(s, "SYM", d1), Some((i + 1) as i32));
}
assert_eq!(table.resolve("s00", "SYM", d1), None);
assert_eq!(table.resolve("s99", "SYM", d1), None);
}
#[test]
fn from_rows_rejects_empty_source_and_empty_source_id() {
let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap();
for bad_source in ["", " ", "\t\n"] {
let err = ProviderMappingTable::from_rows([row(bad_source, "AAPL.US", d1, None, 1)])
.unwrap_err();
assert_eq!(err, ProviderMappingError::EmptySource);
assert!(!err.to_string().is_empty());
}
for bad_id in ["", " ", "\t\r\n"] {
let err =
ProviderMappingTable::from_rows([row("eod", bad_id, d1, None, 1)]).unwrap_err();
assert_eq!(
err,
ProviderMappingError::EmptySourceId {
source: "eod".to_string()
}
);
assert!(err.to_string().contains("eod"));
}
}
#[test]
fn from_rows_rejects_invalid_listing_id_and_invalid_range() {
let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap();
let d0 = d1 - 1;
for bad_id in [0, -1, i32::MIN] {
let err = ProviderMappingTable::from_rows([row("eod", "AAPL.US", d1, None, bad_id)])
.unwrap_err();
assert_eq!(
err,
ProviderMappingError::InvalidListingId {
source: "eod".to_string(),
source_id: "AAPL.US".to_string(),
listing_id: bad_id,
}
);
assert!(err.to_string().contains("listing_id"));
}
let err = ProviderMappingTable::from_rows([row("eod", "AAPL.US", d1, Some(d0), 1)])
.unwrap_err();
assert_eq!(
err,
ProviderMappingError::InvalidRange {
source: "eod".to_string(),
source_id: "AAPL.US".to_string(),
valid_from: d1,
valid_to: d0,
}
);
assert!(err.to_string().contains("valid_to < valid_from"));
}
#[test]
fn from_rows_rejects_duplicate_valid_from_including_exact_duplicates() {
let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap();
let d2 = ymd_to_epoch_days(2022, 1, 2).unwrap();
// Bitwise-identical duplicate row is rejected (matches Postgres PK).
let exact_dup = ProviderMappingTable::from_rows([
row("eod", "AAPL.US", d1, Some(d2), 1),
row("eod", "AAPL.US", d1, Some(d2), 1),
])
.unwrap_err();
assert_eq!(
exact_dup,
ProviderMappingError::DuplicateValidFrom {
source: "eod".to_string(),
source_id: "AAPL.US".to_string(),
valid_from: d1,
}
);
assert!(exact_dup.to_string().contains("duplicate primary key"));
// Same valid_from with different listing_id / valid_to is also rejected.
let diff_dup = ProviderMappingTable::from_rows([
row("eod", "AAPL.US", d1, Some(d2), 1),
row("eod", "AAPL.US", d1, None, 2),
])
.unwrap_err();
assert_eq!(
diff_dup,
ProviderMappingError::DuplicateValidFrom {
source: "eod".to_string(),
source_id: "AAPL.US".to_string(),
valid_from: d1,
}
);
}
#[test]
fn from_rows_rejects_overlapping_ranges_and_open_ended_followed_by_later() {
let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap();
let d2 = ymd_to_epoch_days(2021, 1, 1).unwrap();
let d3 = ymd_to_epoch_days(2022, 1, 1).unwrap();
// Touching endpoint (valid_to == next valid_from) is an overlap because valid_to is inclusive.
let touching = ProviderMappingTable::from_rows([
row("eod", "FB.US", d1, Some(d2), 1),
row("eod", "FB.US", d2, Some(d3), 2),
])
.unwrap_err();
assert_eq!(
touching,
ProviderMappingError::OverlappingRanges {
source: "eod".to_string(),
source_id: "FB.US".to_string(),
first_valid_from: d1,
first_valid_to: Some(d2),
second_valid_from: d2,
second_valid_to: Some(d3),
}
);
assert!(touching.to_string().contains("overlapping"));
// Interior overlap.
let interior = ProviderMappingTable::from_rows([
row("eod", "FB.US", d1, Some(d3), 1),
row("eod", "FB.US", d2, None, 2),
])
.unwrap_err();
assert!(matches!(
interior,
ProviderMappingError::OverlappingRanges { .. }
));
// Open-ended row followed by a later row.
let open_then_later = ProviderMappingTable::from_rows([
row("eod", "FB.US", d2, Some(d3), 2),
row("eod", "FB.US", d1, None, 1),
])
.unwrap_err();
assert_eq!(
open_then_later,
ProviderMappingError::OverlappingRanges {
source: "eod".to_string(),
source_id: "FB.US".to_string(),
first_valid_from: d1,
first_valid_to: None,
second_valid_from: d2,
second_valid_to: Some(d3),
}
);
}
#[test]
fn adjacent_ranges_and_i32_extremes_do_not_overflow() {
let d = ymd_to_epoch_days(2022, 6, 8).unwrap();
let table = ProviderMappingTable::from_rows([
row("eod", "ADJ.US", d - 100, Some(d), 1),
row("eod", "ADJ.US", d + 1, Some(d + 1), 2), // single-day range
row("eod", "ADJ.US", d + 2, None, 3),
row("eod", "EXTREME.US", i32::MIN, Some(i32::MIN), 10),
row("eod", "EXTREME.US", i32::MIN + 1, Some(i32::MAX - 1), 11),
row("eod", "EXTREME.US", i32::MAX, Some(i32::MAX), 12),
])
.unwrap();
assert_eq!(table.resolve("eod", "ADJ.US", d), Some(1));
assert_eq!(table.resolve("eod", "ADJ.US", d + 1), Some(2));
assert_eq!(table.resolve("eod", "ADJ.US", d + 2), Some(3));
assert_eq!(table.resolve("eod", "EXTREME.US", i32::MIN), Some(10));
assert_eq!(table.resolve("eod", "EXTREME.US", i32::MIN + 1), Some(11));
assert_eq!(table.resolve("eod", "EXTREME.US", 0), Some(11));
assert_eq!(table.resolve("eod", "EXTREME.US", i32::MAX - 1), Some(11));
assert_eq!(table.resolve("eod", "EXTREME.US", i32::MAX), Some(12));
// Verify valid_to == Some(i32::MAX) with a second overlapping row doesn't overflow.
let err = ProviderMappingTable::from_rows([
row("eod", "MAXOVF", 0, Some(i32::MAX), 1),
row("eod", "MAXOVF", i32::MAX, Some(i32::MAX), 2),
])
.unwrap_err();
assert!(matches!(
err,
ProviderMappingError::OverlappingRanges { .. }
));
}
#[test]
fn empty_table_and_permutation_invariance() {
let empty = ProviderMappingTable::from_rows(std::iter::empty()).unwrap();
assert!(empty.is_empty());
assert_eq!(empty.len(), 0);
assert_eq!(empty.range_count(), 0);
assert_eq!(empty.resolve("eod", "AAPL.US", 19_000), None);
assert!(empty.ranges_for("eod", "AAPL.US").is_empty());
let mut cursor = empty.cursor_for("eod", "AAPL.US");
assert_eq!(cursor.resolve(19_000), None);
let base_rows = vec![
row("eod", "FB.US", 15_000, Some(18_000), 1),
row("eod", "FB.US", 19_000, None, 2),
row("qm", "FB", 15_000, Some(18_000), 1),
row("ib", "107113386", 15_000, Some(16_000), 1),
row("ib", "107113386", 16_001, Some(17_500), 3),
row("ib", "107113386", 18_500, Some(19_500), 4),
row("ceo", "SHOP", 16_500, None, 5),
];
let baseline = ProviderMappingTable::from_rows(base_rows.clone()).unwrap();
let mut rng = TestRng::new(0xDEAD_BEEF_CAFE_0001);
let probe_keys = [
("eod", "FB.US"),
("qm", "FB"),
("ib", "107113386"),
("ceo", "SHOP"),
("eod", "MISSING"),
];
let probe_dates = [
14_999, 15_000, 16_000, 16_001, 17_500, 17_501, 18_000, 18_001, 18_500, 19_000, 19_500,
19_501, 25_000,
];
for _ in 0..8 {
let mut shuffled = base_rows.clone();
rng.shuffle(&mut shuffled);
let candidate = ProviderMappingTable::from_rows(shuffled).unwrap();
assert_eq!(candidate.len(), baseline.len());
assert_eq!(candidate.range_count(), baseline.range_count());
for &(src, id) in &probe_keys {
assert_eq!(
candidate.ranges_for(src, id),
baseline.ranges_for(src, id),
"ranges_for mismatch for ({src}, {id})"
);
for &d in &probe_dates {
assert_eq!(
candidate.resolve(src, id, d),
baseline.resolve(src, id, d),
"resolve mismatch for ({src}, {id}, {d})"
);
}
}
}
}
#[test]
fn cursor_matches_resolve_exhaustively_on_fixed_seed_table() {
let mut rng = TestRng::new(0x570C_4B07_C045_0001);
let sources = ["eod", "qm", "ib", "ceo"];
let mut rows = Vec::new();
let mut keys = Vec::new();
let mut next_listing_id = 1i32;
for k in 0..100usize {
let src = sources[k % sources.len()];
let id = format!("KEY{k:03}");
keys.push((src, id.clone()));
let range_count = match k % 5 {
0 => 3,
1 => 2,
_ => 1,
};
let mut cur_start = 10_000 + (rng.next_u64() % 500) as i32;
for r in 0..range_count {
let is_last = r + 1 == range_count;
let open_ended = is_last && (k % 2 == 0);
let len = (rng.next_u64() % 200) as i32;
let valid_to = if open_ended {
None
} else {
Some(cur_start + len)
};
rows.push(row(src, &id, cur_start, valid_to, next_listing_id));
next_listing_id += 1;
// Mix adjacent (gap=1) and interior-gap (gap>1) transitions.
let gap = if r % 2 == 0 {
1
} else {
2 + (rng.next_u64() % 50) as i32
};
cur_start = cur_start + len + gap;
}
}
rng.shuffle(&mut rows);
let table = ProviderMappingTable::from_rows(rows).unwrap();
for (src, id) in &keys {
let mut cursor = table.cursor_for(src, id);
assert_eq!(cursor.ranges(), table.ranges_for(src, id));
// Strictly ascending with repeated dates, pre-first, interior gaps, and post-last.
for d in (9_990..=11_500).step_by(3) {
let expected = table.resolve(src, id, d);
assert_eq!(
cursor.resolve(d),
expected,
"ascending mismatch for ({src}, {id}, {d})"
);
// Repeated same date.
assert_eq!(
cursor.resolve(d),
expected,
"repeat mismatch for ({src}, {id}, {d})"
);
}
// Out-of-order fallback + reset.
for &d in &[11_400, 10_000, 10_500, 9_995, 10_250, 11_500] {
assert_eq!(
cursor.resolve(d),
table.resolve(src, id, d),
"out-of-order mismatch for ({src}, {id}, {d})"
);
}
cursor.reset();
for d in [9_990, 10_100, 10_300, 10_600, 11_500] {
assert_eq!(cursor.resolve(d), table.resolve(src, id, d));
}
}
}
}

View file

@ -0,0 +1,302 @@
//! Public-API and CLI contract tests for `curate_etl::provider_mapping` (M1.2h).
use std::process::{Command, Output};
use curate_etl::{
ymd_to_epoch_days, MappingRange, ProviderMappingCursor, ProviderMappingError,
ProviderMappingRow, ProviderMappingTable,
};
fn row(
source: &str,
source_id: &str,
valid_from: i32,
valid_to: Option<i32>,
listing_id: i32,
) -> ProviderMappingRow {
ProviderMappingRow {
source: source.to_string(),
source_id: source_id.to_string(),
valid_from,
valid_to,
listing_id,
}
}
fn run_cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
.args(args)
.output()
.expect("spawn curate-etl binary")
}
struct ContractRng(u64);
impl ContractRng {
fn new(seed: u64) -> Self {
Self(seed)
}
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn shuffle<T>(&mut self, items: &mut [T]) {
for i in (1..items.len()).rev() {
let j = (self.next_u64() % (i as u64 + 1)) as usize;
items.swap(i, j);
}
}
}
/// Brute-force linear reference oracle over raw rows.
fn brute_force_resolve(
rows: &[ProviderMappingRow],
source: &str,
source_id: &str,
bar_date: i32,
) -> Option<i32> {
let mut found = None;
for r in rows {
if r.source == source
&& r.source_id == source_id
&& bar_date >= r.valid_from
&& r.valid_to.is_none_or(|to| bar_date <= to)
{
assert!(
found.is_none(),
"test fixture must not contain overlapping ranges"
);
found = Some(r.listing_id);
}
}
found
}
#[test]
fn fb_us_ticker_reuse_contract_and_verbatim_whitespace_ids() {
let d_2012_05_17 = ymd_to_epoch_days(2012, 5, 17).unwrap();
let d_2012_05_18 = ymd_to_epoch_days(2012, 5, 18).unwrap();
let d_2022_06_08 = ymd_to_epoch_days(2022, 6, 8).unwrap();
let d_2022_06_09 = ymd_to_epoch_days(2022, 6, 9).unwrap();
let d_2023_06_01 = ymd_to_epoch_days(2023, 6, 1).unwrap();
let d_2025_01_02 = ymd_to_epoch_days(2025, 1, 2).unwrap();
let d_2026_05_01 = ymd_to_epoch_days(2026, 5, 1).unwrap();
let table = ProviderMappingTable::from_rows([
row("eod", "FB.US", d_2012_05_18, Some(d_2022_06_08), 1),
row("eod", "FB.US", d_2025_01_02, None, 2),
row("eod", " FB.US ", d_2012_05_18, None, 99),
row("qm", "FB.US", d_2012_05_18, None, 77),
])
.unwrap();
assert_eq!(table.len(), 3);
assert_eq!(table.range_count(), 4);
assert_eq!(table.resolve("eod", "FB.US", d_2012_05_17), None);
assert_eq!(table.resolve("eod", "FB.US", d_2012_05_18), Some(1));
assert_eq!(table.resolve("eod", "FB.US", d_2022_06_08), Some(1));
assert_eq!(table.resolve("eod", "FB.US", d_2022_06_09), None);
assert_eq!(table.resolve("eod", "FB.US", d_2023_06_01), None);
assert_eq!(table.resolve("eod", "FB.US", d_2025_01_02), Some(2));
assert_eq!(table.resolve("eod", "FB.US", d_2026_05_01), Some(2));
// Verbatim whitespace preservation and source isolation.
assert_eq!(table.resolve("eod", " FB.US ", d_2023_06_01), Some(99));
assert_eq!(table.resolve("qm", "FB.US", d_2023_06_01), Some(77));
assert_eq!(table.resolve("ib", "FB.US", d_2023_06_01), None);
assert_eq!(table.resolve("eod", "FB.US ", d_2023_06_01), None);
}
#[test]
fn typed_error_variants_and_adjacent_range_acceptance() {
let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap();
let d2 = ymd_to_epoch_days(2021, 1, 1).unwrap();
assert_eq!(
ProviderMappingTable::from_rows([row(" ", "A", d1, None, 1)]).unwrap_err(),
ProviderMappingError::EmptySource
);
assert_eq!(
ProviderMappingTable::from_rows([row("eod", "\t", d1, None, 1)]).unwrap_err(),
ProviderMappingError::EmptySourceId {
source: "eod".to_string()
}
);
assert_eq!(
ProviderMappingTable::from_rows([row("eod", "A", d1, None, 0)]).unwrap_err(),
ProviderMappingError::InvalidListingId {
source: "eod".to_string(),
source_id: "A".to_string(),
listing_id: 0,
}
);
assert_eq!(
ProviderMappingTable::from_rows([row("eod", "A", d2, Some(d1), 1)]).unwrap_err(),
ProviderMappingError::InvalidRange {
source: "eod".to_string(),
source_id: "A".to_string(),
valid_from: d2,
valid_to: d1,
}
);
assert_eq!(
ProviderMappingTable::from_rows([
row("eod", "A", d1, Some(d2), 1),
row("eod", "A", d1, Some(d2), 1),
])
.unwrap_err(),
ProviderMappingError::DuplicateValidFrom {
source: "eod".to_string(),
source_id: "A".to_string(),
valid_from: d1,
}
);
assert_eq!(
ProviderMappingTable::from_rows([
row("eod", "A", d1, None, 1),
row("eod", "A", d2, None, 2),
])
.unwrap_err(),
ProviderMappingError::OverlappingRanges {
source: "eod".to_string(),
source_id: "A".to_string(),
first_valid_from: d1,
first_valid_to: None,
second_valid_from: d2,
second_valid_to: None,
}
);
// Adjacent ranges (valid_to = d1, next valid_from = d1 + 1) succeed.
let adjacent = ProviderMappingTable::from_rows([
row("eod", "A", d1 - 10, Some(d1), 1),
row("eod", "A", d1 + 1, Some(d2), 2),
])
.unwrap();
assert_eq!(
adjacent.ranges_for("eod", "A"),
&[
MappingRange {
valid_from: d1 - 10,
valid_to: Some(d1),
listing_id: 1,
},
MappingRange {
valid_from: d1 + 1,
valid_to: Some(d2),
listing_id: 2,
},
]
);
}
#[test]
fn brute_force_oracle_cursor_equivalence_and_permutation_invariance() {
let mut rng = ContractRng::new(0x1234_5678_9ABC_DEF0);
let sources = ["eod", "qm", "ib", "ceo"];
let mut rows = Vec::new();
let mut keys = Vec::new();
let mut listing_id = 100i32;
for k in 0..40usize {
let src = sources[k % sources.len()];
let id = format!("T{k:03}");
keys.push((src, id.clone()));
let n_ranges = 1 + (k % 3);
let mut start = 15_000 + (rng.next_u64() % 100) as i32;
for r in 0..n_ranges {
let is_last = r + 1 == n_ranges;
let len = (rng.next_u64() % 40) as i32;
let valid_to = if is_last && (k % 2 == 0) {
None
} else {
Some(start + len)
};
rows.push(row(src, &id, start, valid_to, listing_id));
listing_id += 1;
let gap = 1 + (rng.next_u64() % 20) as i32;
start = start + len + gap;
}
}
let mut permuted = rows.clone();
rng.shuffle(&mut permuted);
let table_a = ProviderMappingTable::from_rows(rows.clone()).unwrap();
let table_b = ProviderMappingTable::from_rows(permuted).unwrap();
assert_eq!(table_a.len(), table_b.len());
assert_eq!(table_a.range_count(), table_b.range_count());
for (src, id) in &keys {
assert_eq!(table_a.ranges_for(src, id), table_b.ranges_for(src, id));
let mut cursor = ProviderMappingCursor::new(table_a.ranges_for(src, id));
for d in 14_990..=15_350 {
let expected = brute_force_resolve(&rows, src, id, d);
assert_eq!(table_a.resolve(src, id, d), expected);
assert_eq!(table_b.resolve(src, id, d), expected);
assert_eq!(cursor.resolve(d), expected);
}
}
}
#[test]
fn cli_bench_provider_mapping_is_deterministic_and_rejects_invalid_args() {
let a = run_cli(&["bench-provider-mapping", "50000"]);
let b = run_cli(&["bench-provider-mapping", "50000"]);
assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr));
assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr));
assert!(a.stderr.is_empty());
assert!(b.stderr.is_empty());
let out_a = String::from_utf8_lossy(&a.stdout);
let out_b = String::from_utf8_lossy(&b.stdout);
assert!(out_a.contains("curate-etl bench-provider-mapping"), "{out_a}");
assert!(out_a.contains("keys=60000 "), "{out_a}");
assert!(out_a.contains("rows/s"), "{out_a}");
assert!(out_a.contains("lookups=50000 "), "{out_a}");
assert!(out_a.contains("hits="), "{out_a}");
assert!(out_a.contains("misses="), "{out_a}");
assert!(out_a.contains("lookups/s"), "{out_a}");
assert!(out_a.contains("ns/lookup"), "{out_a}");
assert!(out_a.contains("checksum=0x"), "{out_a}");
let field = |s: &str, prefix: &str| {
s.split_whitespace()
.find(|t| t.starts_with(prefix))
.map(str::to_owned)
};
let checksum_a = field(&out_a, "checksum=");
let checksum_b = field(&out_b, "checksum=");
assert!(checksum_a.is_some(), "{out_a}");
assert_eq!(checksum_a, checksum_b);
assert_eq!(field(&out_a, "hits="), field(&out_b, "hits="));
assert_eq!(field(&out_a, "misses="), field(&out_b, "misses="));
// Help mentions bench-provider-mapping.
let help = run_cli(&["--help"]);
assert!(help.status.success());
assert!(String::from_utf8_lossy(&help.stdout).contains("bench-provider-mapping"));
// Invalid invocations exit 1 with stderr usage mentioning bench-provider-mapping.
for bad in [
&["bench-provider-mapping", "0"][..],
&["bench-provider-mapping", "-5"][..],
&["bench-provider-mapping", "abc"][..],
&["bench-provider-mapping", "10", "20"][..],
] {
let out = run_cli(bad);
assert!(!out.status.success(), "{bad:?} should fail");
assert_eq!(out.status.code(), Some(1), "{bad:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("error:"), "{bad:?}: {err}");
assert!(err.contains("bench-provider-mapping"), "{bad:?}: {err}");
assert!(out.stdout.is_empty(), "{bad:?} wrote to stdout");
}
}