use std::fs::{self, File}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; use parquet::file::reader::{FileReader, SerializedFileReader}; use parquet::record::{Field, RowAccessor}; use super::*; use crate::bson_te_market_data::{MILLIS_PER_DAY, SECONDS_PER_DAY}; use crate::curate_fx::fx_1d_utc_day_end_micros; use crate::fx::{FxSource, FX_PAIR_USDCAD}; use crate::split::ymd_to_epoch_days; static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); struct TestTempDir { path: PathBuf, } impl TestTempDir { fn new(prefix: &str) -> Self { let pid = std::process::id(); let base = std::env::temp_dir(); loop { let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); let candidate = base.join(format!("curate-etl-{prefix}-{pid}-{seq}")); match fs::create_dir(&candidate) { Ok(()) => return Self { path: candidate }, Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, Err(err) => panic!("failed to create temp dir {}: {err}", candidate.display()), } } } } impl Drop for TestTempDir { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.path); } } fn day(y: i32, m: u32, d: u32) -> i32 { ymd_to_epoch_days(y, m, d).expect("valid date") } fn eod_doc(code: &str, date: &str, o: f64, h: f64, l: f64, c: f64, vol: f64) -> Vec { let mut doc = RawDocumentBuf::new(); doc.append(cstr!("eodSearchCode"), code); doc.append(cstr!("date"), date); doc.append(cstr!("open"), o); doc.append(cstr!("high"), h); doc.append(cstr!("low"), l); doc.append(cstr!("close"), c); doc.append(cstr!("volume"), vol); doc.as_bytes().to_vec() } fn te_point_secs(d: i32, o: f64, h: f64, l: f64, c: f64) -> RawDocumentBuf { let mut pt = RawDocumentBuf::new(); pt.append(cstr!("t"), i64::from(d) * SECONDS_PER_DAY + 3_600); pt.append(cstr!("o"), o); pt.append(cstr!("h"), h); pt.append(cstr!("l"), l); pt.append(cstr!("c"), c); pt } fn te_point_ms(d: i32, o: f64, h: f64, l: f64, c: f64) -> RawDocumentBuf { let mut pt = RawDocumentBuf::new(); pt.append(cstr!("t"), i64::from(d) * MILLIS_PER_DAY + 43_200_000); pt.append(cstr!("o"), o); pt.append(cstr!("h"), h); pt.append(cstr!("l"), l); pt.append(cstr!("c"), c); pt } fn assert_report_invariants(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.eod_cad_forex_kept, report.curate_stats.builder.eod.rows_in ); 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.curate_stats.rows_in, report.curate_stats.builder.rows_out ); assert_eq!(report.curate_stats.rows_out, report.curate_stats.rows_in); assert_eq!(report.write_stats.rows_written, report.curate_stats.rows_out); } #[derive(Debug, PartialEq)] struct ReadFxRow { pair: String, session_date: i32, ts_micros: i64, open: f64, high: f64, low: f64, close: f64, source: String, known_at_micros: i64, } fn read_fx_parquet(path: &Path) -> Vec { let file = File::open(path).expect("open fx_1d/part.parquet"); let reader = SerializedFileReader::new(file).expect("parquet reader"); let mut rows = Vec::new(); for row_res in reader.get_row_iter(None).expect("row iter") { let row = row_res.expect("row"); let session_date = match row.get_column_iter().nth(1).unwrap().1 { Field::Date(d) => *d, other => panic!("expected Date field at col 1, got {other:?}"), }; rows.push(ReadFxRow { pair: row.get_string(0).unwrap().clone(), session_date, ts_micros: row.get_timestamp_micros(2).unwrap(), open: row.get_double(3).unwrap(), high: row.get_double(4).unwrap(), low: row.get_double(5).unwrap(), close: row.get_double(6).unwrap(), source: row.get_string(7).unwrap().clone(), known_at_micros: row.get_timestamp_micros(8).unwrap(), }); } rows } fn strip_timing_line(report_text: &str) -> String { report_text .lines() .filter(|l| !l.trim_start().starts_with("timing:")) .collect::>() .join("\n") } #[test] fn end_to_end_curation_precedence_gap_tail_and_permutation_invariance() { let tmp = TestTempDir::new("fx-e2e"); let eod_path = tmp.path.join("eodPrices.bson"); let te_path = tmp.path.join("teMarketData.bson"); let out_a = tmp.path.join("out_a"); let out_b = tmp.path.join("out_b"); let d1 = day(2025, 1, 2); let d2 = day(2025, 1, 3); // interior gap in EOD -> TE fills let d3 = day(2025, 1, 6); let d4 = day(2026, 1, 2); // post-EOD tail -> TE fills // Build EOD docs: CAD.FOREX (d1, d3), wrong-case "cad.forex" (must be skipped!), // other symbol "AAPL.US" (skipped), and 1 malformed doc (missing close -> rejected). let mut malformed_eod = RawDocumentBuf::new(); malformed_eod.append(cstr!("eodSearchCode"), "CAD.FOREX"); malformed_eod.append(cstr!("date"), "2025-01-07"); malformed_eod.append(cstr!("open"), 1.43_f64); malformed_eod.append(cstr!("high"), 1.44_f64); malformed_eod.append(cstr!("low"), 1.42_f64); malformed_eod.append(cstr!("volume"), 0.0_f64); let eod_docs = vec![ eod_doc("CAD.FOREX", "2025-01-02", 1.430, 1.440, 1.425, 1.435, 0.0), eod_doc("cad.forex", "2025-01-03", 9.990, 9.995, 9.985, 9.990, 0.0), eod_doc("AAPL.US", "2025-01-02", 240.0, 245.0, 239.0, 244.0, 1000.0), eod_doc("CAD.FOREX", "2025-01-06", 1.436, 1.442, 1.430, 1.438, 12.0), malformed_eod.as_bytes().to_vec(), ]; // Build TE docs: other symbol ("EURUSD"), uppercase "USDCAD" (overlap d1 + gap d2 + bad point), // lowercase "usdcad" (tail d4 + ignored `monthly`). let mut other_te_daily = RawArrayBuf::new(); other_te_daily.push(te_point_secs(d1, 1.05, 1.06, 1.04, 1.055)); let mut other_te_doc = RawDocumentBuf::new(); other_te_doc.append(cstr!("teSymbol"), "EURUSD"); other_te_doc.append(cstr!("daily"), other_te_daily); let mut bad_te_pt = RawDocumentBuf::new(); bad_te_pt.append(cstr!("t"), i64::from(d4) * MILLIS_PER_DAY); bad_te_pt.append(cstr!("o"), f64::NAN); bad_te_pt.append(cstr!("h"), 1.39_f64); bad_te_pt.append(cstr!("l"), 1.37_f64); bad_te_pt.append(cstr!("c"), 1.38_f64); let mut te_daily_1 = RawArrayBuf::new(); te_daily_1.push(te_point_secs(d1, 1.431, 1.441, 1.426, 1.436)); // overlaps d1 -> EOD wins te_daily_1.push(te_point_ms(d2, 1.434, 1.439, 1.431, 1.437)); // interior gap -> TE fills te_daily_1.push(bad_te_pt); let mut te_doc_1 = RawDocumentBuf::new(); te_doc_1.append(cstr!("teSymbol"), "USDCAD"); te_doc_1.append(cstr!("daily"), te_daily_1); let mut te_daily_2 = RawArrayBuf::new(); te_daily_2.push(te_point_ms(d4, 1.380, 1.390, 1.375, 1.385)); // tail -> TE fills let mut ignored_monthly = RawArrayBuf::new(); ignored_monthly.push("bad-monthly-ignored"); let mut te_doc_2 = RawDocumentBuf::new(); te_doc_2.append(cstr!("monthly"), ignored_monthly); te_doc_2.append(cstr!("daily"), te_daily_2); te_doc_2.append(cstr!("teSymbol"), "usdcad"); let te_docs = [ other_te_doc.as_bytes().to_vec(), te_doc_1.as_bytes().to_vec(), te_doc_2.as_bytes().to_vec(), ]; // Write run A in forward order fs::write(&eod_path, eod_docs.concat()).unwrap(); fs::write(&te_path, te_docs.concat()).unwrap(); let args_a = CurateFx1dArgs { eod_prices: eod_path.clone(), te_market_data: te_path.clone(), te_symbol: DEFAULT_TE_SYMBOL.to_string(), out_dir: out_a.clone(), }; let report_a = run_curate_fx_1d(&args_a).expect("run A succeeds"); assert_report_invariants(&report_a); assert_eq!(report_a.eod_docs_framed, 5); assert_eq!(report_a.eod_cad_forex_kept, 2); assert_eq!(report_a.eod_other_symbol_skipped, 2); // "cad.forex" + "AAPL.US" assert_eq!(report_a.eod_decode.rejected_missing_field, 1); assert_eq!(report_a.te_docs_framed, 3); assert_eq!(report_a.te_decode.docs_matched, 2); assert_eq!(report_a.te_decode.docs_other_symbol, 1); assert_eq!(report_a.te_decode.points_in, 4); assert_eq!(report_a.te_decode.points_decoded, 3); assert_eq!(report_a.te_decode.rejected_non_finite, 1); assert_eq!(report_a.curate_stats.rows_out, 4); assert_eq!(report_a.curate_stats.builder.eod_rows_out, 2); assert_eq!(report_a.curate_stats.builder.te_rows_out, 2); assert_eq!(report_a.curate_stats.builder.te_superseded_by_eod, 1); assert_eq!(report_a.curate_stats.builder.overlap_checked, 1); assert_eq!(report_a.curate_stats.builder.overlap_within_tolerance, 1); assert_eq!(report_a.write_stats.rows_written, 4); assert_eq!(report_a.write_stats.files_written, 1); let parquet_a = out_a.join("fx_1d/part.parquet"); let rows = read_fx_parquet(&parquet_a); assert_eq!(rows.len(), 4); let expected_dates = [d1, d2, d3, d4]; let expected_sources = [ FxSource::EodCadForex.as_str(), FxSource::TeUsdCad.as_str(), FxSource::EodCadForex.as_str(), FxSource::TeUsdCad.as_str(), ]; for (i, row) in rows.iter().enumerate() { assert_eq!(row.pair, FX_PAIR_USDCAD); assert_eq!(row.session_date, expected_dates[i]); let expected_ts = fx_1d_utc_day_end_micros(expected_dates[i]).unwrap(); assert_eq!(row.ts_micros, expected_ts); assert_eq!(row.known_at_micros, expected_ts); assert_eq!(row.source, expected_sources[i]); } // Strictly ascending & unique for w in rows.windows(2) { assert!(w[0].session_date < w[1].session_date); } // d1 EOD bitwise OHLC preserved assert_eq!(rows[0].open.to_bits(), 1.430_f64.to_bits()); assert_eq!(rows[0].high.to_bits(), 1.440_f64.to_bits()); assert_eq!(rows[0].low.to_bits(), 1.425_f64.to_bits()); assert_eq!(rows[0].close.to_bits(), 1.435_f64.to_bits()); // d2 TE gap fill assert_eq!(rows[1].close.to_bits(), 1.437_f64.to_bits()); // d4 TE tail fill assert_eq!(rows[3].close.to_bits(), 1.385_f64.to_bits()); // Write run B with reversed doc order AND shuffled `daily` point order inside `te_doc_1` -> // byte-identical Parquet and identical report (sans timing). let mut te_daily_1_shuffled = RawArrayBuf::new(); let mut bad_te_pt_b = RawDocumentBuf::new(); bad_te_pt_b.append(cstr!("t"), i64::from(d4) * MILLIS_PER_DAY); bad_te_pt_b.append(cstr!("o"), f64::NAN); bad_te_pt_b.append(cstr!("h"), 1.39_f64); bad_te_pt_b.append(cstr!("l"), 1.37_f64); bad_te_pt_b.append(cstr!("c"), 1.38_f64); te_daily_1_shuffled.push(bad_te_pt_b); te_daily_1_shuffled.push(te_point_ms(d2, 1.434, 1.439, 1.431, 1.437)); te_daily_1_shuffled.push(te_point_secs(d1, 1.431, 1.441, 1.426, 1.436)); let mut te_doc_1_shuffled = RawDocumentBuf::new(); te_doc_1_shuffled.append(cstr!("teSymbol"), "USDCAD"); te_doc_1_shuffled.append(cstr!("daily"), te_daily_1_shuffled); let te_docs_shuffled = [ te_doc_2.as_bytes().to_vec(), te_doc_1_shuffled.as_bytes().to_vec(), other_te_doc.as_bytes().to_vec(), ]; let eod_rev: Vec = eod_docs.into_iter().rev().flatten().collect(); let te_rev: Vec = te_docs_shuffled.into_iter().flatten().collect(); let eod_rev_path = tmp.path.join("eodPrices_rev.bson"); let te_rev_path = tmp.path.join("teMarketData_rev.bson"); fs::write(&eod_rev_path, eod_rev).unwrap(); fs::write(&te_rev_path, te_rev).unwrap(); let args_b = CurateFx1dArgs { eod_prices: eod_rev_path, te_market_data: te_rev_path, te_symbol: "usdcad".to_string(), out_dir: out_b.clone(), }; let report_b = run_curate_fx_1d(&args_b).expect("run B succeeds"); assert_report_invariants(&report_b); let parquet_b = out_b.join("fx_1d/part.parquet"); assert_eq!( fs::read(&parquet_a).unwrap(), fs::read(&parquet_b).unwrap(), "shuffled BSON input must yield byte-identical fx_1d/part.parquet" ); assert_eq!( strip_timing_line(&format_curate_fx_report(&report_a)), strip_timing_line(&format_curate_fx_report(&report_b)) ); } #[test] fn failure_modes_return_typed_errors_and_preserve_existing_parquet() { let tmp = TestTempDir::new("fx-fail"); let out_dir = tmp.path.join("out"); let fx_dir = out_dir.join("fx_1d"); fs::create_dir_all(&fx_dir).unwrap(); let live_parquet = fx_dir.join("part.parquet"); let sentinel = b"EXISTING-FX-PARQUET-SENTINEL-BYTES"; fs::write(&live_parquet, sentinel).unwrap(); let valid_eod = tmp.path.join("valid_eod.bson"); fs::write( &valid_eod, eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0), ) .unwrap(); let valid_te = tmp.path.join("valid_te.bson"); let mut valid_te_daily = RawArrayBuf::new(); valid_te_daily.push(te_point_secs(day(2025, 1, 2), 1.43, 1.44, 1.42, 1.435)); let mut valid_te_doc = RawDocumentBuf::new(); valid_te_doc.append(cstr!("teSymbol"), "USDCAD"); valid_te_doc.append(cstr!("daily"), valid_te_daily); fs::write(&valid_te, valid_te_doc.as_bytes()).unwrap(); let check_sentinel = || { assert_eq!( fs::read(&live_parquet).unwrap(), sentinel, "existing fx_1d/part.parquet must remain byte-identical on failure" ); }; // 1. Truncated BSON in eodPrices let trunc_eod = tmp.path.join("trunc_eod.bson"); fs::write(&trunc_eod, [20, 0, 0, 0, 1, 2]).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: trunc_eod, te_market_data: valid_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!(matches!(err, RunCurateFxError::BsonStream { label: "eod-prices", .. }), "{err:?}"); check_sentinel(); // 2. Truncated BSON in teMarketData let trunc_te = tmp.path.join("trunc_te.bson"); fs::write(&trunc_te, [20, 0, 0, 0, 1, 2]).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod.clone(), te_market_data: trunc_te, te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!(err, RunCurateFxError::BsonStream { label: "te-market-data", .. }), "{err:?}" ); check_sentinel(); // 3. Corrupt framed BSON bytes in eodPrices let corrupt_eod = tmp.path.join("corrupt_eod.bson"); fs::write(&corrupt_eod, [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0]).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: corrupt_eod, te_market_data: valid_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!(matches!(err, RunCurateFxError::CorruptEodBson { .. }), "{err:?}"); check_sentinel(); // 4. Corrupt BSON inside teMarketData `daily` array let corrupt_te = tmp.path.join("corrupt_te.bson"); let mut bad_te_bytes = valid_te_doc.as_bytes().to_vec(); // Corrupt the element type byte of the first element inside `daily` array. // Find `daily\0` in raw bytes; the array starts right after `daily\0` (4-byte len, then elem type). let daily_pos = bad_te_bytes .windows(6) .position(|w| w == b"daily\0") .expect("find daily key"); let first_array_elem_type_idx = daily_pos + 6 + 4; bad_te_bytes[first_array_elem_type_idx] = 0xFF; fs::write(&corrupt_te, &bad_te_bytes).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod.clone(), te_market_data: corrupt_te, te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!( err, RunCurateFxError::CorruptTeBson { source: BsonTeMarketDataError::CorruptPointBson { .. }, .. } ), "{err:?}" ); check_sentinel(); // 5. Missing eodPrices file let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: tmp.path.join("does_not_exist_eod.bson"), te_market_data: valid_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!(matches!(err, RunCurateFxError::OpenInput { label: "eod-prices", .. }), "{err:?}"); check_sentinel(); // 6. Missing teMarketData file let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod.clone(), te_market_data: tmp.path.join("does_not_exist_te.bson"), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!(err, RunCurateFxError::OpenInput { label: "te-market-data", .. }), "{err:?}" ); check_sentinel(); // 7. --out pointing at an existing regular file let out_file = tmp.path.join("regular_file"); fs::write(&out_file, b"not-a-dir").unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod.clone(), te_market_data: valid_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_file, }) .unwrap_err(); assert!(matches!(err, RunCurateFxError::InvalidOutDir { .. }), "{err:?}"); check_sentinel(); // 8. Blank and non-USD/CAD te_symbol selectors rejected before reading dumps for bad_sym in [" ", "EURUSD", "CADUSD", " usdcad "] { let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod.clone(), te_market_data: valid_te.clone(), te_symbol: bad_sym.to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!(err, RunCurateFxError::InvalidTeSymbol { .. }), "expected InvalidTeSymbol for '{bad_sym}', got {err:?}" ); check_sentinel(); } // 9. Zero decoded bars across both inputs (only non-matching symbols / empty daily) let other_eod = tmp.path.join("other_eod.bson"); fs::write( &other_eod, eod_doc("EUR.FOREX", "2025-01-02", 1.10, 1.11, 1.09, 1.105, 0.0), ) .unwrap(); let empty_te = tmp.path.join("empty_te.bson"); let mut empty_te_doc = RawDocumentBuf::new(); empty_te_doc.append(cstr!("teSymbol"), "USDCAD"); empty_te_doc.append(cstr!("daily"), RawArrayBuf::new()); fs::write(&empty_te, empty_te_doc.as_bytes()).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: other_eod, te_market_data: empty_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!(matches!(err, RunCurateFxError::NoDecodedBars { .. }), "{err:?}"); check_sentinel(); // 10. Corruption after a semantic reject in TE point must fail with CorruptTeBson // and preserve existing Parquet even when valid bars exist alongside it. let corrupt_after_semantic_te = tmp.path.join("corrupt_after_semantic_te.bson"); let mut bad_pt = RawDocumentBuf::new(); bad_pt.append(cstr!("t"), f64::NAN); bad_pt.append(cstr!("o"), 1.43_f64); bad_pt.append(cstr!("h"), 1.44_f64); bad_pt.append(cstr!("l"), 1.42_f64); bad_pt.append(cstr!("c"), 1.435_f64); let mut mixed_daily = RawArrayBuf::new(); mixed_daily.push(te_point_secs(day(2025, 1, 3), 1.43, 1.44, 1.42, 1.435)); mixed_daily.push(bad_pt); let mut mixed_te_doc = RawDocumentBuf::new(); mixed_te_doc.append(cstr!("teSymbol"), "USDCAD"); mixed_te_doc.append(cstr!("daily"), mixed_daily); let mut mixed_te_bytes = mixed_te_doc.as_bytes().to_vec(); // Corrupt element type of `c` in the second point (after `t: NaN`). let second_c_pos = mixed_te_bytes .windows(3) .rposition(|w| w == b"\x01c\0") .expect("find double element 'c' in second point"); mixed_te_bytes[second_c_pos] = 0xFF; fs::write(&corrupt_after_semantic_te, &mixed_te_bytes).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod.clone(), te_market_data: corrupt_after_semantic_te, te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!( err, RunCurateFxError::CorruptTeBson { source: BsonTeMarketDataError::CorruptPointBson { point_index: 1, .. }, .. } ), "expected CorruptTeBson after semantic point reject, got {err:?}" ); check_sentinel(); // 11. Corruption after a semantic reject in EOD doc must fail with CorruptEodBson // and preserve existing Parquet even when valid bars exist alongside it. let corrupt_after_semantic_eod = tmp.path.join("corrupt_after_semantic_eod.bson"); let mut bad_eod_bytes = eod_doc("CAD.FOREX", "2025-01-03", f64::NAN, 1.44, 1.42, 1.435, 0.0); let close_pos = bad_eod_bytes .windows(7) .position(|w| w == b"\x01close\0") .expect("find double element 'close'"); bad_eod_bytes[close_pos] = 0xFF; let mut combined_eod = eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0); combined_eod.extend_from_slice(&bad_eod_bytes); fs::write(&corrupt_after_semantic_eod, &combined_eod).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: corrupt_after_semantic_eod, te_market_data: valid_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!( err, RunCurateFxError::CorruptEodBson { source: BsonEodPriceError::CorruptBson { .. }, .. } ), "expected CorruptEodBson after semantic EOD reject, got {err:?}" ); check_sentinel(); // 12. Zero publishable rows after FX builder filtering (e.g. zero close) returns NoCuratedRows // and preserves existing Parquet byte-identically. let zero_close_eod = tmp.path.join("zero_close_eod.bson"); fs::write( &zero_close_eod, eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 0.0, 0.0), ) .unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: zero_close_eod, te_market_data: empty_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!( err, RunCurateFxError::NoCuratedRows { eod_bars_in: 1, te_bars_in: 0, .. } ), "expected NoCuratedRows when builder drops all bars, got {err:?}" ); check_sentinel(); // 13. Conflicting duplicates dropping all bars also returns NoCuratedRows and preserves sentinel. let conflict_eod = tmp.path.join("conflict_eod.bson"); let mut conflict_bytes = eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0); conflict_bytes.extend_from_slice(&eod_doc( "CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.436, 0.0, )); fs::write(&conflict_eod, &conflict_bytes).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: conflict_eod, te_market_data: empty_te, te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!( err, RunCurateFxError::NoCuratedRows { eod_bars_in: 2, te_bars_in: 0, .. } ), "expected NoCuratedRows on conflicting duplicates, got {err:?}" ); check_sentinel(); } #[test] fn single_source_runs_succeed_and_rerun_fully_replaces_previous_output() { let tmp = TestTempDir::new("fx-single-source"); let out_dir = tmp.path.join("out"); let empty_file = tmp.path.join("empty.bson"); fs::write(&empty_file, []).unwrap(); // Run 1: EOD-only (TE file is zero bytes). let eod_path = tmp.path.join("eod.bson"); let mut eod_bytes = Vec::new(); eod_bytes.extend_from_slice(&eod_doc( "CAD.FOREX", "2025-01-02", 1.430, 1.440, 1.425, 1.435, 0.0, )); eod_bytes.extend_from_slice(&eod_doc( "CAD.FOREX", "2025-01-03", 1.435, 1.445, 1.430, 1.440, 0.0, )); fs::write(&eod_path, &eod_bytes).unwrap(); let report1 = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: eod_path, te_market_data: empty_file.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .expect("EOD-only run should succeed"); assert_report_invariants(&report1); let parquet_path = out_dir.join("fx_1d").join("part.parquet"); let rows1 = read_fx_parquet(&parquet_path); assert_eq!(rows1.len(), 2); assert!(rows1 .iter() .all(|r| r.source == FxSource::EodCadForex.as_str())); // Run 2: TE-only (EOD file is zero bytes) into the same out_dir must fully replace output. let te_path = tmp.path.join("te.bson"); let mut daily = RawArrayBuf::new(); daily.push(te_point_secs(day(2025, 2, 10), 1.420, 1.430, 1.415, 1.425)); let mut te_doc = RawDocumentBuf::new(); te_doc.append(cstr!("teSymbol"), "USDCAD"); te_doc.append(cstr!("daily"), daily); fs::write(&te_path, te_doc.as_bytes()).unwrap(); let report2 = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: empty_file, te_market_data: te_path, te_symbol: "USDCAD".to_string(), out_dir, }) .expect("TE-only rerun should succeed"); assert_report_invariants(&report2); let rows2 = read_fx_parquet(&parquet_path); assert_eq!(rows2.len(), 1); assert_eq!(rows2[0].session_date, day(2025, 2, 10)); assert_eq!(rows2[0].source, FxSource::TeUsdCad.as_str()); } #[test] fn truncated_dump_after_valid_documents_fails_and_preserves_existing_parquet() { let tmp = TestTempDir::new("fx-trunc-tail"); let out_dir = tmp.path.join("out"); let fx_dir = out_dir.join("fx_1d"); fs::create_dir_all(&fx_dir).unwrap(); let parquet_path = fx_dir.join("part.parquet"); let sentinel = b"SENTINEL_PARQUET_TAIL_TRUNC"; fs::write(&parquet_path, sentinel).unwrap(); let valid_eod = tmp.path.join("valid_eod.bson"); fs::write( &valid_eod, eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0), ) .unwrap(); let valid_te = tmp.path.join("valid_te.bson"); let mut daily = RawArrayBuf::new(); daily.push(te_point_secs(day(2025, 1, 3), 1.43, 1.44, 1.42, 1.435)); let mut te_doc = RawDocumentBuf::new(); te_doc.append(cstr!("teSymbol"), "USDCAD"); te_doc.append(cstr!("daily"), daily); fs::write(&valid_te, te_doc.as_bytes()).unwrap(); // 1. EOD dump truncated mid-document after two valid documents. let trunc_eod = tmp.path.join("trunc_after_valid_eod.bson"); let mut eod_bytes = Vec::new(); eod_bytes.extend_from_slice(&eod_doc( "CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0, )); eod_bytes.extend_from_slice(&eod_doc( "CAD.FOREX", "2025-01-03", 1.435, 1.445, 1.43, 1.44, 0.0, )); let third = eod_doc("CAD.FOREX", "2025-01-06", 1.44, 1.45, 1.435, 1.445, 0.0); eod_bytes.extend_from_slice(&third[..third.len() / 2]); fs::write(&trunc_eod, &eod_bytes).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: trunc_eod, te_market_data: valid_te.clone(), te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .unwrap_err(); assert!( matches!(err, RunCurateFxError::BsonStream { .. }), "expected BsonStream for truncated EOD tail, got {err:?}" ); assert_eq!(fs::read(&parquet_path).unwrap(), sentinel); // 2. TE dump truncated mid-document after a valid document. let trunc_te = tmp.path.join("trunc_after_valid_te.bson"); let mut te_bytes = te_doc.as_bytes().to_vec(); let half = te_doc.as_bytes().len() / 2; te_bytes.extend_from_slice(&te_doc.as_bytes()[..half]); fs::write(&trunc_te, &te_bytes).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: valid_eod, te_market_data: trunc_te, te_symbol: "USDCAD".to_string(), out_dir, }) .unwrap_err(); assert!( matches!(err, RunCurateFxError::BsonStream { .. }), "expected BsonStream for truncated TE tail, got {err:?}" ); assert_eq!(fs::read(&parquet_path).unwrap(), sentinel); } #[test] fn corrupt_bytes_in_non_usdcad_te_document_abort_run_with_exact_offset() { let tmp = TestTempDir::new("fx-corrupt-other-te"); let out_dir = tmp.path.join("out"); let fx_dir = out_dir.join("fx_1d"); fs::create_dir_all(&fx_dir).unwrap(); let parquet_path = fx_dir.join("part.parquet"); let sentinel = b"SENTINEL_PARQUET_OTHER_TE"; fs::write(&parquet_path, sentinel).unwrap(); let empty_eod = tmp.path.join("empty_eod.bson"); fs::write(&empty_eod, []).unwrap(); // First doc: valid USDCAD. let mut daily1 = RawArrayBuf::new(); daily1.push(te_point_secs(day(2025, 1, 3), 1.43, 1.44, 1.42, 1.435)); let mut doc1 = RawDocumentBuf::new(); doc1.append(cstr!("teSymbol"), "USDCAD"); doc1.append(cstr!("daily"), daily1); let doc1_len = doc1.as_bytes().len(); // Second doc: non-USDCAD (EURUSD) with a corrupted element tag after teSymbol. let mut doc2 = RawDocumentBuf::new(); doc2.append(cstr!("teSymbol"), "EURUSD"); doc2.append(cstr!("extra"), 42_i32); let mut doc2_bytes = doc2.as_bytes().to_vec(); let extra_pos = doc2_bytes .windows(7) .position(|w| w == b"\x10extra\0") .expect("find int32 element 'extra'"); doc2_bytes[extra_pos] = 0xFF; let mut te_bytes = doc1.as_bytes().to_vec(); te_bytes.extend_from_slice(&doc2_bytes); let te_path = tmp.path.join("te.bson"); fs::write(&te_path, &te_bytes).unwrap(); let err = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: empty_eod, te_market_data: te_path, te_symbol: "USDCAD".to_string(), out_dir, }) .unwrap_err(); match err { RunCurateFxError::CorruptTeBson { source: BsonTeMarketDataError::CorruptBson { offset, .. }, .. } => assert_eq!(offset, doc1_len), other => panic!("expected CorruptTeBson at offset {doc1_len}, got {other:?}"), } assert_eq!(fs::read(&parquet_path).unwrap(), sentinel); } #[test] fn te_data_quality_doc_rejects_are_counted_and_run_continues() { let tmp = TestTempDir::new("fx-te-doc-rejects"); let out_dir = tmp.path.join("out"); let empty_eod = tmp.path.join("empty_eod.bson"); fs::write(&empty_eod, []).unwrap(); let mut te_bytes = Vec::new(); // 1. Missing `daily` on matched symbol. let mut missing_daily = RawDocumentBuf::new(); missing_daily.append(cstr!("teSymbol"), "USDCAD"); te_bytes.extend_from_slice(missing_daily.as_bytes()); // 2. Non-array `daily` on matched symbol. let mut bad_daily = RawDocumentBuf::new(); bad_daily.append(cstr!("teSymbol"), "USDCAD"); bad_daily.append(cstr!("daily"), "not-an-array"); te_bytes.extend_from_slice(bad_daily.as_bytes()); // 3. Blank `teSymbol`. let mut blank_sym = RawDocumentBuf::new(); blank_sym.append(cstr!("teSymbol"), " "); blank_sym.append(cstr!("daily"), RawArrayBuf::new()); te_bytes.extend_from_slice(blank_sym.as_bytes()); // 4. Valid USDCAD document. let mut valid_daily = RawArrayBuf::new(); valid_daily.push(te_point_secs(day(2025, 1, 6), 1.43, 1.44, 1.42, 1.435)); let mut valid_doc = RawDocumentBuf::new(); valid_doc.append(cstr!("teSymbol"), "USDCAD"); valid_doc.append(cstr!("daily"), valid_daily); te_bytes.extend_from_slice(valid_doc.as_bytes()); let te_path = tmp.path.join("te.bson"); fs::write(&te_path, &te_bytes).unwrap(); let report = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: empty_eod, te_market_data: te_path, te_symbol: "USDCAD".to_string(), out_dir, }) .expect("data-quality rejects should be counted without aborting"); assert_report_invariants(&report); assert_eq!(report.te_decode.docs_in, 4); assert_eq!(report.te_decode.docs_matched, 1); assert_eq!(report.te_decode.rejected_daily_missing, 1); assert_eq!(report.te_decode.rejected_daily_not_array, 1); assert_eq!(report.te_decode.rejected_empty_symbol, 1); assert_eq!(report.write_stats.rows_written, 1); } #[test] fn te_utc_day_edge_timestamps_never_have_known_at_before_raw_t() { let tmp = TestTempDir::new("fx-no-lookahead"); let out_dir = tmp.path.join("out"); let empty_eod = tmp.path.join("empty_eod.bson"); fs::write(&empty_eod, []).unwrap(); // (raw_t, expected_session_date, raw_t_micros) sorted by expected_session_date across // pre-1970 and post-1970 UTC day edges in both seconds and milliseconds. let cases: &[(i64, i32, i64)] = &[ (-100_000_000_001, -1158, -100_000_000_001_000), // 1966-10-30 14:13:19.999 UTC (ms) (-86_401, -2, -86_401_000_000), // 1969-12-30 23:59:59 UTC (s) (-1, -1, -1_000_000), // 1969-12-31 23:59:59 UTC (s) (0, 0, 0), // 1970-01-01 00:00:00 UTC (s) (86_400, 1, 86_400_000_000), // 1970-01-02 00:00:00 UTC (s) (1_735_689_599_999, day(2024, 12, 31), 1_735_689_599_999_000), // 2024-12-31 23:59:59.999 UTC (ms) (1_735_689_600_000, day(2025, 1, 1), 1_735_689_600_000_000), // 2025-01-01 00:00:00.000 UTC (ms) ]; let mut daily = RawArrayBuf::new(); for &(raw_t, _, _) in cases { let mut pt = RawDocumentBuf::new(); pt.append(cstr!("t"), raw_t); pt.append(cstr!("o"), 1.35_f64); pt.append(cstr!("h"), 1.36_f64); pt.append(cstr!("l"), 1.34_f64); pt.append(cstr!("c"), 1.355_f64); daily.push(pt); } let mut te_doc = RawDocumentBuf::new(); te_doc.append(cstr!("teSymbol"), "USDCAD"); te_doc.append(cstr!("daily"), daily); let te_path = tmp.path.join("te.bson"); fs::write(&te_path, te_doc.as_bytes()).unwrap(); let report = run_curate_fx_1d(&CurateFx1dArgs { eod_prices: empty_eod, te_market_data: te_path, te_symbol: "USDCAD".to_string(), out_dir: out_dir.clone(), }) .expect("day-edge run should succeed"); assert_report_invariants(&report); let rows = read_fx_parquet(&out_dir.join("fx_1d").join("part.parquet")); assert_eq!(rows.len(), cases.len()); for (row, &(_, expected_day, raw_t_micros)) in rows.iter().zip(cases.iter()) { assert_eq!(row.session_date, expected_day); assert_eq!( row.known_at_micros, fx_1d_utc_day_end_micros(expected_day).expect("valid day-end micros") ); assert!( row.known_at_micros >= raw_t_micros, "look-ahead violation: session_date={} known_at={} < raw_t={}", row.session_date, row.known_at_micros, raw_t_micros ); } }