T-100: M1.2r — tools/curate-etl: pure shorts curation stage (source-keyed ceoShorts reports → provider_mapping → ShortsParquetRows → Zstd Parquet) with tests and local benchmark (no new crates)
This commit is contained in:
parent
3d856c5022
commit
0d115cb66b
7 changed files with 1851 additions and 3 deletions
|
|
@ -688,3 +688,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`
|
||||
|
|
|
|||
|
|
@ -4224,6 +4224,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::*;
|
||||
|
|
@ -5221,4 +5659,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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use crate::bench::{
|
|||
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,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -33,6 +33,7 @@ pub enum CliAction {
|
|||
BenchParquetAdj(usize),
|
||||
BenchParquetCorporateActions(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -57,7 +58,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-parquet-fx [rows] Run fixed-seed fx_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_FX_BENCH_ROWS})\n\
|
||||
{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-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})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -81,7 +83,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-parquet-fx [rows]\n\
|
||||
{name} bench-parquet-adj [rows]\n\
|
||||
{name} bench-parquet-corporate-actions [rows]\n\
|
||||
{name} bench-curate-bars [rows]"
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -244,6 +247,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}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -531,6 +546,7 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-adj"));
|
||||
assert!(full.contains("bench-parquet-corporate-actions"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
|
|
@ -548,6 +564,7 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-adj"));
|
||||
assert!(short.contains("bench-parquet-corporate-actions"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -565,4 +582,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;
|
||||
782
tools/curate-etl/src/curate_shorts_tests.rs
Normal file
782
tools/curate-etl/src/curate_shorts_tests.rs
Normal file
|
|
@ -0,0 +1,782 @@
|
|||
use std::borrow::Cow;
|
||||
use std::error::Error;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
||||
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use super::*;
|
||||
use crate::provider_mapping::ProviderMappingRow;
|
||||
use crate::shorts::{build_shorts, SHORTS_SOURCE_CEO};
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDirGuard {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDirGuard {
|
||||
fn new(label: &str) -> Self {
|
||||
let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed);
|
||||
let pid = std::process::id();
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("curate-etl-curate-shorts-{label}-{pid}-{seq}"));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create test temp dir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDirGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn report(
|
||||
key: &str,
|
||||
report_date: i32,
|
||||
shares_short: f64,
|
||||
net_change: Option<f64>,
|
||||
pct_float: Option<f64>,
|
||||
) -> CeoShortReport<String> {
|
||||
CeoShortReport {
|
||||
key: key.to_string(),
|
||||
report_date,
|
||||
shares_short,
|
||||
net_change,
|
||||
pct_float,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_row(
|
||||
source: &str,
|
||||
source_id: &str,
|
||||
valid_from: i32,
|
||||
valid_to: Option<i32>,
|
||||
listing_id: i32,
|
||||
) -> ProviderMappingRow {
|
||||
ProviderMappingRow {
|
||||
source: source.to_string(),
|
||||
source_id: source_id.to_string(),
|
||||
valid_from,
|
||||
valid_to,
|
||||
listing_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_conservation_and_order(out: &CurateShortsOutput) {
|
||||
let s = &out.stats;
|
||||
assert_eq!(
|
||||
s.rows_in, s.builder.rows_out,
|
||||
"rows_in != builder.rows_out: {s:?}"
|
||||
);
|
||||
assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}");
|
||||
assert_eq!(
|
||||
s.rows_in,
|
||||
s.rows_out
|
||||
+ s.dropped_unmapped
|
||||
+ s.listing_collision_collapsed
|
||||
+ s.listing_collision_dropped,
|
||||
"curate accounting conservation mismatch: {s:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
s.builder.rows_in,
|
||||
s.builder.rows_out
|
||||
+ s.builder.dropped_invalid_shares_short
|
||||
+ s.builder.duplicate_collapsed
|
||||
+ s.builder.duplicate_conflict_dropped,
|
||||
"builder accounting conservation mismatch: {s:?}"
|
||||
);
|
||||
|
||||
let mut distinct_listings = 0usize;
|
||||
let mut prev_listing: Option<i32> = None;
|
||||
for row in &out.rows {
|
||||
assert_eq!(row.source.as_ref(), SHORTS_SOURCE_CEO);
|
||||
if prev_listing != Some(row.listing_id) {
|
||||
distinct_listings += 1;
|
||||
prev_listing = Some(row.listing_id);
|
||||
}
|
||||
}
|
||||
assert_eq!(s.listings_out, distinct_listings);
|
||||
|
||||
for pair in out.rows.windows(2) {
|
||||
assert!(
|
||||
(pair[0].listing_id, pair[0].report_date) < (pair[1].listing_id, pair[1].report_date),
|
||||
"output rows must be strictly sorted and unique by (listing_id, report_date): {:?} vs {:?}",
|
||||
(pair[0].listing_id, pair[0].report_date),
|
||||
(pair[1].listing_id, pair[1].report_date),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_parquet_rows(path: &Path) -> (usize, Vec<ShortsParquetRow>) {
|
||||
let file = File::open(path).expect("open parquet file");
|
||||
let reader = SerializedFileReader::new(file).expect("open parquet reader");
|
||||
let metadata = reader.metadata();
|
||||
let footer_rows = metadata.file_metadata().num_rows() as usize;
|
||||
let mut out = Vec::with_capacity(footer_rows);
|
||||
|
||||
for rg_idx in 0..metadata.num_row_groups() {
|
||||
let rg_reader = reader.get_row_group(rg_idx).expect("row group reader");
|
||||
let num_rows = metadata.row_group(rg_idx).num_rows() as usize;
|
||||
|
||||
let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows);
|
||||
let report_date = read_i32_col(rg_reader.get_column_reader(1).unwrap(), num_rows);
|
||||
let known_at_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows);
|
||||
let shares_short = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows);
|
||||
let net_change = read_opt_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows);
|
||||
let pct_float = read_opt_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows);
|
||||
let source = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows);
|
||||
|
||||
for i in 0..num_rows {
|
||||
out.push(ShortsParquetRow {
|
||||
listing_id: listing_id[i],
|
||||
report_date: report_date[i],
|
||||
known_at_micros: known_at_micros[i],
|
||||
shares_short: shares_short[i],
|
||||
net_change: net_change[i],
|
||||
pct_float: pct_float[i],
|
||||
source: Cow::Owned(source[i].clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
(footer_rows, out)
|
||||
}
|
||||
|
||||
fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec<i32> {
|
||||
let mut values = Vec::with_capacity(expected);
|
||||
match reader {
|
||||
ColumnReader::Int32ColumnReader(mut r) => {
|
||||
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
|
||||
assert_eq!(records, expected);
|
||||
}
|
||||
_ => panic!("expected Int32ColumnReader"),
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec<i64> {
|
||||
let mut values = Vec::with_capacity(expected);
|
||||
match reader {
|
||||
ColumnReader::Int64ColumnReader(mut r) => {
|
||||
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
|
||||
assert_eq!(records, expected);
|
||||
}
|
||||
_ => panic!("expected Int64ColumnReader"),
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec<f64> {
|
||||
let mut values = Vec::with_capacity(expected);
|
||||
match reader {
|
||||
ColumnReader::DoubleColumnReader(mut r) => {
|
||||
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
|
||||
assert_eq!(records, expected);
|
||||
}
|
||||
_ => panic!("expected DoubleColumnReader"),
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec<Option<f64>> {
|
||||
let mut raw_values = Vec::with_capacity(expected);
|
||||
let mut def_levels = Vec::with_capacity(expected);
|
||||
match reader {
|
||||
ColumnReader::DoubleColumnReader(mut r) => {
|
||||
let (records, _, levels) = r
|
||||
.read_records(expected, Some(&mut def_levels), None, &mut raw_values)
|
||||
.unwrap();
|
||||
assert_eq!(records, expected);
|
||||
assert_eq!(levels, expected);
|
||||
}
|
||||
_ => panic!("expected DoubleColumnReader"),
|
||||
}
|
||||
let mut out = Vec::with_capacity(expected);
|
||||
let mut val_idx = 0usize;
|
||||
for lvl in def_levels {
|
||||
if lvl == 1 {
|
||||
out.push(Some(raw_values[val_idx]));
|
||||
val_idx += 1;
|
||||
} else {
|
||||
out.push(None);
|
||||
}
|
||||
}
|
||||
assert_eq!(val_idx, raw_values.len());
|
||||
out
|
||||
}
|
||||
|
||||
fn read_str_col(reader: ColumnReader, expected: usize) -> Vec<String> {
|
||||
let mut values = Vec::with_capacity(expected);
|
||||
match reader {
|
||||
ColumnReader::ByteArrayColumnReader(mut r) => {
|
||||
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
|
||||
assert_eq!(records, expected);
|
||||
}
|
||||
_ => panic!("expected ByteArrayColumnReader"),
|
||||
}
|
||||
values
|
||||
.into_iter()
|
||||
.map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn assert_row_bitwise_eq(actual: &ShortsParquetRow, expected: &ShortsParquetRow) {
|
||||
assert_eq!(actual.listing_id, expected.listing_id);
|
||||
assert_eq!(actual.report_date, expected.report_date);
|
||||
assert_eq!(actual.known_at_micros, expected.known_at_micros);
|
||||
assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits());
|
||||
assert_eq!(
|
||||
actual.net_change.map(f64::to_bits),
|
||||
expected.net_change.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(
|
||||
actual.pct_float.map(f64::to_bits),
|
||||
expected.pct_float.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(actual.source, expected.source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn happy_path_two_ceo_symbols_resort_by_listing_id_and_preserve_builder_known_at_and_source() {
|
||||
// Assign RY (lexicographically after ABX) a smaller listing_id (10 vs 20) to prove
|
||||
// post-mapping re-sorting by (listing_id, report_date).
|
||||
let d_est = day(2024, 1, 15); // Winter (EST)
|
||||
let d_edt = day(2024, 7, 15); // Summer (EDT)
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "ABX", day(2015, 1, 1), None, 20),
|
||||
map_row("ceo", "RY", day(2015, 1, 1), None, 10),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let input = vec![
|
||||
report("ABX", d_est, 12_500_000.0, Some(-250_000.0), Some(0.75)),
|
||||
report("ABX", d_edt, 13_100_000.0, Some(600_000.0), None),
|
||||
report("RY", d_est, 8_200_000.0, None, Some(0.60)),
|
||||
report("RY", d_edt, 8_050_000.0, Some(-150_000.0), Some(0.58)),
|
||||
];
|
||||
|
||||
let built = build_shorts(input.clone()).unwrap();
|
||||
let out = curate_shorts(input, "ceo", &mapping).unwrap();
|
||||
|
||||
assert_conservation_and_order(&out);
|
||||
assert_eq!(out.stats.builder, built.stats);
|
||||
assert_eq!(out.stats.rows_in, 4);
|
||||
assert_eq!(out.stats.rows_out, 4);
|
||||
assert_eq!(out.stats.listings_out, 2);
|
||||
assert_eq!(out.stats.dropped_unmapped, 0);
|
||||
assert_eq!(out.stats.listing_collision_collapsed, 0);
|
||||
assert_eq!(out.stats.listing_collision_dropped, 0);
|
||||
|
||||
// Listing 10 (RY) comes first despite "RY" > "ABX".
|
||||
let ry_built: Vec<_> = built.rows.iter().filter(|r| r.key == "RY").collect();
|
||||
let abx_built: Vec<_> = built.rows.iter().filter(|r| r.key == "ABX").collect();
|
||||
assert_eq!(ry_built.len(), 2);
|
||||
assert_eq!(abx_built.len(), 2);
|
||||
|
||||
for (actual, expected) in out.rows[0..2].iter().zip(ry_built.iter()) {
|
||||
assert_eq!(actual.listing_id, 10);
|
||||
assert_eq!(actual.report_date, expected.report_date);
|
||||
assert_eq!(actual.known_at_micros, expected.known_at_utc_micros);
|
||||
assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits());
|
||||
assert_eq!(
|
||||
actual.net_change.map(f64::to_bits),
|
||||
expected.net_change.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(
|
||||
actual.pct_float.map(f64::to_bits),
|
||||
expected.pct_float.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(actual.source.as_ref(), SHORTS_SOURCE_CEO);
|
||||
assert_eq!(actual.source.as_ref(), "ceo_shorts");
|
||||
}
|
||||
|
||||
for (actual, expected) in out.rows[2..4].iter().zip(abx_built.iter()) {
|
||||
assert_eq!(actual.listing_id, 20);
|
||||
assert_eq!(actual.report_date, expected.report_date);
|
||||
assert_eq!(actual.known_at_micros, expected.known_at_utc_micros);
|
||||
assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits());
|
||||
assert_eq!(
|
||||
actual.net_change.map(f64::to_bits),
|
||||
expected.net_change.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(
|
||||
actual.pct_float.map(f64::to_bits),
|
||||
expected.pct_float.map(f64::to_bits)
|
||||
);
|
||||
assert_eq!(actual.source.as_ref(), SHORTS_SOURCE_CEO);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_ranged_ticker_reuse_resolves_on_report_date_and_counts_unmapped_drops() {
|
||||
// Ticker "REUSE":
|
||||
// listing 100: 2020-01-01 ..= 2022-06-15
|
||||
// interior gap: 2022-06-16 ..= 2022-07-04
|
||||
// listing 200: 2022-07-05 ..= 2024-12-31
|
||||
//
|
||||
// Boundary proofs (report_date vs known_at_date):
|
||||
// - 2022-06-15 (report_date == valid_to): known_at_date is +4 TSX bdays later (2022-06-21),
|
||||
// which falls in the gap -> MUST still resolve to listing 100 on report_date.
|
||||
// - 2022-06-30 (report_date in gap): known_at_date is +4 TSX bdays later (2022-07-07, skipping
|
||||
// Canada Day Jul 1), which falls inside listing 200's range -> MUST drop as unmapped.
|
||||
let d_pre = day(2019, 12, 31);
|
||||
let d_r1_start = day(2020, 1, 15);
|
||||
let d_r1_end = day(2022, 6, 15);
|
||||
let d_gap_straddling_r2 = day(2022, 6, 30);
|
||||
let d_r2_start = day(2022, 7, 15);
|
||||
let d_r2_end = day(2024, 12, 31);
|
||||
let d_post = day(2025, 1, 15);
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "REUSE", day(2020, 1, 1), Some(d_r1_end), 100),
|
||||
map_row("ceo", "REUSE", day(2022, 7, 5), Some(d_r2_end), 200),
|
||||
// Different mapping_source must not match "ceo"
|
||||
map_row("eod", "WRONGSRC", day(2015, 1, 1), None, 300),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let input = vec![
|
||||
report("REUSE", d_pre, 1_000.0, None, None), // unmapped (before first range)
|
||||
report("REUSE", d_r1_start, 2_000.0, Some(100.0), None), // -> 100
|
||||
report("REUSE", d_r1_end, 3_000.0, Some(1_000.0), None), // -> 100 (report_date == valid_to)
|
||||
report("REUSE", d_gap_straddling_r2, 4_000.0, None, None), // unmapped (report_date in gap)
|
||||
report("REUSE", d_r2_start, 5_000.0, Some(-200.0), None), // -> 200
|
||||
report("REUSE", d_r2_end, 6_000.0, Some(1_000.0), None), // -> 200 (report_date == valid_to)
|
||||
report("REUSE", d_post, 7_000.0, None, None), // unmapped (after last range)
|
||||
report("UNKNOWN", d_r2_start, 8_000.0, None, None), // unmapped (unknown key)
|
||||
report("WRONGSRC", d_r2_start, 9_000.0, None, None), // unmapped (wrong mapping_source)
|
||||
];
|
||||
|
||||
let out = curate_shorts(input, "ceo", &mapping).unwrap();
|
||||
assert_conservation_and_order(&out);
|
||||
assert_eq!(out.stats.rows_in, 9);
|
||||
assert_eq!(out.stats.rows_out, 4);
|
||||
assert_eq!(out.stats.listings_out, 2);
|
||||
assert_eq!(out.stats.dropped_unmapped, 5);
|
||||
|
||||
let keys: Vec<(i32, i32)> = out.rows.iter().map(|r| (r.listing_id, r.report_date)).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
vec![
|
||||
(100, d_r1_start),
|
||||
(100, d_r1_end),
|
||||
(200, d_r2_start),
|
||||
(200, d_r2_end),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_key_collisions_collapse_bitwise_identical_and_drop_conflicting_groups() {
|
||||
let d1 = day(2024, 3, 15);
|
||||
let d2 = day(2024, 3, 31);
|
||||
let d3 = day(2024, 4, 15);
|
||||
let d4 = day(2024, 4, 30);
|
||||
let d5 = day(2024, 5, 15);
|
||||
let d6 = day(2024, 5, 31);
|
||||
let d7 = day(2024, 6, 15);
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "A", day(2020, 1, 1), None, 10),
|
||||
map_row("ceo", "B", day(2020, 1, 1), None, 10),
|
||||
map_row("ceo", "C", day(2020, 1, 1), None, 10),
|
||||
map_row("ceo", "X", day(2020, 1, 1), None, 20),
|
||||
map_row("ceo", "Y", day(2020, 1, 1), None, 20),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let input = vec![
|
||||
// d1 on listing 10: 3-way identical (with Some optionals and -0.0 normalized to 0.0) -> collapse (+2)
|
||||
report("A", d1, 0.0, Some(-0.0), Some(1.25)),
|
||||
report("B", d1, -0.0, Some(0.0), Some(1.25)),
|
||||
report("C", d1, 0.0, Some(0.0), Some(1.25)),
|
||||
// d2 on listing 10: 2-way identical with None optionals -> collapse (+1)
|
||||
report("A", d2, 50_000.0, None, None),
|
||||
report("B", d2, 50_000.0, None, None),
|
||||
// d3 on listing 10: differing shares_short -> drop entire group of 3
|
||||
report("A", d3, 10_000.0, Some(100.0), Some(0.5)),
|
||||
report("B", d3, 10_000.0, Some(100.0), Some(0.5)),
|
||||
report("C", d3, 10_001.0, Some(100.0), Some(0.5)),
|
||||
// d4 on listing 10: differing net_change (Some vs Some) -> drop group of 2
|
||||
report("A", d4, 10_000.0, Some(100.0), Some(0.5)),
|
||||
report("B", d4, 10_000.0, Some(101.0), Some(0.5)),
|
||||
// d5 on listing 10: differing net_change (Some vs None) -> drop group of 2
|
||||
report("A", d5, 10_000.0, Some(100.0), Some(0.5)),
|
||||
report("B", d5, 10_000.0, None, Some(0.5)),
|
||||
// d6 on listing 10: differing pct_float (Some vs Some) -> drop group of 2
|
||||
report("A", d6, 10_000.0, Some(100.0), Some(0.5)),
|
||||
report("B", d6, 10_000.0, Some(100.0), Some(0.6)),
|
||||
// d7 on listing 10: differing pct_float (Some vs None) -> drop group of 2
|
||||
report("A", d7, 10_000.0, Some(100.0), Some(0.5)),
|
||||
report("B", d7, 10_000.0, Some(100.0), None),
|
||||
// d1 on listing 20: conflicting shares_short -> listing 20 loses all rows
|
||||
report("X", d1, 5_000.0, None, None),
|
||||
report("Y", d1, 5_001.0, None, None),
|
||||
];
|
||||
|
||||
let out = curate_shorts(input, "ceo", &mapping).unwrap();
|
||||
assert_conservation_and_order(&out);
|
||||
assert_eq!(out.stats.rows_in, 18);
|
||||
assert_eq!(out.stats.rows_out, 2);
|
||||
assert_eq!(out.stats.listings_out, 1); // listing 20 lost its only date
|
||||
assert_eq!(out.stats.listing_collision_collapsed, 3);
|
||||
assert_eq!(out.stats.listing_collision_dropped, 13);
|
||||
|
||||
assert_eq!(out.rows[0].listing_id, 10);
|
||||
assert_eq!(out.rows[0].report_date, d1);
|
||||
assert_eq!(out.rows[0].shares_short.to_bits(), 0.0_f64.to_bits());
|
||||
assert_eq!(out.rows[0].net_change.map(f64::to_bits), Some(0.0_f64.to_bits()));
|
||||
assert_eq!(out.rows[0].pct_float, Some(1.25));
|
||||
|
||||
assert_eq!(out.rows[1].listing_id, 10);
|
||||
assert_eq!(out.rows[1].report_date, d2);
|
||||
assert_eq!(out.rows[1].shares_short, 50_000.0);
|
||||
assert_eq!(out.rows[1].net_change, None);
|
||||
assert_eq!(out.rows[1].pct_float, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_caller_and_builder_errors_and_empty_input() {
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "RY", day(2015, 1, 1), None, 10),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
// Blank/whitespace mapping_source returns EmptyMappingSource (even when input has bad dates).
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let err = curate_shorts(
|
||||
[report("RY", day(2007, 12, 31), 100.0, None, None)],
|
||||
blank,
|
||||
&mapping,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(err, CurateShortsError::EmptyMappingSource);
|
||||
assert!(err.source().is_none());
|
||||
assert!(err.to_string().contains("mapping_source"));
|
||||
}
|
||||
|
||||
// Builder DateOutOfRange propagates for pre-2008 and post-2030 rollover dates.
|
||||
for bad_date in [day(2007, 12, 31), day(2030, 12, 30)] {
|
||||
let err = curate_shorts(
|
||||
[report("RY", bad_date, 100.0, None, None)],
|
||||
"ceo",
|
||||
&mapping,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
CurateShortsError::Shorts(ShortsError::DateOutOfRange { .. })
|
||||
));
|
||||
assert!(err.source().is_some());
|
||||
assert!(err.to_string().contains("outside supported calendar range"));
|
||||
}
|
||||
|
||||
// Empty input returns empty rows and zeroed stats.
|
||||
let empty = curate_shorts(
|
||||
std::iter::empty::<CeoShortReport<String>>(),
|
||||
"ceo",
|
||||
&mapping,
|
||||
)
|
||||
.unwrap();
|
||||
assert_conservation_and_order(&empty);
|
||||
assert_eq!(empty.stats, CurateShortsStats::default());
|
||||
assert!(empty.rows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_fixture_conservation_and_permutation_invariance() {
|
||||
let d1 = day(2024, 2, 15);
|
||||
let d2 = day(2024, 2, 29);
|
||||
let d3 = day(2024, 3, 15);
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "S1", day(2020, 1, 1), None, 5),
|
||||
map_row("ceo", "S1_ALIAS", day(2020, 1, 1), None, 5),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let reports = vec![
|
||||
// Builder identical duplicate on S1 d1 (collapses in builder) + identical cross-key alias (collapses in curate)
|
||||
report("S1", d1, 100_000.0, Some(5_000.0), Some(1.5)),
|
||||
report("S1", d1, 100_000.0, Some(5_000.0), Some(1.5)),
|
||||
report("S1_ALIAS", d1, 100_000.0, Some(5_000.0), Some(1.5)),
|
||||
// Cross-key conflicting collision on (5, d2)
|
||||
report("S1", d2, 200_000.0, Some(10_000.0), None),
|
||||
report("S1_ALIAS", d2, 200_000.0, Some(10_001.0), None),
|
||||
// Builder invalid shares_short (dropped in builder before curate)
|
||||
report("S1", d3, -10.0, None, None),
|
||||
// Builder non-finite optional fields (sanitized to None in builder)
|
||||
report("S1", d3, 50_000.0, Some(f64::NAN), Some(f64::INFINITY)),
|
||||
// Unmapped key
|
||||
report("GHOST", d3, 25_000.0, None, None),
|
||||
];
|
||||
|
||||
let raw_built = build_shorts(reports.clone()).unwrap();
|
||||
let curated = curate_shorts(reports.clone(), "ceo", &mapping).unwrap();
|
||||
|
||||
assert_conservation_and_order(&curated);
|
||||
assert_eq!(curated.stats.builder, raw_built.stats);
|
||||
assert_eq!(curated.stats.builder.dropped_invalid_shares_short, 1);
|
||||
assert_eq!(curated.stats.builder.nulled_invalid_net_change, 1);
|
||||
assert_eq!(curated.stats.builder.nulled_invalid_pct_float, 1);
|
||||
assert_eq!(curated.stats.builder.duplicate_collapsed, 1);
|
||||
assert_eq!(curated.stats.rows_in, 6);
|
||||
assert_eq!(curated.stats.dropped_unmapped, 1);
|
||||
assert_eq!(curated.stats.listing_collision_collapsed, 1);
|
||||
assert_eq!(curated.stats.listing_collision_dropped, 2);
|
||||
assert_eq!(curated.stats.rows_out, 2);
|
||||
assert_eq!(curated.stats.listings_out, 1);
|
||||
|
||||
// Reversed input yields bitwise-identical rows and stats.
|
||||
let mut reversed = reports;
|
||||
reversed.reverse();
|
||||
let curated_rev = curate_shorts(reversed, "ceo", &mapping).unwrap();
|
||||
assert_eq!(curated_rev.stats, curated.stats);
|
||||
assert_eq!(curated_rev.rows.len(), curated.rows.len());
|
||||
for (a, b) in curated_rev.rows.iter().zip(curated.rows.iter()) {
|
||||
assert_row_bitwise_eq(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_seed_randomized_fixture_satisfies_conservation_and_parquet_writer_contract() {
|
||||
struct SplitMix64(u64);
|
||||
impl SplitMix64 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
let dates: Vec<i32> = (2018..=2025)
|
||||
.flat_map(|y| {
|
||||
(1..=12).flat_map(move |m| {
|
||||
let mid = day(y, m, 15);
|
||||
let end = if m == 12 {
|
||||
day(y + 1, 1, 1) - 1
|
||||
} else {
|
||||
day(y, m + 1, 1) - 1
|
||||
};
|
||||
[mid, end]
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut mapping_rows = Vec::new();
|
||||
// 0..20: single range -> listing (i + 1)
|
||||
for i in 0..20 {
|
||||
mapping_rows.push(map_row("ceo", &format!("K{i:02}"), day(2018, 1, 1), None, i + 1));
|
||||
}
|
||||
// 20..25: ticker reuse with interior gap -> listings 101..105 / 201..205
|
||||
for i in 0..5 {
|
||||
let key = format!("K{:02}", 20 + i);
|
||||
mapping_rows.push(map_row(
|
||||
"ceo",
|
||||
&key,
|
||||
day(2018, 1, 1),
|
||||
Some(day(2021, 6, 30)),
|
||||
101 + i,
|
||||
));
|
||||
mapping_rows.push(map_row(
|
||||
"ceo",
|
||||
&key,
|
||||
day(2022, 1, 1),
|
||||
None,
|
||||
201 + i,
|
||||
));
|
||||
}
|
||||
// 25..30: aliases of listings 1..=5
|
||||
for i in 0..5 {
|
||||
mapping_rows.push(map_row(
|
||||
"ceo",
|
||||
&format!("K{:02}", 25 + i),
|
||||
day(2018, 1, 1),
|
||||
None,
|
||||
i + 1,
|
||||
));
|
||||
}
|
||||
// 30..35: unmapped keys
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap();
|
||||
|
||||
let mut rng = SplitMix64(0x570C_4B07_5407_7E57);
|
||||
let mut reports = Vec::with_capacity(2_500);
|
||||
for _ in 0..2_500 {
|
||||
let key_idx = (rng.next_u64() % 35) as usize;
|
||||
let report_date = dates[(rng.next_u64() as usize) % dates.len()];
|
||||
let roll = rng.next_u64() % 100;
|
||||
let shares_short = if roll == 0 {
|
||||
-1.0
|
||||
} else if roll == 1 {
|
||||
f64::NAN
|
||||
} else {
|
||||
// Small quantized values so collisions have both identical and conflicting cases
|
||||
((rng.next_u64() % 4) * 1_000) as f64
|
||||
};
|
||||
let net_change = match rng.next_u64() % 5 {
|
||||
0 => None,
|
||||
1 => Some(f64::NAN),
|
||||
v => Some((v as f64 - 3.0) * 500.0),
|
||||
};
|
||||
let pct_float = match rng.next_u64() % 5 {
|
||||
0 => None,
|
||||
1 => Some(f64::INFINITY),
|
||||
v => Some(v as f64 * 0.25),
|
||||
};
|
||||
reports.push(CeoShortReport {
|
||||
key: format!("K{key_idx:02}"),
|
||||
report_date,
|
||||
shares_short,
|
||||
net_change,
|
||||
pct_float,
|
||||
});
|
||||
}
|
||||
|
||||
let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap();
|
||||
assert_conservation_and_order(&out);
|
||||
assert!(out.stats.rows_out > 0);
|
||||
assert!(out.stats.dropped_unmapped > 0);
|
||||
assert!(out.stats.listing_collision_collapsed > 0);
|
||||
assert!(out.stats.listing_collision_dropped > 0);
|
||||
|
||||
// Stage output must always satisfy write_shorts_dataset's strict contract.
|
||||
let tmp = TempDirGuard::new("rand-parquet");
|
||||
let write_stats =
|
||||
write_shorts_dataset(tmp.path(), &out.rows, ShortsWriteOptions::default()).unwrap();
|
||||
assert_eq!(write_stats.rows_written, out.rows.len());
|
||||
assert_eq!(write_stats.files_written, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_and_write_shorts_round_trips_parquet_and_protects_out_dir_on_error() {
|
||||
let tmp = TempDirGuard::new("round-trip");
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
map_row("ceo", "ABX", day(2015, 1, 1), None, 20),
|
||||
map_row("ceo", "RY", day(2015, 1, 1), None, 10),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let reports = vec![
|
||||
report("ABX", day(2024, 1, 15), 12_500_000.0, Some(-250_000.0), Some(0.75)),
|
||||
report("ABX", day(2024, 7, 15), 13_100_000.0, Some(600_000.0), None),
|
||||
report("RY", day(2024, 1, 15), 8_200_000.0, None, Some(0.60)),
|
||||
report("RY", day(2024, 7, 15), 8_050_000.0, Some(-150_000.0), Some(0.58)),
|
||||
];
|
||||
|
||||
let stage = curate_shorts(reports.clone(), "ceo", &mapping).unwrap();
|
||||
let report_res = curate_and_write_shorts(
|
||||
tmp.path(),
|
||||
reports.clone(),
|
||||
"ceo",
|
||||
&mapping,
|
||||
ShortsWriteOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(report_res.curate_stats, stage.stats);
|
||||
assert_eq!(report_res.write_stats.rows_written, stage.rows.len());
|
||||
assert_eq!(report_res.write_stats.files_written, 1);
|
||||
|
||||
let shorts_dir = tmp.path().join("shorts");
|
||||
let part_path = shorts_dir.join("part.parquet");
|
||||
assert!(part_path.exists(), "expected {}", part_path.display());
|
||||
|
||||
// No transient .write.lock, .tmp, or .bak files remain.
|
||||
for entry in fs::read_dir(&shorts_dir).expect("read shorts dir") {
|
||||
let name = entry.unwrap().file_name().to_string_lossy().into_owned();
|
||||
assert_eq!(
|
||||
name, "part.parquet",
|
||||
"unexpected transient file '{name}' in {}",
|
||||
shorts_dir.display()
|
||||
);
|
||||
}
|
||||
|
||||
let (footer_rows, read_back) = read_parquet_rows(&part_path);
|
||||
assert_eq!(footer_rows, stage.stats.rows_out);
|
||||
assert_eq!(read_back.len(), stage.rows.len());
|
||||
for (actual, expected) in read_back.iter().zip(stage.rows.iter()) {
|
||||
assert_row_bitwise_eq(actual, expected);
|
||||
}
|
||||
|
||||
// Curate error with pre-existing part.parquet leaves the live file byte-for-byte intact.
|
||||
let original_bytes = fs::read(&part_path).expect("read original part.parquet");
|
||||
let curate_err = curate_and_write_shorts(
|
||||
tmp.path(),
|
||||
reports,
|
||||
" ",
|
||||
&mapping,
|
||||
ShortsWriteOptions::default(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
curate_err,
|
||||
CurateShortsWriteError::Curate(CurateShortsError::EmptyMappingSource)
|
||||
));
|
||||
assert!(curate_err.source().is_some());
|
||||
assert!(curate_err.to_string().contains("curation failed"));
|
||||
assert_eq!(fs::read(&part_path).unwrap(), original_bytes);
|
||||
|
||||
// Curate error on a fresh directory creates no shorts/ directory at all.
|
||||
let fresh_tmp = TempDirGuard::new("curate-err-fresh");
|
||||
let date_err = curate_and_write_shorts(
|
||||
fresh_tmp.path(),
|
||||
[report("RY", day(2007, 12, 31), 100.0, None, None)],
|
||||
"ceo",
|
||||
&mapping,
|
||||
ShortsWriteOptions::default(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
date_err,
|
||||
CurateShortsWriteError::Curate(CurateShortsError::Shorts(ShortsError::DateOutOfRange { .. }))
|
||||
));
|
||||
assert!(!fresh_tmp.path().join("shorts").exists());
|
||||
|
||||
// ParquetShortsError propagates cleanly.
|
||||
let pq_err = curate_and_write_shorts(
|
||||
fresh_tmp.path(),
|
||||
std::iter::empty::<CeoShortReport<String>>(),
|
||||
"ceo",
|
||||
&mapping,
|
||||
ShortsWriteOptions {
|
||||
row_group_rows: 0,
|
||||
..ShortsWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
pq_err,
|
||||
CurateShortsWriteError::Parquet(ParquetShortsError::InvalidRowGroupRows)
|
||||
));
|
||||
assert!(pq_err.source().is_some());
|
||||
assert!(pq_err.to_string().contains("Parquet write failed"));
|
||||
|
||||
// Empty input is a clean no-op without creating shorts/.
|
||||
let empty_report = curate_and_write_shorts(
|
||||
fresh_tmp.path(),
|
||||
std::iter::empty::<CeoShortReport<String>>(),
|
||||
"ceo",
|
||||
&mapping,
|
||||
ShortsWriteOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(empty_report.curate_stats, CurateShortsStats::default());
|
||||
assert_eq!(empty_report.write_stats, ShortsWriteStats::default());
|
||||
assert!(!fresh_tmp.path().join("shorts").exists());
|
||||
}
|
||||
|
|
@ -97,3 +97,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,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use curate_etl::bench::{
|
|||
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, run_curate_bars_benchmark,
|
||||
run_curate_shorts_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -546,6 +547,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));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue