T-112: M1.2ab — tools/curate-etl: third runnable command curate-corporate-actions (concatenated-BSON qmSplits + qmDividends files + provider_mapping TSV + Pass 6 delisting-outcomes TSV → corporate_actions/part.parquet) with end-to-end tests and local benchmark (no new crates, no MongoDB connection)

This commit is contained in:
Studio 2026-11-29 02:18:49 -05:00
parent 3cd35b692f
commit 9594d82cdf
2 changed files with 254 additions and 48 deletions

View file

@ -59,7 +59,7 @@ use std::sync::Arc;
use std::time::Instant;
use crate::bson_eod_prices::parse_ymd_strict_days;
use crate::bson_qm_actions::BsonQmActionDecodeStats;
use crate::bson_qm_actions::{BsonQmActionDecodeStats, BsonQmActionError};
use crate::bson_stream::{
decode_qm_dividend_chunks, decode_qm_split_chunks, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader,
@ -126,7 +126,8 @@ pub(crate) struct CurateCorporateActionsTimedRun {
/// Typed errors returned by [`run_curate_corporate_actions`] and [`load_delistings_tsv`].
///
/// Every variant's `Display` output is a single line naming the offending path (and 1-based line
/// number for TSV parse errors, or stream byte offset via [`BsonStreamError`]).
/// number for TSV parse errors, or absolute stream byte offset via [`BsonStreamError`] /
/// `CorruptBson`).
#[derive(Debug)]
pub enum RunCurateCorporateActionsError {
InvalidOutDir {
@ -157,6 +158,12 @@ pub enum RunCurateCorporateActionsError {
path: PathBuf,
source: BsonStreamError,
},
CorruptBson {
label: &'static str,
path: PathBuf,
offset: u64,
source: BsonQmActionError,
},
CurateWrite {
out_dir: PathBuf,
source: CurateCorporateActionsWriteError,
@ -190,6 +197,16 @@ impl fmt::Display for RunCurateCorporateActionsError {
path,
source,
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
Self::CorruptBson {
label,
path,
offset,
source,
} => write!(
f,
"corrupt {label} BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CurateWrite { out_dir, source } => {
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
}
@ -203,6 +220,7 @@ impl Error for RunCurateCorporateActionsError {
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
Self::ProviderMapping { source, .. } => Some(source),
Self::BsonStream { source, .. } => Some(source),
Self::CorruptBson { source, .. } => Some(source),
Self::CurateWrite { source, .. } => Some(source),
Self::InvalidOutDir { .. } | Self::TsvParse { .. } => None,
}
@ -398,6 +416,16 @@ fn load_provider_mapping_table(
})
}
#[inline]
fn is_structural_bson_error(err: &BsonQmActionError) -> bool {
matches!(
err,
BsonQmActionError::TruncatedDocument { .. }
| BsonQmActionError::CorruptDocumentLength { .. }
| BsonQmActionError::CorruptBson { .. }
)
}
#[inline]
fn intern_qm_key(keys: &mut HashSet<Arc<str>>, raw: &str) -> Arc<str> {
if let Some(existing) = keys.get(raw) {
@ -481,18 +509,33 @@ fn decode_all_inputs(
},
)?;
let mut splits: Vec<(Arc<str>, SplitActionEvent)> = Vec::new();
let splits_decode = decode_qm_split_chunks(
let mut splits_corrupt_err: Option<(u64, BsonQmActionError)> = None;
let splits_decode_res = decode_qm_split_chunks(
&mut splits_reader,
|split| {
let key = intern_qm_key(&mut qm_keys, split.qm_search_code);
splits.push((key, split.to_split_action_event()));
},
|_offset, _err| {},
)
.map_err(|source| RunCurateCorporateActionsError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
|offset, err| {
if splits_corrupt_err.is_none() && is_structural_bson_error(&err) {
splits_corrupt_err = Some((offset, err));
}
},
);
if let Some((offset, source)) = splits_corrupt_err {
return Err(RunCurateCorporateActionsError::CorruptBson {
label: "qm-splits",
path: args.qm_splits.clone(),
offset,
source,
});
}
let splits_decode = splits_decode_res.map_err(|source| {
RunCurateCorporateActionsError::BsonStream {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
}
})?;
let splits_docs_framed = splits_reader.docs_framed();
let splits_bytes_read = splits_reader.bytes_read();
@ -514,18 +557,33 @@ fn decode_all_inputs(
},
)?;
let mut dividends: Vec<(Arc<str>, DividendActionEvent)> = Vec::new();
let dividends_decode = decode_qm_dividend_chunks(
let mut dividends_corrupt_err: Option<(u64, BsonQmActionError)> = None;
let dividends_decode_res = decode_qm_dividend_chunks(
&mut dividends_reader,
|div| {
let key = intern_qm_key(&mut qm_keys, div.qm_search_code);
dividends.push((key, div.to_dividend_action_event()));
},
|_offset, _err| {},
)
.map_err(|source| RunCurateCorporateActionsError::BsonStream {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
|offset, err| {
if dividends_corrupt_err.is_none() && is_structural_bson_error(&err) {
dividends_corrupt_err = Some((offset, err));
}
},
);
if let Some((offset, source)) = dividends_corrupt_err {
return Err(RunCurateCorporateActionsError::CorruptBson {
label: "qm-dividends",
path: args.qm_dividends.clone(),
offset,
source,
});
}
let dividends_decode = dividends_decode_res.map_err(|source| {
RunCurateCorporateActionsError::BsonStream {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
}
})?;
let dividends_docs_framed = dividends_reader.docs_framed();
let dividends_bytes_read = dividends_reader.bytes_read();

View file

@ -210,7 +210,8 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
let divs_a = dir.path().join("divs_a.bson");
let divs_b = dir.path().join("divs_b.bson");
let divs_fx_alt = dir.path().join("divs_fx_alt.bson");
let map_path = dir.path().join("provider_mapping.tsv");
let map_a = dir.path().join("provider_mapping_a.tsv");
let map_b = dir.path().join("provider_mapping_b.tsv");
let delist_a = dir.path().join("delistings_a.tsv");
let delist_b = dir.path().join("delistings_b.tsv");
let out_a = dir.path().join("out_a");
@ -225,18 +226,33 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
// - 300: SIVB:US ended 2023-03-10, reused by listing 999 on 2023-03-20.. -> OTC transfer to 301 (SIVBQ:US) on 2023-03-28
// - 400: DEL30:US (-0.3 terminal delisting)
// - 500: DEL100:US (-1.0 terminal delisting)
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\
qm\tRVS:US\t2010-01-01\t\t250\n\
qm\tSIVB:US\t2010-01-01\t2023-03-10\t300\n\
qm\tSIVB:US\t2023-03-20\t\t999\n\
qm\tSIVBQ:US\t2023-03-28\t\t301\n\
qm\tDEL30:US\t2015-01-01\t\t400\n\
qm\tDEL100:US\t2015-01-01\t\t500\n",
);
let map_rows_a = [
"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",
"qm\tRVS:US\t2010-01-01\t\t250\n",
"qm\tSIVB:US\t2010-01-01\t2023-03-10\t300\n",
"qm\tSIVB:US\t2023-03-20\t\t999\n",
"qm\tSIVBQ:US\t2023-03-28\t\t301\n",
"qm\tDEL30:US\t2015-01-01\t\t400\n",
"qm\tDEL100:US\t2015-01-01\t\t500\n",
];
let map_rows_b = [
map_rows_a[8],
map_rows_a[5],
map_rows_a[2],
map_rows_a[6],
map_rows_a[0],
map_rows_a[4],
map_rows_a[7],
map_rows_a[1],
map_rows_a[3],
];
let map_bytes_a = map_rows_a.concat();
let map_bytes_b = map_rows_b.concat();
assert_eq!(map_bytes_a.len(), map_bytes_b.len());
write_bytes(&map_a, map_bytes_a.as_bytes());
write_bytes(&map_b, map_bytes_b.as_bytes());
// Splits:
// - NVDA 10:1 with declared_date < ex_date (DeclaredDate)
@ -274,19 +290,22 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
// - SIVB:US -> SIVBQ:US on 2023-03-28 with from_listing_id=300 (across ended range & reuse!)
// - DEL30:US -0.3 on 2023-09-15 (no from_listing_id)
// - DEL100:US -1.0 on 2024-02-01 (with explicit from_listing_id=500)
let delist_rows_a = "SIVB:US\t2023-03-28\t300\tSIVBQ:US\t\n\
DEL30:US\t2023-09-15\t\t\t-0.3\n\
DEL100:US\t2024-02-01\t500\t\t-1.0\n";
let delist_rows_b = "DEL100:US\t2024-02-01\t500\t\t-1.0\r\n\
SIVB:US\t2023-03-28\t300\tSIVBQ:US\t\r\n\
DEL30:US\t2023-09-15\t\t\t-0.3\r\n\r\n";
write_bytes(&delist_a, delist_rows_a.as_bytes());
write_bytes(&delist_b, delist_rows_b.as_bytes());
let delist_rows_a = [
"SIVB:US\t2023-03-28\t300\tSIVBQ:US\t\n",
"DEL30:US\t2023-09-15\t\t\t-0.3\n",
"DEL100:US\t2024-02-01\t500\t\t-1.0\n",
];
let delist_rows_b = [delist_rows_a[2], delist_rows_a[0], delist_rows_a[1]];
let delist_bytes_a = delist_rows_a.concat();
let delist_bytes_b = delist_rows_b.concat();
assert_eq!(delist_bytes_a.len(), delist_bytes_b.len());
write_bytes(&delist_a, delist_bytes_a.as_bytes());
write_bytes(&delist_b, delist_bytes_b.as_bytes());
let args_a = CurateCorporateActionsArgs {
qm_splits: splits_a.clone(),
qm_dividends: divs_a.clone(),
provider_mapping: map_path.clone(),
provider_mapping: map_a.clone(),
delistings: Some(delist_a.clone()),
out_dir: out_a.clone(),
};
@ -296,7 +315,7 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
let args_b = CurateCorporateActionsArgs {
qm_splits: splits_b,
qm_dividends: divs_b,
provider_mapping: map_path.clone(),
provider_mapping: map_b,
delistings: Some(delist_b),
out_dir: out_b.clone(),
};
@ -306,7 +325,7 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
let args_fx = CurateCorporateActionsArgs {
qm_splits: splits_a.clone(),
qm_dividends: divs_fx_alt,
provider_mapping: map_path.clone(),
provider_mapping: map_a.clone(),
delistings: Some(delist_a.clone()),
out_dir: out_fx_alt.clone(),
};
@ -316,7 +335,7 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
let args_timed = CurateCorporateActionsArgs {
qm_splits: splits_a,
qm_dividends: divs_a,
provider_mapping: map_path.clone(),
provider_mapping: map_a.clone(),
delistings: Some(delist_a),
out_dir: out_timed.clone(),
};
@ -324,7 +343,7 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
assert_conservation(&timed.report);
// Direct in-memory curate_corporate_actions comparison.
let mapping = load_provider_mapping_table(&map_path).unwrap();
let mapping = load_provider_mapping_table(&map_a).unwrap();
let direct = curate_corporate_actions(
vec![
(
@ -507,14 +526,19 @@ fn end_to_end_round_trip_matches_direct_curate_corporate_actions_and_is_determin
assert_eq!(bytes_a, bytes_fx, "usdFxRate must have zero effect on Parquet output");
assert_eq!(bytes_a, bytes_timed, "timed runner must produce byte-identical Parquet");
// Non-timing report lines must be identical between run_a and timed (same byte sizes),
// and curate/write/builder stats identical between run_a and run_b.
// Complete non-timing report must be identical across shuffled inputs (with preserved byte
// lengths) and between run_a and timed.
let formatted_a = strip_timing_line(&format_curate_corporate_actions_report(&report_a));
let formatted_b = strip_timing_line(&format_curate_corporate_actions_report(&report_b));
let formatted_timed = strip_timing_line(&format_curate_corporate_actions_report(&timed.report));
assert_eq!(
strip_timing_line(&format_curate_corporate_actions_report(&report_a)),
strip_timing_line(&format_curate_corporate_actions_report(&timed.report))
formatted_a, formatted_b,
"shuffled inputs must produce identical non-timing report"
);
assert_eq!(
formatted_a, formatted_timed,
"timed runner must produce identical non-timing report"
);
assert_eq!(report_a.curate_stats, report_b.curate_stats);
assert_eq!(report_a.write_stats, report_b.write_stats);
assert_ne!(timed.checksum, 0);
}
@ -1039,3 +1063,127 @@ fn failure_modes_return_typed_errors_and_preserve_existing_output() {
assert!(msg.contains("out_obstructed"), "{msg}");
assert_eq!(fs::read(&blocker).unwrap(), b"blocker");
}
#[test]
fn structurally_corrupt_bson_with_intact_length_fails_with_offset_and_preserves_existing_parquet() {
let dir = TestTempDir::new("corrupt-bson-body");
let splits_ok = dir.path().join("splits_ok.bson");
let divs_ok = dir.path().join("divs_ok.bson");
let map_ok = dir.path().join("provider_mapping.tsv");
let out_dir = dir.path().join("out");
let valid_split_1 = split_doc("NVDA:US", "2024-06-10", 10.0, Some("2024-05-22"));
let valid_split_2 = split_doc("NVDA:US", "2021-07-20", 4.0, Some("2021-05-21"));
let valid_div_1 = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some("2024-05-22"), Some(1.0));
let valid_div_2 = div_doc("NVDA:US", "2024-09-12", 0.01, "USD", Some("2024-08-28"), Some(1.0));
let valid_div_3 = div_doc("NVDA:US", "2024-12-05", 0.01, "USD", Some("2024-11-20"), Some(1.0));
write_bytes(&map_ok, b"qm\tNVDA:US\t2010-01-01\t\t100\n");
write_bytes(&splits_ok, &[&valid_split_1[..], &valid_split_2[..]].concat());
write_bytes(
&divs_ok,
&[&valid_div_1[..], &valid_div_2[..], &valid_div_3[..]].concat(),
);
// Publish an initial valid dataset so we can verify rebuild failures leave it byte-identical.
let initial = run_curate_corporate_actions(&CurateCorporateActionsArgs {
qm_splits: splits_ok.clone(),
qm_dividends: divs_ok.clone(),
provider_mapping: map_ok.clone(),
delistings: None,
out_dir: out_dir.clone(),
})
.expect("initial publish");
assert_eq!(initial.write_stats.rows_written, 5);
let pq_path = out_dir.join("corporate_actions/part.parquet");
let prev_parquet_bytes = fs::read(&pq_path).expect("read initial parquet");
// 1. Dividend document with intact 4-byte length prefix but damaged trailing null terminator
// (0x00 -> 0xFF) at absolute byte offset `valid_div_1.len()`, followed by a valid 3rd doc.
let mut damaged_div = valid_div_2.clone();
*damaged_div.last_mut().unwrap() = 0xFF;
let corrupt_divs_path = dir.path().join("damaged_null_divs.bson");
write_bytes(
&corrupt_divs_path,
&[&valid_div_1[..], &damaged_div[..], &valid_div_3[..]].concat(),
);
let expected_div_offset = valid_div_1.len() as u64;
let err = run_curate_corporate_actions(&CurateCorporateActionsArgs {
qm_splits: splits_ok.clone(),
qm_dividends: corrupt_divs_path,
provider_mapping: map_ok.clone(),
delistings: None,
out_dir: out_dir.clone(),
})
.expect_err("damaged null terminator in dividends must fail");
assert!(
matches!(
err,
RunCurateCorporateActionsError::CorruptBson {
label: "qm-dividends",
offset,
..
} if offset == expected_div_offset
),
"expected CorruptBson for qm-dividends at offset {expected_div_offset}, got {err:?}"
);
let msg = assert_single_line_err(&err);
assert!(msg.contains("damaged_null_divs.bson"), "{msg}");
assert!(
msg.contains(&format!("offset {expected_div_offset}")),
"expected offset {expected_div_offset} in '{msg}'"
);
assert_eq!(
fs::read(&pq_path).unwrap(),
prev_parquet_bytes,
"pre-existing Parquet must stay byte-identical after corrupt dividend BSON"
);
// 2. Split document with intact length prefix and trailing null terminator, but corrupt
// element bytes (invalid UTF-8 inside the `qmSearchCode` string value) at non-zero offset.
let mut damaged_split = valid_split_2.clone();
let needle = b"NVDA:US";
let pos = damaged_split
.windows(needle.len())
.position(|w| w == needle)
.expect("find qmSearchCode bytes");
damaged_split[pos] = 0xFF;
let corrupt_splits_path = dir.path().join("damaged_elem_splits.bson");
write_bytes(
&corrupt_splits_path,
&[&valid_split_1[..], &damaged_split[..]].concat(),
);
let expected_split_offset = valid_split_1.len() as u64;
let err = run_curate_corporate_actions(&CurateCorporateActionsArgs {
qm_splits: corrupt_splits_path,
qm_dividends: divs_ok,
provider_mapping: map_ok,
delistings: None,
out_dir: out_dir.clone(),
})
.expect_err("corrupt element bytes in splits must fail");
assert!(
matches!(
err,
RunCurateCorporateActionsError::CorruptBson {
label: "qm-splits",
offset,
..
} if offset == expected_split_offset
),
"expected CorruptBson for qm-splits at offset {expected_split_offset}, got {err:?}"
);
let msg = assert_single_line_err(&err);
assert!(msg.contains("damaged_elem_splits.bson"), "{msg}");
assert!(
msg.contains(&format!("offset {expected_split_offset}")),
"expected offset {expected_split_offset} in '{msg}'"
);
assert_eq!(
fs::read(&pq_path).unwrap(),
prev_parquet_bytes,
"pre-existing Parquet must stay byte-identical after corrupt split BSON"
);
}