diff --git a/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs b/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs new file mode 100644 index 00000000..5b31b765 --- /dev/null +++ b/tools/curate-etl/tests/run_curate_corporate_actions_qa_contract.rs @@ -0,0 +1,604 @@ +//! QA contract tests for the `curate-corporate-actions` command (T-112 / M1.2ab). +//! +//! Exercises only the public crate API and the built binary, and checks the runner against a +//! hand-computed oracle instead of the crate's own stage: +//! - file -> Parquet output equals hand-written expected rows (all 11 columns, bit-exact), with +//! `known_at` checked against literal UTC instants for 16:00 ET in EST and EDT, late declarations +//! clamped to `ex_date` (no look-ahead), `usdFxRate` ignored, `1:1` / `0.0` cash dropped, an OTC +//! transfer across an ended outgoing range, ticker reuse, foreign mapping sources ignored, and a +//! delisting whose `from_listing_id` disagrees with the mapping dropped; +//! - the binary prints the deterministic report, exits 0, and the report counters agree with the +//! oracle fixture; +//! - binary runtime failure on a bad delistings TSV row: single-line stderr with `path:line:`, +//! exit 1, no usage text, `--out` not created; +//! - a corrupt BSON document in the middle of `qmSplits` fails the binary and leaves the previous +//! dataset byte-identical. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use curate_etl::{ + run_curate_corporate_actions, ymd_to_epoch_days, CorporateActionKind, + CorporateActionsParquetRow, CurateCorporateActionsArgs, KnownAtSource, +}; + +const MICROS_PER_DAY: i64 = 86_400_000_000; +const MICROS_PER_HOUR: i64 = 3_600_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-run-ca-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } + + fn join(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn write_file(path: &Path, bytes: &[u8]) { + File::create(path) + .and_then(|mut f| f.write_all(bytes)) + .expect("write fixture"); +} + +fn days(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +/// 16:00 EST == 21:00 UTC. +fn close_est(day: i32) -> i64 { + i64::from(day) * MICROS_PER_DAY + 21 * MICROS_PER_HOUR +} + +/// 16:00 EDT == 20:00 UTC. +fn close_edt(day: i32) -> i64 { + i64::from(day) * MICROS_PER_DAY + 20 * MICROS_PER_HOUR +} + +fn split_doc(code: &str, date: &str, declared: Option<&str>, ratio: f64) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + if let Some(d) = declared { + doc.append(cstr!("declared"), d); + } + doc.append(cstr!("splitratio"), ratio); + doc.append(cstr!("usdFxRate"), 1_i32); + doc.into_bytes() +} + +fn div_doc(code: &str, date: &str, declared: Option<&str>, cash: f64, currency: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + if let Some(d) = declared { + doc.append(cstr!("declared"), d); + } + doc.append(cstr!("amount"), cash); + doc.append(cstr!("currency"), currency); + // Deliberately bogus for CAD: must have no effect on the output. + doc.append(cstr!("usdFxRate"), 1_i32); + doc.into_bytes() +} + +const MAPPING_TSV: &str = "\ +qm\tAAPL:US\t1970-01-01\t\t1\n\ +qm\tXYZ:CA\t1970-01-01\t\t2\n\ +qm\tSIVB:US\t1970-01-01\t2023-03-27\t3\n\ +qm\tSIVB:US\t2024-01-01\t\t30\n\ +qm\tSIVBQ:US\t2023-03-28\t\t4\n\ +qm\tDEAD:US\t1970-01-01\t\t5\n\ +qm\tGONE:US\t1970-01-01\t\t6\n\ +eod\tAAPL:US\t1970-01-01\t\t99\n\ +eod\tNOTQM:US\t1970-01-01\t\t98\n"; + +const DELISTINGS_TSV: &str = "\ +SIVB:US\t2023-03-28\t3\tSIVBQ:US\t\n\ +DEAD:US\t2021-11-10\t\t\t-0.3\n\ +GONE:US\t2022-03-01\t6\t\t-1.0\n\ +SIVB:US\t2024-06-03\t\t\t-1.0\n\ +AAPL:US\t2022-05-02\t7\t\t-0.5\n\ +NOTQM:US\t2022-05-02\t\t\t-1.0\n"; + +struct Fixture { + _dir: TempDir, + args: CurateCorporateActionsArgs, +} + +fn oracle_fixture(tag: &str) -> Fixture { + let dir = TempDir::new(tag); + let mut splits = Vec::new(); + splits.extend(split_doc("AAPL:US", "2020-08-31", Some("2020-07-30"), 4.0)); + splits.extend(split_doc("XYZ:CA", "2020-01-15", None, 0.05)); + splits.extend(split_doc("AAPL:US", "2021-01-04", Some("2020-12-01"), 1.0)); + splits.extend(split_doc("UNMAPPED:US", "2020-05-05", None, 2.0)); + let mut divs = Vec::new(); + divs.extend(div_doc( + "AAPL:US", + "2020-02-07", + Some("2020-01-28"), + 0.77, + "USD", + )); + divs.extend(div_doc( + "XYZ:CA", + "2020-06-15", + Some("2020-06-20"), + 0.5, + "CAD", + )); + divs.extend(div_doc("AAPL:US", "2020-05-08", None, 0.0, "USD")); + + let args = CurateCorporateActionsArgs { + qm_splits: dir.join("qmSplits.bson"), + qm_dividends: dir.join("qmDividends.bson"), + provider_mapping: dir.join("provider_mapping.tsv"), + delistings: Some(dir.join("delistings.tsv")), + out_dir: dir.join("out"), + }; + write_file(&args.qm_splits, &splits); + write_file(&args.qm_dividends, &divs); + write_file(&args.provider_mapping, MAPPING_TSV.as_bytes()); + write_file(args.delistings.as_ref().unwrap(), DELISTINGS_TSV.as_bytes()); + Fixture { _dir: dir, args } +} + +fn row( + listing_id: i32, + ex_date: i32, + declared_date: Option, + kind: CorporateActionKind, +) -> CorporateActionsParquetRow { + 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: 0, + known_at_source: KnownAtSource::ExDateFallback, + } +} + +/// Hand-computed expected output for [`oracle_fixture`], sorted by `(listing_id, ex_date, kind)`. +fn oracle_rows() -> Vec { + use CorporateActionKind::*; + vec![ + // AAPL dividend, declared 2020-01-28 (EST). + CorporateActionsParquetRow { + cash_amount: Some(0.77), + currency: Some(Cow::Borrowed("USD")), + known_at_micros: close_est(days(2020, 1, 28)), + known_at_source: KnownAtSource::DeclaredDate, + ..row(1, days(2020, 2, 7), Some(days(2020, 1, 28)), Dividend) + }, + // AAPL 4:1 split, declared 2020-07-30 (EDT). + CorporateActionsParquetRow { + ratio: Some(4.0), + known_at_micros: close_edt(days(2020, 7, 30)), + known_at_source: KnownAtSource::DeclaredDate, + ..row(1, days(2020, 8, 31), Some(days(2020, 7, 30)), Split) + }, + // XYZ 1:20 reverse split, no declared -> ex_date fallback (EST). + CorporateActionsParquetRow { + ratio: Some(0.05), + known_at_micros: close_est(days(2020, 1, 15)), + known_at_source: KnownAtSource::ExDateFallback, + ..row(2, days(2020, 1, 15), None, Split) + }, + // XYZ CAD dividend declared after ex_date -> clamped to ex_date (EDT), no look-ahead. + CorporateActionsParquetRow { + cash_amount: Some(0.5), + currency: Some(Cow::Borrowed("CAD")), + known_at_micros: close_edt(days(2020, 6, 15)), + known_at_source: KnownAtSource::ExDateFallback, + ..row(2, days(2020, 6, 15), Some(days(2020, 6, 20)), Dividend) + }, + // SIVB -> SIVBQ OTC transfer across the ended outgoing range (EDT; DST began 2023-03-12). + CorporateActionsParquetRow { + successor_listing_id: Some(4), + known_at_micros: close_edt(days(2023, 3, 28)), + known_at_source: KnownAtSource::DelistDate, + ..row(3, days(2023, 3, 28), None, OtcDelistTransfer) + }, + // DEAD -0.3 terminal (EST; DST ended 2021-11-07). + CorporateActionsParquetRow { + terminal_return: Some(-0.3), + known_at_micros: close_est(days(2021, 11, 10)), + known_at_source: KnownAtSource::DelistDate, + ..row(5, days(2021, 11, 10), None, Delisting) + }, + // GONE -1.0 terminal with matching from_listing_id (EST). + CorporateActionsParquetRow { + terminal_return: Some(-1.0), + known_at_micros: close_est(days(2022, 3, 1)), + known_at_source: KnownAtSource::DelistDate, + ..row(6, days(2022, 3, 1), None, Delisting) + }, + // Reused SIVB ticker resolves to the new occupant on 2024-06-03 (EDT). + CorporateActionsParquetRow { + terminal_return: Some(-1.0), + known_at_micros: close_edt(days(2024, 6, 3)), + known_at_source: KnownAtSource::DelistDate, + ..row(30, days(2024, 6, 3), None, Delisting) + }, + ] +} + +fn expand(vals: Vec, defs: Vec, n: usize) -> Vec> { + if defs.is_empty() { + assert_eq!(vals.len(), n); + return vals.into_iter().map(Some).collect(); + } + assert_eq!(defs.len(), n); + let mut it = vals.into_iter(); + let out = defs + .iter() + .map(|&d| if d == 0 { None } else { it.next() }) + .collect(); + assert!(it.next().is_none(), "every value consumed"); + out +} + +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:?}"), + } +} + +fn read_rows(path: &Path) -> Vec { + 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> { + 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"); + expand(v, d, n) + }; + let f64s = |idx: usize| -> Vec> { + 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> { + let (mut v, mut d) = (Vec::new(), 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, Some(&mut d), None, &mut v).expect("read"); + expand(v, d, n) + }; + let strs = |idx: usize| -> Vec> { + 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 = v + .into_iter() + .map(|b| String::from_utf8(b.data().to_vec()).expect("utf8")) + .collect(); + expand(v, d, n) + }; + let (lid, ed, decl, kind) = (i32s(0), i32s(1), i32s(2), strs(3)); + let (ratio, cash, cur, succ) = (f64s(4), f64s(5), strs(6), i32s(7)); + let (tr, ka, src) = (f64s(8), i64s(9), strs(10)); + for i in 0..n { + out.push(CorporateActionsParquetRow { + listing_id: lid[i].expect("listing_id"), + ex_date: ed[i].expect("ex_date"), + declared_date: decl[i], + kind: parse_kind(kind[i].as_deref().expect("kind")), + 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].expect("known_at"), + known_at_source: parse_source(src[i].as_deref().expect("source")), + }); + } + } + out +} + +fn bits(v: Option) -> Option { + v.map(f64::to_bits) +} + +fn assert_rows_bitwise( + actual: &[CorporateActionsParquetRow], + expected: &[CorporateActionsParquetRow], +) { + assert_eq!(actual.len(), expected.len(), "row count: {actual:#?}"); + 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" + ); + 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_micros" + ); + assert_eq!( + a.known_at_source, e.known_at_source, + "row {i} known_at_source" + ); + } +} + +fn part_path(out_dir: &Path) -> PathBuf { + out_dir.join("corporate_actions").join("part.parquet") +} + +fn dir_names(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir) + .expect("read dir") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +fn bin() -> Command { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) +} + +fn cli_args(args: &CurateCorporateActionsArgs) -> Vec { + let mut v = vec![ + "curate-corporate-actions".to_string(), + format!("--qm-splits={}", args.qm_splits.display()), + format!("--qm-dividends={}", args.qm_dividends.display()), + format!("--provider-mapping={}", args.provider_mapping.display()), + format!("--out={}", args.out_dir.display()), + ]; + if let Some(d) = &args.delistings { + v.push(format!("--delistings={}", d.display())); + } + v +} + +#[test] +fn run_output_matches_hand_computed_oracle_rows_bit_for_bit() { + let fx = oracle_fixture("oracle"); + + let report = run_curate_corporate_actions(&fx.args).expect("run succeeds"); + + let actual = read_rows(&part_path(&fx.args.out_dir)); + assert_rows_bitwise(&actual, &oracle_rows()); + assert_eq!(report.write_stats.rows_written, 8); + assert_eq!(report.curate_stats.rows_out, 8); + // Only `part.parquet` is left in the dataset dir: no temp/lock/backup files. + assert_eq!( + dir_names(&fx.args.out_dir.join("corporate_actions")), + vec!["part.parquet".to_string()] + ); +} + +#[test] +fn run_report_counters_match_oracle_fixture_drops() { + let fx = oracle_fixture("counters"); + + let r = run_curate_corporate_actions(&fx.args).expect("run succeeds"); + + assert_eq!(r.splits_docs_framed, 4); + assert_eq!(r.splits_decode.decoded, 4); + assert_eq!(r.splits_decode.rejected_total(), 0); + assert_eq!(r.dividends_docs_framed, 3); + assert_eq!(r.dividends_decode.decoded, 3); + assert_eq!(r.delistings_rows_loaded, 6); + assert_eq!(r.delistings_bytes_read, DELISTINGS_TSV.len() as u64); + let b = &r.curate_stats.builder; + assert_eq!( + (b.splits_in, b.splits_out, b.split_noops_dropped), + (4, 3, 1) + ); + assert_eq!( + ( + b.dividends_in, + b.dividends_out, + b.dividend_zero_cash_dropped + ), + (3, 2, 1) + ); + assert_eq!( + ( + b.delistings_in, + b.otc_delist_transfers_out, + b.delistings_out + ), + (6, 1, 5) + ); + assert_eq!(b.delist_without_outcome, 0); + let c = &r.curate_stats; + assert_eq!(c.rows_in, 11); + // UNMAPPED:US split, AAPL delisting with mismatched from_listing_id 7, and NOTQM:US + // (mapped only under the foreign `eod` source). + assert_eq!(c.dropped_unmapped, 3); + assert_eq!(c.dropped_unmapped_successor, 0); + assert_eq!(c.dropped_self_successor, 0); + assert_eq!(c.dropped_known_at_out_of_range, 0); + assert_eq!( + c.listing_collision_collapsed + c.listing_collision_dropped, + 0 + ); + assert_eq!(c.rows_out, 8); + assert_eq!(c.listings_out, 6); +} + +#[test] +fn binary_happy_path_prints_report_and_writes_oracle_rows() { + let fx = oracle_fixture("bin-ok"); + + let res = bin().args(cli_args(&fx.args)).output().expect("spawn"); + + assert!( + res.status.success(), + "stderr: {}", + String::from_utf8_lossy(&res.stderr) + ); + assert!( + res.stderr.is_empty(), + "stderr: {}", + String::from_utf8_lossy(&res.stderr) + ); + let stdout = String::from_utf8(res.stdout).expect("utf8"); + assert!( + stdout.starts_with("curate-etl curate-corporate-actions\n"), + "{stdout}" + ); + for needle in [ + "delistings_tsv: rows_loaded=6", + "builder: splits_in=4 splits_out=3 split_noops=1 dividends_in=3 dividends_out=2 zero_div=1 delistings_in=6 otc_out=1 delistings_out=5 delist_no_outcome=0", + "curate: rows_in=11 rows_out=8 listings_out=6 unmapped=3", + "write: rows_written=8 files_written=1", + "timing: elapsed_secs=", + ] { + assert!(stdout.contains(needle), "missing {needle:?} in:\n{stdout}"); + } + assert_rows_bitwise(&read_rows(&part_path(&fx.args.out_dir)), &oracle_rows()); +} + +#[test] +fn binary_bad_delistings_row_fails_single_line_with_path_and_line_and_leaves_out_absent() { + let fx = oracle_fixture("bin-bad-delist"); + let delist = fx.args.delistings.clone().unwrap(); + // Line 3 sets both successor and terminal_return. + write_file( + &delist, + b"DEAD:US\t2021-11-10\t\t\t-0.3\nGONE:US\t2022-03-01\t6\t\t-1.0\nSIVB:US\t2023-03-28\t3\tSIVBQ:US\t-1.0\n", + ); + + let res = bin().args(cli_args(&fx.args)).output().expect("spawn"); + + assert_eq!(res.status.code(), Some(1)); + assert!(res.stdout.is_empty()); + let stderr = String::from_utf8(res.stderr).expect("utf8"); + assert_eq!(stderr.lines().count(), 1, "single line: {stderr}"); + assert!(stderr.starts_with("error: "), "{stderr}"); + assert!( + stderr.contains(&format!("{}:3:", delist.display())), + "path:line in {stderr}" + ); + assert!( + !stderr.contains("Usage") && !stderr.contains("usage"), + "{stderr}" + ); + assert!(!fx.args.out_dir.exists(), "--out must not be created"); +} + +#[test] +fn binary_corrupt_mid_stream_split_doc_fails_and_keeps_previous_dataset_byte_identical() { + let fx = oracle_fixture("bin-corrupt"); + run_curate_corporate_actions(&fx.args).expect("seed run"); + let before = fs::read(part_path(&fx.args.out_dir)).expect("read seeded part"); + + // Rewrite qmSplits: valid doc, then a doc whose trailing NUL is damaged (length intact), + // then another valid doc that would otherwise change the output. + let first = split_doc("AAPL:US", "2020-08-31", Some("2020-07-30"), 4.0); + let mut bad = split_doc("XYZ:CA", "2020-01-15", None, 0.05); + let last = bad.len() - 1; + bad[last] = 0x7F; + let third = split_doc("DEAD:US", "2021-01-04", None, 3.0); + let mut bytes = first.clone(); + bytes.extend(&bad); + bytes.extend(&third); + write_file(&fx.args.qm_splits, &bytes); + + let res = bin().args(cli_args(&fx.args)).output().expect("spawn"); + + assert_eq!(res.status.code(), Some(1)); + let stderr = String::from_utf8(res.stderr).expect("utf8"); + assert_eq!(stderr.lines().count(), 1, "single line: {stderr}"); + assert!( + stderr.contains(&fx.args.qm_splits.display().to_string()), + "{stderr}" + ); + assert!( + stderr.contains(&format!("byte offset {}", first.len())), + "offset of the corrupt doc in: {stderr}" + ); + assert_eq!( + fs::read(part_path(&fx.args.out_dir)).expect("read part"), + before + ); + assert_eq!( + dir_names(&fx.args.out_dir.join("corporate_actions")), + vec!["part.parquet".to_string()] + ); +}