526 lines
19 KiB
Rust
526 lines
19 KiB
Rust
//! QA contract tests for the `curate-adj-factors` command (T-111 / M1.2aa).
|
|
//!
|
|
//! Covers gaps left by `src/run_curate_adj_tests.rs` and `tests/cli.rs`, checking the runner
|
|
//! against independent references instead of its own logic:
|
|
//! - seeded randomized differential: file -> Parquet command output vs a naive in-test linear-scan
|
|
//! `prev_close` reference (last bar with `session_date < ex_date` for the listing the code maps
|
|
//! to on `ex_date`) feeding the public `curate_adj_factors` stage directly;
|
|
//! - `bars_1d` partition discovery: non-`year=YYYY` entries are ignored, a `year=YYYY` directory
|
|
//! without `part.parquet` fails closed and leaves the previous snapshot byte-identical;
|
|
//! - rerun semantics: the same inputs republish a byte-identical snapshot, and new inputs replace
|
|
//! it in place;
|
|
//! - binary runtime failure: single-line stderr naming the path, exit code 1, `--out` not created.
|
|
|
|
use std::borrow::Cow;
|
|
use std::collections::BTreeSet;
|
|
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 curate_etl::{
|
|
curate_adj_factors, epoch_days_to_ymd, et_session_close_utc_micros, read_adj_factors_dataset,
|
|
run_curate_adj_factors, write_bars_1d_dataset, ymd_to_epoch_days, AdjFactorsParquetRow,
|
|
Bars1dParquetRow, Bars1dWriteOptions, CurateAdjFactorsArgs, CurateAdjFactorsRunReport,
|
|
DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent,
|
|
};
|
|
|
|
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-adj-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);
|
|
}
|
|
}
|
|
|
|
/// 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)
|
|
}
|
|
|
|
fn below(&mut self, n: u64) -> u64 {
|
|
self.next_u64() % n
|
|
}
|
|
}
|
|
|
|
fn write_file(path: &Path, bytes: &[u8]) {
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent).expect("create parent dirs");
|
|
}
|
|
File::create(path)
|
|
.and_then(|mut f| f.write_all(bytes))
|
|
.expect("write fixture");
|
|
}
|
|
|
|
fn ymd_string(days: i32) -> String {
|
|
let (y, m, d) = epoch_days_to_ymd(days);
|
|
format!("{y:04}-{m:02}-{d:02}")
|
|
}
|
|
|
|
fn days(y: i32, m: u32, d: u32) -> i32 {
|
|
ymd_to_epoch_days(y, m, d).expect("valid date")
|
|
}
|
|
|
|
fn is_weekday(day: i32) -> bool {
|
|
// 1970-01-01 was a Thursday.
|
|
!matches!((day + 4).rem_euclid(7), 0 | 6)
|
|
}
|
|
|
|
fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
|
|
let mut doc = RawDocumentBuf::new();
|
|
doc.append(cstr!("qmSearchCode"), code);
|
|
doc.append(cstr!("date"), date);
|
|
if ratio.is_finite() && ratio > 0.0 {
|
|
doc.append(cstr!("splitratio"), 1.0 / ratio);
|
|
doc.append(cstr!("forfactor"), 1.0_f64);
|
|
doc.append(cstr!("tofactor"), ratio);
|
|
} else {
|
|
doc.append(cstr!("splitratio"), ratio);
|
|
}
|
|
doc.into_bytes()
|
|
}
|
|
|
|
fn div_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec<u8> {
|
|
let mut doc = RawDocumentBuf::new();
|
|
doc.append(cstr!("qmSearchCode"), code);
|
|
doc.append(cstr!("date"), date);
|
|
doc.append(cstr!("amount"), cash);
|
|
doc.append(cstr!("currency"), currency);
|
|
doc.append(cstr!("usdFxRate"), 1_i32);
|
|
doc.into_bytes()
|
|
}
|
|
|
|
fn bar(listing_id: i32, session_date: i32, close: f64, currency: &'static str) -> Bars1dParquetRow {
|
|
let ts_micros = et_session_close_utc_micros(session_date).expect("valid ts");
|
|
Bars1dParquetRow {
|
|
listing_id,
|
|
ts_micros,
|
|
session_date,
|
|
open: close,
|
|
high: close + 1.0,
|
|
low: close - 1.0,
|
|
close,
|
|
volume: 10_000.0,
|
|
vwap: None,
|
|
currency: Cow::Borrowed(currency),
|
|
source: Cow::Borrowed("eod"),
|
|
known_at_micros: ts_micros,
|
|
}
|
|
}
|
|
|
|
fn assert_rows_bit_eq(got: &[AdjFactorsParquetRow], expected: &[AdjFactorsParquetRow]) {
|
|
assert_eq!(got.len(), expected.len(), "row count");
|
|
for (i, (a, b)) in got.iter().zip(expected).enumerate() {
|
|
assert_eq!(a.listing_id, b.listing_id, "row {i} listing_id");
|
|
assert_eq!(a.ex_date, b.ex_date, "row {i} ex_date");
|
|
assert_eq!(
|
|
a.split_factor.to_bits(),
|
|
b.split_factor.to_bits(),
|
|
"row {i} split_factor"
|
|
);
|
|
assert_eq!(
|
|
a.div_cash.to_bits(),
|
|
b.div_cash.to_bits(),
|
|
"row {i} div_cash"
|
|
);
|
|
assert_eq!(a.div_currency, b.div_currency, "row {i} div_currency");
|
|
assert_eq!(
|
|
a.cum_split_factor.to_bits(),
|
|
b.cum_split_factor.to_bits(),
|
|
"row {i} cum_split_factor"
|
|
);
|
|
assert_eq!(
|
|
a.cum_total_factor.to_bits(),
|
|
b.cum_total_factor.to_bits(),
|
|
"row {i} cum_total_factor"
|
|
);
|
|
assert_eq!(
|
|
a.known_at_micros, b.known_at_micros,
|
|
"row {i} known_at_micros"
|
|
);
|
|
}
|
|
}
|
|
|
|
fn assert_conservation(r: &CurateAdjFactorsRunReport) {
|
|
assert_eq!(r.splits_docs_framed as usize, r.splits_decode.docs_in);
|
|
assert_eq!(
|
|
r.splits_decode.docs_in,
|
|
r.splits_decode.rejected_total()
|
|
+ r.curate_stats.splits_dropped_unmapped
|
|
+ r.curate_stats.splits_dropped_fenced
|
|
+ r.curate_stats.splits_collision_collapsed
|
|
+ r.curate_stats.builder.split_events_in
|
|
);
|
|
assert_eq!(r.dividends_docs_framed as usize, r.dividends_decode.docs_in);
|
|
assert_eq!(
|
|
r.dividends_decode.docs_in,
|
|
r.dividends_decode.rejected_total()
|
|
+ r.curate_stats.dividends_dropped_unmapped
|
|
+ r.curate_stats.dividends_dropped_fenced
|
|
+ r.curate_stats.dividends_collision_collapsed
|
|
+ r.curate_stats.builder.dividend_events_in
|
|
);
|
|
assert_eq!(
|
|
r.dividends_decode.decoded,
|
|
r.dividends_with_prev_close
|
|
+ r.dividends_without_prev_close
|
|
+ r.curate_stats.dividends_dropped_unmapped
|
|
);
|
|
}
|
|
|
|
fn currency_of(listing_id: i32) -> &'static str {
|
|
if listing_id % 2 == 0 {
|
|
"CAD"
|
|
} else {
|
|
"USD"
|
|
}
|
|
}
|
|
|
|
fn mapping_tsv(rows: &[ProviderMappingRow]) -> String {
|
|
rows.iter()
|
|
.map(|r| {
|
|
format!(
|
|
"{}\t{}\t{}\t{}\t{}\n",
|
|
r.source,
|
|
r.source_id,
|
|
ymd_string(r.valid_from),
|
|
r.valid_to.map(ymd_string).unwrap_or_default(),
|
|
r.listing_id
|
|
)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn seeded_differential_prev_close_matches_naive_linear_scan_reference() {
|
|
let tmp = TempDir::new("diff");
|
|
let mut rng = Rng(0x0A0D_1111_C0DE_F00D);
|
|
|
|
// Listings 1..=10 each own code `Q{lid}:US` open-ended; `REUSE:US` maps to 11 during 2019
|
|
// and to 12 from 2020-06-01 (gap 2020-01-01..2020-05-31 is unmapped).
|
|
let mut mapping_rows: Vec<ProviderMappingRow> = (1..=10)
|
|
.map(|lid| ProviderMappingRow {
|
|
source: "qm".to_string(),
|
|
source_id: format!("Q{lid}:US"),
|
|
valid_from: days(2015, 1, 1),
|
|
valid_to: None,
|
|
listing_id: lid,
|
|
})
|
|
.collect();
|
|
mapping_rows.push(ProviderMappingRow {
|
|
source: "qm".to_string(),
|
|
source_id: "REUSE:US".to_string(),
|
|
valid_from: days(2019, 1, 1),
|
|
valid_to: Some(days(2019, 12, 31)),
|
|
listing_id: 11,
|
|
});
|
|
mapping_rows.push(ProviderMappingRow {
|
|
source: "qm".to_string(),
|
|
source_id: "REUSE:US".to_string(),
|
|
valid_from: days(2020, 6, 1),
|
|
valid_to: None,
|
|
listing_id: 12,
|
|
});
|
|
let map_path = tmp.join("provider_mapping.tsv");
|
|
write_file(&map_path, mapping_tsv(&mapping_rows).as_bytes());
|
|
let mapping = ProviderMappingTable::from_rows(mapping_rows.clone()).expect("mapping");
|
|
|
|
// Bars: random weekday sessions in 2018..=2021 per listing (listing 7 has no bars at all).
|
|
let bar_lo = days(2018, 1, 1);
|
|
let bar_hi = days(2021, 12, 31);
|
|
let mut bars: Vec<(i32, i32, f64)> = Vec::new();
|
|
for lid in 1..=12 {
|
|
if lid == 7 {
|
|
continue;
|
|
}
|
|
let mut dates = BTreeSet::new();
|
|
while dates.len() < 60 {
|
|
let d = bar_lo + rng.below((bar_hi - bar_lo + 1) as u64) as i32;
|
|
if is_weekday(d) {
|
|
dates.insert(d);
|
|
}
|
|
}
|
|
for d in dates {
|
|
let close = 20.0 + (rng.below(18_000) as f64) / 100.0;
|
|
bars.push((lid, d, close));
|
|
}
|
|
}
|
|
let bar_rows: Vec<Bars1dParquetRow> = bars
|
|
.iter()
|
|
.map(|&(lid, d, close)| bar(lid, d, close, currency_of(lid)))
|
|
.collect();
|
|
let bars_root = tmp.join("bars_root");
|
|
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).expect("bars");
|
|
|
|
// Dividends + splits: distinct dates per code in 2017..=2022; ~35% land exactly on a bar date
|
|
// of the mapped listing so the strict `<` boundary is exercised many times.
|
|
let ev_lo = days(2017, 1, 1);
|
|
let ev_hi = days(2022, 12, 31);
|
|
let mut codes: Vec<String> = (1..=10).map(|lid| format!("Q{lid}:US")).collect();
|
|
codes.push("REUSE:US".to_string());
|
|
codes.push("NOPE:US".to_string());
|
|
|
|
let mut div_events: Vec<(String, DividendEvent)> = Vec::new();
|
|
let mut split_events: Vec<(String, SplitEvent)> = Vec::new();
|
|
let mut div_bytes = Vec::new();
|
|
let mut split_bytes = Vec::new();
|
|
let mut on_bar_date_hits = 0usize;
|
|
|
|
for code in &codes {
|
|
// Bar dates owned by the listing this code maps to on that same date.
|
|
let own_bar_dates: Vec<i32> = bars
|
|
.iter()
|
|
.filter(|&&(bl, bd, _)| mapping.resolve("qm", code, bd) == Some(bl))
|
|
.map(|&(_, bd, _)| bd)
|
|
.collect();
|
|
let mut used = BTreeSet::new();
|
|
for _ in 0..40 {
|
|
let ex_date = if !own_bar_dates.is_empty() && rng.below(100) < 35 {
|
|
on_bar_date_hits += 1;
|
|
own_bar_dates[rng.below(own_bar_dates.len() as u64) as usize]
|
|
} else {
|
|
ev_lo + rng.below((ev_hi - ev_lo + 1) as u64) as i32
|
|
};
|
|
if !used.insert(ex_date) {
|
|
continue;
|
|
}
|
|
let lid = mapping.resolve("qm", code, ex_date);
|
|
let natural_ccy = lid.map(currency_of).unwrap_or("USD");
|
|
let ccy = if rng.below(10) == 0 {
|
|
if natural_ccy == "USD" {
|
|
"CAD"
|
|
} else {
|
|
"USD"
|
|
}
|
|
} else {
|
|
natural_ccy
|
|
};
|
|
let cash = (1 + rng.below(150)) as f64 / 100.0;
|
|
|
|
// Naive reference: linear scan for the max session_date < ex_date of the mapped listing.
|
|
let (prev_close, prev_ccy) = match lid {
|
|
Some(l) => bars
|
|
.iter()
|
|
.filter(|&&(bl, bd, _)| bl == l && bd < ex_date)
|
|
.max_by_key(|&&(_, bd, _)| bd)
|
|
.map(|&(_, _, c)| (Some(c), Some(currency_of(l).to_string())))
|
|
.unwrap_or((None, None)),
|
|
None => (None, None),
|
|
};
|
|
div_bytes.extend(div_doc(code, &ymd_string(ex_date), cash, ccy));
|
|
div_events.push((
|
|
code.clone(),
|
|
DividendEvent {
|
|
ex_date,
|
|
cash,
|
|
currency: ccy.to_string(),
|
|
prev_close,
|
|
prev_close_currency: prev_ccy,
|
|
},
|
|
));
|
|
|
|
if rng.below(8) == 0 {
|
|
let ratio = [2.0, 3.0, 0.5, 1.0][rng.below(4) as usize];
|
|
split_bytes.extend(split_doc(code, &ymd_string(ex_date), ratio));
|
|
split_events.push((code.clone(), SplitEvent { ex_date, ratio }));
|
|
}
|
|
}
|
|
}
|
|
assert!(
|
|
on_bar_date_hits > 20,
|
|
"fixture must exercise ex_date == bar date"
|
|
);
|
|
|
|
let splits_path = tmp.join("qmSplits.bson");
|
|
let divs_path = tmp.join("qmDividends.bson");
|
|
write_file(&splits_path, &split_bytes);
|
|
write_file(&divs_path, &div_bytes);
|
|
|
|
let out = tmp.join("out");
|
|
let report = run_curate_adj_factors(&CurateAdjFactorsArgs {
|
|
qm_splits: splits_path,
|
|
qm_dividends: divs_path,
|
|
provider_mapping: map_path,
|
|
bars_1d_dir: bars_root.join("bars_1d"),
|
|
out_dir: out.clone(),
|
|
})
|
|
.expect("run_curate_adj_factors");
|
|
assert_conservation(&report);
|
|
|
|
let expected_with = div_events
|
|
.iter()
|
|
.filter(|(_, e)| e.prev_close.is_some())
|
|
.count();
|
|
let expected_unmapped = div_events
|
|
.iter()
|
|
.filter(|(c, e)| mapping.resolve("qm", c, e.ex_date).is_none())
|
|
.count();
|
|
assert_eq!(report.dividends_with_prev_close, expected_with);
|
|
assert_eq!(
|
|
report.dividends_without_prev_close,
|
|
div_events.len() - expected_with - expected_unmapped
|
|
);
|
|
assert_eq!(
|
|
report.curate_stats.dividends_dropped_unmapped,
|
|
expected_unmapped
|
|
);
|
|
assert!(expected_unmapped > 0 && report.dividends_without_prev_close > 0);
|
|
assert!(report.curate_stats.builder.dividends_currency_mismatch > 0);
|
|
|
|
let direct = curate_adj_factors(&mapping, "qm", split_events, div_events).expect("direct");
|
|
let snap = read_adj_factors_dataset(&out).expect("read back");
|
|
assert_rows_bit_eq(&snap.rows, &direct.rows);
|
|
assert_eq!(report.curate_stats, direct.stats);
|
|
}
|
|
|
|
fn simple_fixture(tmp: &TempDir) -> CurateAdjFactorsArgs {
|
|
let map_path = tmp.join("provider_mapping.tsv");
|
|
write_file(&map_path, b"qm\tAAA:US\t2015-01-01\t\t1\n");
|
|
let bars_root = tmp.join("bars_root");
|
|
write_bars_1d_dataset(
|
|
&bars_root,
|
|
&[
|
|
bar(1, days(2023, 12, 29), 50.0, "USD"),
|
|
bar(1, days(2024, 3, 14), 60.0, "USD"),
|
|
],
|
|
Bars1dWriteOptions::default(),
|
|
)
|
|
.expect("bars");
|
|
let splits = tmp.join("qmSplits.bson");
|
|
let divs = tmp.join("qmDividends.bson");
|
|
write_file(&splits, &split_doc("AAA:US", "2024-06-03", 2.0));
|
|
write_file(&divs, &div_doc("AAA:US", "2024-03-15", 0.6, "USD"));
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits,
|
|
qm_dividends: divs,
|
|
provider_mapping: map_path,
|
|
bars_1d_dir: bars_root.join("bars_1d"),
|
|
out_dir: tmp.join("out"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn non_year_entries_are_ignored_and_year_dir_without_part_file_fails_atomically() {
|
|
let tmp = TempDir::new("partitions");
|
|
let args = simple_fixture(&tmp);
|
|
|
|
// Stray entries that are not `year=YYYY` partitions must be skipped.
|
|
write_file(&args.bars_1d_dir.join("README.txt"), b"not a partition");
|
|
fs::create_dir_all(args.bars_1d_dir.join("year=20x4")).unwrap();
|
|
fs::create_dir_all(args.bars_1d_dir.join("year=12345")).unwrap();
|
|
fs::create_dir_all(args.bars_1d_dir.join("tmp")).unwrap();
|
|
let report = run_curate_adj_factors(&args).expect("stray entries ignored");
|
|
assert_eq!(report.bars_files_read, 2);
|
|
assert_eq!(report.bars_rows_loaded, 2);
|
|
assert_eq!(report.dividends_with_prev_close, 1);
|
|
let published = args.out_dir.join("adj_factors/part.parquet");
|
|
let before = fs::read(&published).unwrap();
|
|
|
|
// A real `year=YYYY` directory with no `part.parquet` must fail closed, naming the path.
|
|
let empty_year = args.bars_1d_dir.join("year=2022");
|
|
fs::create_dir_all(&empty_year).unwrap();
|
|
let err = run_curate_adj_factors(&args).expect_err("missing part.parquet must fail");
|
|
let msg = err.to_string();
|
|
assert!(!msg.contains('\n'), "single-line error: {msg}");
|
|
assert!(msg.contains("year=2022"), "error names partition: {msg}");
|
|
assert_eq!(fs::read(&published).unwrap(), before, "snapshot untouched");
|
|
}
|
|
|
|
#[test]
|
|
fn rerun_same_inputs_is_byte_identical_and_new_inputs_replace_snapshot() {
|
|
let tmp = TempDir::new("rerun");
|
|
let args = simple_fixture(&tmp);
|
|
let published = args.out_dir.join("adj_factors/part.parquet");
|
|
|
|
run_curate_adj_factors(&args).expect("first run");
|
|
let first = fs::read(&published).unwrap();
|
|
let first_rows = read_adj_factors_dataset(&args.out_dir).unwrap().rows;
|
|
assert_eq!(first_rows.len(), 2);
|
|
|
|
run_curate_adj_factors(&args).expect("second run");
|
|
assert_eq!(
|
|
fs::read(&published).unwrap(),
|
|
first,
|
|
"rerun is byte-identical"
|
|
);
|
|
|
|
// New dividend export with an extra event replaces the snapshot.
|
|
let mut divs = div_doc("AAA:US", "2024-03-15", 0.6, "USD");
|
|
divs.extend(div_doc("AAA:US", "2024-01-02", 0.5, "USD"));
|
|
write_file(&args.qm_dividends, &divs);
|
|
let report = run_curate_adj_factors(&args).expect("third run");
|
|
assert_eq!(report.dividends_with_prev_close, 2);
|
|
let rows = read_adj_factors_dataset(&args.out_dir).unwrap().rows;
|
|
assert_eq!(rows.len(), 3);
|
|
assert!(rows.iter().any(|r| r.ex_date == days(2024, 1, 2)));
|
|
// No leftover temp files next to the published snapshot.
|
|
let entries: Vec<_> = fs::read_dir(args.out_dir.join("adj_factors"))
|
|
.unwrap()
|
|
.map(|e| e.unwrap().file_name().into_string().unwrap())
|
|
.collect();
|
|
assert_eq!(entries, vec!["part.parquet".to_string()], "{entries:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn binary_runtime_failure_prints_single_line_error_and_creates_no_out_dir() {
|
|
let tmp = TempDir::new("bin-fail");
|
|
let args = simple_fixture(&tmp);
|
|
let missing_bars = tmp.join("no_such_bars");
|
|
|
|
let output = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
|
.args([
|
|
"curate-adj-factors",
|
|
"--qm-splits",
|
|
args.qm_splits.to_str().unwrap(),
|
|
"--qm-dividends",
|
|
args.qm_dividends.to_str().unwrap(),
|
|
"--provider-mapping",
|
|
args.provider_mapping.to_str().unwrap(),
|
|
"--bars-1d",
|
|
missing_bars.to_str().unwrap(),
|
|
"--out",
|
|
args.out_dir.to_str().unwrap(),
|
|
])
|
|
.output()
|
|
.expect("spawn curate-etl");
|
|
|
|
assert_eq!(output.status.code(), Some(1));
|
|
assert!(output.stdout.is_empty());
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
assert_eq!(stderr.trim_end().lines().count(), 1, "{stderr}");
|
|
assert!(stderr.starts_with("error: "), "{stderr}");
|
|
assert!(stderr.contains("no_such_bars"), "{stderr}");
|
|
assert!(
|
|
!args.out_dir.exists(),
|
|
"--out must not be created on failure"
|
|
);
|
|
}
|