T-96: M1.2n — tools/curate-etl: Zstd Parquet writer for corporate_actions/part.parquet (contract schema, atomic single-file publish) with round-trip tests and local benchmark (no new crates)

This commit is contained in:
Studio 2026-11-28 15:51:35 -05:00
parent 44ef8cda04
commit 6215df190f
8 changed files with 3785 additions and 11 deletions

View file

@ -1,6 +1,6 @@
# `curate-etl`
Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, and the `M1.2m` streaming Zstd Parquet writer for `adj_factors`.
Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, and the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`.
## Scope & Sign Conventions
@ -383,6 +383,56 @@ Rules:
- Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000`
- Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x`
## `corporate_actions` Parquet Writer (`M1.2n`)
`write_corporate_actions_dataset` (`src/parquet_corporate_actions.rs`) streams non-decreasing `(listing_id, ex_date, kind)` `CorporateActionsParquetRow` records (with `CorporateActionsParquetRow::from_corporate_action_row(&CorporateActionRow<i32>, known_at_micros)` construction from `build_corporate_actions`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A).
1. **Exact 11-column contract schema (`corporate_actions_parquet_schema`):**
- `listing_id` (`INT32`, `REQUIRED`)
- `ex_date` (`INT32`, `REQUIRED`, `DATE`)
- `declared_date` (`INT32`, `OPTIONAL`, `DATE`)
- `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"split"` | `"dividend"` | `"otc_delist_transfer"` | `"delisting"`)
- `ratio` (`DOUBLE`, `OPTIONAL`)
- `cash_amount` (`DOUBLE`, `OPTIONAL`)
- `currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`, dictionary-encoded)
- `successor_listing_id` (`INT32`, `OPTIONAL`)
- `terminal_return` (`DOUBLE`, `OPTIONAL`)
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"declared_date"` | `"ex_date_fallback"` | `"delist_date"`)
2. **Layout, compression & streaming:**
- Writes `<out_dir>/corporate_actions/part.parquet` (unpartitioned).
- Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating `<out_dir>/corporate_actions` and without modifying or removing any pre-existing `part.parquet`.
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `CorporateActionsWriteOptions::zstd_level`).
- Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `CorporateActionsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with interned `kind`, `currency`, and `known_at_source` streamed in 4,096-row batches and reused buffers across row groups), flushing and clearing on every row-group boundary.
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
3. **Validation, ordering, concurrency & atomic publish rules:**
- Caller supplies `known_at_micros` (date→timestamp derivation policy belongs to the later Mongo-streaming wiring task).
- Input must be non-decreasing on `(listing_id, ex_date, kind)` using `CorporateActionKind`'s `Ord` (`Split < Dividend < OtcDelistTransfer < Delisting`), matching `build_corporate_actions` output without re-sorting; multiple rows may share the same key (e.g. regular + special dividend on the same ex-date).
- Every streamed row is validated before publication: `ex_date` and optional `declared_date` years must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR` (`1900..=2200`); `split` requires `ratio` finite `> 0.0`; `dividend` requires `cash_amount` finite `> 0.0` and `currency` non-empty after trimming; `otc_delist_transfer` requires `successor_listing_id != listing_id`; `delisting` requires `terminal_return` finite in `[-1.0, 0.0]`; all fields belonging to other kinds must be `None`; and `known_at_source` must match the kind (`delist_date` only for delisting kinds, `declared_date` requires `declared_date.is_some()`).
- Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `<out_dir>/corporate_actions` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`.
4. **Typed errors (`ParquetCorporateActionsError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { prev_listing_id, prev_ex_date, prev_kind, listing_id, ex_date, kind }`
- `ExDateOutOfRange { listing_id, ex_date, year, min_year, max_year }`
- `DeclaredDateOutOfRange { listing_id, ex_date, declared_date, year, min_year, max_year }`
- `InvalidRatio { listing_id, ex_date, value }`
- `InvalidCashAmount { listing_id, ex_date, value }`
- `InvalidCurrency { listing_id, ex_date }`
- `InvalidSuccessorListingId { listing_id, ex_date, successor_listing_id }`
- `InvalidTerminalReturn { listing_id, ex_date, value }`
- `ForbiddenFieldForKind { listing_id, ex_date, kind, field }`
- `InconsistentKnownAtSource { listing_id, ex_date, kind, known_at_source, declared_date }`
- `LockTimeout { path, waited }`
- `RollbackFailed { cause, failures }`
- `Io { path, source }`
- `Parquet { path, source }`
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions`
- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72` (weekday dates `1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes)
- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000`
- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x`
## Local Benchmarks
### `bench-split`
@ -567,13 +617,27 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa
- Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000`
- Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x`
### `bench-parquet-corporate-actions`
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `CorporateActionsParquetRow` rows across `20,000` listings on weekday dates (`1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes), writing `corporate_actions/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory:
```bash
cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions [rows]
```
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions`
- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72`
- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000`
- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x`
## Deferred Follow-Ups (`M1.3+` / `M2`)
This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add:
- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
- Zstd Parquet writer for the remaining curated table (`corporate_actions`) and `qmPrices` OHLC cross-check
- `qmPrices` OHLC cross-check
- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`)
- PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32`
- `rayon` parallel sharding across symbol/date partitions

View file

@ -14,8 +14,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
use crate::corporate_actions::{
build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent,
DividendActionEvent, SplitActionEvent,
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent,
};
use crate::events::{
build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json,
@ -29,6 +29,10 @@ use crate::parquet_adj::{
use crate::parquet_bars::{
write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError,
};
use crate::parquet_corporate_actions::{
write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions,
ParquetCorporateActionsError,
};
use crate::parquet_events::{
write_events_dataset, EventsParquetRow, EventsWriteOptions, ParquetEventsError,
};
@ -64,6 +68,12 @@ pub const DEFAULT_PARQUET_FX_BENCH_ROWS: usize = 1_000_000;
pub const PARQUET_FX_RAW_ROW_BYTES: usize = 70;
pub const DEFAULT_PARQUET_ADJ_BENCH_ROWS: usize = 1_000_000;
pub const PARQUET_ADJ_RAW_ROW_BYTES: usize = 51;
pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000;
/// Uncompressed logical row size estimate for `corporate_actions/part.parquet` (11 columns):
/// `listing_id` (4) + `ex_date` (4) + `declared_date` (4) + `kind` (~8) + `ratio` (8)
/// + `cash_amount` (8) + `currency` (3) + `successor_listing_id` (4) + `terminal_return` (8)
/// + `known_at` (8) + `known_at_source` (~13) = 72 bytes.
pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72;
pub const BENCH_KEY_COUNT: usize = 20_000;
pub const BENCH_EVENT_COUNT: usize = 19_000;
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
@ -73,6 +83,7 @@ const PARQUET_SHORTS_BENCH_BASE_LISTINGS: usize = 12_500;
const PARQUET_EVENTS_BENCH_BASE_LISTINGS: usize = 5_000;
const PARQUET_FX_BENCH_BASE_PAIRS: usize = 80;
const PARQUET_ADJ_BENCH_BASE_LISTINGS: usize = 20_000;
const PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS: usize = 20_000;
const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57;
const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70;
@ -87,6 +98,7 @@ const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404;
const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4;
const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D;
const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F;
const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049;
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
/// Deterministic SplitMix64 generator (zero external dependencies).
@ -1719,6 +1731,14 @@ impl BenchTempDir {
Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-adj")
.map_err(|(path, source)| ParquetAdjError::Io { path, source })
}
fn new_corporate_actions() -> Result<Self, ParquetCorporateActionsError> {
Self::new_in_with_prefix(
&std::env::temp_dir(),
"curate-etl-bench-pq-corporate-actions",
)
.map_err(|(path, source)| ParquetCorporateActionsError::Io { path, source })
}
}
impl Drop for BenchTempDir {
@ -3239,6 +3259,336 @@ pub fn run_parquet_adj_benchmark(
Ok(report)
}
/// Summary metrics produced by [`run_parquet_corporate_actions_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ParquetCorporateActionsBenchReport {
pub rows: usize,
pub read_back_rows: usize,
pub listing_count: usize,
pub files_written: usize,
pub row_groups_written: usize,
pub bytes_written: u64,
pub raw_row_bytes: usize,
pub elapsed_ms: f64,
pub rows_per_sec: f64,
pub mb_per_sec: f64,
pub bytes_per_row: f64,
pub compression_ratio: f64,
}
struct ParquetCorporateActionsBenchIter {
weekdays: Vec<i32>,
listing_count: usize,
base_per_listing: usize,
rem_listings: usize,
cur_listing: usize,
cur_day_idx: usize,
cur_listing_rows: usize,
rng: SplitMix64,
}
impl ParquetCorporateActionsBenchIter {
fn new(rows: usize, weekdays: Vec<i32>) -> Self {
let min_listings = if rows == 0 {
PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS
} else {
rows.div_ceil(weekdays.len())
.max(PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS)
};
let active_listings = rows.min(min_listings);
let base_per_listing = if active_listings == 0 {
0
} else {
rows / active_listings
};
let rem_listings = if active_listings == 0 {
0
} else {
rows % active_listings
};
let mut iter = Self {
weekdays,
listing_count: active_listings,
base_per_listing,
rem_listings,
cur_listing: 0,
cur_day_idx: 0,
cur_listing_rows: 0,
rng: SplitMix64::new(PARQUET_CORPORATE_ACTIONS_BENCH_SEED),
};
if active_listings > 0 {
iter.setup_listing(0);
}
iter
}
fn setup_listing(&mut self, listing_idx: usize) {
self.cur_listing = listing_idx;
self.cur_day_idx = 0;
self.cur_listing_rows =
self.base_per_listing + usize::from(listing_idx < self.rem_listings);
}
}
impl Iterator for ParquetCorporateActionsBenchIter {
type Item = CorporateActionsParquetRow;
fn next(&mut self) -> Option<Self::Item> {
if self.cur_listing >= self.listing_count {
return None;
}
if self.cur_day_idx >= self.cur_listing_rows {
let next_listing = self.cur_listing + 1;
if next_listing >= self.listing_count {
self.cur_listing = next_listing;
return None;
}
self.setup_listing(next_listing);
}
let listing_id = (self.cur_listing as i32) + 1;
let w = self.weekdays.len();
let n = self.cur_listing_rows;
let date_pos = if n == 1 {
(self.cur_listing.wrapping_mul(131)) % w
} else {
(self.cur_day_idx * w) / n
};
let ex_date = self.weekdays[date_pos];
self.cur_day_idx += 1;
let r1 = self.rng.next_u64();
let kind_roll = r1 % 100;
// M1.2c mix: ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes
// (split between otc_delist_transfer and delisting).
if kind_roll < 4 {
let ratio = SAMPLE_RATIOS[((r1 >> 16) as usize) % SAMPLE_RATIOS.len()];
let decl_roll = (r1 >> 40) % 100;
let (declared_date, known_at_day, known_at_source) = if decl_roll < 80 {
let d = ex_date - (14 + ((r1 >> 48) % 8) as i32);
(Some(d), d, KnownAtSource::DeclaredDate)
} else if decl_roll < 98 {
(None, ex_date, KnownAtSource::ExDateFallback)
} else {
(Some(ex_date + 3), ex_date, KnownAtSource::ExDateFallback)
};
Some(CorporateActionsParquetRow {
listing_id,
ex_date,
declared_date,
kind: CorporateActionKind::Split,
ratio: Some(ratio),
cash_amount: None,
currency: None,
successor_listing_id: None,
terminal_return: None,
known_at_micros: i64::from(known_at_day) * 86_400_000_000 + 13 * 3_600_000_000,
known_at_source,
})
} else if kind_roll < 96 {
let currency = if ((r1 >> 8) & 3) == 0 { "CAD" } else { "USD" };
let cash = (((r1 >> 24) % 250) + 1) as f64 * 0.01;
let decl_roll = (r1 >> 40) % 100;
let (declared_date, known_at_day, known_at_source) = if decl_roll < 80 {
let d = ex_date - (14 + ((r1 >> 48) % 8) as i32);
(Some(d), d, KnownAtSource::DeclaredDate)
} else if decl_roll < 98 {
(None, ex_date, KnownAtSource::ExDateFallback)
} else {
(Some(ex_date + 3), ex_date, KnownAtSource::ExDateFallback)
};
Some(CorporateActionsParquetRow {
listing_id,
ex_date,
declared_date,
kind: CorporateActionKind::Dividend,
ratio: None,
cash_amount: Some(cash),
currency: Some(Cow::Borrowed(currency)),
successor_listing_id: None,
terminal_return: None,
known_at_micros: i64::from(known_at_day) * 86_400_000_000 + 13 * 3_600_000_000,
known_at_source,
})
} else if kind_roll < 98 {
Some(CorporateActionsParquetRow {
listing_id,
ex_date,
declared_date: None,
kind: CorporateActionKind::OtcDelistTransfer,
ratio: None,
cash_amount: None,
currency: None,
successor_listing_id: Some(listing_id + 1_000_000),
terminal_return: None,
known_at_micros: i64::from(ex_date) * 86_400_000_000 + 13 * 3_600_000_000,
known_at_source: KnownAtSource::DelistDate,
})
} else {
let terminal_return = match (r1 >> 24) % 4 {
0 => -1.0,
1 => -0.5,
2 => -0.3,
_ => 0.0,
};
Some(CorporateActionsParquetRow {
listing_id,
ex_date,
declared_date: None,
kind: CorporateActionKind::Delisting,
ratio: None,
cash_amount: None,
currency: None,
successor_listing_id: None,
terminal_return: Some(terminal_return),
known_at_micros: i64::from(ex_date) * 86_400_000_000 + 13 * 3_600_000_000,
known_at_source: KnownAtSource::DelistDate,
})
}
}
}
fn verify_parquet_corporate_actions_row_count(
out_dir: &Path,
expected_rows: usize,
) -> Result<usize, ParquetCorporateActionsError> {
if expected_rows == 0 {
return Ok(0);
}
let path = out_dir.join("corporate_actions/part.parquet");
let file = File::open(&path).map_err(|source| ParquetCorporateActionsError::Io {
path: path.clone(),
source,
})?;
let reader =
SerializedFileReader::new(file).map_err(|source| ParquetCorporateActionsError::Parquet {
path: path.clone(),
source,
})?;
let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err(
|_| ParquetCorporateActionsError::Parquet {
path: path.clone(),
source: ParquetError::General(format!(
"negative or overflowing Parquet footer row count: {}",
reader.metadata().file_metadata().num_rows()
)),
},
)?;
if read_back_rows != expected_rows {
return Err(ParquetCorporateActionsError::Parquet {
path,
source: ParquetError::General(format!(
"parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}"
)),
});
}
Ok(read_back_rows)
}
fn run_parquet_corporate_actions_benchmark_tracked(
rows: usize,
) -> Result<(ParquetCorporateActionsBenchReport, PathBuf), ParquetCorporateActionsError> {
let temp = BenchTempDir::new_corporate_actions()?;
let temp_path = temp.path.clone();
if rows == 0 {
let stats = write_corporate_actions_dataset(
&temp.path,
std::iter::empty::<CorporateActionsParquetRow>(),
CorporateActionsWriteOptions::default(),
)?;
let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, 0)?;
let report = ParquetCorporateActionsBenchReport {
rows: 0,
read_back_rows,
listing_count: 0,
files_written: stats.files_written,
row_groups_written: stats.row_groups_written,
bytes_written: stats.bytes_written,
raw_row_bytes: PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES,
elapsed_ms: 0.0,
rows_per_sec: 0.0,
mb_per_sec: 0.0,
bytes_per_row: 0.0,
compression_ratio: 0.0,
};
drop(temp);
return Ok((report, temp_path));
}
let weekdays = collect_bench_weekdays_1990_2025();
let iter = ParquetCorporateActionsBenchIter::new(rows, weekdays);
let listing_count = iter.listing_count;
let start = Instant::now();
let stats = write_corporate_actions_dataset(
&temp.path,
iter,
CorporateActionsWriteOptions::default(),
)?;
let elapsed_secs = start.elapsed().as_secs_f64();
let elapsed_ms = elapsed_secs * 1_000.0;
if stats.rows_written != rows {
return Err(ParquetCorporateActionsError::Parquet {
path: temp.path.join("corporate_actions/part.parquet"),
source: ParquetError::General(format!(
"writer row count mismatch: expected {rows}, stats reported {}",
stats.rows_written
)),
});
}
let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, rows)?;
let (rows_per_sec, _) = compute_rates(rows, elapsed_secs);
let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() {
(stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs
} else {
0.0
};
let bytes_per_row = stats.bytes_written as f64 / rows as f64;
let raw_bytes = (rows as f64) * (PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES as f64);
let compression_ratio = if stats.bytes_written > 0 {
raw_bytes / (stats.bytes_written as f64)
} else {
0.0
};
drop(temp);
Ok((
ParquetCorporateActionsBenchReport {
rows,
read_back_rows,
listing_count,
files_written: stats.files_written,
row_groups_written: stats.row_groups_written,
bytes_written: stats.bytes_written,
raw_row_bytes: PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES,
elapsed_ms,
rows_per_sec,
mb_per_sec,
bytes_per_row,
compression_ratio,
},
temp_path,
))
}
/// Runs the fixed-seed Zstd Parquet `corporate_actions` writer benchmark for `rows` sorted
/// split/dividend/delisting rows spanning `1990..=2025` across up to `20,000` listings, reads back
/// the Parquet footer row count, and deletes its temporary output directory.
pub fn run_parquet_corporate_actions_benchmark(
rows: usize,
) -> Result<ParquetCorporateActionsBenchReport, ParquetCorporateActionsError> {
let (report, _) = run_parquet_corporate_actions_benchmark_tracked(rows)?;
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
@ -3961,4 +4311,75 @@ mod tests {
"error must report expected (255) and actual (250) row counts, got: {msg}"
);
}
#[test]
fn parquet_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() {
let (a, dir_a) = run_parquet_corporate_actions_benchmark_tracked(25_000).unwrap();
let (b, dir_b) = run_parquet_corporate_actions_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.read_back_rows, 25_000);
assert_eq!(a.listing_count, PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS);
assert_eq!(a.files_written, 1);
assert_eq!(a.files_written, b.files_written);
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.raw_row_bytes, PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES);
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0);
assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0);
assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0);
}
#[test]
fn parquet_corporate_actions_benchmark_zero_rows_handles_cleanly() {
let (report, dir) = run_parquet_corporate_actions_benchmark_tracked(0).unwrap();
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
assert_eq!(report.rows, 0);
assert_eq!(report.read_back_rows, 0);
assert_eq!(report.listing_count, 0);
assert_eq!(report.files_written, 0);
assert_eq!(report.row_groups_written, 0);
assert_eq!(report.bytes_written, 0);
assert_eq!(report.raw_row_bytes, PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES);
assert_eq!(report.elapsed_ms, 0.0);
assert_eq!(report.rows_per_sec, 0.0);
assert_eq!(report.mb_per_sec, 0.0);
assert_eq!(report.bytes_per_row, 0.0);
assert_eq!(report.compression_ratio, 0.0);
}
#[test]
fn verify_parquet_corporate_actions_row_count_returns_error_on_mismatch() {
let temp = BenchTempDir::new_corporate_actions().unwrap();
let weekdays = collect_bench_weekdays_1990_2025();
let iter = ParquetCorporateActionsBenchIter::new(250, weekdays);
write_corporate_actions_dataset(&temp.path, iter, CorporateActionsWriteOptions::default())
.unwrap();
let matched = verify_parquet_corporate_actions_row_count(&temp.path, 250).unwrap();
assert_eq!(matched, 250);
let err = verify_parquet_corporate_actions_row_count(&temp.path, 255).unwrap_err();
let msg = err.to_string();
assert!(
matches!(err, ParquetCorporateActionsError::Parquet { .. }),
"expected Parquet error, got {err:?}"
);
assert!(
msg.contains("255") && msg.contains("250"),
"error must report expected (255) and actual (250) row counts, got: {msg}"
);
}
}

