T-113: tests
This commit is contained in:
parent
823143905a
commit
f6daec2801
1 changed files with 416 additions and 0 deletions
416
tools/curate-etl/tests/run_curate_fx_qa_contract.rs
Normal file
416
tools/curate-etl/tests/run_curate_fx_qa_contract.rs
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
//! QA contract tests for the `curate-fx-1d` runner and the `teMarketData` stream decoder
|
||||
//! (T-113 / M1.2ac), via the public crate API only.
|
||||
//!
|
||||
//! Covers gaps left by the in-crate `run_curate_fx_tests.rs` / `bson_te_market_data_tests.rs`:
|
||||
//! - poison look-ahead through real dump files: appending absurd future EOD docs and TE points
|
||||
//! leaves every earlier published row bit-identical;
|
||||
//! - small-chunk streaming (`decode_te_market_data_stream`) yields the same bars and stats as a
|
||||
//! one-shot buffer decode, and a corrupt point in a later document reports its absolute offset;
|
||||
//! - `--te-symbol` validation runs before any input is opened and never creates `--out`;
|
||||
//! - a selector given in lower case still matches a mixed-case `teSymbol` in the dump;
|
||||
//! - non-numeric `t` (BSON `DateTime`) is a counted point reject, not a silent date guess;
|
||||
//! - documented Known Limit: `CAD.FOREX` docs without `volume` are rejected, TE still publishes.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::{
|
||||
decode_te_market_data_buffer, decode_te_market_data_stream, run_curate_fx_1d,
|
||||
ymd_to_epoch_days, BsonStreamOptions, BsonTeMarketDataError, CurateFx1dArgs,
|
||||
CurateFx1dRunReport, FxDailyBar, RunCurateFxError, TE_MILLIS_PER_DAY, TE_SECONDS_PER_DAY,
|
||||
};
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
use parquet::record::{Field, RowAccessor};
|
||||
|
||||
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-curate-fx-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);
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn ymd(d: i32) -> String {
|
||||
// Civil-from-days (Howard Hinnant), sufficient for fixture date strings.
|
||||
let z = i64::from(d) + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let dd = doy - (153 * mp + 2) / 5 + 1;
|
||||
let mm = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let yy = yoe + era * 400 + i64::from(mm <= 2);
|
||||
format!("{yy:04}-{mm:02}-{dd:02}")
|
||||
}
|
||||
|
||||
fn eod_doc(code: &str, d: i32, c: f64, with_volume: bool) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), ymd(d).as_str());
|
||||
doc.append(cstr!("open"), c);
|
||||
doc.append(cstr!("high"), c + 0.004);
|
||||
doc.append(cstr!("low"), c - 0.004);
|
||||
doc.append(cstr!("close"), c);
|
||||
if with_volume {
|
||||
doc.append(cstr!("volume"), 0.0_f64);
|
||||
}
|
||||
doc.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn te_point(d: i32, c: f64, millis: bool) -> RawDocumentBuf {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
if millis {
|
||||
pt.append(cstr!("t"), i64::from(d) * TE_MILLIS_PER_DAY + 79_200_000);
|
||||
} else {
|
||||
pt.append(cstr!("t"), (i64::from(d) * TE_SECONDS_PER_DAY + 7_200) as f64);
|
||||
}
|
||||
pt.append(cstr!("o"), c);
|
||||
pt.append(cstr!("h"), c + 0.004);
|
||||
pt.append(cstr!("l"), c - 0.004);
|
||||
pt.append(cstr!("c"), c);
|
||||
pt
|
||||
}
|
||||
|
||||
fn te_doc(symbol: &str, points: Vec<RawDocumentBuf>) -> Vec<u8> {
|
||||
let mut daily = RawArrayBuf::new();
|
||||
for p in points {
|
||||
daily.push(p);
|
||||
}
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("teSymbol"), symbol);
|
||||
doc.append(cstr!("daily"), daily);
|
||||
doc.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn write_file(path: &Path, docs: &[Vec<u8>]) {
|
||||
let bytes: Vec<u8> = docs.iter().flatten().copied().collect();
|
||||
fs::write(path, bytes).expect("write fixture");
|
||||
}
|
||||
|
||||
fn args(dir: &Path, te_symbol: &str) -> CurateFx1dArgs {
|
||||
CurateFx1dArgs {
|
||||
eod_prices: dir.join("eodPrices.bson"),
|
||||
te_market_data: dir.join("teMarketData.bson"),
|
||||
te_symbol: te_symbol.to_string(),
|
||||
out_dir: dir.join("out"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct Row {
|
||||
session_date: i32,
|
||||
ts: i64,
|
||||
bits: [u64; 4],
|
||||
source: String,
|
||||
known_at: i64,
|
||||
}
|
||||
|
||||
fn read_rows(out_dir: &Path) -> Vec<Row> {
|
||||
let file = File::open(out_dir.join("fx_1d/part.parquet")).expect("open part.parquet");
|
||||
let reader = SerializedFileReader::new(file).expect("parquet reader");
|
||||
reader
|
||||
.get_row_iter(None)
|
||||
.expect("row iter")
|
||||
.map(|r| {
|
||||
let r = r.expect("row");
|
||||
let session_date = match r.get_column_iter().nth(1).unwrap().1 {
|
||||
Field::Date(d) => *d,
|
||||
other => panic!("expected Date, got {other:?}"),
|
||||
};
|
||||
Row {
|
||||
session_date,
|
||||
ts: r.get_timestamp_micros(2).unwrap(),
|
||||
bits: [
|
||||
r.get_double(3).unwrap().to_bits(),
|
||||
r.get_double(4).unwrap().to_bits(),
|
||||
r.get_double(5).unwrap().to_bits(),
|
||||
r.get_double(6).unwrap().to_bits(),
|
||||
],
|
||||
source: r.get_string(7).unwrap().clone(),
|
||||
known_at: r.get_timestamp_micros(8).unwrap(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn assert_conserved(report: &CurateFx1dRunReport) {
|
||||
assert_eq!(report.eod_docs_framed as usize, report.eod_decode.docs_in);
|
||||
assert_eq!(
|
||||
report.eod_decode.docs_in,
|
||||
report.eod_decode.decoded + report.eod_decode.rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
report.eod_decode.decoded,
|
||||
report.eod_cad_forex_kept + report.eod_other_symbol_skipped
|
||||
);
|
||||
assert_eq!(report.te_docs_framed as usize, report.te_decode.docs_in);
|
||||
assert_eq!(
|
||||
report.te_decode.docs_in,
|
||||
report.te_decode.docs_matched
|
||||
+ report.te_decode.docs_other_symbol
|
||||
+ report.te_decode.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
report.te_decode.points_in,
|
||||
report.te_decode.points_decoded + report.te_decode.rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
report.te_decode.points_decoded,
|
||||
report.curate_stats.builder.te.rows_in
|
||||
);
|
||||
assert_eq!(report.write_stats.rows_written, report.curate_stats.rows_out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poison_future_eod_and_te_rows_leave_earlier_published_rows_bit_identical() {
|
||||
// Arrange: EOD 2024-01-02..2024-01-11 with a gap on 01-05, TE overlap + gap fill + tail.
|
||||
let tmp = TempDir::new("poison");
|
||||
let d0 = day(2024, 1, 2);
|
||||
let mut eod: Vec<Vec<u8>> = Vec::new();
|
||||
for i in 0..10 {
|
||||
if i == 3 {
|
||||
continue;
|
||||
}
|
||||
eod.push(eod_doc("CAD.FOREX", d0 + i, 1.34 + f64::from(i) * 0.001, true));
|
||||
}
|
||||
let te_points: Vec<RawDocumentBuf> = (0..14)
|
||||
.map(|i| te_point(d0 + i, 1.35 + f64::from(i) * 0.001, i % 2 == 0))
|
||||
.collect();
|
||||
let base_te = vec![te_doc("USDCAD", te_points.clone())];
|
||||
write_file(&tmp.0.join("eodPrices.bson"), &eod);
|
||||
write_file(&tmp.0.join("teMarketData.bson"), &base_te);
|
||||
let a = args(&tmp.0, "USDCAD");
|
||||
|
||||
// Act 1: baseline publish.
|
||||
let base_report = run_curate_fx_1d(&a).expect("baseline run");
|
||||
let base_rows = read_rows(&a.out_dir);
|
||||
assert_conserved(&base_report);
|
||||
assert_eq!(base_rows.len(), 14);
|
||||
|
||||
// Act 2: append absurd future facts in both sources (EOD on a later date, TE far tail).
|
||||
let far = day(2030, 6, 3);
|
||||
eod.push(eod_doc("CAD.FOREX", far, 99.0, true));
|
||||
let mut poisoned_points = te_points;
|
||||
poisoned_points.push(te_point(far + 1, 77.0, true));
|
||||
poisoned_points.push(te_point(far + 2, 55.0, false));
|
||||
write_file(&tmp.0.join("eodPrices.bson"), &eod);
|
||||
write_file(
|
||||
&tmp.0.join("teMarketData.bson"),
|
||||
&[te_doc("USDCAD", poisoned_points)],
|
||||
);
|
||||
let poison_report = run_curate_fx_1d(&a).expect("poisoned run");
|
||||
let poison_rows = read_rows(&a.out_dir);
|
||||
|
||||
// Assert: earlier rows unchanged bit-for-bit; only the 3 future rows are new.
|
||||
assert_conserved(&poison_report);
|
||||
assert_eq!(poison_rows.len(), base_rows.len() + 3);
|
||||
assert_eq!(&poison_rows[..base_rows.len()], &base_rows[..]);
|
||||
for r in &poison_rows {
|
||||
assert_eq!(r.ts, r.known_at);
|
||||
assert_eq!(r.ts, (i64::from(r.session_date) + 1) * 86_400_000_000 - 1);
|
||||
}
|
||||
let tail: Vec<(i32, &str)> = poison_rows[base_rows.len()..]
|
||||
.iter()
|
||||
.map(|r| (r.session_date, r.source.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
tail,
|
||||
vec![
|
||||
(far, "eod_cad_forex"),
|
||||
(far + 1, "te_usdcad"),
|
||||
(far + 2, "te_usdcad")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_chunk_te_stream_matches_buffer_decode_and_rebases_corrupt_point_offset() {
|
||||
// Arrange: three docs (other symbol, USDCAD, usdcad) concatenated.
|
||||
let d0 = day(2025, 3, 3);
|
||||
let doc_a = te_doc("EURUSD", vec![te_point(d0, 1.08, true)]);
|
||||
let doc_b = te_doc(
|
||||
"USDCAD",
|
||||
(0..20).map(|i| te_point(d0 + i, 1.40, i % 3 == 0)).collect(),
|
||||
);
|
||||
let doc_c = te_doc("usdcad", vec![te_point(d0 + 30, 1.41, false)]);
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(&doc_a);
|
||||
buf.extend_from_slice(&doc_b);
|
||||
buf.extend_from_slice(&doc_c);
|
||||
let tiny = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 16,
|
||||
..BsonStreamOptions::default()
|
||||
};
|
||||
|
||||
// Act
|
||||
let mut buf_bars: Vec<FxDailyBar> = Vec::new();
|
||||
let buf_stats = decode_te_market_data_buffer(&buf, "USDCAD", |b| buf_bars.push(b), |_, e| {
|
||||
panic!("unexpected buffer error {e:?}")
|
||||
});
|
||||
let mut stream_bars: Vec<FxDailyBar> = Vec::new();
|
||||
let stream_stats = decode_te_market_data_stream(
|
||||
&buf[..],
|
||||
tiny,
|
||||
"USDCAD",
|
||||
|b| stream_bars.push(b),
|
||||
|_, e| panic!("unexpected stream error {e:?}"),
|
||||
)
|
||||
.expect("stream decode");
|
||||
|
||||
// Assert: identical stats and bars regardless of chunking.
|
||||
assert_eq!(stream_stats, buf_stats);
|
||||
assert_eq!(stream_stats.docs_in, 3);
|
||||
assert_eq!(stream_stats.docs_matched, 2);
|
||||
assert_eq!(stream_stats.docs_other_symbol, 1);
|
||||
assert_eq!(stream_stats.points_decoded, 21);
|
||||
assert_eq!(stream_bars, buf_bars);
|
||||
|
||||
// Arrange: corrupt the element type byte of `c` inside the last doc's point.
|
||||
let mut corrupt = buf.clone();
|
||||
let doc_c_offset = doc_a.len() + doc_b.len();
|
||||
let rel = doc_c
|
||||
.windows(3)
|
||||
.rposition(|w| w == b"\x01c\0")
|
||||
.expect("find 'c' double element");
|
||||
corrupt[doc_c_offset + rel] = 0xEE;
|
||||
|
||||
// Act
|
||||
let mut errs: Vec<(u64, BsonTeMarketDataError)> = Vec::new();
|
||||
decode_te_market_data_stream(&corrupt[..], tiny, "USDCAD", |_| {}, |o, e| errs.push((o, e)))
|
||||
.expect("framing still valid");
|
||||
|
||||
// Assert: the structural point error is reported at the absolute offset of doc C.
|
||||
assert_eq!(errs.len(), 1, "{errs:?}");
|
||||
assert_eq!(errs[0].0, doc_c_offset as u64);
|
||||
match &errs[0].1 {
|
||||
BsonTeMarketDataError::CorruptPointBson { offset, point_index, .. } => {
|
||||
assert_eq!(*offset, doc_c_offset);
|
||||
assert_eq!(*point_index, 0);
|
||||
}
|
||||
other => panic!("expected CorruptPointBson, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_te_selector_is_rejected_before_opening_inputs_or_creating_out() {
|
||||
let tmp = TempDir::new("selector");
|
||||
// Inputs deliberately absent: validation must fire first (InvalidTeSymbol, not OpenInput).
|
||||
for bad in [" USDCAD", "USDCAD ", "USD/CAD", "USDCAD:CUR", "EURUSD", "CADUSD", ""] {
|
||||
let a = args(&tmp.0, bad);
|
||||
match run_curate_fx_1d(&a) {
|
||||
Err(RunCurateFxError::InvalidTeSymbol { value }) => assert_eq!(value, bad),
|
||||
other => panic!("selector {bad:?}: expected InvalidTeSymbol, got {other:?}"),
|
||||
}
|
||||
assert!(!a.out_dir.exists(), "selector {bad:?} created --out");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lower_case_selector_matches_mixed_case_te_symbol_and_skips_whitespace_padded_symbol() {
|
||||
let tmp = TempDir::new("case");
|
||||
let d0 = day(2026, 2, 2);
|
||||
write_file(&tmp.0.join("eodPrices.bson"), &[]);
|
||||
write_file(
|
||||
&tmp.0.join("teMarketData.bson"),
|
||||
&[
|
||||
te_doc("UsdCad", vec![te_point(d0, 1.36, true)]),
|
||||
te_doc(" USDCAD", vec![te_point(d0 + 1, 9.99, true)]),
|
||||
],
|
||||
);
|
||||
let a = args(&tmp.0, "usdcad");
|
||||
|
||||
let report = run_curate_fx_1d(&a).expect("run");
|
||||
let rows = read_rows(&a.out_dir);
|
||||
|
||||
assert_conserved(&report);
|
||||
assert_eq!(report.te_decode.docs_matched, 1);
|
||||
assert_eq!(report.te_decode.docs_other_symbol, 1);
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].session_date, d0);
|
||||
assert_eq!(rows[0].source, "te_usdcad");
|
||||
assert_eq!(rows[0].bits[3], 1.36_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_point_with_datetime_t_is_counted_wrong_type_and_not_published() {
|
||||
let tmp = TempDir::new("datetime-t");
|
||||
let d0 = day(2026, 3, 2);
|
||||
let mut dt_point = RawDocumentBuf::new();
|
||||
dt_point.append(
|
||||
cstr!("t"),
|
||||
DateTime::from_millis(i64::from(d0 + 1) * TE_MILLIS_PER_DAY),
|
||||
);
|
||||
dt_point.append(cstr!("o"), 1.37_f64);
|
||||
dt_point.append(cstr!("h"), 1.38_f64);
|
||||
dt_point.append(cstr!("l"), 1.36_f64);
|
||||
dt_point.append(cstr!("c"), 1.37_f64);
|
||||
write_file(&tmp.0.join("eodPrices.bson"), &[]);
|
||||
write_file(
|
||||
&tmp.0.join("teMarketData.bson"),
|
||||
&[te_doc("USDCAD", vec![te_point(d0, 1.36, false), dt_point])],
|
||||
);
|
||||
let a = args(&tmp.0, "USDCAD");
|
||||
|
||||
let report = run_curate_fx_1d(&a).expect("run");
|
||||
let rows = read_rows(&a.out_dir);
|
||||
|
||||
assert_conserved(&report);
|
||||
assert_eq!(report.te_decode.points_in, 2);
|
||||
assert_eq!(report.te_decode.points_decoded, 1);
|
||||
assert_eq!(report.te_decode.rejected_wrong_type, 1);
|
||||
assert_eq!(rows.iter().map(|r| r.session_date).collect::<Vec<_>>(), vec![d0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cad_forex_without_volume_is_rejected_as_missing_field_and_te_still_publishes() {
|
||||
// Pins the README Known Limit: the reused eodPrices decoder requires `volume`.
|
||||
let tmp = TempDir::new("no-volume");
|
||||
let d0 = day(2025, 12, 1);
|
||||
write_file(
|
||||
&tmp.0.join("eodPrices.bson"),
|
||||
&[
|
||||
eod_doc("CAD.FOREX", d0, 1.40, false),
|
||||
eod_doc("CAD.FOREX", d0 + 1, 1.41, true),
|
||||
],
|
||||
);
|
||||
write_file(
|
||||
&tmp.0.join("teMarketData.bson"),
|
||||
&[te_doc("USDCAD", vec![te_point(d0, 1.39, true)])],
|
||||
);
|
||||
let a = args(&tmp.0, "USDCAD");
|
||||
|
||||
let report = run_curate_fx_1d(&a).expect("run");
|
||||
let rows = read_rows(&a.out_dir);
|
||||
|
||||
assert_conserved(&report);
|
||||
assert_eq!(report.eod_decode.rejected_missing_field, 1);
|
||||
assert_eq!(report.eod_cad_forex_kept, 1);
|
||||
let got: Vec<(i32, &str)> = rows
|
||||
.iter()
|
||||
.map(|r| (r.session_date, r.source.as_str()))
|
||||
.collect();
|
||||
assert_eq!(got, vec![(d0, "te_usdcad"), (d0 + 1, "eod_cad_forex")]);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue