1044 lines
39 KiB
Rust
1044 lines
39 KiB
Rust
use std::borrow::Cow;
|
|
use std::fs::{self, File};
|
|
use std::io::Write;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
use bson::raw::{cstr, RawDocumentBuf};
|
|
|
|
use super::*;
|
|
use crate::bson_stream::DEFAULT_MAX_DOC_BYTES;
|
|
use crate::curate_adj::{
|
|
adj_factors_for_bar, read_adj_factors_dataset, read_adj_factors_dataset_as_of,
|
|
AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError,
|
|
};
|
|
use crate::curate_bars::BARS_1D_SOURCE_EOD;
|
|
use crate::parquet_bars::{write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions};
|
|
use crate::session_close::et_session_close_utc_micros;
|
|
use crate::split::ymd_to_epoch_days;
|
|
|
|
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
|
|
|
struct TestTempDir {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl TestTempDir {
|
|
fn new(tag: &str) -> Self {
|
|
let pid = std::process::id();
|
|
let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
|
|
let path = std::env::temp_dir().join(format!("curate-etl-run-adj-{tag}-{pid}-{seq}"));
|
|
fs::create_dir_all(&path).expect("create test temp dir");
|
|
Self { path }
|
|
}
|
|
|
|
fn path(&self) -> &Path {
|
|
&self.path
|
|
}
|
|
}
|
|
|
|
impl Drop for TestTempDir {
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
fn write_bytes(path: &Path, bytes: &[u8]) {
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent).expect("create parent dirs");
|
|
}
|
|
let mut f = File::create(path).expect("create fixture file");
|
|
f.write_all(bytes).expect("write fixture bytes");
|
|
}
|
|
|
|
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, usd_fx_rate: Option<f64>) -> 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);
|
|
if let Some(fx) = usd_fx_rate {
|
|
doc.append(cstr!("usdFxRate"), fx);
|
|
}
|
|
doc.into_bytes()
|
|
}
|
|
|
|
fn bar_row(listing_id: i32, y: i32, m: u32, d: u32, close: f64, currency: &'static str) -> Bars1dParquetRow {
|
|
let session_date = ymd_to_epoch_days(y, m, d).expect("valid bar date");
|
|
let ts_micros = et_session_close_utc_micros(session_date).expect("valid ts");
|
|
Bars1dParquetRow {
|
|
listing_id,
|
|
ts_micros,
|
|
session_date,
|
|
open: close - 0.5,
|
|
high: close + 1.0,
|
|
low: close - 1.0,
|
|
close,
|
|
volume: 100_000.0,
|
|
vwap: None,
|
|
currency: Cow::Borrowed(currency),
|
|
source: Cow::Borrowed(BARS_1D_SOURCE_EOD),
|
|
known_at_micros: ts_micros,
|
|
}
|
|
}
|
|
|
|
fn assert_row_bit_eq(a: &AdjFactorsParquetRow, b: &AdjFactorsParquetRow) {
|
|
assert_eq!(a.listing_id, b.listing_id);
|
|
assert_eq!(a.ex_date, b.ex_date);
|
|
assert_eq!(a.split_factor.to_bits(), b.split_factor.to_bits());
|
|
assert_eq!(a.div_cash.to_bits(), b.div_cash.to_bits());
|
|
assert_eq!(a.div_currency, b.div_currency);
|
|
assert_eq!(a.cum_split_factor.to_bits(), b.cum_split_factor.to_bits());
|
|
assert_eq!(a.cum_total_factor.to_bits(), b.cum_total_factor.to_bits());
|
|
assert_eq!(a.known_at_micros, b.known_at_micros);
|
|
}
|
|
|
|
fn assert_conservation(report: &CurateAdjFactorsRunReport) {
|
|
assert_eq!(
|
|
report.splits_docs_framed as usize, report.splits_decode.docs_in,
|
|
"splits_docs_framed must equal splits_decode.docs_in"
|
|
);
|
|
assert_eq!(
|
|
report.splits_decode.docs_in,
|
|
report.splits_decode.rejected_total()
|
|
+ report.curate_stats.splits_dropped_unmapped
|
|
+ report.curate_stats.splits_dropped_fenced
|
|
+ report.curate_stats.splits_collision_collapsed
|
|
+ report.curate_stats.builder.split_events_in,
|
|
"split conservation invariant failed: {report:?}"
|
|
);
|
|
assert_eq!(
|
|
report.dividends_docs_framed as usize, report.dividends_decode.docs_in,
|
|
"dividends_docs_framed must equal dividends_decode.docs_in"
|
|
);
|
|
assert_eq!(
|
|
report.dividends_decode.docs_in,
|
|
report.dividends_decode.rejected_total()
|
|
+ report.curate_stats.dividends_dropped_unmapped
|
|
+ report.curate_stats.dividends_dropped_fenced
|
|
+ report.curate_stats.dividends_collision_collapsed
|
|
+ report.curate_stats.builder.dividend_events_in,
|
|
"dividend conservation invariant failed: {report:?}"
|
|
);
|
|
assert_eq!(
|
|
report.dividends_decode.decoded,
|
|
report.dividends_with_prev_close
|
|
+ report.dividends_without_prev_close
|
|
+ report.curate_stats.dividends_dropped_unmapped,
|
|
"dividend prev_close conservation invariant failed: {report:?}"
|
|
);
|
|
}
|
|
|
|
fn strip_timing_line(report: &str) -> String {
|
|
report
|
|
.lines()
|
|
.filter(|line| !line.trim_start().starts_with("timing:"))
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
}
|
|
|
|
#[test]
|
|
fn end_to_end_round_trip_matches_direct_curate_adj_factors_bitwise_and_is_deterministic() {
|
|
let dir = TestTempDir::new("e2e-roundtrip");
|
|
let splits_a = dir.path().join("splits_a.bson");
|
|
let splits_b = dir.path().join("splits_b.bson");
|
|
let divs_a = dir.path().join("divs_a.bson");
|
|
let divs_b = dir.path().join("divs_b.bson");
|
|
let map_path = dir.path().join("provider_mapping.tsv");
|
|
let bars_root = dir.path().join("bars_root");
|
|
let out_a = dir.path().join("out_a");
|
|
let out_b = dir.path().join("out_b");
|
|
let out_timed = dir.path().join("out_timed");
|
|
|
|
write_bytes(
|
|
&map_path,
|
|
b"qm\tNVDA:US\t2010-01-01\t\t100\n\
|
|
qm\tRY:CA\t2010-01-01\t\t200\n\
|
|
qm\tRY_ALT:CA\t2010-01-01\t\t200\n",
|
|
);
|
|
|
|
// Write multi-year bars_1d dataset via write_bars_1d_dataset.
|
|
let bar_rows = vec![
|
|
bar_row(100, 2021, 7, 19, 751.19, "USD"),
|
|
bar_row(100, 2021, 7, 20, 186.12, "USD"),
|
|
bar_row(100, 2024, 6, 7, 1208.88, "USD"),
|
|
bar_row(100, 2024, 6, 10, 121.79, "USD"),
|
|
bar_row(100, 2024, 6, 11, 120.91, "USD"),
|
|
bar_row(200, 2024, 4, 24, 136.50, "CAD"),
|
|
bar_row(200, 2024, 4, 25, 135.00, "CAD"),
|
|
];
|
|
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap();
|
|
|
|
// Splits: NVDA 4:1 (2021-07-20) + 10:1 (2024-06-10) + 1:1 no-op + unmapped.
|
|
let s1 = split_doc("NVDA:US", "2021-07-20", 4.0);
|
|
let s2 = split_doc("NVDA:US", "2024-06-10", 10.0);
|
|
let s3 = split_doc("NVDA:US", "2022-03-01", 1.0);
|
|
let s4 = split_doc("UNKNOWN:US", "2023-01-05", 2.0);
|
|
write_bytes(&splits_a, &[&s1[..], &s2[..], &s3[..], &s4[..]].concat());
|
|
write_bytes(&splits_b, &[&s4[..], &s2[..], &s3[..], &s1[..]].concat());
|
|
|
|
// Dividends: NVDA USD div on 2024-06-11 (prev_close = 121.79 on 2024-06-10),
|
|
// RY:CA + RY_ALT:CA identical CAD div on 2024-04-25 with bogus usdFxRate: 1 (prev_close = 136.50 on 2024-04-24).
|
|
let d1 = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some(1.0));
|
|
let d2 = div_doc("RY:CA", "2024-04-25", 1.38, "CAD", Some(1.0));
|
|
let d3 = div_doc("RY_ALT:CA", "2024-04-25", 1.38, "CAD", Some(1.0));
|
|
write_bytes(&divs_a, &[&d1[..], &d2[..], &d3[..]].concat());
|
|
write_bytes(&divs_b, &[&d3[..], &d1[..], &d2[..]].concat());
|
|
|
|
let args_a = CurateAdjFactorsArgs {
|
|
qm_splits: splits_a,
|
|
qm_dividends: divs_a,
|
|
provider_mapping: map_path.clone(),
|
|
bars_1d_dir: bars_root.join("bars_1d"),
|
|
out_dir: out_a.clone(),
|
|
};
|
|
let report_a = run_curate_adj_factors(&args_a).expect("run_curate_adj_factors A");
|
|
assert_conservation(&report_a);
|
|
|
|
// Compare against calling curate_adj_factors directly on the same in-memory events.
|
|
let mapping = load_provider_mapping_table(&map_path).unwrap();
|
|
let direct = curate_adj_factors(
|
|
&mapping,
|
|
"qm",
|
|
vec![
|
|
(
|
|
"NVDA:US",
|
|
SplitEvent {
|
|
ex_date: ymd_to_epoch_days(2021, 7, 20).unwrap(),
|
|
ratio: 4.0,
|
|
},
|
|
),
|
|
(
|
|
"NVDA:US",
|
|
SplitEvent {
|
|
ex_date: ymd_to_epoch_days(2024, 6, 10).unwrap(),
|
|
ratio: 10.0,
|
|
},
|
|
),
|
|
(
|
|
"NVDA:US",
|
|
SplitEvent {
|
|
ex_date: ymd_to_epoch_days(2022, 3, 1).unwrap(),
|
|
ratio: 1.0,
|
|
},
|
|
),
|
|
(
|
|
"UNKNOWN:US",
|
|
SplitEvent {
|
|
ex_date: ymd_to_epoch_days(2023, 1, 5).unwrap(),
|
|
ratio: 2.0,
|
|
},
|
|
),
|
|
],
|
|
vec![
|
|
(
|
|
"NVDA:US",
|
|
DividendEvent {
|
|
ex_date: ymd_to_epoch_days(2024, 6, 11).unwrap(),
|
|
cash: 0.01,
|
|
currency: "USD".to_string(),
|
|
prev_close: Some(121.79),
|
|
prev_close_currency: Some("USD".to_string()),
|
|
},
|
|
),
|
|
(
|
|
"RY:CA",
|
|
DividendEvent {
|
|
ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(),
|
|
cash: 1.38,
|
|
currency: "CAD".to_string(),
|
|
prev_close: Some(136.50),
|
|
prev_close_currency: Some("CAD".to_string()),
|
|
},
|
|
),
|
|
(
|
|
"RY_ALT:CA",
|
|
DividendEvent {
|
|
ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(),
|
|
cash: 1.38,
|
|
currency: "CAD".to_string(),
|
|
prev_close: Some(136.50),
|
|
prev_close_currency: Some("CAD".to_string()),
|
|
},
|
|
),
|
|
],
|
|
)
|
|
.expect("direct curate_adj_factors");
|
|
|
|
let snap_a = read_adj_factors_dataset(&out_a).expect("read_adj_factors_dataset");
|
|
assert_eq!(snap_a.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot);
|
|
assert_eq!(snap_a.rows.len(), direct.rows.len());
|
|
for (got, expected) in snap_a.rows.iter().zip(direct.rows.iter()) {
|
|
assert_row_bit_eq(got, expected);
|
|
}
|
|
|
|
// Point-in-time reader must reject the retrospective snapshot automatically.
|
|
let pit_err = read_adj_factors_dataset_as_of(
|
|
&out_a,
|
|
AdjPointInTimeFence::as_of(et_session_close_utc_micros(ymd_to_epoch_days(2024, 6, 11).unwrap()).unwrap()),
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(
|
|
pit_err,
|
|
CurateAdjReadError::RetrospectiveSnapshotRejected { .. }
|
|
));
|
|
|
|
// Shuffled BSON + root bars_1d dir layout produces byte-identical Parquet and identical non-timing report.
|
|
let args_b = CurateAdjFactorsArgs {
|
|
qm_splits: splits_b,
|
|
qm_dividends: divs_b,
|
|
provider_mapping: map_path,
|
|
bars_1d_dir: bars_root, // parent root containing `bars_1d/`
|
|
out_dir: out_b.clone(),
|
|
};
|
|
let report_b = run_curate_adj_factors(&args_b).expect("run_curate_adj_factors B");
|
|
assert_conservation(&report_b);
|
|
assert_eq!(
|
|
strip_timing_line(&format_curate_adj_report(&report_a)),
|
|
strip_timing_line(&format_curate_adj_report(&report_b))
|
|
);
|
|
assert_eq!(
|
|
fs::read(out_a.join("adj_factors/part.parquet")).unwrap(),
|
|
fs::read(out_b.join("adj_factors/part.parquet")).unwrap()
|
|
);
|
|
|
|
// Stage-timed helper produces byte-identical Parquet as well.
|
|
let args_timed = CurateAdjFactorsArgs {
|
|
out_dir: out_timed.clone(),
|
|
..args_a
|
|
};
|
|
let timed = run_curate_adj_factors_timed(&args_timed).expect("run_curate_adj_factors_timed");
|
|
assert_conservation(&timed.report);
|
|
assert_eq!(
|
|
fs::read(out_a.join("adj_factors/part.parquet")).unwrap(),
|
|
fs::read(out_timed.join("adj_factors/part.parquet")).unwrap()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn prev_close_strictly_before_ex_date_and_none_when_missing_or_unmapped() {
|
|
let dir = TestTempDir::new("prev-close-boundary");
|
|
let splits_path = dir.path().join("splits.bson");
|
|
let divs_path = dir.path().join("divs.bson");
|
|
let map_path = dir.path().join("map.tsv");
|
|
let bars_root = dir.path().join("bars_root");
|
|
let out_dir = dir.path().join("out");
|
|
|
|
write_bytes(
|
|
&map_path,
|
|
b"qm\tAAA:US\t2020-01-01\t\t1\n\
|
|
qm\tNOBAR:US\t2020-01-01\t\t2\n",
|
|
);
|
|
|
|
// Listing 1 has bars on Friday 2024-05-03 (close=100.0) and Monday 2024-05-06 (close=50.0).
|
|
// Listing 2 has no bars at all.
|
|
let bar_rows = vec![
|
|
bar_row(1, 2024, 5, 3, 100.0, "USD"),
|
|
bar_row(1, 2024, 5, 6, 50.0, "USD"),
|
|
];
|
|
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap();
|
|
|
|
write_bytes(&splits_path, b"");
|
|
let mut divs = Vec::new();
|
|
// 1. Ex-date 2024-05-06 (Monday): bar on 2024-05-06 (close=50.0) MUST NOT be used;
|
|
// must use Friday 2024-05-03 (close=100.0) -> div_factor = 1 - 2.0 / 100.0 = 0.98.
|
|
divs.extend_from_slice(&div_doc("AAA:US", "2024-05-06", 2.0, "USD", None));
|
|
// 2. Ex-date 2024-05-03 (same day as earliest bar): no bar strictly before -> prev_close = None -> factor 1.0.
|
|
divs.extend_from_slice(&div_doc("AAA:US", "2024-05-03", 1.0, "USD", None));
|
|
// 3. Listing 2 has no bars -> prev_close = None -> factor 1.0.
|
|
divs.extend_from_slice(&div_doc("NOBAR:US", "2024-05-10", 1.0, "USD", None));
|
|
// 4. Unmapped dividend -> dropped as unmapped, not counted in with/without prev_close.
|
|
divs.extend_from_slice(&div_doc("UNMAPPED:US", "2024-05-10", 1.0, "USD", None));
|
|
write_bytes(&divs_path, &divs);
|
|
|
|
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_dir.clone(),
|
|
})
|
|
.expect("run_curate_adj_factors");
|
|
assert_conservation(&report);
|
|
|
|
assert_eq!(report.dividends_with_prev_close, 1);
|
|
assert_eq!(report.dividends_without_prev_close, 2);
|
|
assert_eq!(report.curate_stats.dividends_dropped_unmapped, 1);
|
|
assert_eq!(report.curate_stats.builder.dividends_missing_prev_close, 2);
|
|
|
|
let snap = read_adj_factors_dataset(&out_dir).unwrap();
|
|
assert_eq!(snap.rows.len(), 3);
|
|
|
|
let d_may03 = ymd_to_epoch_days(2024, 5, 3).unwrap();
|
|
let d_may06 = ymd_to_epoch_days(2024, 5, 6).unwrap();
|
|
let row_may03 = snap
|
|
.rows
|
|
.iter()
|
|
.find(|r| r.listing_id == 1 && r.ex_date == d_may03)
|
|
.unwrap();
|
|
let row_may06 = snap
|
|
.rows
|
|
.iter()
|
|
.find(|r| r.listing_id == 1 && r.ex_date == d_may06)
|
|
.unwrap();
|
|
|
|
// If 2024-05-06 had wrongly used its own close (50.0), factor would be 50 / (50 - 2) = 50 / 48.
|
|
// Using strictly prior close (100.0) gives 100 / (100 - 2) = 100 / 98.
|
|
let expected_factor = 100.0 / 98.0;
|
|
assert!((row_may06.cum_total_factor - expected_factor).abs() < 1e-12);
|
|
// 2024-05-03 had no earlier bar (div factor = 1.0), compounded with 2024-05-06 -> 100 / 98.
|
|
assert!((row_may03.cum_total_factor - expected_factor).abs() < 1e-12);
|
|
|
|
let row_nobar = snap.rows.iter().find(|r| r.listing_id == 2).unwrap();
|
|
assert_eq!(row_nobar.cum_total_factor, 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn financial_invariants_nvda_chain_noop_cad_fx_ignore_mismatch_and_malformed_bson_rejects() {
|
|
let dir = TestTempDir::new("financial-invariants");
|
|
let splits_path = dir.path().join("splits.bson");
|
|
let divs_path = dir.path().join("divs.bson");
|
|
let map_path = dir.path().join("map.tsv");
|
|
let bars_root = dir.path().join("bars_root");
|
|
let out_dir = dir.path().join("out");
|
|
|
|
write_bytes(
|
|
&map_path,
|
|
b"qm\tNVDA:US\t2015-01-01\t\t10\n\
|
|
qm\tSHOP:CA\t2015-01-01\t\t20\n\
|
|
qm\tMISMATCH:CA\t2015-01-01\t\t30\n",
|
|
);
|
|
|
|
let bar_rows = vec![
|
|
bar_row(20, 2024, 5, 1, 100.0, "CAD"),
|
|
bar_row(30, 2024, 5, 1, 100.0, "CAD"),
|
|
];
|
|
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap();
|
|
|
|
// Splits: NVDA 4:1 (2021-07-20), NVDA 10:1 (2024-06-10), 1:1 no-op, plus 2 malformed BSON docs
|
|
// (one invalid date, one internally-corrupt length-framed doc).
|
|
let mut splits = Vec::new();
|
|
splits.extend_from_slice(&split_doc("NVDA:US", "2021-07-20", 4.0));
|
|
splits.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0));
|
|
splits.extend_from_slice(&split_doc("NVDA:US", "2023-01-10", 1.0));
|
|
splits.extend_from_slice(&split_doc("NVDA:US", "2023-02-29", 2.0)); // malformed date reject
|
|
// Valid outer 4-byte length prefix (12 bytes), invalid interior BSON bytes -> CorruptBson reject.
|
|
let mut corrupt_doc = Vec::from(12_i32.to_le_bytes());
|
|
corrupt_doc.extend_from_slice(&[0x7f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x01]);
|
|
splits.extend_from_slice(&corrupt_doc);
|
|
write_bytes(&splits_path, &splits);
|
|
|
|
// Dividends:
|
|
// - CAD dividend with bogus usdFxRate: 1 -> curated in CAD using CAD prev_close=100.0 -> factor = 0.95.
|
|
// - USD dividend on CAD bar -> currency mismatch -> factor = 1.0.
|
|
// - Malformed dividend (negative cash) -> decode reject without aborting.
|
|
let mut divs = Vec::new();
|
|
divs.extend_from_slice(&div_doc("SHOP:CA", "2024-05-02", 5.0, "CAD", Some(1.0)));
|
|
divs.extend_from_slice(&div_doc("MISMATCH:CA", "2024-05-02", 5.0, "USD", Some(1.0)));
|
|
divs.extend_from_slice(&div_doc("SHOP:CA", "2024-05-03", -1.0, "CAD", Some(1.0)));
|
|
write_bytes(&divs_path, &divs);
|
|
|
|
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_dir.clone(),
|
|
})
|
|
.expect("run_curate_adj_factors");
|
|
assert_conservation(&report);
|
|
|
|
assert_eq!(report.splits_docs_framed, 5);
|
|
assert_eq!(report.splits_decode.rejected_total(), 2);
|
|
assert_eq!(report.splits_decode.split_noop_ratio_one, 1);
|
|
assert_eq!(report.curate_stats.builder.split_noops_dropped, 1);
|
|
assert_eq!(report.dividends_docs_framed, 3);
|
|
assert_eq!(report.dividends_decode.rejected_total(), 1);
|
|
assert_eq!(report.curate_stats.builder.dividends_currency_mismatch, 1);
|
|
|
|
let snap = read_adj_factors_dataset(&out_dir).unwrap();
|
|
|
|
// NVDA 4:1 then 10:1 chain: cum_split_factor 40 -> 10 on rows, and 40 -> 10 -> 1 across dates.
|
|
let d_2021 = ymd_to_epoch_days(2021, 7, 20).unwrap();
|
|
let d_2024 = ymd_to_epoch_days(2024, 6, 10).unwrap();
|
|
let nvda_rows: Vec<&AdjFactorsParquetRow> =
|
|
snap.rows.iter().filter(|r| r.listing_id == 10).collect();
|
|
assert_eq!(nvda_rows.len(), 2, "1:1 no-op must not emit a row");
|
|
assert_eq!(nvda_rows[0].ex_date, d_2021);
|
|
assert_eq!(nvda_rows[0].cum_split_factor, 40.0);
|
|
assert_eq!(nvda_rows[1].ex_date, d_2024);
|
|
assert_eq!(nvda_rows[1].cum_split_factor, 10.0);
|
|
|
|
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2021 - 1), (40.0, 40.0));
|
|
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2021), (10.0, 10.0));
|
|
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2024 - 1), (10.0, 10.0));
|
|
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2024), (1.0, 1.0));
|
|
|
|
// CAD dividend ignores bogus usdFxRate: 1 and uses CAD prev_close = 100.0 -> 100 / 95.
|
|
let shop_row = snap.rows.iter().find(|r| r.listing_id == 20).unwrap();
|
|
assert_eq!(shop_row.div_currency.as_deref(), Some("CAD"));
|
|
assert!((shop_row.cum_total_factor - (100.0 / 95.0)).abs() < 1e-12);
|
|
|
|
// Currency-mismatched dividend falls back to factor 1.0.
|
|
let mismatch_row = snap.rows.iter().find(|r| r.listing_id == 30).unwrap();
|
|
assert_eq!(mismatch_row.div_currency.as_deref(), Some("USD"));
|
|
assert_eq!(mismatch_row.cum_total_factor, 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn failure_modes_preserve_preexisting_adj_factors_snapshot_byte_for_byte() {
|
|
let dir = TestTempDir::new("atomicity-failures");
|
|
let splits_ok = dir.path().join("splits_ok.bson");
|
|
let divs_ok = dir.path().join("divs_ok.bson");
|
|
let map_ok = dir.path().join("map_ok.tsv");
|
|
let bars_ok = dir.path().join("bars_ok");
|
|
let out_dir = dir.path().join("out");
|
|
|
|
write_bytes(&map_ok, b"qm\tNVDA:US\t2015-01-01\t\t10\n");
|
|
write_bars_1d_dataset(
|
|
&bars_ok,
|
|
&[bar_row(10, 2024, 6, 7, 1200.0, "USD")],
|
|
Bars1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
write_bytes(&splits_ok, &split_doc("NVDA:US", "2024-06-10", 10.0));
|
|
write_bytes(&divs_ok, b"");
|
|
|
|
// Seed a valid pre-existing snapshot at `<out_dir>/adj_factors/part.parquet`.
|
|
run_curate_adj_factors(&CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
})
|
|
.expect("seed baseline snapshot");
|
|
let live_part = out_dir.join("adj_factors/part.parquet");
|
|
let baseline_bytes = fs::read(&live_part).expect("read baseline snapshot");
|
|
assert!(!baseline_bytes.is_empty());
|
|
|
|
let assert_failed_atomically_all = |args: CurateAdjFactorsArgs, expected_substrs: &[&str]| {
|
|
let err = run_curate_adj_factors(&args).expect_err("expected failure");
|
|
let msg = err.to_string();
|
|
assert_eq!(msg.lines().count(), 1, "error must be single-line: {msg}");
|
|
for expected_substr in expected_substrs {
|
|
assert!(
|
|
msg.contains(expected_substr),
|
|
"expected error containing '{expected_substr}', got: {msg}"
|
|
);
|
|
}
|
|
assert_eq!(
|
|
fs::read(&live_part).expect("live snapshot still exists"),
|
|
baseline_bytes,
|
|
"pre-existing adj_factors/part.parquet must remain byte-identical after failure ({msg})"
|
|
);
|
|
};
|
|
let assert_failed_atomically = |args: CurateAdjFactorsArgs, expected_substr: &str| {
|
|
assert_failed_atomically_all(args, &[expected_substr]);
|
|
};
|
|
|
|
// 1. Missing qmSplits file.
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: dir.path().join("missing_splits.bson"),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"missing_splits.bson",
|
|
);
|
|
|
|
// 2. Missing qmDividends file.
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: dir.path().join("missing_divs.bson"),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"missing_divs.bson",
|
|
);
|
|
|
|
// 3. Missing provider_mapping file.
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: dir.path().join("missing_map.tsv"),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"missing_map.tsv",
|
|
);
|
|
|
|
// 4. Missing bars_1d dir.
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: dir.path().join("missing_bars_dir"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"missing_bars_dir",
|
|
);
|
|
|
|
// 5. Non-directory bars_1d path.
|
|
let not_a_dir = dir.path().join("bars_file.txt");
|
|
write_bytes(¬_a_dir, b"nope");
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: not_a_dir,
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"bars_file.txt",
|
|
);
|
|
|
|
// 5b. Existing root directory with no year=YYYY partitions and no bars_1d/ dataset.
|
|
let empty_root_bars = dir.path().join("empty_root_no_bars");
|
|
fs::create_dir_all(&empty_root_bars).unwrap();
|
|
assert_failed_atomically_all(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: empty_root_bars,
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
&["empty_root_no_bars", "no year=YYYY partitions"],
|
|
);
|
|
|
|
// 5c. Existing root directory with an empty nested bars_1d/ directory (no year=YYYY partitions).
|
|
let empty_nested_bars = dir.path().join("empty_nested_bars");
|
|
fs::create_dir_all(empty_nested_bars.join("bars_1d")).unwrap();
|
|
assert_failed_atomically_all(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: empty_nested_bars,
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
&["empty_nested_bars", "no year=YYYY partitions"],
|
|
);
|
|
|
|
// 6. Wrong-schema bars_1d part.parquet (place adj_factors part.parquet inside year=2024/).
|
|
let wrong_schema_bars = dir.path().join("wrong_schema_bars");
|
|
write_bytes(
|
|
&wrong_schema_bars.join("year=2024/part.parquet"),
|
|
&baseline_bytes,
|
|
);
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: wrong_schema_bars,
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"schema mismatch",
|
|
);
|
|
|
|
// 7. Corrupt bars_1d part.parquet.
|
|
let corrupt_bars = dir.path().join("corrupt_bars");
|
|
write_bytes(&corrupt_bars.join("year=2024/part.parquet"), b"not parquet");
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: corrupt_bars,
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"part.parquet",
|
|
);
|
|
|
|
// 8. Missing part.parquet in year=YYYY partition.
|
|
let missing_part_bars = dir.path().join("missing_part_bars");
|
|
fs::create_dir_all(missing_part_bars.join("year=2024")).unwrap();
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: missing_part_bars,
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"part.parquet",
|
|
);
|
|
|
|
// 9. Malformed provider_mapping.tsv (reports 1-based line number).
|
|
let bad_map = dir.path().join("bad_map.tsv");
|
|
write_bytes(&bad_map, b"qm\tNVDA:US\t2015-01-01\t\t10\nbad_row\n");
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: bad_map,
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"bad_map.tsv:2:",
|
|
);
|
|
|
|
// 10. Truncated BSON stream.
|
|
let trunc_splits = dir.path().join("trunc_splits.bson");
|
|
let mut doc = split_doc("NVDA:US", "2024-06-10", 10.0);
|
|
doc.truncate(doc.len() - 3);
|
|
write_bytes(&trunc_splits, &doc);
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: trunc_splits,
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"trunc_splits.bson",
|
|
);
|
|
|
|
// 11. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES).
|
|
let huge_divs = dir.path().join("huge_divs.bson");
|
|
let huge_len = (DEFAULT_MAX_DOC_BYTES as i32) + 512;
|
|
let mut huge_bytes = Vec::from(huge_len.to_le_bytes());
|
|
huge_bytes.push(0);
|
|
write_bytes(&huge_divs, &huge_bytes);
|
|
assert_failed_atomically(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok.clone(),
|
|
qm_dividends: huge_divs,
|
|
provider_mapping: map_ok.clone(),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
"huge_divs.bson",
|
|
);
|
|
|
|
// 12. Conflicting cross-key split curation error (must name qmSplits input path).
|
|
let alias_map = dir.path().join("alias_map.tsv");
|
|
write_bytes(
|
|
&alias_map,
|
|
b"qm\tNVDA:US\t2015-01-01\t\t10\nqm\tNVDA_ALT:US\t2015-01-01\t\t10\n",
|
|
);
|
|
let conflict_splits = dir.path().join("conflict_splits.bson");
|
|
write_bytes(
|
|
&conflict_splits,
|
|
&[
|
|
&split_doc("NVDA:US", "2024-06-10", 10.0)[..],
|
|
&split_doc("NVDA_ALT:US", "2024-06-10", 4.0)[..],
|
|
]
|
|
.concat(),
|
|
);
|
|
assert_failed_atomically_all(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: conflict_splits,
|
|
qm_dividends: divs_ok.clone(),
|
|
provider_mapping: alias_map.clone(),
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
},
|
|
&["conflict_splits.bson", "conflicting cross-key splits"],
|
|
);
|
|
|
|
// 13. Conflicting cross-key dividend curation error (must name qmDividends input path).
|
|
let conflict_divs = dir.path().join("conflict_divs.bson");
|
|
write_bytes(
|
|
&conflict_divs,
|
|
&[
|
|
&div_doc("NVDA:US", "2024-06-11", 0.10, "USD", None)[..],
|
|
&div_doc("NVDA_ALT:US", "2024-06-11", 0.20, "USD", None)[..],
|
|
]
|
|
.concat(),
|
|
);
|
|
assert_failed_atomically_all(
|
|
CurateAdjFactorsArgs {
|
|
qm_splits: splits_ok,
|
|
qm_dividends: conflict_divs,
|
|
provider_mapping: alias_map,
|
|
bars_1d_dir: bars_ok.join("bars_1d"),
|
|
out_dir,
|
|
},
|
|
&["conflict_divs.bson", "conflicting cross-key dividends"],
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn prev_close_cross_year_multi_row_group_and_layout_parity() {
|
|
let dir = TestTempDir::new("cross-year-rg");
|
|
let bars_root = dir.path().join("bars_root");
|
|
let bars = vec![
|
|
bar_row(10, 2023, 12, 27, 98.0, "USD"),
|
|
bar_row(10, 2023, 12, 28, 99.0, "USD"),
|
|
bar_row(10, 2023, 12, 29, 100.0, "USD"),
|
|
bar_row(10, 2024, 1, 2, 105.0, "USD"),
|
|
bar_row(10, 2024, 1, 3, 106.0, "USD"),
|
|
];
|
|
let write_stats = write_bars_1d_dataset(
|
|
&bars_root,
|
|
bars,
|
|
Bars1dWriteOptions {
|
|
row_group_rows: 2,
|
|
..Bars1dWriteOptions::default()
|
|
},
|
|
)
|
|
.unwrap();
|
|
assert!(write_stats.row_groups_written >= 3);
|
|
|
|
let map_path = dir.path().join("map.tsv");
|
|
write_bytes(&map_path, b"qm\tX:US\t2020-01-01\t\t10\n");
|
|
|
|
let splits_path = dir.path().join("splits.bson");
|
|
write_bytes(&splits_path, b"");
|
|
|
|
let divs_path = dir.path().join("divs.bson");
|
|
// Ex-date 2024-01-02 must use 2023-12-29 close (100.0), not 2024-01-02 close (105.0).
|
|
write_bytes(&divs_path, &div_doc("X:US", "2024-01-02", 2.0, "USD", None));
|
|
|
|
let out_direct = dir.path().join("out_direct");
|
|
let report_direct = run_curate_adj_factors(&CurateAdjFactorsArgs {
|
|
qm_splits: splits_path.clone(),
|
|
qm_dividends: divs_path.clone(),
|
|
provider_mapping: map_path.clone(),
|
|
bars_1d_dir: bars_root.join("bars_1d"),
|
|
out_dir: out_direct.clone(),
|
|
})
|
|
.unwrap();
|
|
assert_conservation(&report_direct);
|
|
assert_eq!(report_direct.dividends_with_prev_close, 1);
|
|
|
|
let out_parent = dir.path().join("out_parent");
|
|
let report_parent = run_curate_adj_factors(&CurateAdjFactorsArgs {
|
|
qm_splits: splits_path,
|
|
qm_dividends: divs_path,
|
|
provider_mapping: map_path,
|
|
bars_1d_dir: bars_root,
|
|
out_dir: out_parent.clone(),
|
|
})
|
|
.unwrap();
|
|
assert_conservation(&report_parent);
|
|
|
|
// Both --bars-1d layouts produce byte-identical Parquet output.
|
|
let bytes_direct = fs::read(out_direct.join("adj_factors/part.parquet")).unwrap();
|
|
let bytes_parent = fs::read(out_parent.join("adj_factors/part.parquet")).unwrap();
|
|
assert_eq!(bytes_direct, bytes_parent);
|
|
|
|
let read_back = read_adj_factors_dataset(&out_direct).unwrap();
|
|
assert_eq!(read_back.rows.len(), 1);
|
|
let expected_factor = 100.0_f64 / (100.0_f64 - 2.0_f64);
|
|
assert!((read_back.rows[0].cum_total_factor - expected_factor).abs() < 1e-12);
|
|
}
|
|
|
|
#[test]
|
|
fn ticker_reuse_resolves_prev_close_per_mapping_window_and_gap_is_unmapped() {
|
|
let dir = TestTempDir::new("ticker-reuse");
|
|
let bars_root = dir.path().join("bars_root");
|
|
write_bars_1d_dataset(
|
|
&bars_root,
|
|
vec![
|
|
bar_row(101, 2021, 6, 14, 50.0, "USD"),
|
|
bar_row(202, 2023, 6, 14, 200.0, "USD"),
|
|
],
|
|
Bars1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
|
|
let map_path = dir.path().join("map.tsv");
|
|
write_bytes(
|
|
&map_path,
|
|
b"qm\tREUSED:US\t2020-01-01\t2021-12-31\t101\nqm\tREUSED:US\t2023-01-01\t\t202\n",
|
|
);
|
|
|
|
let splits_path = dir.path().join("splits.bson");
|
|
write_bytes(&splits_path, b"");
|
|
|
|
let divs_path = dir.path().join("divs.bson");
|
|
let mut div_bytes = Vec::new();
|
|
// Window 1 -> listing 101 (prev_close = 50.0)
|
|
div_bytes.extend_from_slice(&div_doc("REUSED:US", "2021-06-15", 1.0, "USD", None));
|
|
// Gap -> unmapped
|
|
div_bytes.extend_from_slice(&div_doc("REUSED:US", "2022-06-15", 1.0, "USD", None));
|
|
// Window 2 -> listing 202 (prev_close = 200.0)
|
|
div_bytes.extend_from_slice(&div_doc("REUSED:US", "2023-06-15", 4.0, "USD", None));
|
|
write_bytes(&divs_path, &div_bytes);
|
|
|
|
let out_dir = dir.path().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_dir.clone(),
|
|
})
|
|
.unwrap();
|
|
assert_conservation(&report);
|
|
assert_eq!(report.dividends_with_prev_close, 2);
|
|
assert_eq!(report.dividends_without_prev_close, 0);
|
|
assert_eq!(report.curate_stats.dividends_dropped_unmapped, 1);
|
|
|
|
let read_back = read_adj_factors_dataset(&out_dir).unwrap();
|
|
assert_eq!(read_back.rows.len(), 2);
|
|
let r101 = read_back.rows.iter().find(|r| r.listing_id == 101).unwrap();
|
|
let r202 = read_back.rows.iter().find(|r| r.listing_id == 202).unwrap();
|
|
assert!((r101.cum_total_factor - (50.0_f64 / 49.0_f64)).abs() < 1e-12);
|
|
assert!((r202.cum_total_factor - (200.0_f64 / 196.0_f64)).abs() < 1e-12);
|
|
}
|
|
|
|
#[test]
|
|
fn dividend_at_or_above_prev_close_falls_back_to_unit_factor() {
|
|
let dir = TestTempDir::new("div-ge-close");
|
|
let bars_root = dir.path().join("bars_root");
|
|
write_bars_1d_dataset(
|
|
&bars_root,
|
|
vec![bar_row(10, 2024, 5, 1, 10.0, "USD")],
|
|
Bars1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
|
|
let map_path = dir.path().join("map.tsv");
|
|
write_bytes(&map_path, b"qm\tBIG:US\t2020-01-01\t\t10\n");
|
|
|
|
let splits_path = dir.path().join("splits.bson");
|
|
write_bytes(&splits_path, b"");
|
|
|
|
let divs_path = dir.path().join("divs.bson");
|
|
write_bytes(&divs_path, &div_doc("BIG:US", "2024-05-02", 10.0, "USD", None));
|
|
|
|
let out_dir = dir.path().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_dir.clone(),
|
|
})
|
|
.unwrap();
|
|
assert_conservation(&report);
|
|
assert_eq!(report.dividends_with_prev_close, 1);
|
|
|
|
let read_back = read_adj_factors_dataset(&out_dir).unwrap();
|
|
assert_eq!(read_back.rows.len(), 1);
|
|
assert_eq!(read_back.rows[0].cum_total_factor.to_bits(), 1.0_f64.to_bits());
|
|
}
|
|
|
|
#[test]
|
|
fn empty_inputs_publish_readable_empty_snapshot() {
|
|
let dir = TestTempDir::new("empty-inputs");
|
|
let bars_root = dir.path().join("bars_root");
|
|
write_bars_1d_dataset(
|
|
&bars_root,
|
|
vec![bar_row(10, 2024, 1, 2, 100.0, "USD")],
|
|
Bars1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
|
|
let map_path = dir.path().join("map.tsv");
|
|
let splits_path = dir.path().join("splits.bson");
|
|
let divs_path = dir.path().join("divs.bson");
|
|
write_bytes(&map_path, b"");
|
|
write_bytes(&splits_path, b"");
|
|
write_bytes(&divs_path, b"");
|
|
|
|
let out_dir = dir.path().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_dir.clone(),
|
|
})
|
|
.unwrap();
|
|
assert_conservation(&report);
|
|
assert_eq!(report.write_stats.rows_written, 0);
|
|
|
|
let read_back = read_adj_factors_dataset(&out_dir).unwrap();
|
|
assert!(read_back.rows.is_empty());
|
|
assert_eq!(
|
|
read_back.snapshot_kind,
|
|
AdjSnapshotKind::RetrospectiveSnapshot
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn duplicate_bar_across_partitions_and_out_file_fail_atomically() {
|
|
let dir = TestTempDir::new("dup-bar-and-out-file");
|
|
let bars_root = dir.path().join("bars_root");
|
|
write_bars_1d_dataset(
|
|
&bars_root,
|
|
vec![bar_row(10, 2024, 1, 2, 100.0, "USD")],
|
|
Bars1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
|
|
let map_path = dir.path().join("map.tsv");
|
|
let splits_path = dir.path().join("splits.bson");
|
|
let divs_path = dir.path().join("divs.bson");
|
|
write_bytes(&map_path, b"qm\tNVDA:US\t2015-01-01\t\t10\n");
|
|
write_bytes(&splits_path, &split_doc("NVDA:US", "2024-06-10", 10.0));
|
|
write_bytes(&divs_path, b"");
|
|
|
|
let out_dir = dir.path().join("out");
|
|
run_curate_adj_factors(&CurateAdjFactorsArgs {
|
|
qm_splits: splits_path.clone(),
|
|
qm_dividends: divs_path.clone(),
|
|
provider_mapping: map_path.clone(),
|
|
bars_1d_dir: bars_root.join("bars_1d"),
|
|
out_dir: out_dir.clone(),
|
|
})
|
|
.unwrap();
|
|
let baseline_path = out_dir.join("adj_factors/part.parquet");
|
|
let baseline_bytes = fs::read(&baseline_path).unwrap();
|
|
|
|
// Copy year=2024/part.parquet into year=2025/part.parquet to create duplicate (listing_id, session_date).
|
|
let dup_bars = dir.path().join("dup_bars");
|
|
let part_bytes = fs::read(bars_root.join("bars_1d/year=2024/part.parquet")).unwrap();
|
|
write_bytes(&dup_bars.join("year=2024/part.parquet"), &part_bytes);
|
|
write_bytes(&dup_bars.join("year=2025/part.parquet"), &part_bytes);
|
|
|
|
let err = run_curate_adj_factors(&CurateAdjFactorsArgs {
|
|
qm_splits: splits_path.clone(),
|
|
qm_dividends: divs_path.clone(),
|
|
provider_mapping: map_path.clone(),
|
|
bars_1d_dir: dup_bars,
|
|
out_dir: out_dir.clone(),
|
|
})
|
|
.unwrap_err();
|
|
let msg = err.to_string();
|
|
assert!(!msg.contains('\n'), "error must be single-line: {msg}");
|
|
assert!(msg.contains("duplicate"), "unexpected error: {msg}");
|
|
assert_eq!(fs::read(&baseline_path).unwrap(), baseline_bytes);
|
|
|
|
// --out pointing at an existing regular file must fail without modifying the file.
|
|
let out_file = dir.path().join("out_is_file");
|
|
write_bytes(&out_file, b"untouched");
|
|
let err = 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_file.clone(),
|
|
})
|
|
.unwrap_err();
|
|
let msg = err.to_string();
|
|
assert!(!msg.contains('\n'), "error must be single-line: {msg}");
|
|
assert!(msg.contains("out_is_file"), "unexpected error: {msg}");
|
|
assert_eq!(fs::read(&out_file).unwrap(), b"untouched");
|
|
}
|