stock-bot/tools/curate-etl/src/provider_mapping.rs

1055 lines
38 KiB
Rust

//! 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 input rows (both valid builds and typed validation
/// errors).
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;
let mut row_error: Option<ProviderMappingError> = None;
for row in rows {
if let Some(err) = validate_row(&row) {
if matches!(err, ProviderMappingError::EmptySource) {
return Err(err);
}
match &row_error {
None => row_error = Some(err),
Some(current) if cmp_row_error(&err, current).is_lt() => {
row_error = Some(err);
}
Some(_) => {}
}
continue;
}
if row_error.is_some() {
continue;
}
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;
}
if let Some(err) = row_error {
return Err(err);
}
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)
}
fn validate_row(row: &ProviderMappingRow) -> Option<ProviderMappingError> {
if row.source.trim().is_empty() {
return Some(ProviderMappingError::EmptySource);
}
if row.source_id.trim().is_empty() {
return Some(ProviderMappingError::EmptySourceId {
source: row.source.clone(),
});
}
if row.listing_id <= 0 {
return Some(ProviderMappingError::InvalidListingId {
source: row.source.clone(),
source_id: row.source_id.clone(),
listing_id: row.listing_id,
});
}
if let Some(valid_to) = row.valid_to {
if valid_to < row.valid_from {
return Some(ProviderMappingError::InvalidRange {
source: row.source.clone(),
source_id: row.source_id.clone(),
valid_from: row.valid_from,
valid_to,
});
}
}
None
}
fn cmp_row_error(a: &ProviderMappingError, b: &ProviderMappingError) -> std::cmp::Ordering {
use std::cmp::Ordering;
use ProviderMappingError as E;
let rank = |err: &E| -> u8 {
match err {
E::EmptySource => 0,
E::EmptySourceId { .. } => 1,
E::InvalidListingId { .. } => 2,
E::InvalidRange { .. } => 3,
E::DuplicateValidFrom { .. } => 4,
E::OverlappingRanges { .. } => 5,
}
};
rank(a).cmp(&rank(b)).then_with(|| match (a, b) {
(E::EmptySource, E::EmptySource) => Ordering::Equal,
(E::EmptySourceId { source: sa }, E::EmptySourceId { source: sb }) => sa.cmp(sb),
(
E::InvalidListingId {
source: sa,
source_id: ida,
listing_id: la,
},
E::InvalidListingId {
source: sb,
source_id: idb,
listing_id: lb,
},
) => (sa, ida, la).cmp(&(sb, idb, lb)),
(
E::InvalidRange {
source: sa,
source_id: ida,
valid_from: fa,
valid_to: ta,
},
E::InvalidRange {
source: sb,
source_id: idb,
valid_from: fb,
valid_to: tb,
},
) => (sa, ida, fa, ta).cmp(&(sb, idb, fb, tb)),
_ => Ordering::Equal,
})
}
#[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));
}
}
}
#[test]
fn from_rows_returns_identical_typed_error_across_permutations_of_mixed_invalid_batch() {
let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap();
let d2 = ymd_to_epoch_days(2022, 6, 8).unwrap();
// Mixed-invalid batch: whitespace-only source_id on `eod` + invalid range on `qm` +
// invalid listing_id on `ib` + valid rows + duplicate key on `ceo`.
let mixed_batch = vec![
row("ceo", "SHOP", d1, None, 10),
row("ceo", "SHOP", d1, None, 10),
row("qm", "FB", d2, Some(d1), 2),
row("ib", "107113386", d1, None, 0),
row("eod", " ", d1, None, 1),
row("eod", "AAPL.US", d1, None, 3),
];
let expected = ProviderMappingError::EmptySourceId {
source: "eod".to_string(),
};
let forward_err = ProviderMappingTable::from_rows(mixed_batch.clone()).unwrap_err();
let mut reversed = mixed_batch.clone();
reversed.reverse();
let reversed_err = ProviderMappingTable::from_rows(reversed).unwrap_err();
assert_eq!(forward_err, expected);
assert_eq!(reversed_err, forward_err);
let mut rng = TestRng::new(0xBAD0_C0DE_0001_0002);
for _ in 0..8 {
let mut shuffled = mixed_batch.clone();
rng.shuffle(&mut shuffled);
assert_eq!(
ProviderMappingTable::from_rows(shuffled).unwrap_err(),
expected
);
}
// Same-variant tie-breaking must also be order-independent.
let same_variant_cases: Vec<(Vec<ProviderMappingRow>, ProviderMappingError)> = vec![
(
vec![
row("qm", " ", d1, None, 1),
row("eod", "\t", d1, None, 2),
row("ib", "", d1, None, 3),
],
ProviderMappingError::EmptySourceId {
source: "eod".to_string(),
},
),
(
vec![
row("qm", "Z", d1, None, 0),
row("eod", "A", d1, None, -1),
row("eod", "A", d1, None, -5),
],
ProviderMappingError::InvalidListingId {
source: "eod".to_string(),
source_id: "A".to_string(),
listing_id: -5,
},
),
(
vec![
row("qm", "B", d2, Some(d1), 2),
row("eod", "A", d2, Some(d1 + 1), 1),
row("eod", "A", d2, Some(d1), 3),
],
ProviderMappingError::InvalidRange {
source: "eod".to_string(),
source_id: "A".to_string(),
valid_from: d2,
valid_to: d1,
},
),
(
vec![
row("qm", "B", d2, Some(d1), 2),
row(" ", "A", d1, None, 1),
row("eod", " ", d1, None, 3),
],
ProviderMappingError::EmptySource,
),
(
vec![
row("a", "DUP", d1, None, 1),
row("a", "DUP", d1, None, 2),
row("z", "BAD", d2, Some(d1), 3),
],
ProviderMappingError::InvalidRange {
source: "z".to_string(),
source_id: "BAD".to_string(),
valid_from: d2,
valid_to: d1,
},
),
];
for (batch, expected_err) in same_variant_cases {
let mut rev = batch.clone();
rev.reverse();
assert_eq!(
ProviderMappingTable::from_rows(batch).unwrap_err(),
expected_err
);
assert_eq!(
ProviderMappingTable::from_rows(rev).unwrap_err(),
expected_err
);
}
}
}