View file

@ -7,9 +7,9 @@ use crate::bench::{
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_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_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,
};
/// Parsed CLI command to execute.
@ -30,6 +30,7 @@ pub enum CliAction {
BenchParquetEvents(usize),
BenchParquetFx(usize),
BenchParquetAdj(usize),
BenchParquetCorporateActions(usize),
}
/// Formats full help text including binary name and version.
@ -52,7 +53,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\
{name} bench-parquet-events [rows] Run fixed-seed events Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_EVENTS_BENCH_ROWS})\n\
{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})"
{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})"
)
}
@ -74,7 +76,8 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-parquet-shorts [rows]\n\
{name} bench-parquet-events [rows]\n\
{name} bench-parquet-fx [rows]\n\
{name} bench-parquet-adj [rows]"
{name} bench-parquet-adj [rows]\n\
{name} bench-parquet-corporate-actions [rows]"
)
}
@ -215,6 +218,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
["bench-parquet-adj", _, ..] => {
Err("too many arguments for bench-parquet-adj".to_string())
}
["bench-parquet-corporate-actions"] => Ok(CliAction::BenchParquetCorporateActions(
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS,
)),
["bench-parquet-corporate-actions", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchParquetCorporateActions(n)),
_ => Err(format!(
"invalid row count '{raw}' (expected a positive integer)"
)),
},
["bench-parquet-corporate-actions", _, ..] => {
Err("too many arguments for bench-parquet-corporate-actions".to_string())
}
[other, ..] => Err(format!("unknown argument '{other}'")),
}
}
@ -466,6 +481,24 @@ mod tests {
assert!(parse_args(&to_args(&["bench-parquet-adj", "10", "20"])).is_err());
}
#[test]
fn parses_and_validates_bench_parquet_corporate_actions_args() {
assert_eq!(
parse_args(&to_args(&["bench-parquet-corporate-actions"])),
Ok(CliAction::BenchParquetCorporateActions(
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS
))
);
assert_eq!(
parse_args(&to_args(&["bench-parquet-corporate-actions", "25000"])),
Ok(CliAction::BenchParquetCorporateActions(25_000))
);
assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "-5"])).is_err());
assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "10", "20"])).is_err());
}
#[test]
fn usage_strings_mention_all_benchmarks() {
let full = format_usage("curate-etl", "0.1.0");
@ -482,6 +515,7 @@ mod tests {
assert!(full.contains("bench-parquet-events"));
assert!(full.contains("bench-parquet-fx"));
assert!(full.contains("bench-parquet-adj"));
assert!(full.contains("bench-parquet-corporate-actions"));
let short = format_usage_stderr("curate-etl");
assert!(short.contains("bench-split"));
@ -497,5 +531,6 @@ mod tests {
assert!(short.contains("bench-parquet-events"));
assert!(short.contains("bench-parquet-fx"));
assert!(short.contains("bench-parquet-adj"));
assert!(short.contains("bench-parquet-corporate-actions"));
}
}

View file

@ -9,6 +9,7 @@ pub mod events;
pub mod fx;
pub mod parquet_adj;
pub mod parquet_bars;
pub mod parquet_corporate_actions;
pub mod parquet_events;
pub mod parquet_fx;
mod parquet_publish;
@ -51,6 +52,10 @@ pub use parquet_bars::{
Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS,
DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
};
pub use parquet_corporate_actions::{
corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow,
CorporateActionsWriteOptions, CorporateActionsWriteStats, ParquetCorporateActionsError,
};
pub use parquet_events::{
events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions,
EventsWriteStats, ParquetEventsError,

View file

@ -6,8 +6,9 @@ use std::process::ExitCode;
use curate_etl::bench::{
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark,
run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark,
run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
run_shorts_benchmark, run_split_benchmark,
};
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
@ -446,6 +447,36 @@ fn main() -> ExitCode {
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchParquetCorporateActions(rows)) => {
let report = match run_parquet_corporate_actions_benchmark(rows) {
Ok(report) => report,
Err(err) => {
eprintln!("error: parquet corporate_actions benchmark failed: {err}");
return ExitCode::FAILURE;
}
};
println!("curate-etl bench-parquet-corporate-actions");
println!(
" input: rows={} listings={} raw_row_bytes={}",
report.rows, report.listing_count, report.raw_row_bytes
);
println!(
" output: files={} row_groups={} bytes={} read_back_rows={}",
report.files_written,
report.row_groups_written,
report.bytes_written,
report.read_back_rows
);
println!(
" perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x",
report.elapsed_ms,
report.rows_per_sec,
report.mb_per_sec,
report.bytes_per_row,
report.compression_ratio
);
ExitCode::SUCCESS
}
Err(msg) => {
eprintln!("error: {msg}");
eprintln!("{}", format_usage_stderr(NAME));

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -381,6 +381,25 @@ pub(crate) fn write_i32_col(
col.close()
}
pub(crate) fn write_optional_i32_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[i32],
def_levels: &[i16],
) -> Result<(), ParquetError> {
let mut col = next_column(rg_writer)?;
match col.untyped() {
ColumnWriter::Int32ColumnWriter(typed) => {
typed.write_batch(values, Some(def_levels), None)?;
}
_ => {
return Err(ParquetError::General(
"expected INT32 column writer".to_string(),
));
}
}
col.close()
}
pub(crate) fn write_i64_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[i64],
@ -418,6 +437,14 @@ pub(crate) fn write_f64_col(
col.close()
}
pub(crate) fn write_optional_f64_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
values: &[f64],
def_levels: &[i16],
) -> Result<(), ParquetError> {
write_f64_col(rg_writer, values, Some(def_levels))
}
pub(crate) fn write_interned_str_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
ids: &[u32],