T-110: merge dev

This commit is contained in:
Studio 2026-11-29 01:02:58 -05:00
commit 18cc2bc553
8 changed files with 2982 additions and 7 deletions

View file

@ -967,6 +967,51 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a
- Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s`
- Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s`
## `corporate_actions` Curation Stage (`M1.2u`)
`curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`.
1. **Field & timestamp rules:**
- Calls `build_corporate_actions` unchanged (`1:1` split no-ops, `0.0` cash dividends, and delistings without an outcome drop inside the builder; same-key multi-dividends stay separate; late declarations clamp to `ex_date` with `KnownAtSource::ExDateFallback`; local `currency` is preserved).
- Resolves `(mapping_source, key, ex_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) for `split`, `dividend`, and terminal `delisting` rows.
- For `otc_delist_transfer` rows, Pass 6 anchors `ex_date` (and `known_at`) to `effectiveDate` (the successor's first OTC trading date), which normally falls after the outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` starts `2023-03-28`) and may coincide with ticker reuse. `otc_delist_transfer` therefore requires Pass 6's outgoing listing identity via `CurateDelistingInput::from_listing_id` (`Some(id)`): curation selects only a `provider_mapping` range for `(mapping_source, key)` with `valid_from <= ex_date` and `listing_id == id` (never attaching to an unrelated ticker occupant), and any identity-less `otc_delist_transfer` (`from_listing_id = None`) drops into `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to `successor_listing_id`. Never emits an `otc_delist_transfer` with `successor_listing_id = None` or `successor_listing_id == listing_id`.
- Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source corporate-action records carry no intraday announcement time) and carries `known_at_source` through unchanged.
- Carries `ex_date`, `declared_date`, `kind`, `ratio`, `cash_amount`, `currency`, and `terminal_return` through bit-exactly (`"USD"`/`"CAD"` interned as `Cow::Borrowed`).
2. **Drop & collision policy (never panics or aborts on bad rows):**
- Strict drop priority per built row:
1. `dropped_unmapped`: no covering `provider_mapping` range for `(mapping_source, key, ex_date)` (or, for `otc_delist_transfer`, missing `from_listing_id = None` or no range with `valid_from <= ex_date` matching `from_listing_id = Some(id)`; or, for terminal `delisting` with `from_listing_id = Some(id)`, active occupant does not match `id`).
2. `dropped_unmapped_successor`: `otc_delist_transfer` whose `successor_key` has no covering range on `ex_date`.
3. `dropped_self_successor`: `otc_delist_transfer` whose `successor_key` resolves to the row's own `listing_id`.
4. `dropped_known_at_out_of_range`: `known_at_date` falls outside `et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window.
- After re-sorting deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`):
- Cross-key conflicting `split` ratios on the same `(listing_id, ex_date)` (`> 1` source key and `> 1` distinct `ratio` bit pattern) drop the entire group (`listing_collision_dropped`).
- Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount same-day regular + special dividends) while collapsing cross-key aliases.
- Exact conservation invariant in `CurateCorporateActionsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`.
- Typed caller errors: `CurateCorporateActionsError` (`CorporateAction(CorporateActionError)`, `EmptyMappingSource`) and `CurateCorporateActionsWriteError` (`Curate(CurateCorporateActionsError)`, `Parquet(ParquetCorporateActionsError)`). A curate error in `curate_and_write_corporate_actions` returns before invoking `write_corporate_actions_dataset`, leaving `out_dir` untouched.
### `bench-curate-corporate-actions`
Fixed-seed (`std`-only SplitMix64) benchmark over `520,000` source-keyed corporate-action events (~3.6% splits ≈20.3k incl. `1:1` no-ops and alias collisions, ~95.4% USD/CAD dividends ≈494.6k incl. `0.0` drops and same-day multi-dividends, ~1.0% delisting outcomes ≈5.1k incl. OTC transfers and `-0.3`/`-1.0`/no-outcome) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps, aliases, unmapped/self successors, and pre-1976 dates, separately timing in-memory `curate_corporate_actions` and Zstd Parquet `write_corporate_actions_dataset` into a temp directory with footer row-count verification and cleanup:
```bash
cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions [events]
```
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1ab7caad4`): `cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions`
- Input: `events=520000`, `splits=20262`, `dividends=494624`, `delistings=5114`, `keys=20000`
- Builder: `rows_out=514224`, `splits_out=19938`, `split_noops=324`, `divs_out=489671`, `zero_div=4953`, `otc_out=2856`, `delist_out=1759`, `delist_no_outcome=499`
- Output: `rows_out=494518` (`95.10%` retained), `listings_out=19996`, `files=1`, `row_groups=1`, `bytes=3802001`, `read_back_rows=494518`
- Curation stats: `unmapped=12886`, `unmapped_succ=511`, `self_succ=531`, `known_at_oor=2526`, `coll_collapsed=1398`, `coll_dropped=1854`
- Run 1:
- Stage (in-memory): `elapsed=278.66 ms`, `throughput=1866040 events/s`, `latency=535.89 ns/event`, `checksum=0x0c22a1a1ab7caad4`
- Parquet write: `elapsed=84.14 ms`, `throughput=5877527 rows/s`
- Combined (stage → Parquet): `elapsed=362.80 ms`, `throughput=1433288 events/s`
- Run 2:
- Stage (in-memory): `elapsed=284.33 ms`, `throughput=1828877 events/s`, `latency=546.78 ns/event`, `checksum=0x0c22a1a1ab7caad4`
- Parquet write: `elapsed=87.57 ms`, `throughput=5647404 rows/s`
- Combined (stage → Parquet): `elapsed=371.89 ms`, `throughput=1398252 events/s`
## `curate-bars-1d` Command (`M1.2z`)
End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` into `<out>/bars_1d/year=YYYY/part.parquet` with zero extra crates and no database connections.

View file

