T-97: merge dev
This commit is contained in:
commit
ade1a5c233
8 changed files with 2645 additions and 6 deletions
|
|
@ -726,3 +726,41 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x098ac03b
|
|||
- Stage (in-memory): `elapsed=1181.40 ms`, `throughput=1692903 rows/s`, `latency=590.70 ns/row`, single-core 846M projection `499.7 s` (`8.33 min`), `checksum=0x098ac03b74d9899a`
|
||||
- Parquet write: `elapsed=708.69 ms`, `throughput=2748627 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1890.09 ms`, `throughput=1058151 rows/s`, single-core 846M projection `799.5 s` (`13.33 min`, projected at batch=`2000000` and `97.40%` retention)
|
||||
|
||||
## `shorts` Curation Stage (`M1.2r`)
|
||||
|
||||
`curate_shorts` and `curate_and_write_shorts` (`src/curate_shorts.rs`) join `build_shorts`, `ProviderMappingTable`, and `write_shorts_dataset` into contract `ShortsParquetRow` records sorted and unique by `(listing_id, report_date)`.
|
||||
|
||||
1. **Field rules:**
|
||||
- Calls `build_shorts` unchanged (finite `>= 0.0` `shares_short` validation, non-finite optional `net_change`/`pct_float` sanitization to `None`, `-0.0` normalization, same-`(key, report_date)` deduplication, `+4` Canadian TSX business-day CIRO lag, and `known_at_micros = 17:00:00 America/Toronto` UTC microseconds).
|
||||
- Resolves `(mapping_source, key, report_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by `(key, report_date)`).
|
||||
- **Point-in-time mapping boundary:** `provider_mapping` is resolved strictly on `report_date` (the reporting period the short position describes), not on `known_at_date` (`+4` TSX business days later).
|
||||
- Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO = "ceo_shorts"`) as `Cow::Borrowed`.
|
||||
2. **Drop & collision policy (never panics or aborts on bad rows):**
|
||||
- Rows whose `(mapping_source, key, report_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`.
|
||||
- After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`, `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any of those fields differ (`listing_collision_dropped += g`).
|
||||
- Exact conservation invariant in `CurateShortsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped`.
|
||||
- Typed caller errors: `CurateShortsError` (`Shorts(ShortsError)`, `EmptyMappingSource`) and `CurateShortsWriteError` (`Curate(CurateShortsError)`, `Parquet(ParquetShortsError)`). A curate error in `curate_and_write_shorts` returns before invoking `write_shorts_dataset`, leaving `out_dir` untouched.
|
||||
|
||||
### `bench-curate-shorts`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `ceoShorts` reports across `12,500` `String` keys per `1,000,000`-row block (`25,000` keys at `2,000,000` rows over the `218` semi-monthly dates `2017-04-15..=2026-04-30`, with per-key coprime-stride cursors guarded against exhaustion, date-ranged ticker reuse with an interior gap, unmapped keys, explicit builder duplicates, invalid `shares_short`/non-finite optional field slices, and identical/conflicting cross-key collisions), separately timing in-memory `curate_shorts` and Zstd Parquet `write_shorts_dataset` into a temp directory with footer row-count verification and cleanup:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-curate-shorts [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0xde3b3bd654c65ebe`): `cargo run --release -p curate-etl --offline -- bench-curate-shorts`
|
||||
|
||||
- Input: `rows=2000000`, `keys=25000`
|
||||
- Builder: `rows_out=1990174`, `invalid_shares=4005`, `nulled_net_change=1953`, `nulled_pct_float=1956`, `dup_collapsed=1937`, `dup_conflict_dropped=3884`
|
||||
- Output: `rows_out=1936876` (`96.84%` retained), `listings_out=25000`, `files=1`, `row_groups=2`, `bytes=17721340`, `read_back_rows=1936876`
|
||||
- Curation stats: `unmapped=43484`, `coll_collapsed=3410`, `coll_dropped=6404`
|
||||
- Run 1:
|
||||
- Stage (in-memory): `elapsed=1091.40 ms`, `throughput=1832514 rows/s`, `latency=545.70 ns/row`, `checksum=0xde3b3bd654c65ebe`
|
||||
- Parquet write: `elapsed=224.75 ms`, `throughput=8617888 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1316.15 ms`, `throughput=1519586 rows/s`
|
||||
- Run 2:
|
||||
- Stage (in-memory): `elapsed=1002.51 ms`, `throughput=1994998 rows/s`, `latency=501.25 ns/row`, `checksum=0xde3b3bd654c65ebe`
|
||||
- Parquet write: `elapsed=228.03 ms`, `throughput=8494083 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1230.53 ms`, `throughput=1625311 rows/s`
|
||||
|
|
|
|||
|
|
@ -4420,6 +4420,444 @@ pub fn run_curate_bars_benchmark(rows: usize) -> Result<CurateBarsBenchReport, C
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_SHORTS_BENCH_ROWS: usize = 2_000_000;
|
||||
const CURATE_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_C04A_5407;
|
||||
const CURATE_SHORTS_BENCH_KEY_COUNT: usize = 12_500;
|
||||
const CURATE_SHORTS_BENCH_ROWS_PER_KEY_BLOCK: usize = 1_000_000;
|
||||
|
||||
/// Errors returned by [`run_curate_shorts_benchmark`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateShortsBenchError {
|
||||
/// Curation stage or Parquet write error.
|
||||
Write(crate::curate_shorts::CurateShortsWriteError),
|
||||
/// Fixture exhausted the unique semi-monthly date pool for a key before generating all
|
||||
/// requested rows.
|
||||
FixtureDatePoolExhausted {
|
||||
rows: usize,
|
||||
key_count: usize,
|
||||
key_idx: usize,
|
||||
capacity: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CurateShortsBenchError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Write(err) => write!(f, "{err}"),
|
||||
Self::FixtureDatePoolExhausted {
|
||||
rows,
|
||||
key_count,
|
||||
key_idx,
|
||||
capacity,
|
||||
} => write!(
|
||||
f,
|
||||
"curate-shorts benchmark fixture exhausted unique semi-monthly date pool (capacity {capacity} dates/key) for key_idx={key_idx} while generating {rows} rows across {key_count} keys"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CurateShortsBenchError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Write(err) => Some(err),
|
||||
Self::FixtureDatePoolExhausted { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::curate_shorts::CurateShortsWriteError> for CurateShortsBenchError {
|
||||
fn from(err: crate::curate_shorts::CurateShortsWriteError) -> Self {
|
||||
Self::Write(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::curate_shorts::CurateShortsError> for CurateShortsBenchError {
|
||||
fn from(err: crate::curate_shorts::CurateShortsError) -> Self {
|
||||
Self::Write(crate::curate_shorts::CurateShortsWriteError::from(err))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParquetShortsError> for CurateShortsBenchError {
|
||||
fn from(err: ParquetShortsError) -> Self {
|
||||
Self::Write(crate::curate_shorts::CurateShortsWriteError::from(err))
|
||||
}
|
||||
}
|
||||
|
||||
/// Scales the benchmark key space in `12,500`-key blocks per `1,000,000` rows so larger batches
|
||||
/// keep ordinary `(key, report_date)` pairs unique across the `218` semi-monthly dates
|
||||
/// (`2017-04-15..=2026-04-30`) without exhausting the per-key date pool.
|
||||
fn curate_shorts_bench_key_count(rows: usize) -> usize {
|
||||
let blocks = rows.div_ceil(CURATE_SHORTS_BENCH_ROWS_PER_KEY_BLOCK).max(1);
|
||||
CURATE_SHORTS_BENCH_KEY_COUNT.saturating_mul(blocks)
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_curate_shorts_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CurateShortsBenchReport {
|
||||
pub rows: usize,
|
||||
pub key_count: usize,
|
||||
pub rows_out: usize,
|
||||
pub listings_out: usize,
|
||||
pub stage_elapsed_ms: f64,
|
||||
pub stage_rows_per_sec: f64,
|
||||
pub stage_ns_per_row: f64,
|
||||
pub parquet_elapsed_ms: f64,
|
||||
pub parquet_rows_per_sec: f64,
|
||||
pub total_elapsed_ms: f64,
|
||||
pub total_rows_per_sec: f64,
|
||||
pub files_written: usize,
|
||||
pub row_groups_written: usize,
|
||||
pub bytes_written: u64,
|
||||
pub read_back_rows: usize,
|
||||
pub checksum: u64,
|
||||
pub stats: crate::curate_shorts::CurateShortsStats,
|
||||
}
|
||||
|
||||
struct CurateShortsBenchFixture {
|
||||
reports: Vec<CeoShortReport<String>>,
|
||||
provider_mapping: ProviderMappingTable,
|
||||
key_count: usize,
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
injected_dup_identical: usize,
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
injected_dup_conflict: usize,
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
injected_alias_identical: usize,
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
injected_alias_conflict: usize,
|
||||
}
|
||||
|
||||
fn build_curate_shorts_bench_fixture(
|
||||
rows: usize,
|
||||
key_count: usize,
|
||||
date_pool_limit: Option<usize>,
|
||||
) -> Result<CurateShortsBenchFixture, CurateShortsBenchError> {
|
||||
assert!(
|
||||
key_count >= CURATE_SHORTS_BENCH_KEY_COUNT
|
||||
&& key_count % CURATE_SHORTS_BENCH_KEY_COUNT == 0,
|
||||
"key_count ({key_count}) must be a positive multiple of {CURATE_SHORTS_BENCH_KEY_COUNT}"
|
||||
);
|
||||
let scale = key_count / CURATE_SHORTS_BENCH_KEY_COUNT;
|
||||
|
||||
let all_dates = semi_monthly_report_dates();
|
||||
let pool_len = date_pool_limit.map_or(all_dates.len(), |limit| limit.clamp(1, all_dates.len()));
|
||||
let valid_from_start = ymd_to_epoch_days(2017, 1, 1).expect("valid start");
|
||||
let reuse_end = ymd_to_epoch_days(2021, 6, 30).expect("valid reuse end");
|
||||
let reuse_resume = ymd_to_epoch_days(2022, 1, 1).expect("valid reuse resume");
|
||||
|
||||
let single_range_end = 11_750 * scale;
|
||||
let reuse_end_idx = 12_125 * scale;
|
||||
let alias_end_idx = 12_250 * scale;
|
||||
let alias_count = alias_end_idx - reuse_end_idx;
|
||||
let ordinary_key_count = key_count - alias_count;
|
||||
let reuse_lid_offset = key_count.max(100_000);
|
||||
|
||||
let keys: Vec<String> = (0..key_count).map(|i| format!("CEO{i:05}")).collect();
|
||||
|
||||
// Build provider_mapping (scaled proportionally per 12,500-key block):
|
||||
// - 0..single_range_end: open-ended single range -> listing (i + 1)
|
||||
// - single_range_end..reuse_end_idx: two ranges with H2-2021 gap -> listings (i + 1) and (i + reuse_lid_offset + 1)
|
||||
// - reuse_end_idx..alias_end_idx: aliases of listings 1..=alias_count (cross-key collisions)
|
||||
// - alias_end_idx..key_count: unmapped keys
|
||||
let mut mapping_rows: Vec<ProviderMappingRow> =
|
||||
Vec::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16);
|
||||
for (i, key) in keys.iter().enumerate() {
|
||||
if i < single_range_end {
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "ceo".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: None,
|
||||
listing_id: (i + 1) as i32,
|
||||
});
|
||||
} else if i < reuse_end_idx {
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "ceo".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: Some(reuse_end),
|
||||
listing_id: (i + 1) as i32,
|
||||
});
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "ceo".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: reuse_resume,
|
||||
valid_to: None,
|
||||
listing_id: (i + reuse_lid_offset + 1) as i32,
|
||||
});
|
||||
} else if i < alias_end_idx {
|
||||
let alias_lid = (i - reuse_end_idx + 1) as i32;
|
||||
mapping_rows.push(ProviderMappingRow {
|
||||
source: "ceo".to_string(),
|
||||
source_id: key.clone(),
|
||||
valid_from: valid_from_start,
|
||||
valid_to: None,
|
||||
listing_id: alias_lid,
|
||||
});
|
||||
}
|
||||
}
|
||||
let provider_mapping =
|
||||
ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping");
|
||||
|
||||
let mut rng = SplitMix64::new(CURATE_SHORTS_BENCH_SEED);
|
||||
let mut reports: Vec<CeoShortReport<String>> = Vec::with_capacity(rows);
|
||||
|
||||
// Per-key coprime-stride cursors with explicit usage guards guarantee unique
|
||||
// (key, report_date) pairs across the 218 semi-monthly dates (53 is prime and coprime to
|
||||
// 218 = 2 * 109) so all builder duplicates and cross-key collisions are injected explicitly.
|
||||
const DATE_STRIDE: usize = 53;
|
||||
let date_stride = if date_pool_limit.is_none() {
|
||||
DATE_STRIDE
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let mut date_cursor: Vec<usize> = (0..key_count)
|
||||
.map(|_| (rng.next_u64() as usize) % pool_len)
|
||||
.collect();
|
||||
let mut date_used: Vec<usize> = vec![0; key_count];
|
||||
|
||||
let mut last_alias_pair: Option<(usize, CeoShortReport<String>)> = None;
|
||||
let mut last_ordinary_report: Option<CeoShortReport<String>> = None;
|
||||
let mut injected_dup_identical = 0usize;
|
||||
let mut injected_dup_conflict = 0usize;
|
||||
let mut injected_alias_identical = 0usize;
|
||||
let mut injected_alias_conflict = 0usize;
|
||||
|
||||
for _ in 0..rows {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 4 {
|
||||
if let Some((alias_idx, mut prev)) = last_alias_pair.take() {
|
||||
prev.key = keys[reuse_end_idx + alias_idx].clone();
|
||||
if roll >= 2 {
|
||||
prev.shares_short += 100.0;
|
||||
injected_alias_conflict += 1;
|
||||
} else {
|
||||
injected_alias_identical += 1;
|
||||
}
|
||||
reports.push(prev);
|
||||
continue;
|
||||
}
|
||||
} else if roll < 6 {
|
||||
if let Some(mut prev) = last_ordinary_report.take() {
|
||||
if roll == 5 {
|
||||
prev.shares_short += 50.0;
|
||||
injected_dup_conflict += 1;
|
||||
} else {
|
||||
injected_dup_identical += 1;
|
||||
}
|
||||
reports.push(prev);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let key_idx = if roll < 12 {
|
||||
(rng.next_u64() as usize) % alias_count
|
||||
} else {
|
||||
// Skip alias keys reuse_end_idx..alias_end_idx for ordinary reports so alias
|
||||
// collisions are purely explicit.
|
||||
let slot = (rng.next_u64() as usize) % ordinary_key_count;
|
||||
if slot < reuse_end_idx {
|
||||
slot
|
||||
} else {
|
||||
slot + alias_count
|
||||
}
|
||||
};
|
||||
|
||||
if date_used[key_idx] >= pool_len {
|
||||
return Err(CurateShortsBenchError::FixtureDatePoolExhausted {
|
||||
rows,
|
||||
key_count,
|
||||
key_idx,
|
||||
capacity: pool_len,
|
||||
});
|
||||
}
|
||||
date_used[key_idx] += 1;
|
||||
let offset = date_cursor[key_idx];
|
||||
date_cursor[key_idx] = (offset + date_stride) % pool_len;
|
||||
let report_date = all_dates[offset];
|
||||
|
||||
let is_invalid_shares = roll == 12 || roll == 13;
|
||||
let shares_short = if roll == 12 {
|
||||
-1.0
|
||||
} else if roll == 13 {
|
||||
f64::NAN
|
||||
} else {
|
||||
((rng.next_u64() % 5_000_000) + 100) as f64
|
||||
};
|
||||
let net_change = if roll == 14 {
|
||||
Some(f64::NAN)
|
||||
} else if rng.next_u64() % 5 == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(((rng.next_u64() % 200_001) as i64 - 100_000) as f64)
|
||||
};
|
||||
let pct_float = if roll == 15 {
|
||||
Some(f64::INFINITY)
|
||||
} else if rng.next_u64() % 4 == 0 {
|
||||
None
|
||||
} else {
|
||||
Some((rng.next_u64() % 3_500) as f64 * 0.01)
|
||||
};
|
||||
|
||||
let rep = CeoShortReport {
|
||||
key: keys[key_idx].clone(),
|
||||
report_date,
|
||||
shares_short,
|
||||
net_change,
|
||||
pct_float,
|
||||
};
|
||||
if !is_invalid_shares {
|
||||
if key_idx < alias_count {
|
||||
last_alias_pair = Some((key_idx, rep.clone()));
|
||||
} else if (alias_count..single_range_end).contains(&key_idx) {
|
||||
last_ordinary_report = Some(rep.clone());
|
||||
}
|
||||
}
|
||||
reports.push(rep);
|
||||
}
|
||||
|
||||
Ok(CurateShortsBenchFixture {
|
||||
reports,
|
||||
provider_mapping,
|
||||
key_count,
|
||||
injected_dup_identical,
|
||||
injected_dup_conflict,
|
||||
injected_alias_identical,
|
||||
injected_alias_conflict,
|
||||
})
|
||||
}
|
||||
|
||||
fn run_curate_shorts_benchmark_tracked(
|
||||
rows: usize,
|
||||
) -> Result<(CurateShortsBenchReport, PathBuf), CurateShortsBenchError> {
|
||||
use crate::curate_shorts::{curate_shorts, CurateShortsStats, CurateShortsWriteError};
|
||||
|
||||
let temp = BenchTempDir::new_in_with_prefix(
|
||||
&std::env::temp_dir(),
|
||||
"curate-etl-bench-curate-shorts",
|
||||
)
|
||||
.map_err(|(path, source)| {
|
||||
CurateShortsBenchError::Write(CurateShortsWriteError::Parquet(ParquetShortsError::Io {
|
||||
path,
|
||||
source,
|
||||
}))
|
||||
})?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
if rows == 0 {
|
||||
let mapping = ProviderMappingTable::default();
|
||||
let curated = curate_shorts(
|
||||
std::iter::empty::<CeoShortReport<String>>(),
|
||||
"ceo",
|
||||
&mapping,
|
||||
)?;
|
||||
let write_stats =
|
||||
write_shorts_dataset(&temp.path, &curated.rows, ShortsWriteOptions::default())?;
|
||||
let read_back_rows = verify_parquet_shorts_row_count(&temp.path, 0)?;
|
||||
drop(temp);
|
||||
return Ok((
|
||||
CurateShortsBenchReport {
|
||||
rows: 0,
|
||||
key_count: CURATE_SHORTS_BENCH_KEY_COUNT,
|
||||
rows_out: 0,
|
||||
listings_out: 0,
|
||||
stage_elapsed_ms: 0.0,
|
||||
stage_rows_per_sec: 0.0,
|
||||
stage_ns_per_row: 0.0,
|
||||
parquet_elapsed_ms: 0.0,
|
||||
parquet_rows_per_sec: 0.0,
|
||||
total_elapsed_ms: 0.0,
|
||||
total_rows_per_sec: 0.0,
|
||||
files_written: write_stats.files_written,
|
||||
row_groups_written: write_stats.row_groups_written,
|
||||
bytes_written: write_stats.bytes_written,
|
||||
read_back_rows,
|
||||
checksum: 0,
|
||||
stats: CurateShortsStats::default(),
|
||||
},
|
||||
temp_path,
|
||||
));
|
||||
}
|
||||
|
||||
let key_count = curate_shorts_bench_key_count(rows);
|
||||
let fixture = build_curate_shorts_bench_fixture(rows, key_count, None)?;
|
||||
let fixture_key_count = fixture.key_count;
|
||||
|
||||
// 1. Time pure in-memory curation stage.
|
||||
let stage_start = Instant::now();
|
||||
let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping)?;
|
||||
let stage_elapsed_secs = stage_start.elapsed().as_secs_f64();
|
||||
let stage_elapsed_ms = stage_elapsed_secs * 1_000.0;
|
||||
|
||||
let mut hash = 0u64;
|
||||
for row in &curated.rows {
|
||||
hash = mix_u64(hash, row.listing_id as u64);
|
||||
hash = mix_u64(hash, row.report_date as u64);
|
||||
hash = mix_u64(hash, row.known_at_micros as u64);
|
||||
hash = mix_u64(hash, row.shares_short.to_bits());
|
||||
hash = match row.net_change {
|
||||
Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()),
|
||||
None => mix_u64(hash, 0),
|
||||
};
|
||||
hash = match row.pct_float {
|
||||
Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()),
|
||||
None => mix_u64(hash, 0),
|
||||
};
|
||||
hash = mix_str_u64(hash, row.source.as_ref());
|
||||
}
|
||||
let checksum = black_box(hash);
|
||||
|
||||
// 2. Separately time Parquet write to temp dir.
|
||||
let parquet_start = Instant::now();
|
||||
let write_stats =
|
||||
write_shorts_dataset(&temp.path, &curated.rows, ShortsWriteOptions::default())?;
|
||||
let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64();
|
||||
let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0;
|
||||
|
||||
let read_back_rows = verify_parquet_shorts_row_count(&temp.path, curated.rows.len())?;
|
||||
|
||||
let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs);
|
||||
let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs);
|
||||
let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs;
|
||||
let total_elapsed_ms = total_elapsed_secs * 1_000.0;
|
||||
let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs);
|
||||
|
||||
let report = CurateShortsBenchReport {
|
||||
rows,
|
||||
key_count: fixture_key_count,
|
||||
rows_out: curated.stats.rows_out,
|
||||
listings_out: curated.stats.listings_out,
|
||||
stage_elapsed_ms,
|
||||
stage_rows_per_sec,
|
||||
stage_ns_per_row,
|
||||
parquet_elapsed_ms,
|
||||
parquet_rows_per_sec,
|
||||
total_elapsed_ms,
|
||||
total_rows_per_sec,
|
||||
files_written: write_stats.files_written,
|
||||
row_groups_written: write_stats.row_groups_written,
|
||||
bytes_written: write_stats.bytes_written,
|
||||
read_back_rows,
|
||||
checksum,
|
||||
stats: curated.stats,
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
Ok((report, temp_path))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed `shorts` curation stage + Zstd Parquet write benchmark for `rows`
|
||||
/// source-keyed `ceoShorts` reports across `12,500` `String` source keys per `1,000,000`-row block
|
||||
/// (semi-monthly dates `2017-04-15..=2026-04-30`, with date-ranged ticker reuse, unmapped keys,
|
||||
/// builder duplicates, invalid numeric slices, and cross-key collisions).
|
||||
pub fn run_curate_shorts_benchmark(
|
||||
rows: usize,
|
||||
) -> Result<CurateShortsBenchReport, CurateShortsBenchError> {
|
||||
let (report, _) = run_curate_shorts_benchmark_tracked(rows)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -5449,4 +5887,179 @@ mod tests {
|
|||
);
|
||||
assert!(curated.stats.rows_out > 20_000 * 90 / 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_shorts_benchmark_small_run_is_deterministic_and_cleans_up() {
|
||||
let (a, dir_a) = run_curate_shorts_benchmark_tracked(25_000).unwrap();
|
||||
let (b, dir_b) = run_curate_shorts_benchmark_tracked(25_000).unwrap();
|
||||
|
||||
assert!(
|
||||
!dir_a.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_a.display()
|
||||
);
|
||||
assert!(
|
||||
!dir_b.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_b.display()
|
||||
);
|
||||
assert_eq!(a.rows, 25_000);
|
||||
assert_eq!(a.stats.builder.rows_in, 25_000);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.read_back_rows, a.rows_out);
|
||||
assert_eq!(a.listings_out, b.listings_out);
|
||||
assert_eq!(a.files_written, 1);
|
||||
assert_eq!(a.bytes_written, b.bytes_written);
|
||||
assert!(a.bytes_written > 0);
|
||||
assert_eq!(a.stats, b.stats);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0);
|
||||
assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0);
|
||||
assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0);
|
||||
assert!(a.stats.builder.dropped_invalid_shares_short > 0);
|
||||
assert!(a.stats.builder.nulled_invalid_net_change > 0);
|
||||
assert!(a.stats.builder.nulled_invalid_pct_float > 0);
|
||||
assert!(a.stats.builder.duplicate_collapsed > 0);
|
||||
assert!(a.stats.builder.duplicate_conflict_dropped > 0);
|
||||
assert_eq!(
|
||||
a.stats.builder.rows_in,
|
||||
a.stats.builder.rows_out
|
||||
+ a.stats.builder.dropped_invalid_shares_short
|
||||
+ a.stats.builder.duplicate_collapsed
|
||||
+ a.stats.builder.duplicate_conflict_dropped
|
||||
);
|
||||
assert_eq!(a.stats.rows_in, a.stats.builder.rows_out);
|
||||
assert_eq!(
|
||||
a.stats.rows_in,
|
||||
a.stats.rows_out
|
||||
+ a.stats.dropped_unmapped
|
||||
+ a.stats.listing_collision_collapsed
|
||||
+ a.stats.listing_collision_dropped
|
||||
);
|
||||
assert!(a.stats.dropped_unmapped > 0);
|
||||
assert!(a.stats.listing_collision_collapsed > 0);
|
||||
assert!(a.stats.listing_collision_dropped > 0);
|
||||
assert!(
|
||||
a.rows_out > a.rows * 90 / 100,
|
||||
"expected >90% retention with unique ordinary pairs, got {}/{}",
|
||||
a.rows_out,
|
||||
a.rows
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_shorts_benchmark_zero_rows_handles_cleanly() {
|
||||
let (report, dir) = run_curate_shorts_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.rows_out, 0);
|
||||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.listings_out, 0);
|
||||
assert_eq!(report.files_written, 0);
|
||||
assert_eq!(report.bytes_written, 0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.stage_rows_per_sec, 0.0);
|
||||
assert_eq!(report.parquet_rows_per_sec, 0.0);
|
||||
assert_eq!(report.total_rows_per_sec, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_shorts_benchmark_distinguishes_deliberate_duplicates_from_cursor_exhaustion() {
|
||||
use crate::curate_shorts::curate_shorts;
|
||||
|
||||
// 1. Below cursor exhaustion: every builder duplicate and cross-key listing collision
|
||||
// must match the explicitly injected counts with zero accidental cursor wraps.
|
||||
let fixture =
|
||||
build_curate_shorts_bench_fixture(10_000, CURATE_SHORTS_BENCH_KEY_COUNT, Some(8))
|
||||
.expect("10,000 rows across 12,500 keys fits within 8 dates/key");
|
||||
assert!(fixture.injected_dup_identical > 0);
|
||||
assert!(fixture.injected_dup_conflict > 0);
|
||||
assert!(fixture.injected_alias_identical > 0);
|
||||
assert!(fixture.injected_alias_conflict > 0);
|
||||
|
||||
let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping).unwrap();
|
||||
assert_eq!(
|
||||
curated.stats.builder.duplicate_collapsed,
|
||||
fixture.injected_dup_identical,
|
||||
"builder identical duplicates must match explicit injections only"
|
||||
);
|
||||
assert_eq!(
|
||||
curated.stats.builder.duplicate_conflict_dropped,
|
||||
fixture.injected_dup_conflict * 2,
|
||||
"builder conflicting duplicates must match explicit injections only (2 rows per pair)"
|
||||
);
|
||||
assert_eq!(
|
||||
curated.stats.listing_collision_collapsed,
|
||||
fixture.injected_alias_identical,
|
||||
"listing identical collisions must match explicit injections only"
|
||||
);
|
||||
assert_eq!(
|
||||
curated.stats.listing_collision_dropped,
|
||||
fixture.injected_alias_conflict * 2,
|
||||
"listing conflicting collisions must match explicit injections only (2 rows per pair)"
|
||||
);
|
||||
|
||||
// 2. Past cursor exhaustion: the fixture must reject the run with a clear error rather
|
||||
// than silently wrapping.
|
||||
let err = match build_curate_shorts_bench_fixture(
|
||||
120_000,
|
||||
CURATE_SHORTS_BENCH_KEY_COUNT,
|
||||
Some(4),
|
||||
) {
|
||||
Ok(_) => panic!("120,000 rows across 12,500 keys must exhaust a 4-date pool"),
|
||||
Err(err) => err,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
CurateShortsBenchError::FixtureDatePoolExhausted {
|
||||
rows: 120_000,
|
||||
key_count: CURATE_SHORTS_BENCH_KEY_COUNT,
|
||||
capacity: 4,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected FixtureDatePoolExhausted, got {err:?}"
|
||||
);
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
msg.contains("4") && msg.contains("120000") && msg.contains("12500"),
|
||||
"error message should explain the fixture limit, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_shorts_benchmark_scales_key_space_for_large_batches() {
|
||||
use crate::curate_shorts::curate_shorts;
|
||||
|
||||
assert_eq!(curate_shorts_bench_key_count(0), 12_500);
|
||||
assert_eq!(curate_shorts_bench_key_count(1_000_000), 12_500);
|
||||
assert_eq!(curate_shorts_bench_key_count(1_000_001), 25_000);
|
||||
assert_eq!(curate_shorts_bench_key_count(2_000_000), 25_000);
|
||||
assert_eq!(curate_shorts_bench_key_count(5_000_000), 62_500);
|
||||
|
||||
let scaled_keys = curate_shorts_bench_key_count(2_000_000);
|
||||
let fixture = build_curate_shorts_bench_fixture(25_000, scaled_keys, None).unwrap();
|
||||
assert_eq!(fixture.key_count, 25_000);
|
||||
|
||||
let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping).unwrap();
|
||||
assert_eq!(
|
||||
curated.stats.builder.duplicate_collapsed,
|
||||
fixture.injected_dup_identical
|
||||
);
|
||||
assert_eq!(
|
||||
curated.stats.builder.duplicate_conflict_dropped,
|
||||
fixture.injected_dup_conflict * 2
|
||||
);
|
||||
assert_eq!(
|
||||
curated.stats.listing_collision_collapsed,
|
||||
fixture.injected_alias_identical
|
||||
);
|
||||
assert_eq!(
|
||||
curated.stats.listing_collision_dropped,
|
||||
fixture.injected_alias_conflict * 2
|
||||
);
|
||||
assert!(curated.stats.rows_out > 25_000 * 90 / 100);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@
|
|||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
|
|
@ -34,6 +34,7 @@ pub enum CliAction {
|
|||
BenchParquetCorporateActions(usize),
|
||||
BenchBsonEodPrices(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -59,7 +60,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})"
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -84,7 +86,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-parquet-adj [rows]\n\
|
||||
{name} bench-parquet-corporate-actions [rows]\n\
|
||||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-curate-bars [rows]"
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -259,6 +262,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-curate-bars", _, ..] => {
|
||||
Err("too many arguments for bench-curate-bars".to_string())
|
||||
}
|
||||
["bench-curate-shorts"] => {
|
||||
Ok(CliAction::BenchCurateShorts(DEFAULT_CURATE_SHORTS_BENCH_ROWS))
|
||||
}
|
||||
["bench-curate-shorts", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateShorts(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-shorts", _, ..] => {
|
||||
Err("too many arguments for bench-curate-shorts".to_string())
|
||||
}
|
||||
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -565,6 +580,7 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-corporate-actions"));
|
||||
assert!(full.contains("bench-bson-eod-prices"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
|
|
@ -583,6 +599,7 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-corporate-actions"));
|
||||
assert!(short.contains("bench-bson-eod-prices"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -600,4 +617,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-curate-bars", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-bars", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_shorts_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-shorts"])),
|
||||
Ok(CliAction::BenchCurateShorts(
|
||||
DEFAULT_CURATE_SHORTS_BENCH_ROWS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-shorts", "100000"])),
|
||||
Ok(CliAction::BenchCurateShorts(100_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-shorts", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-shorts", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-shorts", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-shorts", "10", "20"])).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
315
tools/curate-etl/src/curate_shorts.rs
Normal file
315
tools/curate-etl/src/curate_shorts.rs
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
//! Pure, in-memory `shorts` curation stage joining [`crate::shorts::build_shorts`],
|
||||
//! [`crate::provider_mapping::ProviderMappingTable`], and
|
||||
//! [`crate::parquet_shorts::write_shorts_dataset`] into contract [`ShortsParquetRow`]s.
|
||||
//!
|
||||
//! # Contract & Point-in-Time Rules
|
||||
//! - Calls [`build_shorts`] unchanged to validate `shares_short`, sanitize non-finite optional
|
||||
//! fields, deduplicate same-`(key, report_date)` reports, apply the locked `+4` Canadian TSX
|
||||
//! business-day CIRO lag, and stamp `known_at_utc_micros = 17:00:00 America/Toronto` plus
|
||||
//! `source = SHORTS_SOURCE_CEO` (`"ceo_shorts"`).
|
||||
//! - Resolves each output row's `(mapping_source, key, report_date)` to a permanent
|
||||
//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`]
|
||||
//! (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by
|
||||
//! `(key, report_date)`).
|
||||
//! - **Point-in-time mapping boundary (`report_date`, not `known_at_date`):** `provider_mapping`
|
||||
//! is resolved strictly on `report_date` (the reporting period the short position describes),
|
||||
//! not on `known_at_date` (when CIRO disseminates the report `+4` business days later). A ticker
|
||||
//! that changes listing or delists between `report_date` and `known_at_date` still belongs to
|
||||
//! the listing that was active on `report_date`.
|
||||
//! - Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO` = `"ceo_shorts"`)
|
||||
//! as `Cow::Borrowed`.
|
||||
//! - Re-sorts mapped rows in place by `(listing_id, report_date)` and compacts cross-`key`
|
||||
//! collisions on the same `(listing_id, report_date)`: bitwise-identical
|
||||
//! `(known_at_micros, shares_short, net_change, pct_float)` collapses to one row
|
||||
//! (`listing_collision_collapsed`), while any conflict drops the entire group
|
||||
//! (`listing_collision_dropped`), mirroring `build_shorts`'s duplicate policy.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::parquet_shorts::{
|
||||
write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions,
|
||||
ShortsWriteStats,
|
||||
};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::shorts::{build_shorts, CeoShortReport, ShortsError, ShortsStats};
|
||||
|
||||
/// Accounting summary produced alongside [`CurateShortsOutput::rows`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `rows_in == builder.rows_out`
|
||||
/// - `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped`
|
||||
/// - `builder` independently satisfies all [`ShortsStats`] conservation invariants.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct CurateShortsStats {
|
||||
pub builder: ShortsStats,
|
||||
pub rows_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub listings_out: usize,
|
||||
pub dropped_unmapped: usize,
|
||||
pub listing_collision_collapsed: usize,
|
||||
pub listing_collision_dropped: usize,
|
||||
}
|
||||
|
||||
/// Output of [`curate_shorts`]: contract Parquet rows sorted and unique by
|
||||
/// `(listing_id, report_date)` and full stage + builder stats.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateShortsOutput {
|
||||
pub rows: Vec<ShortsParquetRow>,
|
||||
pub stats: CurateShortsStats,
|
||||
}
|
||||
|
||||
/// Typed caller errors returned by [`curate_shorts`].
|
||||
///
|
||||
/// Bad single rows (unmapped dates and cross-`key` collisions) are dropped and counted in
|
||||
/// [`CurateShortsStats`] rather than aborting the stage.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CurateShortsError {
|
||||
/// Error propagated from [`build_shorts`] (e.g., `report_date` outside `2008..=2030`).
|
||||
Shorts(ShortsError),
|
||||
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateShortsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
Self::Shorts(err) => write!(f, "{err}"),
|
||||
Self::EmptyMappingSource => {
|
||||
write!(f, "mapping_source must not be empty or blank")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateShortsError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Shorts(err) => Some(err),
|
||||
Self::EmptyMappingSource => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ShortsError> for CurateShortsError {
|
||||
fn from(err: ShortsError) -> Self {
|
||||
Self::Shorts(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Combined stats returned by [`curate_and_write_shorts`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CurateShortsWriteReport {
|
||||
pub curate_stats: CurateShortsStats,
|
||||
pub write_stats: ShortsWriteStats,
|
||||
}
|
||||
|
||||
/// Typed error returned by [`curate_and_write_shorts`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateShortsWriteError {
|
||||
Curate(CurateShortsError),
|
||||
Parquet(ParquetShortsError),
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateShortsWriteError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Curate(err) => write!(f, "shorts curation failed: {err}"),
|
||||
Self::Parquet(err) => write!(f, "shorts Parquet write failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateShortsWriteError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Curate(err) => Some(err),
|
||||
Self::Parquet(err) => Some(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurateShortsError> for CurateShortsWriteError {
|
||||
fn from(err: CurateShortsError) -> Self {
|
||||
Self::Curate(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParquetShortsError> for CurateShortsWriteError {
|
||||
fn from(err: ParquetShortsError) -> Self {
|
||||
Self::Parquet(err)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parquet_row_values_bit_eq(a: &ShortsParquetRow, b: &ShortsParquetRow) -> bool {
|
||||
a.known_at_micros == b.known_at_micros
|
||||
&& a.shares_short.to_bits() == b.shares_short.to_bits()
|
||||
&& a.net_change.map(f64::to_bits) == b.net_change.map(f64::to_bits)
|
||||
&& a.pct_float.map(f64::to_bits) == b.pct_float.map(f64::to_bits)
|
||||
}
|
||||
|
||||
/// Pure `shorts` curation stage: validates, deduplicates, and point-in-time lags source-keyed
|
||||
/// `ceoShorts` reports via [`build_shorts`], resolves `(mapping_source, key, report_date) ->
|
||||
/// listing_id` through `provider_mapping`, and emits contract [`ShortsParquetRow`]s sorted and
|
||||
/// unique by `(listing_id, report_date)`.
|
||||
///
|
||||
/// Mapping lookup uses `report_date` (the reporting period the short position describes), not
|
||||
/// `known_at_date`. Rows with no covering mapping range are dropped into `dropped_unmapped`.
|
||||
///
|
||||
/// After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same
|
||||
/// `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`,
|
||||
/// `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`)
|
||||
/// and drop the entire group when any of those fields differ (`listing_collision_dropped += g`).
|
||||
pub fn curate_shorts<K, I>(
|
||||
reports: I,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
) -> Result<CurateShortsOutput, CurateShortsError>
|
||||
where
|
||||
K: Ord + Clone + AsRef<str>,
|
||||
I: IntoIterator<Item = CeoShortReport<K>>,
|
||||
{
|
||||
if mapping_source.trim().is_empty() {
|
||||
return Err(CurateShortsError::EmptyMappingSource);
|
||||
}
|
||||
|
||||
let built = build_shorts(reports)?;
|
||||
|
||||
let mut stats = CurateShortsStats {
|
||||
builder: built.stats,
|
||||
rows_in: built.rows.len(),
|
||||
..CurateShortsStats::default()
|
||||
};
|
||||
|
||||
let mut rows: Vec<ShortsParquetRow> = Vec::with_capacity(built.rows.len());
|
||||
let total_built = built.rows.len();
|
||||
let mut idx = 0usize;
|
||||
|
||||
while idx < total_built {
|
||||
let run_start = idx;
|
||||
let run_key = &built.rows[run_start].key;
|
||||
idx += 1;
|
||||
while idx < total_built && built.rows[idx].key == *run_key {
|
||||
idx += 1;
|
||||
}
|
||||
let run_end = idx;
|
||||
|
||||
let mut cursor = mapping.cursor_for(mapping_source, run_key.as_ref());
|
||||
if cursor.ranges().is_empty() {
|
||||
stats.dropped_unmapped += run_end - run_start;
|
||||
continue;
|
||||
}
|
||||
|
||||
for row in &built.rows[run_start..run_end] {
|
||||
let Some(listing_id) = cursor.resolve(row.report_date) else {
|
||||
stats.dropped_unmapped += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
rows.push(ShortsParquetRow {
|
||||
listing_id,
|
||||
report_date: row.report_date,
|
||||
known_at_micros: row.known_at_utc_micros,
|
||||
shares_short: row.shares_short,
|
||||
net_change: row.net_change,
|
||||
pct_float: row.pct_float,
|
||||
source: Cow::Borrowed(row.source),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Free builder rows before sorting/compacting mapped contract rows to cut peak RAM.
|
||||
drop(built.rows);
|
||||
|
||||
rows.sort_unstable_by(|a, b| {
|
||||
a.listing_id
|
||||
.cmp(&b.listing_id)
|
||||
.then_with(|| a.report_date.cmp(&b.report_date))
|
||||
});
|
||||
|
||||
let mut write_idx = 0usize;
|
||||
let mut read_idx = 0usize;
|
||||
let total_mapped = rows.len();
|
||||
let mut last_listing_id: Option<i32> = None;
|
||||
|
||||
while read_idx < total_mapped {
|
||||
let listing_id = rows[read_idx].listing_id;
|
||||
let report_date = rows[read_idx].report_date;
|
||||
let mut group_end = read_idx + 1;
|
||||
while group_end < total_mapped
|
||||
&& rows[group_end].listing_id == listing_id
|
||||
&& rows[group_end].report_date == report_date
|
||||
{
|
||||
group_end += 1;
|
||||
}
|
||||
let group_len = group_end - read_idx;
|
||||
|
||||
if group_len == 1 {
|
||||
if write_idx != read_idx {
|
||||
rows.swap(write_idx, read_idx);
|
||||
}
|
||||
if last_listing_id != Some(listing_id) {
|
||||
stats.listings_out += 1;
|
||||
last_listing_id = Some(listing_id);
|
||||
}
|
||||
write_idx += 1;
|
||||
} else {
|
||||
let first = &rows[read_idx];
|
||||
let all_identical = rows[read_idx + 1..group_end]
|
||||
.iter()
|
||||
.all(|other| parquet_row_values_bit_eq(first, other));
|
||||
|
||||
if all_identical {
|
||||
stats.listing_collision_collapsed += group_len - 1;
|
||||
if write_idx != read_idx {
|
||||
rows.swap(write_idx, read_idx);
|
||||
}
|
||||
if last_listing_id != Some(listing_id) {
|
||||
stats.listings_out += 1;
|
||||
last_listing_id = Some(listing_id);
|
||||
}
|
||||
write_idx += 1;
|
||||
} else {
|
||||
stats.listing_collision_dropped += group_len;
|
||||
}
|
||||
}
|
||||
|
||||
read_idx = group_end;
|
||||
}
|
||||
rows.truncate(write_idx);
|
||||
stats.rows_out = rows.len();
|
||||
|
||||
Ok(CurateShortsOutput { rows, stats })
|
||||
}
|
||||
|
||||
/// Thin end-to-end wrapper running [`curate_shorts`] and publishing the resulting contract rows
|
||||
/// via [`write_shorts_dataset`] to `<out_dir>/shorts/part.parquet`.
|
||||
///
|
||||
/// Any [`CurateShortsError`] returns before [`write_shorts_dataset`] is invoked, leaving
|
||||
/// `out_dir` untouched.
|
||||
pub fn curate_and_write_shorts<P, K, I>(
|
||||
out_dir: P,
|
||||
reports: I,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
options: ShortsWriteOptions,
|
||||
) -> Result<CurateShortsWriteReport, CurateShortsWriteError>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
K: Ord + Clone + AsRef<str>,
|
||||
I: IntoIterator<Item = CeoShortReport<K>>,
|
||||
{
|
||||
let curated = curate_shorts(reports, mapping_source, mapping)?;
|
||||
let write_stats = write_shorts_dataset(out_dir, &curated.rows, options)?;
|
||||
Ok(CurateShortsWriteReport {
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "curate_shorts_tests.rs"]
|
||||
mod tests;
|
||||
1065
tools/curate-etl/src/curate_shorts_tests.rs
Normal file
1065
tools/curate-etl/src/curate_shorts_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -102,3 +102,9 @@ pub use curate_bars::{
|
|||
CurateBars1dWriteReport, CurateBarsError, CurateBarsWriteError, BARS_1D_SESSION_CLOSE_HOUR_ET,
|
||||
BARS_1D_SESSION_CLOSE_MINUTE_ET, BARS_1D_SESSION_CLOSE_SECOND_ET, BARS_1D_SOURCE_EOD,
|
||||
};
|
||||
|
||||
pub mod curate_shorts;
|
||||
pub use curate_shorts::{
|
||||
curate_and_write_shorts, curate_shorts, CurateShortsError, CurateShortsOutput,
|
||||
CurateShortsStats, CurateShortsWriteError, CurateShortsWriteReport,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark, run_events_benchmark,
|
||||
run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_shorts_benchmark,
|
||||
run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
|
|
@ -572,6 +572,64 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateShorts(rows)) => {
|
||||
let report = match run_curate_shorts_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-shorts benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.rows > 0 {
|
||||
(report.rows_out as f64 / report.rows as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-shorts");
|
||||
println!(
|
||||
" input: rows={} keys={}",
|
||||
report.rows, report.key_count
|
||||
);
|
||||
println!(
|
||||
" builder: rows_out={} invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict_dropped={}",
|
||||
report.stats.builder.rows_out,
|
||||
report.stats.builder.dropped_invalid_shares_short,
|
||||
report.stats.builder.nulled_invalid_net_change,
|
||||
report.stats.builder.nulled_invalid_pct_float,
|
||||
report.stats.builder.duplicate_collapsed,
|
||||
report.stats.builder.duplicate_conflict_dropped
|
||||
);
|
||||
println!(
|
||||
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.stage_elapsed_ms,
|
||||
report.stage_rows_per_sec,
|
||||
report.stage_ns_per_row,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows,
|
||||
report.parquet_elapsed_ms,
|
||||
report.parquet_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.total_elapsed_ms, report.total_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" curate: unmapped={} coll_collapsed={} coll_dropped={}",
|
||||
report.stats.dropped_unmapped,
|
||||
report.stats.listing_collision_collapsed,
|
||||
report.stats.listing_collision_dropped
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
509
tools/curate-etl/tests/curate_shorts_qa_contract.rs
Normal file
509
tools/curate-etl/tests/curate_shorts_qa_contract.rs
Normal file
|
|
@ -0,0 +1,509 @@
|
|||
//! QA contract tests for the public `shorts` curation stage (T-100 / M1.2r).
|
||||
//!
|
||||
//! Covers gaps left by the in-crate `curate_shorts_tests.rs`, checking against independent
|
||||
//! references rather than the stage's own logic:
|
||||
//! - `known_at_micros` pinned to hand-computed `+4` TSX business-day `17:00 ET` instants across
|
||||
//! holidays and both DST regimes;
|
||||
//! - seeded differential test against a naive reference that resolves `provider_mapping` by
|
||||
//! linear scan over the raw mapping rows on `report_date` (never through the table/cursor);
|
||||
//! - truncation and poison look-ahead tests at several cutoffs with non-empty baselines;
|
||||
//! - ticker change (two keys → one listing over disjoint ranges) kept without collisions;
|
||||
//! - successful re-publish replaces a larger `part.parquet`, multi-row-group round trip;
|
||||
//! - `bench-curate-shorts` binary run: deterministic checksum and `read_back_rows == rows_out`.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use curate_etl::{
|
||||
curate_and_write_shorts, curate_shorts, CeoShortReport, CurateShortsOutput,
|
||||
ProviderMappingRow, ProviderMappingTable, ShortsParquetRow, ShortsWriteOptions,
|
||||
SHORTS_SOURCE_CEO,
|
||||
};
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
const MICROS_PER_HOUR: i64 = 3_600_000_000;
|
||||
const MICROS_PER_DAY: i64 = 86_400_000_000;
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-etl-curate-shorts-qa-{tag}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic SplitMix64 (fixed seed per test).
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
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 below(&mut self, n: u64) -> u64 {
|
||||
self.next_u64() % n
|
||||
}
|
||||
}
|
||||
|
||||
/// Independent civil-from-days (Howard Hinnant), not the crate's `ymd_to_epoch_days`.
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
let y = if m <= 2 { y - 1 } else { y };
|
||||
let era = if y >= 0 { y } else { y - 399 } / 400;
|
||||
let yoe = y - era * 400;
|
||||
let mp = (m as i32 + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + d as i32 - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
|
||||
fn report(key: &str, report_date: i32, shares: f64, net: Option<f64>, pct: Option<f64>) -> CeoShortReport<String> {
|
||||
CeoShortReport {
|
||||
key: key.to_string(),
|
||||
report_date,
|
||||
shares_short: shares,
|
||||
net_change: net,
|
||||
pct_float: pct,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_row(source: &str, id: &str, from: i32, to: Option<i32>, listing_id: i32) -> ProviderMappingRow {
|
||||
ProviderMappingRow {
|
||||
source: source.to_string(),
|
||||
source_id: id.to_string(),
|
||||
valid_from: from,
|
||||
valid_to: to,
|
||||
listing_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_rows_bitwise(actual: &[ShortsParquetRow], expected: &[ShortsParquetRow]) {
|
||||
assert_eq!(actual.len(), expected.len(), "row count mismatch");
|
||||
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
|
||||
assert_eq!(
|
||||
(a.listing_id, a.report_date, a.known_at_micros, a.shares_short.to_bits()),
|
||||
(e.listing_id, e.report_date, e.known_at_micros, e.shares_short.to_bits()),
|
||||
"row {i}"
|
||||
);
|
||||
assert_eq!(a.net_change.map(f64::to_bits), e.net_change.map(f64::to_bits), "row {i}");
|
||||
assert_eq!(a.pct_float.map(f64::to_bits), e.pct_float.map(f64::to_bits), "row {i}");
|
||||
assert_eq!(a.source, e.source, "row {i}");
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_invariants(out: &CurateShortsOutput) {
|
||||
let s = out.stats;
|
||||
assert_eq!(s.rows_in, s.builder.rows_out, "{s:?}");
|
||||
assert_eq!(s.rows_out, out.rows.len(), "{s:?}");
|
||||
assert_eq!(
|
||||
s.rows_in,
|
||||
s.rows_out + s.dropped_unmapped + s.listing_collision_collapsed + s.listing_collision_dropped,
|
||||
"{s:?}"
|
||||
);
|
||||
for w in out.rows.windows(2) {
|
||||
assert!((w[0].listing_id, w[0].report_date) < (w[1].listing_id, w[1].report_date));
|
||||
}
|
||||
let mut listings: Vec<i32> = out.rows.iter().map(|r| r.listing_id).collect();
|
||||
listings.dedup();
|
||||
assert_eq!(s.listings_out, listings.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_at_matches_hand_computed_tsx_plus_four_business_days_at_17_et() {
|
||||
// (report_date, expected known_at date, UTC offset hours of 17:00 ET on that date)
|
||||
let cases = [
|
||||
// Fri before Canada Day (Mon Jul 1): Jul 2,3,4,5 -> Fri Jul 5, EDT (21:00Z).
|
||||
(day(2024, 6, 28), day(2024, 7, 5), 21),
|
||||
// Tue Dec 31, New Year's Day Wed: Jan 2,3,6,7 -> Tue Jan 7 2025, EST (22:00Z).
|
||||
(day(2024, 12, 31), day(2025, 1, 7), 22),
|
||||
// Fri Dec 15 2023, ordinary: Dec 18..21 -> Thu Dec 21, EST.
|
||||
(day(2023, 12, 15), day(2023, 12, 21), 22),
|
||||
// Fri Dec 22 2023? not a report date; use Sun Dec 31 2023: Jan 1 holiday, Jan 2,3,4,5.
|
||||
(day(2023, 12, 31), day(2024, 1, 5), 22),
|
||||
// Fri Mar 15 2024 (DST began Mar 10): Mar 18..21, EDT.
|
||||
(day(2024, 3, 15), day(2024, 3, 21), 21),
|
||||
// Fri Mar 29 2024 is Good Friday; Sun Mar 31 report: Apr 1(open),2,3,4 -> Apr 4.
|
||||
(day(2024, 3, 31), day(2024, 4, 4), 21),
|
||||
// Thu Oct 31 2024 (DST ends Nov 3): Nov 1, 4, 5, 6 -> Wed Nov 6, EST.
|
||||
(day(2024, 10, 31), day(2024, 11, 6), 22),
|
||||
// Mon Nov 11 2024 Remembrance Day is a TSX trading day; Fri Nov 15: 18..21.
|
||||
(day(2024, 11, 15), day(2024, 11, 21), 22),
|
||||
// Thu Jul 31 2025: Aug 1, (Aug 4 Civic Holiday), 5, 6, 7 -> Thu Aug 7, EDT.
|
||||
(day(2025, 7, 31), day(2025, 8, 7), 21),
|
||||
];
|
||||
let mapping = ProviderMappingTable::from_rows([map_row("ceo", "RY", day(2010, 1, 1), None, 7)]).unwrap();
|
||||
let reports: Vec<_> = cases.iter().map(|&(d, _, _)| report("RY", d, 1_000.0, None, None)).collect();
|
||||
|
||||
let out = curate_shorts(reports, "ceo", &mapping).unwrap();
|
||||
assert_invariants(&out);
|
||||
assert_eq!(out.rows.len(), cases.len());
|
||||
|
||||
let mut sorted = cases;
|
||||
sorted.sort_by_key(|c| c.0);
|
||||
for (row, &(rd, known_day, utc_hour)) in out.rows.iter().zip(&sorted) {
|
||||
assert_eq!(row.report_date, rd);
|
||||
let expected = i64::from(known_day) * MICROS_PER_DAY + utc_hour * MICROS_PER_HOUR;
|
||||
assert_eq!(
|
||||
row.known_at_micros, expected,
|
||||
"report_date {rd}: known_at off by {} h",
|
||||
(row.known_at_micros - expected) / MICROS_PER_HOUR
|
||||
);
|
||||
assert_eq!(row.source.as_ref(), SHORTS_SOURCE_CEO);
|
||||
}
|
||||
}
|
||||
|
||||
/// Random universe: plain keys, ticker reuse with a gap, ticker change (two keys sharing one
|
||||
/// listing over disjoint ranges), aliases (overlapping ranges -> collisions), unmapped keys,
|
||||
/// plus decoy rows under a different mapping source.
|
||||
fn random_universe() -> (Vec<ProviderMappingRow>, Vec<String>) {
|
||||
let mut rows = Vec::new();
|
||||
let mut keys = Vec::new();
|
||||
for i in 0..8 {
|
||||
let k = format!("P{i}");
|
||||
rows.push(map_row("ceo", &k, day(2018, 1, 1), None, 10 + i));
|
||||
rows.push(map_row("other", &k, day(2018, 1, 1), None, 900 + i));
|
||||
keys.push(k);
|
||||
}
|
||||
for i in 0..3 {
|
||||
let k = format!("R{i}");
|
||||
rows.push(map_row("ceo", &k, day(2018, 1, 1), Some(day(2020, 6, 15)), 40 + i));
|
||||
rows.push(map_row("ceo", &k, day(2020, 9, 1), None, 50 + i));
|
||||
keys.push(k);
|
||||
}
|
||||
for i in 0..3 {
|
||||
// Ticker change: OLD{i} until 2021-03-31, NEW{i} from 2021-04-01, same listing.
|
||||
let (old, new) = (format!("OLD{i}"), format!("NEW{i}"));
|
||||
rows.push(map_row("ceo", &old, day(2018, 1, 1), Some(day(2021, 3, 31)), 60 + i));
|
||||
rows.push(map_row("ceo", &new, day(2021, 4, 1), None, 60 + i));
|
||||
keys.push(old);
|
||||
keys.push(new);
|
||||
}
|
||||
for i in 0..3 {
|
||||
let k = format!("A{i}");
|
||||
rows.push(map_row("ceo", &k, day(2019, 1, 1), Some(day(2023, 12, 31)), 10 + i));
|
||||
keys.push(k);
|
||||
}
|
||||
for i in 0..3 {
|
||||
keys.push(format!("U{i}"));
|
||||
}
|
||||
(rows, keys)
|
||||
}
|
||||
|
||||
fn report_dates() -> Vec<i32> {
|
||||
let mut v = Vec::new();
|
||||
for y in 2017..=2025 {
|
||||
for m in 1..=12u32 {
|
||||
v.push(day(y, m, 15));
|
||||
let next = if m == 12 { day(y + 1, 1, 1) } else { day(y, m + 1, 1) };
|
||||
v.push(next - 1);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn random_reports(seed: u64, n: usize, keys: &[String], dates: &[i32]) -> Vec<CeoShortReport<String>> {
|
||||
let mut rng = Rng(seed);
|
||||
let mut out: Vec<CeoShortReport<String>> = Vec::with_capacity(n);
|
||||
while out.len() < n {
|
||||
// Echo the previous plain-key report under its alias key (`P{i}` -> `A{i}`), identical
|
||||
// or conflicting, so cross-key collisions are hit deterministically.
|
||||
let echo = rng.below(10);
|
||||
if echo < 2 {
|
||||
if let Some(prev) = out.last() {
|
||||
if let Some(i) = prev.key.strip_prefix('P').filter(|i| ["0", "1", "2"].contains(i)) {
|
||||
let mut copy = report(&format!("A{i}"), prev.report_date, prev.shares_short, prev.net_change, prev.pct_float);
|
||||
if echo == 1 {
|
||||
copy.shares_short += 1.0;
|
||||
}
|
||||
out.push(copy);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push({
|
||||
let key = &keys[rng.below(keys.len() as u64) as usize];
|
||||
let d = dates[rng.below(dates.len() as u64) as usize];
|
||||
let shares = match rng.below(50) {
|
||||
0 => -5.0,
|
||||
1 => f64::NAN,
|
||||
_ => (rng.below(3) * 500) as f64,
|
||||
};
|
||||
let net = match rng.below(4) {
|
||||
0 => None,
|
||||
1 => Some(f64::NEG_INFINITY),
|
||||
v => Some(v as f64 * 10.0),
|
||||
};
|
||||
let pct = match rng.below(3) {
|
||||
0 => None,
|
||||
v => Some(v as f64 * 0.5),
|
||||
};
|
||||
report(key, d, shares, net, pct)
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Naive reference built directly from `build_shorts` output and the raw mapping rows.
|
||||
fn reference(
|
||||
reports: Vec<CeoShortReport<String>>,
|
||||
source: &str,
|
||||
mapping_rows: &[ProviderMappingRow],
|
||||
) -> (Vec<ShortsParquetRow>, usize, usize, usize) {
|
||||
let built = curate_etl::build_shorts(reports).unwrap();
|
||||
let mut groups: BTreeMap<(i32, i32), Vec<ShortsParquetRow>> = BTreeMap::new();
|
||||
let mut unmapped = 0;
|
||||
for r in built.rows {
|
||||
let hit = mapping_rows.iter().find(|m| {
|
||||
m.source == source
|
||||
&& m.source_id == r.key
|
||||
&& m.valid_from <= r.report_date
|
||||
&& m.valid_to.is_none_or(|to| r.report_date <= to)
|
||||
});
|
||||
match hit {
|
||||
Some(m) => groups.entry((m.listing_id, r.report_date)).or_default().push(ShortsParquetRow {
|
||||
listing_id: m.listing_id,
|
||||
report_date: r.report_date,
|
||||
known_at_micros: r.known_at_utc_micros,
|
||||
shares_short: r.shares_short,
|
||||
net_change: r.net_change,
|
||||
pct_float: r.pct_float,
|
||||
source: Cow::Borrowed(r.source),
|
||||
}),
|
||||
None => unmapped += 1,
|
||||
}
|
||||
}
|
||||
let key = |r: &ShortsParquetRow| {
|
||||
(r.known_at_micros, r.shares_short.to_bits(), r.net_change.map(f64::to_bits), r.pct_float.map(f64::to_bits))
|
||||
};
|
||||
let (mut out, mut collapsed, mut dropped) = (Vec::new(), 0, 0);
|
||||
for (_, g) in groups {
|
||||
if g.iter().all(|r| key(r) == key(&g[0])) {
|
||||
collapsed += g.len() - 1;
|
||||
out.push(g.into_iter().next().unwrap());
|
||||
} else {
|
||||
dropped += g.len();
|
||||
}
|
||||
}
|
||||
(out, unmapped, collapsed, dropped)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_stage_matches_linear_scan_reference_resolving_on_report_date() {
|
||||
let (mapping_rows, keys) = random_universe();
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows.clone()).unwrap();
|
||||
let dates = report_dates();
|
||||
|
||||
for seed in [0xC0FF_EE00_0000_0001u64, 0xC0FF_EE00_0000_0002, 0xC0FF_EE00_0000_0003] {
|
||||
let reports = random_reports(seed, 4_000, &keys, &dates);
|
||||
let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap();
|
||||
assert_invariants(&out);
|
||||
let (exp, unmapped, collapsed, dropped) = reference(reports, "ceo", &mapping_rows);
|
||||
assert_eq!(out.stats.dropped_unmapped, unmapped, "seed {seed:#x}");
|
||||
assert_eq!(out.stats.listing_collision_collapsed, collapsed, "seed {seed:#x}");
|
||||
assert_eq!(out.stats.listing_collision_dropped, dropped, "seed {seed:#x}");
|
||||
assert!(unmapped > 0 && collapsed > 0 && dropped > 0, "fixture must hit every path: {:?}", out.stats);
|
||||
assert_rows_bitwise(&out.rows, &exp);
|
||||
// No row may come from the decoy "other" source listings.
|
||||
assert!(out.rows.iter().all(|r| r.listing_id < 900));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticker_change_keys_share_one_listing_without_collisions() {
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "OLD", day(2018, 1, 1), Some(day(2021, 3, 31)), 60),
|
||||
map_row("ceo", "NEW", day(2021, 4, 1), None, 60),
|
||||
])
|
||||
.unwrap();
|
||||
let reports = vec![
|
||||
report("OLD", day(2021, 2, 28), 100.0, None, None),
|
||||
report("OLD", day(2021, 3, 31), 200.0, None, None),
|
||||
report("NEW", day(2021, 4, 15), 300.0, None, None),
|
||||
// Stale feed: OLD keeps reporting after the change -> unmapped, not a collision.
|
||||
report("OLD", day(2021, 4, 15), 999.0, None, None),
|
||||
// NEW backfilled before its range -> unmapped.
|
||||
report("NEW", day(2021, 3, 15), 888.0, None, None),
|
||||
];
|
||||
let out = curate_shorts(reports, "ceo", &mapping).unwrap();
|
||||
assert_invariants(&out);
|
||||
assert_eq!(out.stats.dropped_unmapped, 2);
|
||||
assert_eq!(out.stats.listing_collision_collapsed + out.stats.listing_collision_dropped, 0);
|
||||
assert_eq!(out.stats.listings_out, 1);
|
||||
let got: Vec<(i32, f64)> = out.rows.iter().map(|r| (r.report_date, r.shares_short)).collect();
|
||||
assert_eq!(got, vec![(day(2021, 2, 28), 100.0), (day(2021, 3, 31), 200.0), (day(2021, 4, 15), 300.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_and_poison_leave_earlier_rows_unchanged_at_every_cutoff() {
|
||||
let (mapping_rows, keys) = random_universe();
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap();
|
||||
let dates = report_dates();
|
||||
let reports = random_reports(0x7E57_0000_1234_5678, 3_000, &keys, &dates);
|
||||
let full = curate_shorts(reports.clone(), "ceo", &mapping).unwrap();
|
||||
|
||||
for cutoff in [day(2019, 1, 1), day(2020, 7, 1), day(2021, 4, 1), day(2023, 1, 1), day(2025, 6, 1)] {
|
||||
let truncated: Vec<_> = reports.iter().filter(|r| r.report_date < cutoff).cloned().collect();
|
||||
let base = curate_shorts(truncated.clone(), "ceo", &mapping).unwrap();
|
||||
assert_invariants(&base);
|
||||
assert!(base.rows.len() > 10, "cutoff {cutoff}: baseline must not be empty");
|
||||
|
||||
// Truncation: rebuilding from history alone equals the full run's history.
|
||||
let prefix: Vec<_> = full.rows.iter().filter(|r| r.report_date < cutoff).cloned().collect();
|
||||
assert_rows_bitwise(&base.rows, &prefix);
|
||||
|
||||
// Poison: absurd future reports on every key, conflicting aliases included.
|
||||
let mut poisoned = truncated;
|
||||
for (i, k) in keys.iter().enumerate() {
|
||||
poisoned.push(report(k, day(2026, 1, 15), 1e12 + i as f64, Some(-1e9), Some(99.0)));
|
||||
poisoned.push(report(k, cutoff, 7e11 + i as f64, None, Some(50.0)));
|
||||
}
|
||||
let pois = curate_shorts(poisoned, "ceo", &mapping).unwrap();
|
||||
assert_invariants(&pois);
|
||||
let pois_prefix: Vec<_> = pois.rows.into_iter().filter(|r| r.report_date < cutoff).collect();
|
||||
assert_rows_bitwise(&pois_prefix, &base.rows);
|
||||
|
||||
// Every row is published strictly after its report date ends (>= 4 days later).
|
||||
for r in &base.rows {
|
||||
assert!(r.known_at_micros >= (i64::from(r.report_date) + 4) * MICROS_PER_DAY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_parquet(path: &Path) -> (usize, usize, Vec<ShortsParquetRow>) {
|
||||
let reader = SerializedFileReader::new(File::open(path).unwrap()).unwrap();
|
||||
let md = reader.metadata();
|
||||
let footer = md.file_metadata().num_rows() as usize;
|
||||
let mut out = Vec::new();
|
||||
for g in 0..md.num_row_groups() {
|
||||
let rg = reader.get_row_group(g).unwrap();
|
||||
let n = md.row_group(g).num_rows() as usize;
|
||||
let mut lid = Vec::new();
|
||||
let mut rd = Vec::new();
|
||||
let mut ka = Vec::new();
|
||||
let mut ss = Vec::new();
|
||||
let mut src = Vec::new();
|
||||
if let ColumnReader::Int32ColumnReader(mut r) = rg.get_column_reader(0).unwrap() {
|
||||
r.read_records(n, None, None, &mut lid).unwrap();
|
||||
}
|
||||
if let ColumnReader::Int32ColumnReader(mut r) = rg.get_column_reader(1).unwrap() {
|
||||
r.read_records(n, None, None, &mut rd).unwrap();
|
||||
}
|
||||
if let ColumnReader::Int64ColumnReader(mut r) = rg.get_column_reader(2).unwrap() {
|
||||
r.read_records(n, None, None, &mut ka).unwrap();
|
||||
}
|
||||
if let ColumnReader::DoubleColumnReader(mut r) = rg.get_column_reader(3).unwrap() {
|
||||
r.read_records(n, None, None, &mut ss).unwrap();
|
||||
}
|
||||
let opt = |idx: usize| -> Vec<Option<f64>> {
|
||||
let (mut vals, mut defs) = (Vec::new(), Vec::new());
|
||||
if let ColumnReader::DoubleColumnReader(mut r) = rg.get_column_reader(idx).unwrap() {
|
||||
r.read_records(n, Some(&mut defs), None, &mut vals).unwrap();
|
||||
}
|
||||
let mut it = vals.into_iter();
|
||||
defs.into_iter().map(|d| if d == 1 { it.next() } else { None }).collect()
|
||||
};
|
||||
let (net, pct) = (opt(4), opt(5));
|
||||
if let ColumnReader::ByteArrayColumnReader(mut r) = rg.get_column_reader(6).unwrap() {
|
||||
r.read_records(n, None, None, &mut src).unwrap();
|
||||
}
|
||||
assert_eq!((lid.len(), rd.len(), ka.len(), ss.len(), src.len()), (n, n, n, n, n));
|
||||
for i in 0..n {
|
||||
out.push(ShortsParquetRow {
|
||||
listing_id: lid[i],
|
||||
report_date: rd[i],
|
||||
known_at_micros: ka[i],
|
||||
shares_short: ss[i],
|
||||
net_change: net[i],
|
||||
pct_float: pct[i],
|
||||
source: Cow::Owned(String::from_utf8(src[i].data().to_vec()).unwrap()),
|
||||
});
|
||||
}
|
||||
}
|
||||
(footer, md.num_row_groups(), out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn republish_replaces_larger_file_and_multi_row_group_round_trips() {
|
||||
let (mapping_rows, keys) = random_universe();
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap();
|
||||
let dates = report_dates();
|
||||
let tmp = TempDir::new("republish");
|
||||
let part = tmp.0.join("shorts").join("part.parquet");
|
||||
let opts = ShortsWriteOptions { row_group_rows: 97, ..ShortsWriteOptions::default() };
|
||||
|
||||
let big = random_reports(0xB16_0000_0000_0001, 2_000, &keys, &dates);
|
||||
let first = curate_and_write_shorts(&tmp.0, big.clone(), "ceo", &mapping, opts).unwrap();
|
||||
let expected_big = curate_shorts(big, "ceo", &mapping).unwrap();
|
||||
let (footer, groups, rows) = read_parquet(&part);
|
||||
assert_eq!(footer, first.curate_stats.rows_out);
|
||||
assert_eq!(groups, first.write_stats.row_groups_written);
|
||||
assert_eq!(groups, footer.div_ceil(97));
|
||||
assert!(groups > 1);
|
||||
assert_rows_bitwise(&rows, &expected_big.rows);
|
||||
|
||||
let small = random_reports(0x5A1_0000_0000_0002, 50, &keys, &dates);
|
||||
let second = curate_and_write_shorts(&tmp.0, small.clone(), "ceo", &mapping, opts).unwrap();
|
||||
assert!(second.curate_stats.rows_out > 0 && second.curate_stats.rows_out < first.curate_stats.rows_out);
|
||||
let (footer, _, rows) = read_parquet(&part);
|
||||
assert_eq!(footer, second.curate_stats.rows_out);
|
||||
assert_rows_bitwise(&rows, &curate_shorts(small, "ceo", &mapping).unwrap().rows);
|
||||
|
||||
let leftovers: Vec<_> = fs::read_dir(tmp.0.join("shorts"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(leftovers, vec!["part.parquet".to_string()]);
|
||||
}
|
||||
|
||||
fn field<'a>(text: &'a str, name: &str) -> &'a str {
|
||||
text.split_whitespace()
|
||||
.find_map(|t| t.strip_prefix(name))
|
||||
.unwrap_or_else(|| panic!("missing {name} in:\n{text}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_shorts_cli_is_deterministic_and_reads_back_all_rows() {
|
||||
let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_curate-etl")).args(args).output().unwrap();
|
||||
let a = run(&["bench-curate-shorts", "30000"]);
|
||||
let b = run(&["bench-curate-shorts", "30000"]);
|
||||
assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr));
|
||||
assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr));
|
||||
let (ta, tb) = (String::from_utf8_lossy(&a.stdout), String::from_utf8_lossy(&b.stdout));
|
||||
|
||||
assert!(ta.contains("curate-etl bench-curate-shorts"), "{ta}");
|
||||
assert!(ta.contains("rows=30000 keys=12500"), "{ta}");
|
||||
assert_eq!(field(&ta, "checksum="), field(&tb, "checksum="));
|
||||
assert_ne!(field(&ta, "checksum="), "0x0000000000000000");
|
||||
// The builder line also has `rows_out=`, so compare against the stage line's value.
|
||||
let stage_line = ta.lines().find(|l| l.trim_start().starts_with("stage:")).unwrap();
|
||||
assert_eq!(field(stage_line, "rows_out="), field(&ta, "read_back_rows="));
|
||||
|
||||
for bad in [&["bench-curate-shorts", "0"][..], &["bench-curate-shorts", "x"], &["bench-curate-shorts", "1", "2"]] {
|
||||
let o = run(bad);
|
||||
assert!(!o.status.success(), "{bad:?} should fail");
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("bench-curate-shorts"), "{bad:?}");
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue