T-96: tests
This commit is contained in:
parent
a8e63285a1
commit
9505a217b6
1 changed files with 779 additions and 0 deletions
779
tools/curate-etl/tests/parquet_corporate_actions_qa_contract.rs
Normal file
779
tools/curate-etl/tests/parquet_corporate_actions_qa_contract.rs
Normal file
|
|
@ -0,0 +1,779 @@
|
|||
//! QA contract tests for the public `corporate_actions` Parquet writer (T-96 / M1.2n).
|
||||
//!
|
||||
//! Exercises only the public crate API (`curate_etl::*`) and covers gaps left by the in-crate
|
||||
//! unit tests:
|
||||
//! - seeded randomized round-trip of all four kinds across several `row_group_rows` values
|
||||
//! (including 1 and the 4,096-row string batch boundary), bit-exact values and null positions
|
||||
//! for every optional column, and `ceil(n / row_group_rows)` row groups in stats and footer;
|
||||
//! - streaming proof: flushed row groups reach the staging file before later rows are pulled;
|
||||
//! - `build_corporate_actions` -> `from_corporate_action_row` -> writer end-to-end with all
|
||||
//! kinds, a same-day regular + special dividend, and known_at derived from `known_at_date`;
|
||||
//! - currency labels survive the per-row-group interner reset;
|
||||
//! - a late failure after several flushed row groups preserves a seeded `part.parquet`
|
||||
//! byte-identically and leaves no `.tmp`/`.bak`/`.write.lock` behind;
|
||||
//! - invalid options are rejected using finite probe iterators that must never be polled.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use curate_etl::{
|
||||
build_corporate_actions, write_corporate_actions_dataset, ymd_to_epoch_days,
|
||||
CorporateActionKind, CorporateActionsParquetRow, CorporateActionsWriteOptions,
|
||||
DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, ParquetCorporateActionsError,
|
||||
SplitActionEvent,
|
||||
};
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
const MICROS_PER_DAY: i64 = 86_400_000_000;
|
||||
/// Mirrors `parquet_publish::STRING_WRITE_BATCH_ROWS` (crate-private).
|
||||
const STRING_BATCH: usize = 4_096;
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-etl-pq-ca-qa-{tag}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic SplitMix64 (fixed seed per test).
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// Uniform in `(0, 1]` with a random mantissa.
|
||||
fn unit_open(&mut self) -> f64 {
|
||||
((self.next_u64() >> 11) as f64 + 1.0) / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
fn days(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn opts(row_group_rows: usize) -> CorporateActionsWriteOptions {
|
||||
CorporateActionsWriteOptions {
|
||||
row_group_rows,
|
||||
..CorporateActionsWriteOptions::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn dataset_dir(out: &Path) -> PathBuf {
|
||||
out.join("corporate_actions")
|
||||
}
|
||||
|
||||
fn part_path(out: &Path) -> PathBuf {
|
||||
dataset_dir(out).join("part.parquet")
|
||||
}
|
||||
|
||||
fn leftover_transients(out: &Path) -> Vec<String> {
|
||||
let Ok(entries) = fs::read_dir(dataset_dir(out)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
entries
|
||||
.map(|e| {
|
||||
e.expect("dir entry")
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.filter(|name| name != "part.parquet")
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn staging_bytes(dir: &Path) -> u64 {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return 0;
|
||||
};
|
||||
entries
|
||||
.map(|e| e.expect("dir entry"))
|
||||
.filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
|
||||
.map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Generates a valid, sorted row for index `i` (listing changes every 8 rows, ex_date steps
|
||||
/// every 2 rows so consecutive rows can share `(listing_id, ex_date)`).
|
||||
fn random_row(i: usize, rng: &mut Rng) -> CorporateActionsParquetRow {
|
||||
let listing_id = 1 + (i / 8) as i32;
|
||||
let ex_date = days(1995, 1, 2) + ((i % 8) / 2) as i32 * 7;
|
||||
let r = rng.next_u64();
|
||||
let known_at_micros = i64::from(ex_date) * MICROS_PER_DAY + (r % MICROS_PER_DAY as u64) as i64;
|
||||
// Second row of each (listing_id, ex_date) pair must not sort below the first; use kinds
|
||||
// with non-decreasing ordinals inside the pair.
|
||||
let in_pair_second = i % 2 == 1;
|
||||
let kind_roll = r % 4;
|
||||
let kind = match (in_pair_second, kind_roll) {
|
||||
(false, 0) => CorporateActionKind::Split,
|
||||
(false, _) => CorporateActionKind::Dividend,
|
||||
(true, 0) | (true, 1) => CorporateActionKind::Dividend,
|
||||
(true, 2) => CorporateActionKind::OtcDelistTransfer,
|
||||
(true, _) => CorporateActionKind::Delisting,
|
||||
};
|
||||
let decl = (r >> 8) % 3;
|
||||
let (declared_date, known_at_source) = match kind {
|
||||
CorporateActionKind::Split | CorporateActionKind::Dividend => match decl {
|
||||
0 => (
|
||||
Some(ex_date - 1 - ((r >> 16) % 30) as i32),
|
||||
KnownAtSource::DeclaredDate,
|
||||
),
|
||||
1 => (None, KnownAtSource::ExDateFallback),
|
||||
_ => (Some(ex_date + 2), KnownAtSource::ExDateFallback),
|
||||
},
|
||||
_ => (
|
||||
if decl == 0 { Some(ex_date - 5) } else { None },
|
||||
KnownAtSource::DelistDate,
|
||||
),
|
||||
};
|
||||
let mut row = CorporateActionsParquetRow {
|
||||
listing_id,
|
||||
ex_date,
|
||||
declared_date,
|
||||
kind,
|
||||
ratio: None,
|
||||
cash_amount: None,
|
||||
currency: None,
|
||||
successor_listing_id: None,
|
||||
terminal_return: None,
|
||||
known_at_micros,
|
||||
known_at_source,
|
||||
};
|
||||
match kind {
|
||||
CorporateActionKind::Split => row.ratio = Some(rng.unit_open() * 20.0),
|
||||
CorporateActionKind::Dividend => {
|
||||
row.cash_amount = Some(rng.unit_open() * 3.0);
|
||||
row.currency = Some(Cow::Borrowed(if (r >> 24) & 1 == 0 {
|
||||
"USD"
|
||||
} else {
|
||||
"CAD"
|
||||
}));
|
||||
}
|
||||
CorporateActionKind::OtcDelistTransfer => {
|
||||
row.successor_listing_id = Some(listing_id + 1_000_000 + ((r >> 32) % 5) as i32);
|
||||
}
|
||||
CorporateActionKind::Delisting => row.terminal_return = Some(-rng.unit_open() + 0.0),
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
fn parse_kind(s: &str) -> CorporateActionKind {
|
||||
match s {
|
||||
"split" => CorporateActionKind::Split,
|
||||
"dividend" => CorporateActionKind::Dividend,
|
||||
"otc_delist_transfer" => CorporateActionKind::OtcDelistTransfer,
|
||||
"delisting" => CorporateActionKind::Delisting,
|
||||
other => panic!("unexpected kind {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_source(s: &str) -> KnownAtSource {
|
||||
match s {
|
||||
"declared_date" => KnownAtSource::DeclaredDate,
|
||||
"ex_date_fallback" => KnownAtSource::ExDateFallback,
|
||||
"delist_date" => KnownAtSource::DelistDate,
|
||||
other => panic!("unexpected known_at_source {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Expands values + definition levels into `Option<T>` per record.
|
||||
fn expand<T: Clone>(vals: Vec<T>, defs: Vec<i16>, n: usize) -> Vec<Option<T>> {
|
||||
assert_eq!(defs.len(), n, "one definition level per record");
|
||||
let mut vi = 0usize;
|
||||
let out: Vec<Option<T>> = defs
|
||||
.iter()
|
||||
.map(|&d| match d {
|
||||
0 => None,
|
||||
1 => {
|
||||
vi += 1;
|
||||
Some(vals[vi - 1].clone())
|
||||
}
|
||||
other => panic!("unexpected def level {other}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(vi, vals.len(), "every value consumed exactly once");
|
||||
out
|
||||
}
|
||||
|
||||
fn read_rows(path: &Path) -> Vec<CorporateActionsParquetRow> {
|
||||
let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader");
|
||||
let meta = reader.metadata();
|
||||
let mut out = Vec::new();
|
||||
for rg in 0..meta.num_row_groups() {
|
||||
let rg_reader = reader.get_row_group(rg).expect("rg");
|
||||
let n = meta.row_group(rg).num_rows() as usize;
|
||||
let i32s = |idx: usize| -> Vec<Option<i32>> {
|
||||
let (mut v, mut d) = (Vec::new(), Vec::new());
|
||||
let ColumnReader::Int32ColumnReader(mut r) =
|
||||
rg_reader.get_column_reader(idx).expect("col")
|
||||
else {
|
||||
panic!("expected INT32 at {idx}");
|
||||
};
|
||||
r.read_records(n, Some(&mut d), None, &mut v).expect("read");
|
||||
if d.is_empty() {
|
||||
assert_eq!(v.len(), n);
|
||||
v.into_iter().map(Some).collect()
|
||||
} else {
|
||||
expand(v, d, n)
|
||||
}
|
||||
};
|
||||
let f64s = |idx: usize| -> Vec<Option<f64>> {
|
||||
let (mut v, mut d) = (Vec::new(), Vec::new());
|
||||
let ColumnReader::DoubleColumnReader(mut r) =
|
||||
rg_reader.get_column_reader(idx).expect("col")
|
||||
else {
|
||||
panic!("expected DOUBLE at {idx}");
|
||||
};
|
||||
r.read_records(n, Some(&mut d), None, &mut v).expect("read");
|
||||
expand(v, d, n)
|
||||
};
|
||||
let i64s = |idx: usize| -> Vec<i64> {
|
||||
let mut v = Vec::new();
|
||||
let ColumnReader::Int64ColumnReader(mut r) =
|
||||
rg_reader.get_column_reader(idx).expect("col")
|
||||
else {
|
||||
panic!("expected INT64 at {idx}");
|
||||
};
|
||||
r.read_records(n, None, None, &mut v).expect("read");
|
||||
assert_eq!(v.len(), n);
|
||||
v
|
||||
};
|
||||
let strs = |idx: usize| -> Vec<Option<String>> {
|
||||
let (mut v, mut d) = (Vec::new(), Vec::new());
|
||||
let ColumnReader::ByteArrayColumnReader(mut r) =
|
||||
rg_reader.get_column_reader(idx).expect("col")
|
||||
else {
|
||||
panic!("expected BYTE_ARRAY at {idx}");
|
||||
};
|
||||
r.read_records(n, Some(&mut d), None, &mut v).expect("read");
|
||||
let v: Vec<String> = v
|
||||
.into_iter()
|
||||
.map(|b| String::from_utf8(b.data().to_vec()).expect("utf8"))
|
||||
.collect();
|
||||
if d.is_empty() {
|
||||
assert_eq!(v.len(), n);
|
||||
v.into_iter().map(Some).collect()
|
||||
} else {
|
||||
expand(v, d, n)
|
||||
}
|
||||
};
|
||||
|
||||
let lid = i32s(0);
|
||||
let ed = i32s(1);
|
||||
let decl = i32s(2);
|
||||
let kind = strs(3);
|
||||
let ratio = f64s(4);
|
||||
let cash = f64s(5);
|
||||
let cur = strs(6);
|
||||
let succ = i32s(7);
|
||||
let tr = f64s(8);
|
||||
let ka = i64s(9);
|
||||
let src = strs(10);
|
||||
for i in 0..n {
|
||||
out.push(CorporateActionsParquetRow {
|
||||
listing_id: lid[i].expect("listing_id required"),
|
||||
ex_date: ed[i].expect("ex_date required"),
|
||||
declared_date: decl[i],
|
||||
kind: parse_kind(kind[i].as_deref().expect("kind required")),
|
||||
ratio: ratio[i],
|
||||
cash_amount: cash[i],
|
||||
currency: cur[i].clone().map(Cow::Owned),
|
||||
successor_listing_id: succ[i],
|
||||
terminal_return: tr[i],
|
||||
known_at_micros: ka[i],
|
||||
known_at_source: parse_source(src[i].as_deref().expect("source required")),
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn bits(v: Option<f64>) -> Option<u64> {
|
||||
v.map(f64::to_bits)
|
||||
}
|
||||
|
||||
fn assert_bitwise(actual: &[CorporateActionsParquetRow], expected: &[CorporateActionsParquetRow]) {
|
||||
assert_eq!(actual.len(), expected.len(), "row count");
|
||||
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
|
||||
assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id");
|
||||
assert_eq!(a.ex_date, e.ex_date, "row {i} ex_date");
|
||||
assert_eq!(a.declared_date, e.declared_date, "row {i} declared_date");
|
||||
assert_eq!(a.kind, e.kind, "row {i} kind");
|
||||
assert_eq!(bits(a.ratio), bits(e.ratio), "row {i} ratio");
|
||||
assert_eq!(
|
||||
bits(a.cash_amount),
|
||||
bits(e.cash_amount),
|
||||
"row {i} cash_amount"
|
||||
);
|
||||
assert_eq!(a.currency, e.currency, "row {i} currency");
|
||||
assert_eq!(
|
||||
a.successor_listing_id, e.successor_listing_id,
|
||||
"row {i} successor_listing_id"
|
||||
);
|
||||
assert_eq!(
|
||||
bits(a.terminal_return),
|
||||
bits(e.terminal_return),
|
||||
"row {i} terminal_return"
|
||||
);
|
||||
assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at");
|
||||
assert_eq!(
|
||||
a.known_at_source, e.known_at_source,
|
||||
"row {i} known_at_source"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn row_group_sizes(path: &Path) -> Vec<i64> {
|
||||
let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader");
|
||||
reader
|
||||
.metadata()
|
||||
.row_groups()
|
||||
.iter()
|
||||
.map(|rg| rg.num_rows())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_random_streams_of_all_kinds_round_trip_with_expected_row_group_layout() {
|
||||
// Arrange: one fixed stream, written with several row-group sizes around the string batch.
|
||||
let total = 2 * STRING_BATCH + 37;
|
||||
let mut rng = Rng(0xC0A0_0096_0000_0001);
|
||||
let rows: Vec<CorporateActionsParquetRow> =
|
||||
(0..total).map(|i| random_row(i, &mut rng)).collect();
|
||||
for kind in [
|
||||
CorporateActionKind::Split,
|
||||
CorporateActionKind::Dividend,
|
||||
CorporateActionKind::OtcDelistTransfer,
|
||||
CorporateActionKind::Delisting,
|
||||
] {
|
||||
assert!(
|
||||
rows.iter().any(|r| r.kind == kind),
|
||||
"fixture covers {kind:?}"
|
||||
);
|
||||
}
|
||||
|
||||
for rgr in [1usize, 7, STRING_BATCH, STRING_BATCH + 1, total, total + 10] {
|
||||
let tmp = TempDir::new("random");
|
||||
|
||||
// Act
|
||||
let stats = write_corporate_actions_dataset(&tmp.0, &rows, opts(rgr)).unwrap();
|
||||
|
||||
// Assert
|
||||
let path = part_path(&tmp.0);
|
||||
let expected_groups = total.div_ceil(rgr);
|
||||
assert_eq!(stats.rows_written, total, "rgr={rgr}");
|
||||
assert_eq!(stats.files_written, 1, "rgr={rgr}");
|
||||
assert_eq!(stats.row_groups_written, expected_groups, "rgr={rgr}");
|
||||
assert_eq!(stats.bytes_written, fs::metadata(&path).unwrap().len());
|
||||
let sizes = row_group_sizes(&path);
|
||||
assert_eq!(sizes.len(), expected_groups, "rgr={rgr}");
|
||||
assert!(sizes[..sizes.len() - 1].iter().all(|&s| s == rgr as i64));
|
||||
assert_bitwise(&read_rows(&path), &rows);
|
||||
assert!(leftover_transients(&tmp.0).is_empty(), "rgr={rgr}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Lazy source that records the staging-file size each time a new row group starts.
|
||||
struct ObservingIter {
|
||||
dir: PathBuf,
|
||||
total: usize,
|
||||
row_group_rows: usize,
|
||||
next_idx: usize,
|
||||
rng: Rng,
|
||||
observed_at_group_start: Vec<u64>,
|
||||
}
|
||||
|
||||
impl Iterator for ObservingIter {
|
||||
type Item = CorporateActionsParquetRow;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.next_idx >= self.total {
|
||||
return None;
|
||||
}
|
||||
if self.next_idx % self.row_group_rows == 0 {
|
||||
self.observed_at_group_start.push(staging_bytes(&self.dir));
|
||||
}
|
||||
let r = random_row(self.next_idx, &mut self.rng);
|
||||
self.next_idx += 1;
|
||||
Some(r)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_groups_are_flushed_to_staging_before_remaining_rows_are_pulled() {
|
||||
// Arrange: 3 row groups of 40,000 random-mantissa rows (each group well beyond the
|
||||
// writer's in-memory BufWriter capacity once compressed).
|
||||
let tmp = TempDir::new("streaming");
|
||||
let row_group_rows = 40_000;
|
||||
let mut iter = ObservingIter {
|
||||
dir: dataset_dir(&tmp.0),
|
||||
total: 3 * row_group_rows,
|
||||
row_group_rows,
|
||||
next_idx: 0,
|
||||
rng: Rng(0xC0A0_0096_0000_0002),
|
||||
observed_at_group_start: Vec::new(),
|
||||
};
|
||||
|
||||
// Act
|
||||
let stats =
|
||||
write_corporate_actions_dataset(&tmp.0, iter.by_ref(), opts(row_group_rows)).unwrap();
|
||||
|
||||
// Assert
|
||||
assert_eq!(stats.rows_written, 3 * row_group_rows);
|
||||
assert_eq!(stats.row_groups_written, 3);
|
||||
let obs = &iter.observed_at_group_start;
|
||||
assert_eq!(obs.len(), 3, "one observation per row-group start");
|
||||
assert_eq!(
|
||||
obs[0], 0,
|
||||
"nothing on disk before the first row is buffered"
|
||||
);
|
||||
assert!(
|
||||
obs[1] > 0,
|
||||
"row group 1 must reach staging before group 2 is pulled: {obs:?}"
|
||||
);
|
||||
assert!(
|
||||
obs[2] > obs[1],
|
||||
"row group 2 must reach staging before group 3: {obs:?}"
|
||||
);
|
||||
assert!(stats.bytes_written > obs[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builder_output_with_all_kinds_writes_without_resorting_and_round_trips() {
|
||||
// Arrange: events deliberately supplied out of order; builder sorts, writer must accept.
|
||||
let d = days;
|
||||
let splits = vec![
|
||||
(
|
||||
7i32,
|
||||
SplitActionEvent {
|
||||
ex_date: d(2020, 8, 31),
|
||||
ratio: 4.0,
|
||||
declared_date: Some(d(2020, 7, 30)),
|
||||
},
|
||||
),
|
||||
(
|
||||
3i32,
|
||||
SplitActionEvent {
|
||||
ex_date: d(1999, 6, 1),
|
||||
ratio: 0.05,
|
||||
declared_date: None,
|
||||
},
|
||||
),
|
||||
];
|
||||
let dividends = vec![
|
||||
(
|
||||
7i32,
|
||||
DividendActionEvent {
|
||||
ex_date: d(2020, 8, 31),
|
||||
cash: 0.82,
|
||||
currency: "USD".to_string(),
|
||||
declared_date: Some(d(2020, 7, 30)),
|
||||
},
|
||||
),
|
||||
(
|
||||
7i32,
|
||||
DividendActionEvent {
|
||||
ex_date: d(2020, 8, 31),
|
||||
cash: 1.5,
|
||||
currency: "USD".to_string(),
|
||||
declared_date: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
3i32,
|
||||
DividendActionEvent {
|
||||
ex_date: d(2001, 3, 15),
|
||||
cash: 0.25,
|
||||
currency: "CAD".to_string(),
|
||||
declared_date: Some(d(2001, 3, 20)),
|
||||
},
|
||||
),
|
||||
];
|
||||
let delistings = vec![
|
||||
(
|
||||
7i32,
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: d(2023, 3, 13),
|
||||
successor_key: Some(70i32),
|
||||
terminal_return: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
3i32,
|
||||
DelistingOutcomeEvent {
|
||||
delist_date: d(2008, 10, 1),
|
||||
successor_key: None,
|
||||
terminal_return: Some(-1.0),
|
||||
},
|
||||
),
|
||||
];
|
||||
let built = build_corporate_actions(splits, dividends, delistings).unwrap();
|
||||
let expected: Vec<CorporateActionsParquetRow> = built
|
||||
.rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
CorporateActionsParquetRow::from_corporate_action_row(
|
||||
r,
|
||||
i64::from(r.known_at_date) * MICROS_PER_DAY,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
expected.len(),
|
||||
7,
|
||||
"builder keeps every event incl. same-day dividends"
|
||||
);
|
||||
let tmp = TempDir::new("builder");
|
||||
|
||||
// Act
|
||||
let stats = write_corporate_actions_dataset(&tmp.0, &expected, opts(2)).unwrap();
|
||||
|
||||
// Assert
|
||||
assert_eq!(stats.rows_written, 7);
|
||||
assert_eq!(stats.row_groups_written, 4);
|
||||
let actual = read_rows(&part_path(&tmp.0));
|
||||
assert_bitwise(&actual, &expected);
|
||||
let kinds: Vec<CorporateActionKind> = actual.iter().map(|r| r.kind).collect();
|
||||
assert!(kinds.contains(&CorporateActionKind::OtcDelistTransfer));
|
||||
assert!(kinds.contains(&CorporateActionKind::Delisting));
|
||||
let same_day_divs = actual
|
||||
.iter()
|
||||
.filter(|r| {
|
||||
r.listing_id == 7
|
||||
&& r.ex_date == d(2020, 8, 31)
|
||||
&& r.kind == CorporateActionKind::Dividend
|
||||
})
|
||||
.count();
|
||||
assert_eq!(same_day_divs, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currency_labels_survive_interner_reset_between_row_groups() {
|
||||
// Arrange: group 1 only CAD, group 2 only USD, group 3 a mix starting with a null currency
|
||||
// (non-dividend) — a stale interner would relabel ids across groups.
|
||||
let mk = |i: usize, cur: Option<&'static str>| {
|
||||
let ex_date = days(2010, 1, 4) + i as i32;
|
||||
match cur {
|
||||
Some(c) => CorporateActionsParquetRow {
|
||||
listing_id: 1,
|
||||
ex_date,
|
||||
declared_date: None,
|
||||
kind: CorporateActionKind::Dividend,
|
||||
ratio: None,
|
||||
cash_amount: Some(0.1 + i as f64),
|
||||
currency: Some(Cow::Borrowed(c)),
|
||||
successor_listing_id: None,
|
||||
terminal_return: None,
|
||||
known_at_micros: i64::from(ex_date) * MICROS_PER_DAY,
|
||||
known_at_source: KnownAtSource::ExDateFallback,
|
||||
},
|
||||
None => CorporateActionsParquetRow {
|
||||
listing_id: 1,
|
||||
ex_date,
|
||||
declared_date: None,
|
||||
kind: CorporateActionKind::Split,
|
||||
ratio: Some(2.0),
|
||||
cash_amount: None,
|
||||
currency: None,
|
||||
successor_listing_id: None,
|
||||
terminal_return: None,
|
||||
known_at_micros: i64::from(ex_date) * MICROS_PER_DAY,
|
||||
known_at_source: KnownAtSource::ExDateFallback,
|
||||
},
|
||||
}
|
||||
};
|
||||
let rows = vec![
|
||||
mk(0, Some("CAD")),
|
||||
mk(1, Some("CAD")),
|
||||
mk(2, Some("USD")),
|
||||
mk(3, Some("USD")),
|
||||
mk(4, None),
|
||||
mk(5, Some("USD")),
|
||||
mk(6, Some("CAD")),
|
||||
];
|
||||
let tmp = TempDir::new("interner");
|
||||
|
||||
// Act
|
||||
write_corporate_actions_dataset(&tmp.0, &rows, opts(2)).unwrap();
|
||||
|
||||
// Assert
|
||||
let back = read_rows(&part_path(&tmp.0));
|
||||
let currencies: Vec<Option<&str>> = back.iter().map(|r| r.currency.as_deref()).collect();
|
||||
assert_eq!(
|
||||
currencies,
|
||||
vec![
|
||||
Some("CAD"),
|
||||
Some("CAD"),
|
||||
Some("USD"),
|
||||
Some("USD"),
|
||||
None,
|
||||
Some("USD"),
|
||||
Some("CAD")
|
||||
]
|
||||
);
|
||||
assert_bitwise(&back, &rows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_invalid_row_after_flushed_row_groups_preserves_seeded_file_and_cleans_up() {
|
||||
// Arrange: seed a valid part.parquet, then stream 3 full row groups plus a bad last row.
|
||||
let tmp = TempDir::new("late-fail");
|
||||
let mut rng = Rng(0xC0A0_0096_0000_0003);
|
||||
let seed_rows: Vec<_> = (0..16).map(|i| random_row(i, &mut rng)).collect();
|
||||
write_corporate_actions_dataset(&tmp.0, &seed_rows, opts(4)).unwrap();
|
||||
let before = fs::read(part_path(&tmp.0)).unwrap();
|
||||
|
||||
let mut rows: Vec<_> = (0..30_000).map(|i| random_row(i, &mut rng)).collect();
|
||||
let mut bad = rows.last().unwrap().clone();
|
||||
bad.listing_id += 1;
|
||||
bad.kind = CorporateActionKind::Delisting;
|
||||
bad.ratio = None;
|
||||
bad.cash_amount = None;
|
||||
bad.currency = None;
|
||||
bad.successor_listing_id = None;
|
||||
bad.terminal_return = Some(-1.000_000_1);
|
||||
bad.known_at_source = KnownAtSource::DelistDate;
|
||||
rows.push(bad.clone());
|
||||
|
||||
// Act
|
||||
let err = write_corporate_actions_dataset(&tmp.0, &rows, opts(10_000)).unwrap_err();
|
||||
|
||||
// Assert
|
||||
match err {
|
||||
ParquetCorporateActionsError::InvalidTerminalReturn {
|
||||
listing_id,
|
||||
ex_date,
|
||||
value,
|
||||
} => {
|
||||
assert_eq!(listing_id, bad.listing_id);
|
||||
assert_eq!(ex_date, bad.ex_date);
|
||||
assert_eq!(bits(value), bits(Some(-1.000_000_1)));
|
||||
}
|
||||
other => panic!("expected InvalidTerminalReturn, got {other:?}"),
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(part_path(&tmp.0)).unwrap(),
|
||||
before,
|
||||
"seed file byte-identical"
|
||||
);
|
||||
assert!(
|
||||
leftover_transients(&tmp.0).is_empty(),
|
||||
"no staging/backup/lock left: {:?}",
|
||||
leftover_transients(&tmp.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsorted_kind_within_same_listing_and_date_is_rejected_with_both_keys() {
|
||||
// Arrange: dividend then split on the same (listing_id, ex_date) violates kind order.
|
||||
let tmp = TempDir::new("unsorted-kind");
|
||||
let mut rng = Rng(0xC0A0_0096_0000_0004);
|
||||
let mut div = random_row(1, &mut rng);
|
||||
while div.kind != CorporateActionKind::Dividend {
|
||||
div = random_row(1, &mut rng);
|
||||
}
|
||||
let split = CorporateActionsParquetRow {
|
||||
kind: CorporateActionKind::Split,
|
||||
ratio: Some(2.0),
|
||||
cash_amount: None,
|
||||
currency: None,
|
||||
..div.clone()
|
||||
};
|
||||
|
||||
// Act
|
||||
let err = write_corporate_actions_dataset(&tmp.0, [&div, &split], opts(1)).unwrap_err();
|
||||
|
||||
// Assert
|
||||
match err {
|
||||
ParquetCorporateActionsError::UnsortedInput {
|
||||
prev_listing_id,
|
||||
prev_ex_date,
|
||||
prev_kind,
|
||||
listing_id,
|
||||
ex_date,
|
||||
kind,
|
||||
} => {
|
||||
assert_eq!(
|
||||
(prev_listing_id, prev_ex_date, prev_kind),
|
||||
(div.listing_id, div.ex_date, CorporateActionKind::Dividend)
|
||||
);
|
||||
assert_eq!(
|
||||
(listing_id, ex_date, kind),
|
||||
(div.listing_id, div.ex_date, CorporateActionKind::Split)
|
||||
);
|
||||
}
|
||||
other => panic!("expected UnsortedInput, got {other:?}"),
|
||||
}
|
||||
assert!(!part_path(&tmp.0).exists());
|
||||
assert!(leftover_transients(&tmp.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_options_are_rejected_before_a_finite_iterator_is_polled() {
|
||||
// Arrange: finite probes (once_with) so a regression cannot buffer rows unboundedly.
|
||||
let tmp = TempDir::new("options");
|
||||
let polled = Cell::new(0usize);
|
||||
let make_probe = || {
|
||||
std::iter::once_with(|| {
|
||||
polled.set(polled.get() + 1);
|
||||
let mut rng = Rng(0xC0A0_0096_0000_0005);
|
||||
random_row(0, &mut rng)
|
||||
})
|
||||
};
|
||||
|
||||
// Act
|
||||
let zero_rg = write_corporate_actions_dataset(&tmp.0, make_probe(), opts(0)).unwrap_err();
|
||||
let bad_zstd = write_corporate_actions_dataset(
|
||||
&tmp.0,
|
||||
make_probe(),
|
||||
CorporateActionsWriteOptions {
|
||||
zstd_level: 23,
|
||||
..CorporateActionsWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
// Assert
|
||||
assert!(matches!(
|
||||
zero_rg,
|
||||
ParquetCorporateActionsError::InvalidRowGroupRows
|
||||
));
|
||||
assert!(matches!(
|
||||
bad_zstd,
|
||||
ParquetCorporateActionsError::InvalidZstdLevel { level: 23 }
|
||||
));
|
||||
assert_eq!(
|
||||
polled.get(),
|
||||
0,
|
||||
"iterator must not be polled on invalid options"
|
||||
);
|
||||
assert!(
|
||||
!dataset_dir(&tmp.0).exists(),
|
||||
"no dataset directory created"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue