//! End-to-end binary integration tests for `curate-etl curate-shorts` (`M1.2ad`). use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::sync::atomic::{AtomicU64, Ordering}; use bson::raw::{cstr, RawDocumentBuf}; use bson::DateTime as BsonDateTime; use curate_etl::{ymd_to_epoch_days, SHORTS_SOURCE_CEO}; use parquet::basic::{LogicalType, Repetition, TimeUnit, Type as PhysicalType}; use parquet::file::reader::{FileReader, SerializedFileReader}; use parquet::record::RowAccessor; static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); struct TempDir { path: PathBuf, } impl TempDir { 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-it-shorts-{tag}-{pid}-{seq}")); let _ = fs::remove_dir_all(&path); fs::create_dir_all(&path).expect("create integration test temp dir"); Self { path } } } impl Drop for TempDir { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.path); } } fn run(args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_curate-etl")) .args(args) .output() .expect("spawn curate-etl binary") } fn stdout(o: &Output) -> String { String::from_utf8_lossy(&o.stdout).into_owned() } fn stderr(o: &Output) -> String { String::from_utf8_lossy(&o.stderr).into_owned() } fn write_bytes(path: &Path, bytes: &[u8]) { let mut f = File::create(path).expect("create file"); f.write_all(bytes).expect("write file"); } fn day(y: i32, m: u32, d: u32) -> i32 { ymd_to_epoch_days(y, m, d).expect("valid date") } fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { let epoch_day = day(y, m, d); let secs = i64::from(epoch_day) * 86_400 + i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second); secs * 1_000_000 } fn make_doc( sym: &str, report_date: i32, shares_short: f64, net_change: Option, pct_float: Option, ) -> Vec { let mut doc = RawDocumentBuf::new(); doc.append(cstr!("symbol"), sym); doc.append( cstr!("timestamp"), BsonDateTime::from_millis(i64::from(report_date) * 86_400_000), ); doc.append(cstr!("sharesShort"), shares_short); if let Some(v) = net_change { doc.append(cstr!("netChange"), v); } if let Some(v) = pct_float { doc.append(cstr!("pctFloat"), v); } doc.into_bytes() } #[derive(Debug, PartialEq)] struct ReadRow { listing_id: i32, report_date: i32, known_at: i64, shares_short: f64, net_change: Option, pct_float: Option, source: String, } fn read_shorts_parquet(path: &Path) -> Vec { let file = File::open(path).expect("open shorts/part.parquet"); let reader = SerializedFileReader::new(file).expect("parse parquet"); let schema = reader.metadata().file_metadata().schema(); let fields = schema.get_fields(); assert_eq!(fields.len(), 7, "expected 7 contract columns"); let expected_cols: [(&str, PhysicalType, Repetition, Option); 7] = [ ("listing_id", PhysicalType::INT32, Repetition::REQUIRED, None), ( "report_date", PhysicalType::INT32, Repetition::REQUIRED, Some(LogicalType::Date), ), ( "known_at", PhysicalType::INT64, Repetition::REQUIRED, Some(LogicalType::timestamp(true, TimeUnit::MICROS)), ), ( "shares_short", PhysicalType::DOUBLE, Repetition::REQUIRED, None, ), ( "net_change", PhysicalType::DOUBLE, Repetition::OPTIONAL, None, ), ( "pct_float", PhysicalType::DOUBLE, Repetition::OPTIONAL, None, ), ( "source", PhysicalType::BYTE_ARRAY, Repetition::REQUIRED, Some(LogicalType::String), ), ]; for (field, (name, phys, rep, logical)) in fields.iter().zip(expected_cols) { assert_eq!(field.name(), name); assert_eq!(field.get_physical_type(), phys); assert_eq!(field.get_basic_info().repetition(), rep); assert_eq!(field.get_basic_info().logical_type_ref(), logical.as_ref()); } let mut out = Vec::new(); let iter = reader.get_row_iter(None).expect("row iter"); for row_res in iter { let row = row_res.expect("row"); let listing_id = row.get_int(0).expect("listing_id"); let report_date = match row.get_column_iter().nth(1).expect("report_date").1 { parquet::record::Field::Date(d) => *d, other => panic!("expected Date for report_date, got {other:?}"), }; let known_at = row.get_timestamp_micros(2).expect("known_at"); let shares_short = row.get_double(3).expect("shares_short"); let net_change = row.get_double(4).ok(); let pct_float = row.get_double(5).ok(); let source = row.get_string(6).expect("source").to_owned(); out.push(ReadRow { listing_id, report_date, known_at, shares_short, net_change, pct_float, source, }); } out } #[test] fn end_to_end_est_edt_holiday_known_at_sorting_and_determinism() { let dir = TempDir::new("e2e"); let map_path = dir.path.join("provider_mapping.tsv"); let bson_fwd = dir.path.join("shorts_fwd.bson"); let bson_rev = dir.path.join("shorts_rev.bson"); let out_1 = dir.path.join("out_1"); let out_2 = dir.path.join("out_2"); let out_rev = dir.path.join("out_rev"); write_bytes( &map_path, concat!( "ceo\tRY\t2015-01-01\t\t200\n", "ceo\tTD\t2015-01-01\t\t100\n", ) .as_bytes(), ); // Three cases: // 1. EST: 2024-01-15 (Mon) + 4 TSX bdays -> 2024-01-19 (Fri) 17:00 EST = 22:00 UTC // 2. EDT: 2024-07-15 (Mon) + 4 TSX bdays -> 2024-07-19 (Fri) 17:00 EDT = 21:00 UTC // 3. Holiday crossing (Good Friday 2024-03-29): // 2024-03-28 (Thu) + 4 TSX bdays -> Mon Apr 1 (1), Tue Apr 2 (2), Wed Apr 3 (3), Thu Apr 4 (4) // = 2024-04-04 17:00 EDT = 21:00 UTC // Deliberately emitted unsorted (listing 200 before 100, later dates before earlier) + 1 unmapped key. let docs = vec![ make_doc("RY", day(2024, 7, 15), 250_000.0, Some(5_000.0), Some(1.2)), make_doc("TD", day(2024, 3, 28), 300_000.0, Some(-2_500.0), None), make_doc("TD", day(2024, 1, 15), 180_000.0, None, Some(0.8)), make_doc("UNMAPPED", day(2024, 1, 15), 10_000.0, None, None), ]; let mut fwd_bytes = Vec::new(); for d in &docs { fwd_bytes.extend_from_slice(d); } write_bytes(&bson_fwd, &fwd_bytes); let mut rev_bytes = Vec::new(); for d in docs.iter().rev() { rev_bytes.extend_from_slice(d); } write_bytes(&bson_rev, &rev_bytes); let invoke = |bson: &Path, out: &Path| { run(&[ "curate-shorts", "--ceo-shorts", bson.to_str().unwrap(), "--provider-mapping", map_path.to_str().unwrap(), "--out", out.to_str().unwrap(), "--shares-short-field", "sharesShort", "--net-change-field", "netChange", "--pct-float-field", "pctFloat", ]) }; let res1 = invoke(&bson_fwd, &out_1); assert!(res1.status.success(), "{}", stderr(&res1)); assert!(stderr(&res1).is_empty(), "{}", stderr(&res1)); let out_text = stdout(&res1); assert!(out_text.contains("curate-etl curate-shorts"), "{out_text}"); assert!(out_text.contains("dropped_unmapped=1"), "{out_text}"); assert!(out_text.contains("rows_written=3"), "{out_text}"); let rows = read_shorts_parquet(&out_1.join("shorts/part.parquet")); assert_eq!( rows, vec![ ReadRow { listing_id: 100, report_date: day(2024, 1, 15), known_at: utc_micros(2024, 1, 19, 22, 0, 0), // EST 17:00 = 22:00 UTC shares_short: 180_000.0, net_change: None, pct_float: Some(0.8), source: SHORTS_SOURCE_CEO.to_string(), }, ReadRow { listing_id: 100, report_date: day(2024, 3, 28), known_at: utc_micros(2024, 4, 4, 21, 0, 0), // crosses Good Friday -> EDT 17:00 = 21:00 UTC shares_short: 300_000.0, net_change: Some(-2_500.0), pct_float: None, source: SHORTS_SOURCE_CEO.to_string(), }, ReadRow { listing_id: 200, report_date: day(2024, 7, 15), known_at: utc_micros(2024, 7, 19, 21, 0, 0), // EDT 17:00 = 21:00 UTC shares_short: 250_000.0, net_change: Some(5_000.0), pct_float: Some(1.2), source: SHORTS_SOURCE_CEO.to_string(), }, ] ); // Determinism: repeated run and reversed BSON order must produce byte-identical Parquet. let res2 = invoke(&bson_fwd, &out_2); assert!(res2.status.success(), "{}", stderr(&res2)); let res_rev = invoke(&bson_rev, &out_rev); assert!(res_rev.status.success(), "{}", stderr(&res_rev)); let bytes_1 = fs::read(out_1.join("shorts/part.parquet")).unwrap(); let bytes_2 = fs::read(out_2.join("shorts/part.parquet")).unwrap(); let bytes_rev = fs::read(out_rev.join("shorts/part.parquet")).unwrap(); assert_eq!(bytes_1, bytes_2, "repeated run must be byte-identical"); assert_eq!(bytes_1, bytes_rev, "reversed input must be byte-identical"); } #[test] fn failure_modes_exit_nonzero_without_usage_and_preserve_preexisting_parquet() { let dir = TempDir::new("failures"); let out_dir = dir.path.join("out"); let shorts_dir = out_dir.join("shorts"); fs::create_dir_all(&shorts_dir).unwrap(); let sentinel_path = shorts_dir.join("part.parquet"); let sentinel = b"PREEXISTING-SHORTS-SENTINEL".to_vec(); write_bytes(&sentinel_path, &sentinel); let valid_map = dir.path.join("valid_map.tsv"); write_bytes(&valid_map, b"ceo\tRY\t2020-01-01\t\t101\n"); let valid_bson = dir.path.join("valid.bson"); write_bytes(&valid_bson, &make_doc("RY", day(2024, 3, 15), 100.0, None, None)); // 1. Missing input file let missing = dir.path.join("missing.bson"); let res = run(&[ "curate-shorts", "--ceo-shorts", missing.to_str().unwrap(), "--provider-mapping", valid_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!(!res.status.success()); assert!(stdout(&res).is_empty()); let err = stderr(&res); assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); assert!(!err.contains("Usage:"), "{err}"); assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); // 2. Truncated BSON let trunc_bson = dir.path.join("trunc.bson"); write_bytes(&trunc_bson, &[25, 0, 0, 0, 0x02, b'a']); let res = run(&[ "curate-shorts", "--ceo-shorts", trunc_bson.to_str().unwrap(), "--provider-mapping", valid_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!(!res.status.success()); let err = stderr(&res); assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); assert!(!err.contains("Usage:"), "{err}"); assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); // 3. Malformed mapping TSV let bad_map = dir.path.join("bad_map.tsv"); write_bytes(&bad_map, b"ceo\tRY\tbad-date\t\t101\n"); let res = run(&[ "curate-shorts", "--ceo-shorts", valid_bson.to_str().unwrap(), "--provider-mapping", bad_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!(!res.status.success()); let err = stderr(&res); assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); assert!(!err.contains("Usage:"), "{err}"); assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); // 4. All-unmapped keys -> exits 0, counts dropped_unmapped=1, preserves sentinel let unmapped_bson = dir.path.join("unmapped.bson"); write_bytes( &unmapped_bson, &make_doc("NO_SUCH_KEY", day(2024, 3, 15), 100.0, None, None), ); let res = run(&[ "curate-shorts", "--ceo-shorts", unmapped_bson.to_str().unwrap(), "--provider-mapping", valid_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!(res.status.success(), "{}", stderr(&res)); let out = stdout(&res); assert!(out.contains("dropped_unmapped=1"), "{out}"); assert!(out.contains("rows_written=0"), "{out}"); assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel); // 5. Corrupt UTF-8 in an unused text field of an otherwise valid, mapped report -> // must fail closed with non-zero exit and preserve pre-existing shorts/part.parquet. let mut unused_corrupt_doc = RawDocumentBuf::new(); unused_corrupt_doc.append(cstr!("symbol"), "RY"); unused_corrupt_doc.append( cstr!("timestamp"), BsonDateTime::from_millis(i64::from(day(2024, 3, 15)) * 86_400_000), ); unused_corrupt_doc.append(cstr!("sharesShort"), 100.0_f64); unused_corrupt_doc.append(cstr!("unusedNote"), "CORRUPT"); let mut unused_corrupt_bytes = unused_corrupt_doc.into_bytes(); let pos = unused_corrupt_bytes .windows(7) .position(|w| w == b"CORRUPT") .expect("locate CORRUPT marker"); unused_corrupt_bytes[pos] = 0xff; unused_corrupt_bytes[pos + 1] = 0xfe; let unused_corrupt_bson = dir.path.join("unused_corrupt.bson"); write_bytes(&unused_corrupt_bson, &unused_corrupt_bytes); let res = run(&[ "curate-shorts", "--ceo-shorts", unused_corrupt_bson.to_str().unwrap(), "--provider-mapping", valid_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!(!res.status.success(), "corrupt unused string must fail closed"); assert!(stdout(&res).is_empty()); let err = stderr(&res); assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); assert!(!err.contains("Usage:"), "{err}"); assert_eq!( fs::read(&sentinel_path).unwrap(), sentinel, "existing shorts/part.parquet must remain byte-identical" ); // 6. Malformed element inside an unused embedded document -> must also fail closed. let mut inner = RawDocumentBuf::new(); inner.append(cstr!("k"), 7_i32); let mut nested_corrupt_doc = RawDocumentBuf::new(); nested_corrupt_doc.append(cstr!("symbol"), "RY"); nested_corrupt_doc.append( cstr!("timestamp"), BsonDateTime::from_millis(i64::from(day(2024, 3, 15)) * 86_400_000), ); nested_corrupt_doc.append(cstr!("sharesShort"), 100.0_f64); nested_corrupt_doc.append(cstr!("meta"), inner); let mut nested_corrupt_bytes = nested_corrupt_doc.into_bytes(); let k_pos = nested_corrupt_bytes .windows(3) .position(|w| w == [0x10, b'k', 0x00]) .expect("locate nested int32 element"); nested_corrupt_bytes[k_pos] = 0x7e; let nested_corrupt_bson = dir.path.join("nested_corrupt.bson"); write_bytes(&nested_corrupt_bson, &nested_corrupt_bytes); let res = run(&[ "curate-shorts", "--ceo-shorts", nested_corrupt_bson.to_str().unwrap(), "--provider-mapping", valid_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!(!res.status.success(), "corrupt embedded doc must fail closed"); assert!(stdout(&res).is_empty()); let err = stderr(&res); assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); assert!(!err.contains("Usage:"), "{err}"); assert_eq!( fs::read(&sentinel_path).unwrap(), sentinel, "existing shorts/part.parquet must remain byte-identical" ); // 7. Damaged BSON array index in an unused array field ("0" -> "8") -> // must fail closed with non-zero exit and preserve pre-existing shorts/part.parquet. let mut arr = bson::RawArrayBuf::new(); arr.push(10_i32); arr.push(20_i32); let mut arr_corrupt_doc = RawDocumentBuf::new(); arr_corrupt_doc.append(cstr!("symbol"), "RY"); arr_corrupt_doc.append( cstr!("timestamp"), BsonDateTime::from_millis(i64::from(day(2024, 3, 15)) * 86_400_000), ); arr_corrupt_doc.append(cstr!("sharesShort"), 100.0_f64); arr_corrupt_doc.append(cstr!("tags"), arr); let mut arr_corrupt_bytes = arr_corrupt_doc.into_bytes(); let idx0_pos = arr_corrupt_bytes .windows(3) .position(|w| w == [0x10, b'0', 0x00]) .expect("locate array index 0 int32 element"); arr_corrupt_bytes[idx0_pos + 1] = b'8'; let arr_corrupt_bson = dir.path.join("array_index_corrupt.bson"); write_bytes(&arr_corrupt_bson, &arr_corrupt_bytes); let res = run(&[ "curate-shorts", "--ceo-shorts", arr_corrupt_bson.to_str().unwrap(), "--provider-mapping", valid_map.to_str().unwrap(), "--out", out_dir.to_str().unwrap(), "--shares-short-field", "sharesShort", ]); assert!( !res.status.success(), "damaged BSON array index must fail closed" ); assert!(stdout(&res).is_empty()); let err = stderr(&res); assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}"); assert!(!err.contains("Usage:"), "{err}"); assert!( err.contains("array index"), "expected array index corruption detail in stderr, got: {err}" ); assert_eq!( fs::read(&sentinel_path).unwrap(), sentinel, "existing shorts/part.parquet must remain byte-identical" ); }