@ -6801,6 +6801,475 @@ pub fn run_curate_adj_benchmark(
Ok(report)
}
pub const DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 520_000;
const CURATE_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C04A_AC72;
const CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT: usize = 20_000;
/// Summary metrics produced by [`run_curate_corporate_actions_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CurateCorporateActionsBenchReport {
pub events: usize,
pub splits_in: usize,
pub dividends_in: usize,
pub delistings_in: usize,
pub key_count: usize,
pub rows_out: usize,
pub listings_out: usize,
pub stage_elapsed_ms: f64,
pub stage_events_per_sec: f64,
pub stage_ns_per_event: f64,
pub parquet_elapsed_ms: f64,
pub parquet_rows_per_sec: f64,
pub total_elapsed_ms: f64,
pub total_events_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_corporate_actions::CurateCorporateActionsStats,
}
struct CurateCorporateActionsBenchFixture {
splits: Vec<(String, SplitActionEvent)>,
dividends: Vec<(String, DividendActionEvent)>,
delistings: Vec<crate::curate_corporate_actions::CurateDelistingInput<String>>,
provider_mapping: ProviderMappingTable,
key_count: usize,
}
fn build_curate_corporate_actions_bench_fixture(
events: usize,
) -> CurateCorporateActionsBenchFixture {
const KEY_COUNT: usize = CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT;
const SINGLE_RANGE_END: usize = 18_000;
const REUSE_END: usize = 19_000;
const ALIAS_END: usize = 19_500;
const ALIAS_COUNT: usize = ALIAS_END - REUSE_END;
const OTC_SUCC_COUNT: usize = 500;
let valid_from_start = ymd_to_epoch_days(1970, 1, 1).expect("valid start");
let reuse_end = ymd_to_epoch_days(2015, 6, 30).expect("valid reuse end");
let reuse_resume = ymd_to_epoch_days(2016, 1, 1).expect("valid reuse resume");
let in_range_start = ymd_to_epoch_days(1977, 1, 3).expect("valid in-range start");
let in_range_end = ymd_to_epoch_days(2025, 12, 31).expect("valid in-range end");
let in_range_span = (in_range_end - in_range_start + 1) as u64;
let pre_1976_day = ymd_to_epoch_days(1975, 6, 15).expect("valid pre-1976 day");
let keys: Vec<String> = (0..KEY_COUNT).map(|i| format!("CA{i:05}")).collect();
let otc_keys: Vec<String> = (0..OTC_SUCC_COUNT).map(|i| format!("OTC{i:05}")).collect();
let mut mapping_rows: Vec<ProviderMappingRow> =
Vec::with_capacity(KEY_COUNT + (REUSE_END - SINGLE_RANGE_END) + OTC_SUCC_COUNT);
for (i, key) in keys.iter().enumerate() {
if i < SINGLE_RANGE_END {
mapping_rows.push(ProviderMappingRow {
source: "qm".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 {
mapping_rows.push(ProviderMappingRow {
source: "qm".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: "qm".to_string(),
source_id: key.clone(),
valid_from: reuse_resume,
valid_to: None,
listing_id: (i + 100_001) as i32,
});
} else if i < ALIAS_END {
let alias_lid = (i - REUSE_END + 1) as i32;
mapping_rows.push(ProviderMappingRow {
source: "qm".to_string(),
source_id: key.clone(),
valid_from: valid_from_start,
valid_to: None,
listing_id: alias_lid,
});
}
}
for (i, otc_key) in otc_keys.iter().enumerate() {
mapping_rows.push(ProviderMappingRow {
source: "qm".to_string(),
source_id: otc_key.clone(),
valid_from: valid_from_start,
valid_to: None,
listing_id: (500_001 + i) as i32,
});
}
let provider_mapping =
ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping");
let mut rng = SplitMix64::new(CURATE_CORPORATE_ACTIONS_BENCH_SEED);
let mut splits: Vec<(String, SplitActionEvent)> = Vec::with_capacity(events / 25 + 64);
let mut dividends: Vec<(String, DividendActionEvent)> = Vec::with_capacity(events);
let mut delistings: Vec<crate::curate_corporate_actions::CurateDelistingInput<String>> =
Vec::with_capacity(events / 90 + 32);
let mut generated = 0usize;
while generated < events {
let r1 = rng.next_u64();
let r2 = rng.next_u64();
let kind_roll = r1 % 1_000;
let is_pre_1976 = ((r1 >> 10) % 200) == 0;
let ex_date = if is_pre_1976 {
pre_1976_day
} else {
in_range_start + ((r2 % in_range_span) as i32)
};
if kind_roll < 36 {
// ~3.6% splits (~18.7k at 520k), including 1:1 no-ops and alias collisions.
let is_alias_target = !is_pre_1976 && ((r1 >> 18) % 10) == 0;
let key_idx = if is_alias_target {
((r2 >> 24) as usize) % ALIAS_COUNT
} else {
((r2 >> 24) as usize) % KEY_COUNT
};
let is_noop = ((r1 >> 22) % 50) == 0;
let ratio = if is_noop {
1.0
} else {
SAMPLE_RATIOS[((r1 >> 28) as usize) % SAMPLE_RATIOS.len()]
};
let decl_roll = (r1 >> 36) % 100;
let declared_date = if decl_roll < 80 {
Some(ex_date - 21)
} else if decl_roll < 98 {
None
} else {
Some(ex_date + 3)
};
let ev = SplitActionEvent {
ex_date,
ratio,
declared_date,
};
splits.push((keys[key_idx].clone(), ev));
generated += 1;
if is_alias_target && !is_noop && generated < events {
let alias_key = keys[REUSE_END + key_idx].clone();
let alias_ratio = if ((r1 >> 44) & 1) == 0 {
ratio
} else {
ratio * 1.5
};
splits.push((
alias_key,
SplitActionEvent {
ex_date,
ratio: alias_ratio,
declared_date,
},
));
generated += 1;
}
} else if kind_roll < 990 {
// ~95.4% dividends (~496k at 520k), USD/CAD, 0.0 drops, multi-dividends, alias dups.
let key_idx = ((r2 >> 24) as usize) % KEY_COUNT;
let is_zero = ((r1 >> 18) % 100) == 0;
let cash = if is_zero {
0.0
} else {
(((r1 >> 26) % 250) + 1) as f64 * 0.01
};
let currency = if ((r1 >> 34) & 3) == 0 { "CAD" } else { "USD" };
let decl_roll = (r1 >> 38) % 100;
let declared_date = if decl_roll < 80 {
Some(ex_date - 21)
} else if decl_roll < 98 {
None
} else {
Some(ex_date + 3)
};
dividends.push((
keys[key_idx].clone(),
DividendActionEvent {
ex_date,
cash,
currency: currency.to_string(),
declared_date,
},
));
generated += 1;
if !is_zero && !is_pre_1976 && generated < events {
if ((r1 >> 46) % 100) == 0 {
// Same-key same-day special dividend.
dividends.push((
keys[key_idx].clone(),
DividendActionEvent {
ex_date,
cash: cash * 2.0,
currency: currency.to_string(),
declared_date,
},
));
generated += 1;
} else if key_idx < ALIAS_COUNT && ((r1 >> 52) % 25) == 0 {
// Identical cross-key alias dividend.
dividends.push((
keys[REUSE_END + key_idx].clone(),
DividendActionEvent {
ex_date,
cash,
currency: currency.to_string(),
declared_date,
},
));
generated += 1;
}
}
} else {
// ~1.0% delistings (~5.2k at 520k): OTC transfers (valid/unmapped/self), -0.3, -1.0, none.
let key_idx = ((r2 >> 24) as usize) % KEY_COUNT;
let outcome_roll = (r1 >> 18) % 100;
let ev = if outcome_roll < 35 {
let succ_idx = ((r2 >> 40) as usize) % OTC_SUCC_COUNT;
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key: Some(otc_keys[succ_idx].clone()),
terminal_return: None,
}
} else if outcome_roll < 45 {
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key: Some("OTC_UNMAPPED".to_string()),
terminal_return: None,
}
} else if outcome_roll < 55 {
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key: Some(keys[key_idx].clone()),
terminal_return: None,
}
} else if outcome_roll < 75 {
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key: None,
terminal_return: Some(-0.3),
}
} else if outcome_roll < 90 {
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key: None,
terminal_return: Some(-1.0),
}
} else {
DelistingOutcomeEvent {
delist_date: ex_date,
successor_key: None,
terminal_return: None,
}
};
let from_listing_id = if outcome_roll < 55 {
if key_idx < SINGLE_RANGE_END {
Some((key_idx + 1) as i32)
} else if key_idx < REUSE_END {
if ex_date >= reuse_resume {
Some((key_idx + 100_001) as i32)
} else {
Some((key_idx + 1) as i32)
}
} else if key_idx < ALIAS_END {
Some((key_idx - REUSE_END + 1) as i32)
} else {
None
}
} else {
None
};
delistings.push(crate::curate_corporate_actions::CurateDelistingInput {
key: keys[key_idx].clone(),
event: ev,
from_listing_id,
});
generated += 1;
}
}
CurateCorporateActionsBenchFixture {
splits,
dividends,
delistings,
provider_mapping,
key_count: KEY_COUNT,
}
}
fn run_curate_corporate_actions_benchmark_tracked(
events: usize,
) -> Result<
(CurateCorporateActionsBenchReport, PathBuf),
crate::curate_corporate_actions::CurateCorporateActionsWriteError,
> {
use crate::curate_corporate_actions::{
curate_corporate_actions, CurateCorporateActionsStats, CurateCorporateActionsWriteError,
};
let temp = BenchTempDir::new_in_with_prefix(
&std::env::temp_dir(),
"curate-etl-bench-curate-corp-actions",
)
.map_err(|(path, source)| {
CurateCorporateActionsWriteError::Parquet(ParquetCorporateActionsError::Io { path, source })
})?;
let temp_path = temp.path.clone();
if events == 0 {
let mapping = ProviderMappingTable::default();
let curated = curate_corporate_actions(
std::iter::empty::<(String, SplitActionEvent)>(),
std::iter::empty::<(String, DividendActionEvent)>(),
std::iter::empty::<(String, DelistingOutcomeEvent<String>)>(),
"qm",
&mapping,
)?;
let write_stats = write_corporate_actions_dataset(
&temp.path,
&curated.rows,
CorporateActionsWriteOptions::default(),
)?;
let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, 0)?;
drop(temp);
return Ok((
CurateCorporateActionsBenchReport {
events: 0,
splits_in: 0,
dividends_in: 0,
delistings_in: 0,
key_count: CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT,
rows_out: 0,
listings_out: 0,
stage_elapsed_ms: 0.0,
stage_events_per_sec: 0.0,
stage_ns_per_event: 0.0,
parquet_elapsed_ms: 0.0,
parquet_rows_per_sec: 0.0,
total_elapsed_ms: 0.0,
total_events_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: CurateCorporateActionsStats::default(),
},
temp_path,
));
}
let fixture = build_curate_corporate_actions_bench_fixture(events);
let splits_in = fixture.splits.len();
let dividends_in = fixture.dividends.len();
let delistings_in = fixture.delistings.len();
let key_count = fixture.key_count;
// 1. Time pure in-memory curation stage.
let stage_start = Instant::now();
let curated = curate_corporate_actions(
fixture.splits,
fixture.dividends,
fixture.delistings,
"qm",
&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.ex_date as u64);
hash = mix_u64(hash, row.declared_date.map_or(u64::MAX, |d| d as u64));
hash = mix_u64(hash, row.kind as u64);
hash = mix_u64(hash, row.ratio.map_or(0, f64::to_bits));
hash = mix_u64(hash, row.cash_amount.map_or(0, f64::to_bits));
if let Some(curr) = row.currency.as_deref() {
hash = mix_str_u64(hash, curr);
}
hash = mix_u64(
hash,
row.successor_listing_id.map_or(u64::MAX, |id| id as u64),
);
hash = mix_u64(hash, row.terminal_return.map_or(0, f64::to_bits));
hash = mix_u64(hash, row.known_at_micros as u64);
hash = mix_u64(hash, row.known_at_source as u64);
}
let checksum = black_box(hash);
// 2. Separately time Parquet write to temp dir.
let parquet_start = Instant::now();
let write_stats = write_corporate_actions_dataset(
&temp.path,
&curated.rows,
CorporateActionsWriteOptions::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_corporate_actions_row_count(&temp.path, curated.rows.len())?;
let (stage_events_per_sec, stage_ns_per_event) = compute_rates(events, 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_events_per_sec, _) = compute_rates(events, total_elapsed_secs);
let report = CurateCorporateActionsBenchReport {
events,
splits_in,
dividends_in,
delistings_in,
key_count,
rows_out: curated.stats.rows_out,
listings_out: curated.stats.listings_out,
stage_elapsed_ms,
stage_events_per_sec,
stage_ns_per_event,
parquet_elapsed_ms,
parquet_rows_per_sec,
total_elapsed_ms,
total_events_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 `corporate_actions` curation stage + Zstd Parquet write benchmark for
/// `events` source-keyed splits (~3.6%), USD/CAD dividends (~95.4%), and delisting outcomes
/// (~1.0%) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps,
/// aliases, unmapped/self successors, and pre-1976 dates.
pub fn run_curate_corporate_actions_benchmark(
events: usize,
) -> Result<
CurateCorporateActionsBenchReport,
crate::curate_corporate_actions::CurateCorporateActionsWriteError,
> {
let (report, _) = run_curate_corporate_actions_benchmark_tracked(events)?;
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
@ -8326,6 +8795,98 @@ mod tests {
);
}
#[test]
fn curate_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() {
let (a, dir_a) = run_curate_corporate_actions_benchmark_tracked(20_000).unwrap();
let (b, dir_b) = run_curate_corporate_actions_benchmark_tracked(20_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.events, 20_000);
assert_eq!(a.splits_in + a.dividends_in + a.delistings_in, 20_000);
assert_eq!(a.stats.builder.splits_in, a.splits_in);
assert_eq!(a.stats.builder.dividends_in, a.dividends_in);
assert_eq!(a.stats.builder.delistings_in, a.delistings_in);
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.row_groups_written, b.row_groups_written);
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_events_per_sec.is_finite() && a.stage_events_per_sec >= 0.0);
assert!(a.stage_ns_per_event.is_finite() && a.stage_ns_per_event >= 0.0);
assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0);
assert!(a.total_events_per_sec.is_finite() && a.total_events_per_sec >= 0.0);
// Conservation invariants
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.dropped_unmapped_successor
+ a.stats.dropped_self_successor
+ a.stats.dropped_known_at_out_of_range
+ a.stats.listing_collision_collapsed
+ a.stats.listing_collision_dropped
);
// All major builder and curation counters exercised
assert!(a.stats.builder.splits_out > 0);
assert!(a.stats.builder.split_noops_dropped > 0);
assert!(a.stats.builder.dividends_out > 0);
assert!(a.stats.builder.dividend_zero_cash_dropped > 0);
assert!(a.stats.builder.otc_delist_transfers_out > 0);
assert!(a.stats.builder.delistings_out > 0);
assert!(a.stats.builder.delist_without_outcome > 0);
assert!(a.stats.dropped_unmapped > 0);
assert!(a.stats.dropped_unmapped_successor > 0);
assert!(a.stats.dropped_self_successor > 0);
assert!(a.stats.dropped_known_at_out_of_range > 0);
assert!(a.stats.listing_collision_collapsed > 0);
assert!(a.stats.listing_collision_dropped > 0);
}
#[test]
fn curate_corporate_actions_benchmark_zero_events_handles_cleanly() {
let (report, dir) = run_curate_corporate_actions_benchmark_tracked(0).unwrap();
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
assert_eq!(report.events, 0);
assert_eq!(report.splits_in, 0);
assert_eq!(report.dividends_in, 0);
assert_eq!(report.delistings_in, 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.row_groups_written, 0);
assert_eq!(report.bytes_written, 0);
assert_eq!(report.checksum, 0);
assert_eq!(report.stage_elapsed_ms, 0.0);
assert_eq!(report.stage_events_per_sec, 0.0);
assert_eq!(report.stage_ns_per_event, 0.0);
assert_eq!(report.parquet_elapsed_ms, 0.0);
assert_eq!(report.parquet_rows_per_sec, 0.0);
assert_eq!(report.total_elapsed_ms, 0.0);
assert_eq!(report.total_events_per_sec, 0.0);
assert_eq!(
report.stats,
crate::curate_corporate_actions::CurateCorporateActionsStats::default()
);
}
#[test]
fn curate_bars_cmd_benchmark_small_run_cleans_up_and_conserves_counts() {
let (report, dir) = run_curate_bars_cmd_benchmark_tracked(4_000).unwrap();

View file

@ -10,7 +10,8 @@ use crate::bench::{
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS,
DEFAULT_CURATE_BARS_CMD_BENCH_ROWS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
DEFAULT_CURATE_BARS_CMD_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
DEFAULT_CURATE_EVENTS_BENCH_ROWS,
DEFAULT_CURATE_FX_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,
@ -48,6 +49,7 @@ pub enum CliAction {
BenchCurateEvents(usize),
BenchCurateFx(usize),
BenchCurateAdj(usize),
BenchCurateCorporateActions(usize),
}
/// Formats full help text including binary name and version.
@ -82,7 +84,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
{name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
{name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})"
{name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\
{name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})"
)
}
@ -115,7 +118,8 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-curate-shorts [rows]\n\
{name} bench-curate-events [rows]\n\
{name} bench-curate-fx [rows]\n\
{name} bench-curate-adj [events]"
{name} bench-curate-adj [events]\n\
{name} bench-curate-corporate-actions [events]"
)
}
@ -457,6 +461,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
)),
},
["bench-curate-adj", _, ..] => Err("too many arguments for bench-curate-adj".to_string()),
["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions(
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
)),
["bench-curate-corporate-actions", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchCurateCorporateActions(n)),
_ => Err(format!(
"invalid event count '{raw}' (expected a positive integer)"
)),
},
["bench-curate-corporate-actions", _, ..] => {
Err("too many arguments for bench-curate-corporate-actions".to_string())
}
[other, ..] => Err(format!("unknown argument '{other}'")),
}
}
@ -805,6 +821,7 @@ mod tests {
assert!(full.contains("bench-curate-events"));
assert!(full.contains("bench-curate-fx"));
assert!(full.contains("bench-curate-adj"));
assert!(full.contains("bench-curate-corporate-actions"));
let short = format_usage_stderr("curate-etl");
assert!(short.contains("bench-split"));
@ -831,6 +848,7 @@ mod tests {
assert!(short.contains("bench-curate-events"));
assert!(short.contains("bench-curate-fx"));
assert!(short.contains("bench-curate-adj"));
assert!(short.contains("bench-curate-corporate-actions"));
}
#[test]
@ -917,6 +935,24 @@ mod tests {
assert!(parse_args(&to_args(&["bench-curate-adj", "10", "20"])).is_err());
}
#[test]
fn parses_and_validates_bench_curate_corporate_actions_args() {
assert_eq!(
parse_args(&to_args(&["bench-curate-corporate-actions"])),
Ok(CliAction::BenchCurateCorporateActions(
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS
))
);
assert_eq!(
parse_args(&to_args(&["bench-curate-corporate-actions", "20000"])),
Ok(CliAction::BenchCurateCorporateActions(20_000))
);
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "-5"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-corporate-actions", "10", "20"])).is_err());
}
#[test]
fn parses_and_validates_bench_curate_bars_cmd_args() {
assert_eq!(

View file

@ -0,0 +1,600 @@
//! Pure, in-memory `corporate_actions` curation stage joining
//! [`crate::corporate_actions::build_corporate_actions`],
//! [`crate::provider_mapping::ProviderMappingTable`],
//! [`crate::session_close::et_session_close_utc_micros`], and
//! [`crate::parquet_corporate_actions::write_corporate_actions_dataset`] into contract
//! [`CorporateActionsParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - Calls [`build_corporate_actions`] unchanged (drops `ratio == 1.0` split no-ops, `cash == 0.0`
//! dividends, and delistings without an outcome; keeps same-key multi-dividends separate; clamps
//! late declarations to `ex_date` with `KnownAtSource::ExDateFallback`).
//! - Resolves each built row's `(mapping_source, key, ex_date) -> listing_id` via
//! [`ProviderMappingTable::cursor_for`] / [`crate::provider_mapping::ProviderMappingCursor::resolve`]
//! (one cursor per contiguous `key` run, since `build_corporate_actions` emits rows sorted by
//! `key` then `ex_date`).
//! - For [`CorporateActionKind::OtcDelistTransfer`] rows, Pass 6 anchors `ex_date` (and `known_at`)
//! to `effectiveDate` (the successor's first OTC trading date), which normally falls after the
//! outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US`
//! starts `2023-03-28`) and may coincide with ticker reuse. `OtcDelistTransfer` therefore requires
//! Pass 6's outgoing listing identity via [`CurateDelistingInput::from_listing_id`] (`Some(id)`):
//! curation selects the `(mapping_source, key)` range with `valid_from <= ex_date` whose
//! `listing_id == id` (so an unrelated occupant of `key` is never linked to the OTC successor),
//! and any identity-less `OtcDelistTransfer` (`from_listing_id = None`) drops into
//! `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to
//! `successor_listing_id`. Unmapped outgoing keys (`dropped_unmapped`), unmapped successors
//! (`dropped_unmapped_successor`), and successors that alias to the row's own `listing_id`
//! (`dropped_self_successor`) are dropped—never emitted with `successor_listing_id = None` or a
//! self-link.
//! - Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of
//! `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source
//! corporate-action records carry no intraday announcement time). Dates outside
//! `1976-01-01..=2030-12-31` drop into `dropped_known_at_out_of_range` without panicking.
//! - Re-sorts mapped rows deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`)
//! and resolves cross-`key` collisions:
//! - `Split` groups on the same `(listing_id, ex_date)` with `> 1` distinct source key and `> 1`
//! distinct `ratio` bit pattern drop the entire group (`listing_collision_dropped`).
//! - Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies
//! (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount
//! same-day regular + special dividends) while deduplicating cross-key aliases.
use std::borrow::Cow;
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::corporate_actions::{
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent,
};
use crate::parquet_corporate_actions::{
write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions,
CorporateActionsWriteStats, ParquetCorporateActionsError,
};
use crate::provider_mapping::{MappingRange, ProviderMappingTable};
use crate::session_close::et_session_close_utc_micros;
/// Accounting summary produced alongside [`CurateCorporateActionsOutput::rows`].
///
/// Conservation invariants:
/// - `rows_in == builder.rows_out`
/// - `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor
/// + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`
/// - `builder` independently satisfies all [`CorporateActionsStats`] conservation invariants.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CurateCorporateActionsStats {
pub builder: CorporateActionsStats,
pub rows_in: usize,
pub rows_out: usize,
pub listings_out: usize,
pub dropped_unmapped: usize,
pub dropped_unmapped_successor: usize,
pub dropped_self_successor: usize,
pub dropped_known_at_out_of_range: usize,
pub listing_collision_collapsed: usize,
pub listing_collision_dropped: usize,
}
/// Output of [`curate_corporate_actions`]: contract Parquet rows sorted deterministically with
/// non-decreasing `(listing_id, ex_date, kind)` plus full stage and builder stats.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateCorporateActionsOutput {
pub rows: Vec<CorporateActionsParquetRow>,
pub stats: CurateCorporateActionsStats,
}
/// Typed caller errors returned by [`curate_corporate_actions`].
///
/// Bad single rows (unmapped keys/successors, self-successors, out-of-range `known_at_date`, and
/// cross-key collisions) are dropped and counted in [`CurateCorporateActionsStats`] rather than
/// aborting the stage.
#[derive(Debug, Clone, PartialEq)]
pub enum CurateCorporateActionsError {
/// Error propagated from [`build_corporate_actions`] (e.g. non-positive split ratio).
CorporateAction(CorporateActionError),
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
EmptyMappingSource,
}
impl fmt::Display for CurateCorporateActionsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CorporateAction(err) => write!(f, "{err}"),
Self::EmptyMappingSource => {
write!(f, "mapping_source must not be empty or blank")
}
}
}
}
impl Error for CurateCorporateActionsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::CorporateAction(err) => Some(err),
Self::EmptyMappingSource => None,
}
}
}
impl From<CorporateActionError> for CurateCorporateActionsError {
fn from(err: CorporateActionError) -> Self {
Self::CorporateAction(err)
}
}
/// Combined stats returned by [`curate_and_write_corporate_actions`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurateCorporateActionsWriteReport {
pub curate_stats: CurateCorporateActionsStats,
pub write_stats: CorporateActionsWriteStats,
}
/// Typed error returned by [`curate_and_write_corporate_actions`].
#[derive(Debug)]
pub enum CurateCorporateActionsWriteError {
Curate(CurateCorporateActionsError),
Parquet(ParquetCorporateActionsError),
}
impl fmt::Display for CurateCorporateActionsWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "corporate_actions curation failed: {err}"),
Self::Parquet(err) => write!(f, "corporate_actions Parquet write failed: {err}"),
}
}
}
impl Error for CurateCorporateActionsWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateCorporateActionsError> for CurateCorporateActionsWriteError {
fn from(err: CurateCorporateActionsError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetCorporateActionsError> for CurateCorporateActionsWriteError {
fn from(err: ParquetCorporateActionsError) -> Self {
Self::Parquet(err)
}
}
/// Input delisting item for [`curate_corporate_actions`], pairing a source key and
/// [`DelistingOutcomeEvent`] with Pass 6's optional outgoing `listing_id` (`from_listing_id` in
/// `corporate_action_continuity`).
///
/// Implements `From<(K, DelistingOutcomeEvent<K>)>` (with `from_listing_id = None`) for terminal
/// delisting callers; `OtcDelistTransfer` rows require `from_listing_id = Some(id)` (via
/// [`CurateDelistingInput::with_from_listing_id`]) so ended or reused outgoing tickers are never
/// attached to an unrelated occupant—identity-less OTC transfers drop into `dropped_unmapped`.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateDelistingInput<K = String> {
pub key: K,
pub event: DelistingOutcomeEvent<K>,
pub from_listing_id: Option<i32>,
}
impl<K> CurateDelistingInput<K> {
/// Creates a delisting input without an explicit Pass 6 outgoing `listing_id`.
#[inline]
pub fn new(key: K, event: DelistingOutcomeEvent<K>) -> Self {
Self {
key,
event,
from_listing_id: None,
}
}
/// Creates a delisting input carrying Pass 6's outgoing `from_listing_id`.
#[inline]
pub fn with_from_listing_id(
key: K,
from_listing_id: i32,
event: DelistingOutcomeEvent<K>,
) -> Self {
Self {
key,
event,
from_listing_id: Some(from_listing_id),
}
}
}
impl<K> From<(K, DelistingOutcomeEvent<K>)> for CurateDelistingInput<K> {
#[inline]
fn from((key, event): (K, DelistingOutcomeEvent<K>)) -> Self {
Self::new(key, event)
}
}
#[derive(Debug, Clone)]
struct DelistingIdentity<K> {
key: K,
ex_date: i32,
kind: CorporateActionKind,
successor_key: Option<K>,
terminal_return_bits: Option<u64>,
from_listing_id: Option<i32>,
}
#[inline]
fn cmp_delisting_identity<K: Ord>(a: &DelistingIdentity<K>, b: &DelistingIdentity<K>) -> Ordering {
a.key
.cmp(&b.key)
.then_with(|| a.ex_date.cmp(&b.ex_date))
.then_with(|| a.kind.cmp(&b.kind))
.then_with(|| a.successor_key.cmp(&b.successor_key))
.then_with(|| a.terminal_return_bits.cmp(&b.terminal_return_bits))
.then_with(|| a.from_listing_id.cmp(&b.from_listing_id))
}
#[inline]
fn resolve_for_listing_on_or_before(
ranges: &[MappingRange],
date: i32,
expected_listing_id: i32,
) -> Option<i32> {
let end = ranges.partition_point(|r| r.valid_from <= date);
ranges[..end]
.iter()
.rev()
.find(|r| r.listing_id == expected_listing_id)
.map(|r| r.listing_id)
}
#[inline]
fn opt_f64_bits(value: Option<f64>) -> Option<u64> {
value.map(f64::to_bits)
}
#[inline]
fn intern_currency(currency: Option<String>) -> Option<Cow<'static, str>> {
currency.map(|c| match c.as_str() {
"USD" => Cow::Borrowed("USD"),
"CAD" => Cow::Borrowed("CAD"),
_ => Cow::Owned(c),
})
}
#[inline]
fn cmp_parquet_row(a: &CorporateActionsParquetRow, b: &CorporateActionsParquetRow) -> Ordering {
a.listing_id
.cmp(&b.listing_id)
.then_with(|| a.ex_date.cmp(&b.ex_date))
.then_with(|| a.kind.cmp(&b.kind))
.then_with(|| a.declared_date.cmp(&b.declared_date))
.then_with(|| opt_f64_bits(a.ratio).cmp(&opt_f64_bits(b.ratio)))
.then_with(|| opt_f64_bits(a.cash_amount).cmp(&opt_f64_bits(b.cash_amount)))
.then_with(|| a.currency.as_deref().cmp(&b.currency.as_deref()))
.then_with(|| a.successor_listing_id.cmp(&b.successor_listing_id))
.then_with(|| opt_f64_bits(a.terminal_return).cmp(&opt_f64_bits(b.terminal_return)))
.then_with(|| a.known_at_micros.cmp(&b.known_at_micros))
.then_with(|| a.known_at_source.cmp(&b.known_at_source))
}
/// Pure `corporate_actions` curation stage: validates and builds source-keyed splits, dividends,
/// and delisting outcomes via [`build_corporate_actions`], resolves `(mapping_source, key,
/// ex_date) -> listing_id` (and OTC transfer `successor_key` on `ex_date`) through
/// `provider_mapping`, stamps `known_at_micros = et_session_close_utc_micros(known_at_date)`,
/// compacts cross-key collisions, and emits contract [`CorporateActionsParquetRow`]s sorted
/// deterministically with non-decreasing `(listing_id, ex_date, kind)`.
pub fn curate_corporate_actions<K, S, D, L, I>(
splits: S,
dividends: D,
delistings: L,
mapping_source: &str,
mapping: &ProviderMappingTable,
) -> Result<CurateCorporateActionsOutput, CurateCorporateActionsError>
where
K: Ord + Clone + AsRef<str>,
S: IntoIterator<Item = (K, SplitActionEvent)>,
D: IntoIterator<Item = (K, DividendActionEvent)>,
L: IntoIterator<Item = I>,
I: Into<CurateDelistingInput<K>>,
{
if mapping_source.trim().is_empty() {
return Err(CurateCorporateActionsError::EmptyMappingSource);
}
let delistings_iter = delistings.into_iter();
let delistings_hint = delistings_iter.size_hint().0;
let mut delistings_for_builder: Vec<(K, DelistingOutcomeEvent<K>)> =
Vec::with_capacity(delistings_hint);
let mut delisting_identities: Vec<DelistingIdentity<K>> = Vec::with_capacity(delistings_hint);
for raw in delistings_iter {
let item = raw.into();
match (&item.event.successor_key, item.event.terminal_return) {
(Some(succ), None) => {
delisting_identities.push(DelistingIdentity {
key: item.key.clone(),
ex_date: item.event.delist_date,
kind: CorporateActionKind::OtcDelistTransfer,
successor_key: Some(succ.clone()),
terminal_return_bits: None,
from_listing_id: item.from_listing_id,
});
}
(None, Some(raw_return)) => {
let norm = if raw_return == 0.0 { 0.0 } else { raw_return };
delisting_identities.push(DelistingIdentity {
key: item.key.clone(),
ex_date: item.event.delist_date,
kind: CorporateActionKind::Delisting,
successor_key: None,
terminal_return_bits: Some(norm.to_bits()),
from_listing_id: item.from_listing_id,
});
}
_ => {}
}
delistings_for_builder.push((item.key, item.event));
}
let built = build_corporate_actions(splits, dividends, delistings_for_builder)?;
delisting_identities.sort_unstable_by(cmp_delisting_identity);
let mut delisting_id_idx = 0usize;
let mut stats = CurateCorporateActionsStats {
builder: built.stats,
rows_in: built.rows.len(),
..CurateCorporateActionsStats::default()
};
let mut tagged: Vec<(CorporateActionsParquetRow, usize)> = Vec::with_capacity(built.rows.len());
let mut current_key: Option<K> = None;
let mut key_run_id: usize = 0;
let mut cursor = mapping.cursor_for(mapping_source, "");
for row in built.rows {
let from_listing_id = match row.kind {
CorporateActionKind::OtcDelistTransfer | CorporateActionKind::Delisting => {
let ident = &delisting_identities[delisting_id_idx];
debug_assert!(ident.key == row.key);
debug_assert_eq!(ident.ex_date, row.ex_date);
debug_assert_eq!(ident.kind, row.kind);
debug_assert!(ident.successor_key == row.successor_key);
debug_assert_eq!(ident.terminal_return_bits, opt_f64_bits(row.terminal_return));
delisting_id_idx += 1;
ident.from_listing_id
}
CorporateActionKind::Split | CorporateActionKind::Dividend => None,
};
let key_changed = match &current_key {
Some(prev) => *prev != row.key,
None => true,
};
if key_changed {
if current_key.is_some() {
key_run_id += 1;
}
cursor = mapping.cursor_for(mapping_source, row.key.as_ref());
current_key = Some(row.key);
}
// Strict drop priority:
// 1. Primary listing lookup -> dropped_unmapped.
// For `OtcDelistTransfer`, Pass 6 anchors `ex_date` to the successor's first OTC
// trading date (`effectiveDate`), after the outgoing listing's primary-venue mapping
// has typically ended (e.g. SIVB.US ends 2023-03-10, SIVBQ.US starts 2023-03-28) and
// possibly after ticker reuse. `OtcDelistTransfer` therefore requires Pass 6's
// `from_listing_id = Some(id)` (selecting only a range with `valid_from <= ex_date`
// matching `id`); identity-less OTC transfers (`None`) always drop into
// `dropped_unmapped` so they can never attach to an unrelated replacement occupant.
if cursor.ranges().is_empty() {
stats.dropped_unmapped += 1;
continue;
}
let primary_listing_id = match (row.kind, from_listing_id) {
(CorporateActionKind::OtcDelistTransfer, Some(expected_id)) => {
resolve_for_listing_on_or_before(cursor.ranges(), row.ex_date, expected_id)
}
(CorporateActionKind::OtcDelistTransfer, None) => None,
(CorporateActionKind::Delisting, Some(expected_id)) => {
cursor.resolve(row.ex_date).filter(|&id| id == expected_id)
}
_ => cursor.resolve(row.ex_date),
};
let Some(listing_id) = primary_listing_id else {
stats.dropped_unmapped += 1;
continue;
};
// 2. For otc_delist_transfer, resolve successor_key on ex_date (Pass 6 effectiveDate)
let successor_listing_id = if row.kind == CorporateActionKind::OtcDelistTransfer {
let Some(ref succ_key) = row.successor_key else {
stats.dropped_unmapped_successor += 1;
continue;
};
let Some(succ_id) = mapping.resolve(mapping_source, succ_key.as_ref(), row.ex_date)
else {
stats.dropped_unmapped_successor += 1;
continue;
};
if succ_id == listing_id {
stats.dropped_self_successor += 1;
continue;
}
Some(succ_id)
} else {
None
};
// 3. Convert known_at_date to 16:00:00 ET UTC microseconds
let Ok(known_at_micros) = et_session_close_utc_micros(row.known_at_date) else {
stats.dropped_known_at_out_of_range += 1;
continue;
};
tagged.push((
CorporateActionsParquetRow {
listing_id,
ex_date: row.ex_date,
declared_date: row.declared_date,
kind: row.kind,
ratio: row.ratio,
cash_amount: row.cash_amount,
currency: intern_currency(row.currency),
successor_listing_id,
terminal_return: row.terminal_return,
known_at_micros,
known_at_source: row.known_at_source,
},
key_run_id,
));
}
tagged.sort_unstable_by(|a, b| cmp_parquet_row(&a.0, &b.0).then_with(|| a.1.cmp(&b.1)));
let mut write_idx = 0usize;
let mut read_idx = 0usize;
let total_mapped = tagged.len();
let mut last_listing_id: Option<i32> = None;
while read_idx < total_mapped {
let listing_id = tagged[read_idx].0.listing_id;
let ex_date = tagged[read_idx].0.ex_date;
let kind = tagged[read_idx].0.kind;
let mut group_end = read_idx + 1;
while group_end < total_mapped
&& tagged[group_end].0.listing_id == listing_id
&& tagged[group_end].0.ex_date == ex_date
&& tagged[group_end].0.kind == kind
{
group_end += 1;
}
let group_len = group_end - read_idx;
// Cross-key conflicting split ratios on the same (listing_id, ex_date) drop the whole group.
if kind == CorporateActionKind::Split && group_len > 1 {
let first_key = tagged[read_idx].1;
let first_ratio = opt_f64_bits(tagged[read_idx].0.ratio);
let mut has_multi_key = false;
let mut has_multi_ratio = false;
for item in &tagged[read_idx + 1..group_end] {
if item.1 != first_key {
has_multi_key = true;
}
if opt_f64_bits(item.0.ratio) != first_ratio {
has_multi_ratio = true;
}
if has_multi_key && has_multi_ratio {
break;
}
}
if has_multi_key && has_multi_ratio {
stats.listing_collision_dropped += group_len;
read_idx = group_end;
continue;
}
}
// Compact contiguous runs of bitwise-identical rows: keep `max_per_key` copies so
// same-key multi-dividends (including equal-amount regular + special) stay separate while
// cross-key alias duplicates collapse cleanly.
let mut run_start = read_idx;
while run_start < group_end {
let mut run_end = run_start + 1;
while run_end < group_end
&& cmp_parquet_row(&tagged[run_start].0, &tagged[run_end].0) == Ordering::Equal
{
run_end += 1;
}
let run_len = run_end - run_start;
let keep_count = if run_len == 1 {
1
} else {
let mut max_per_key = 0usize;
let mut cur_key = tagged[run_start].1;
let mut cur_count = 1usize;
for item in &tagged[run_start + 1..run_end] {
if item.1 == cur_key {
cur_count += 1;
} else {
if cur_count > max_per_key {
max_per_key = cur_count;
}
cur_key = item.1;
cur_count = 1;
}
}
if cur_count > max_per_key {
max_per_key = cur_count;
}
max_per_key
};
stats.listing_collision_collapsed += run_len - keep_count;
for offset in 0..keep_count {
let src_idx = run_start + offset;
if write_idx != src_idx {
tagged.swap(write_idx, src_idx);
}
write_idx += 1;
}
if last_listing_id != Some(listing_id) {
stats.listings_out += 1;
last_listing_id = Some(listing_id);
}
run_start = run_end;
}
read_idx = group_end;
}
tagged.truncate(write_idx);
let rows: Vec<CorporateActionsParquetRow> = tagged.into_iter().map(|(row, _)| row).collect();
stats.rows_out = rows.len();
Ok(CurateCorporateActionsOutput { rows, stats })
}
/// Thin end-to-end wrapper running [`curate_corporate_actions`] and publishing the resulting
/// contract rows via [`write_corporate_actions_dataset`] to
/// `<out_dir>/corporate_actions/part.parquet`.
///
/// Any [`CurateCorporateActionsError`] returns before [`write_corporate_actions_dataset`] is
/// invoked, leaving `out_dir` untouched.
pub fn curate_and_write_corporate_actions<P, K, S, D, L, I>(
out_dir: P,
splits: S,
dividends: D,
delistings: L,
mapping_source: &str,
mapping: &ProviderMappingTable,
options: CorporateActionsWriteOptions,
) -> Result<CurateCorporateActionsWriteReport, CurateCorporateActionsWriteError>
where
P: AsRef<Path>,
K: Ord + Clone + AsRef<str>,
S: IntoIterator<Item = (K, SplitActionEvent)>,
D: IntoIterator<Item = (K, DividendActionEvent)>,
L: IntoIterator<Item = I>,
I: Into<CurateDelistingInput<K>>,
{
let curated = curate_corporate_actions(splits, dividends, delistings, mapping_source, mapping)?;
let write_stats = write_corporate_actions_dataset(out_dir, &curated.rows, options)?;
Ok(CurateCorporateActionsWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_corporate_actions_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -145,6 +145,13 @@ pub use curate_adj::{
CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION,
};
pub mod curate_corporate_actions;
pub use curate_corporate_actions::{
curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError,
CurateCorporateActionsOutput, CurateCorporateActionsStats, CurateCorporateActionsWriteError,
CurateCorporateActionsWriteReport, CurateDelistingInput,
};
pub mod run_curate_bars;
pub use run_curate_bars::{
format_curate_bars_report, load_listing_currencies_tsv, load_provider_mapping_tsv,

View file

@ -7,6 +7,7 @@ use curate_etl::bench::{
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark,
run_curate_adj_benchmark, run_curate_bars_benchmark, run_curate_bars_cmd_benchmark,
run_curate_corporate_actions_benchmark,
run_curate_events_benchmark, run_curate_fx_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,
@ -976,6 +977,73 @@ fn main() -> ExitCode {
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchCurateCorporateActions(events)) => {
let report = match run_curate_corporate_actions_benchmark(events) {
Ok(report) => report,
Err(err) => {
eprintln!("error: curate-corporate-actions benchmark failed: {err}");
return ExitCode::FAILURE;
}
};
let retention_pct = if report.events > 0 {
(report.rows_out as f64 / report.events as f64) * 100.0
} else {
0.0
};
println!("curate-etl bench-curate-corporate-actions");
println!(
" input: events={} splits={} dividends={} delistings={} keys={}",
report.events,
report.splits_in,
report.dividends_in,
report.delistings_in,
report.key_count
);
println!(
" builder: rows_out={} splits_out={} split_noops={} divs_out={} zero_div={} otc_out={} delist_out={} delist_no_outcome={}",
report.stats.builder.rows_out,
report.stats.builder.splits_out,
report.stats.builder.split_noops_dropped,
report.stats.builder.dividends_out,
report.stats.builder.dividend_zero_cash_dropped,
report.stats.builder.otc_delist_transfers_out,
report.stats.builder.delistings_out,
report.stats.builder.delist_without_outcome
);
println!(
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}",
report.rows_out,
retention_pct,
report.listings_out,
report.stage_elapsed_ms,
report.stage_events_per_sec,
report.stage_ns_per_event,
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} events/s",
report.total_elapsed_ms, report.total_events_per_sec
);
println!(
" curate: unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={}",
report.stats.dropped_unmapped,
report.stats.dropped_unmapped_successor,
report.stats.dropped_self_successor,
report.stats.dropped_known_at_out_of_range,
report.stats.listing_collision_collapsed,
report.stats.listing_collision_dropped
);
ExitCode::SUCCESS
}
Err(msg) => {
eprintln!("error: {msg}");
eprintln!("{}", format_usage_stderr(NAME));

View file

@ -1146,7 +1146,7 @@ where
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use parquet::basic::ConvertedType;
@ -1306,7 +1306,7 @@ mod tests {
}
}
pub(super) fn read_parquet_rows(path: &Path) -> Vec<CorporateActionsParquetRow> {
pub(crate) fn read_parquet_rows(path: &Path) -> Vec<CorporateActionsParquetRow> {
let file = File::open(path).expect("open parquet file");
let reader = SerializedFileReader::new(file).expect("open parquet reader");
let metadata = reader.metadata();
@ -1484,7 +1484,7 @@ mod tests {
assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits));
}
pub(super) fn assert_row_bitwise_eq(
pub(crate) fn assert_row_bitwise_eq(
actual: &CorporateActionsParquetRow,
expected: &CorporateActionsParquetRow,
) {
@ -1501,7 +1501,7 @@ mod tests {
assert_eq!(actual.known_at_source, expected.known_at_source);
}
pub(super) fn assert_no_transient_files(dir: &Path) {
pub(crate) fn assert_no_transient_files(dir: &Path) {
if !dir.exists() {
return;
}