T-113: M1.2ac — tools/curate-etl: fourth runnable command curate-fx-1d (concatenated-BSON eodPrices CAD.FOREX + teMarketData USDCAD files → fx_1d/part.parquet) with a zero-copy teMarketData decoder, end-to-end tests and local benchmark (no new crates, no MongoDB connection)
This commit is contained in:
parent
cffcbe23a6
commit
da730a5460
10 changed files with 492 additions and 81 deletions
|
|
@ -1258,10 +1258,10 @@ curate-etl curate-fx-1d \
|
|||
Inputs and output:
|
||||
- `--eod-prices <path>`: concatenated raw BSON (`mongodump` `eodPrices.bson`). Streams through `decode_eod_price_chunks` and keeps only documents whose `eodSearchCode` is **exact** `"CAD.FOREX"` (other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when mapping to `FxDailyBar`).
|
||||
- `--te-market-data <path>`: concatenated raw BSON (`mongodump` `teMarketData.bson`). Streams through `decode_te_market_data_chunks` and keeps only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive, default `USDCAD`).
|
||||
- `--te-symbol <sym>` *(optional)*: target `teMarketData.teSymbol` to match (default: `USDCAD`; must not be empty or whitespace-only).
|
||||
- `--te-symbol <sym>` *(optional)*: target `teMarketData.teSymbol` to match (default: `USDCAD`; must match the USD/CAD allowlist `ALLOWED_TE_SYMBOLS` = `["USDCAD"]` ASCII case-insensitively so non-USD/CAD instruments cannot enter `fx_1d`).
|
||||
- `--out <dir>`: dataset root where `fx_1d/part.parquet` is atomically published.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--te-symbol`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, invalid `--out`, blank `--te-symbol`, truncated/corrupt/oversized BSON framing or element bytes in either input, or zero decoded bars across both inputs) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/fx_1d/part.parquet` byte-identical).
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--te-symbol`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, invalid `--out`, unsupported/blank `--te-symbol`, truncated/corrupt/oversized BSON framing or element bytes in either input, zero decoded bars across both inputs, or zero publishable rows after FX curation) prints a single-line stderr message, exits non-zero, and leaves any pre-existing `<out>/fx_1d/part.parquet` byte-identical.
|
||||
|
||||
### `teMarketData` Input Contract & `t` Epoch Unit Rule
|
||||
|
||||
|
|
|
|||
|
|
@ -350,6 +350,7 @@ fn decode_eod_price_doc_at<'a>(
|
|||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
let mut adj_volume: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonEodPriceError> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
|
|
@ -362,56 +363,113 @@ fn decode_eod_price_doc_at<'a>(
|
|||
match decode_element_value("eodSearchCode", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonEodPriceError::EmptyField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodPriceError::EmptyField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
eod_search_code = Some(s);
|
||||
}
|
||||
eod_search_code = Some(s);
|
||||
}
|
||||
other => {
|
||||
return Err(BsonEodPriceError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodPriceError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("date") {
|
||||
match decode_element_value("date", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
session_date = Some(parse_ymd_strict(s)?);
|
||||
}
|
||||
RawBsonRef::String(s) => match parse_ymd_strict(s) {
|
||||
Ok(d) => session_date = Some(d),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
},
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
let day_i32 = i32::try_from(days)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })?;
|
||||
session_date = Some(day_i32);
|
||||
match i32::try_from(days) {
|
||||
Ok(day_i32) => session_date = Some(day_i32),
|
||||
Err(_) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err =
|
||||
Some(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
other => {
|
||||
return Err(BsonEodPriceError::WrongType {
|
||||
field: "date",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodPriceError::WrongType {
|
||||
field: "date",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("open") {
|
||||
let val = decode_element_value("open", elem, offset)?;
|
||||
open = Some(decode_non_negative_number("open", val)?);
|
||||
match decode_non_negative_number("open", val) {
|
||||
Ok(v) => open = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("high") {
|
||||
let val = decode_element_value("high", elem, offset)?;
|
||||
high = Some(decode_non_negative_number("high", val)?);
|
||||
match decode_non_negative_number("high", val) {
|
||||
Ok(v) => high = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("low") {
|
||||
let val = decode_element_value("low", elem, offset)?;
|
||||
low = Some(decode_non_negative_number("low", val)?);
|
||||
match decode_non_negative_number("low", val) {
|
||||
Ok(v) => low = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("close") {
|
||||
let val = decode_element_value("close", elem, offset)?;
|
||||
close = Some(decode_non_negative_number("close", val)?);
|
||||
match decode_non_negative_number("close", val) {
|
||||
Ok(v) => close = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("volume") {
|
||||
let val = decode_element_value("volume", elem, offset)?;
|
||||
adj_volume = Some(decode_non_negative_number("volume", val)?);
|
||||
match decode_non_negative_number("volume", val) {
|
||||
Ok(v) => adj_volume = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(eod_search_code) = eod_search_code else {
|
||||
return Err(BsonEodPriceError::MissingField {
|
||||
field: "eodSearchCode",
|
||||
|
|
|
|||
|
|
@ -783,3 +783,20 @@ fn corrupt_length_prefix_in_middle_stops_stream_cleanly() {
|
|||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_corruption_after_semantic_reject_takes_precedence() {
|
||||
let doc = make_valid_doc("CAD.FOREX", "2025-01-02", f64::NAN, 1.44, 1.42, 1.435, 0.0);
|
||||
let mut bytes = doc.as_bytes().to_vec();
|
||||
let close_elem_pos = bytes
|
||||
.windows(7)
|
||||
.position(|w| w == b"\x01close\0")
|
||||
.expect("find double element 'close'");
|
||||
bytes[close_elem_pos] = 0xFF;
|
||||
|
||||
let err = decode_eod_price_bytes(&bytes).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson to take precedence over InvalidNumber, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -442,6 +442,7 @@ fn decode_point_doc(
|
|||
let mut high: Option<f64> = None;
|
||||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonTeMarketDataError> = None;
|
||||
|
||||
for elem_res in point_doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
|
|
@ -459,7 +460,14 @@ fn decode_point_doc(
|
|||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_T}': {err}"),
|
||||
})?;
|
||||
session_date = Some(decode_point_t(point_index, val)?);
|
||||
match decode_point_t(point_index, val) {
|
||||
Ok(v) => session_date = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_O {
|
||||
let val = elem
|
||||
.value()
|
||||
|
|
@ -468,7 +476,14 @@ fn decode_point_doc(
|
|||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_O}': {err}"),
|
||||
})?;
|
||||
open = Some(decode_point_price(point_index, FIELD_POINT_O, val)?);
|
||||
match decode_point_price(point_index, FIELD_POINT_O, val) {
|
||||
Ok(v) => open = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_H {
|
||||
let val = elem
|
||||
.value()
|
||||
|
|
@ -477,7 +492,14 @@ fn decode_point_doc(
|
|||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_H}': {err}"),
|
||||
})?;
|
||||
high = Some(decode_point_price(point_index, FIELD_POINT_H, val)?);
|
||||
match decode_point_price(point_index, FIELD_POINT_H, val) {
|
||||
Ok(v) => high = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_L {
|
||||
let val = elem
|
||||
.value()
|
||||
|
|
@ -486,7 +508,14 @@ fn decode_point_doc(
|
|||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_L}': {err}"),
|
||||
})?;
|
||||
low = Some(decode_point_price(point_index, FIELD_POINT_L, val)?);
|
||||
match decode_point_price(point_index, FIELD_POINT_L, val) {
|
||||
Ok(v) => low = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_C {
|
||||
let val = elem
|
||||
.value()
|
||||
|
|
@ -495,11 +524,22 @@ fn decode_point_doc(
|
|||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_C}': {err}"),
|
||||
})?;
|
||||
close = Some(decode_point_price(point_index, FIELD_POINT_C, val)?);
|
||||
match decode_point_price(point_index, FIELD_POINT_C, val) {
|
||||
Ok(v) => close = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(session_date) = session_date else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
|
|
@ -557,6 +597,7 @@ where
|
|||
};
|
||||
|
||||
let mut te_symbol: Option<&str> = None;
|
||||
let mut symbol_err: Option<BsonTeMarketDataError> = None;
|
||||
let mut daily_elem: Option<RawElement<'_>> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
|
|
@ -587,18 +628,19 @@ where
|
|||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
stats.rejected_empty_symbol += 1;
|
||||
on_error(BsonTeMarketDataError::EmptySymbol);
|
||||
return stats;
|
||||
if symbol_err.is_none() {
|
||||
symbol_err = Some(BsonTeMarketDataError::EmptySymbol);
|
||||
}
|
||||
} else {
|
||||
te_symbol = Some(s);
|
||||
}
|
||||
te_symbol = Some(s);
|
||||
}
|
||||
other => {
|
||||
stats.rejected_wrong_symbol_type += 1;
|
||||
on_error(BsonTeMarketDataError::WrongSymbolType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
return stats;
|
||||
if symbol_err.is_none() {
|
||||
symbol_err = Some(BsonTeMarketDataError::WrongSymbolType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_DAILY {
|
||||
|
|
@ -607,6 +649,16 @@ where
|
|||
// `FIELD_MONTHLY` and all other top-level fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = symbol_err {
|
||||
match &err {
|
||||
BsonTeMarketDataError::EmptySymbol => stats.rejected_empty_symbol += 1,
|
||||
BsonTeMarketDataError::WrongSymbolType { .. } => stats.rejected_wrong_symbol_type += 1,
|
||||
_ => stats.rejected_corrupt_document += 1,
|
||||
}
|
||||
on_error(err);
|
||||
return stats;
|
||||
}
|
||||
|
||||
let Some(symbol) = te_symbol else {
|
||||
stats.rejected_missing_symbol += 1;
|
||||
on_error(BsonTeMarketDataError::MissingSymbol);
|
||||
|
|
|
|||
|
|
@ -460,3 +460,63 @@ fn corrupt_bson_bytes_and_streaming_rebase_offsets() {
|
|||
other => panic!("expected CorruptBson with rebased offset, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_corruption_after_semantic_reject_takes_precedence() {
|
||||
// 1. Point with non-finite `t` followed by corrupt element type byte on `c`.
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), f64::NAN);
|
||||
pt.append(cstr!("o"), 1.38_f64);
|
||||
pt.append(cstr!("h"), 1.39_f64);
|
||||
pt.append(cstr!("l"), 1.37_f64);
|
||||
pt.append(cstr!("c"), 1.385_f64);
|
||||
|
||||
let mut daily = RawArrayBuf::new();
|
||||
daily.push(pt);
|
||||
let doc = make_te_doc("USDCAD", daily);
|
||||
let mut bytes = doc.as_bytes().to_vec();
|
||||
let c_elem_pos = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == b"\x01c\0")
|
||||
.expect("find double element 'c'");
|
||||
bytes[c_elem_pos] = 0xFF;
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_market_data_bytes(&bytes, "USDCAD", |b| bars.push(b), |e| errs.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(bars.is_empty());
|
||||
assert_eq!(stats.points_in, 1);
|
||||
assert_eq!(stats.rejected_corrupt_point, 1);
|
||||
assert_eq!(stats.rejected_non_finite, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
errs.as_slice(),
|
||||
[BsonTeMarketDataError::CorruptPointBson { point_index: 0, .. }]
|
||||
),
|
||||
"expected CorruptPointBson to take precedence over NonFiniteValue, got {errs:?}"
|
||||
);
|
||||
|
||||
// 2. Top-level doc with empty `teSymbol` followed by corrupt element type byte on `daily`.
|
||||
let doc_empty_sym = make_te_doc("", RawArrayBuf::new());
|
||||
let mut doc_bytes = doc_empty_sym.as_bytes().to_vec();
|
||||
let daily_elem_pos = doc_bytes
|
||||
.windows(7)
|
||||
.position(|w| w == b"\x04daily\0")
|
||||
.expect("find array element 'daily'");
|
||||
doc_bytes[daily_elem_pos] = 0xFF;
|
||||
|
||||
let mut top_errs = Vec::new();
|
||||
let top_stats =
|
||||
decode_te_market_data_bytes(&doc_bytes, "USDCAD", |_| {}, |e| top_errs.push(e));
|
||||
assert_stats_conserved(&top_stats);
|
||||
assert_eq!(top_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(top_stats.rejected_empty_symbol, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
top_errs.as_slice(),
|
||||
[BsonTeMarketDataError::CorruptBson { .. }]
|
||||
),
|
||||
"expected CorruptBson to take precedence over EmptySymbol, got {top_errs:?}"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ use crate::bench::{
|
|||
use crate::run_curate_adj::CurateAdjFactorsArgs;
|
||||
use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE};
|
||||
use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
|
||||
use crate::run_curate_fx::{CurateFx1dArgs, DEFAULT_TE_SYMBOL};
|
||||
use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
|
|
@ -427,10 +427,10 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
|
|||
if te_symbol.is_some() {
|
||||
return Err("duplicate flag '--te-symbol'".to_string());
|
||||
}
|
||||
if value.trim().is_empty() {
|
||||
return Err(
|
||||
"invalid --te-symbol: must not be empty or whitespace-only".to_string()
|
||||
);
|
||||
if !is_supported_te_symbol(value) {
|
||||
return Err(format!(
|
||||
"invalid --te-symbol '{value}': only USD/CAD selector '{DEFAULT_TE_SYMBOL}' (case-insensitive) is supported for fx_1d"
|
||||
));
|
||||
}
|
||||
te_symbol = Some(value.to_string());
|
||||
}
|
||||
|
|
@ -1859,19 +1859,24 @@ mod tests {
|
|||
"{err}"
|
||||
);
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--te-symbol",
|
||||
" ",
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("invalid --te-symbol"), "{err}");
|
||||
for bad_sym in [" ", "EURUSD", "CADUSD"] {
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--te-symbol",
|
||||
bad_sym,
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.contains("invalid --te-symbol"),
|
||||
"expected invalid --te-symbol for '{bad_sym}', got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
|
|
|
|||
|
|
@ -182,6 +182,7 @@ pub use run_curate_corporate_actions::{
|
|||
|
||||
pub mod run_curate_fx;
|
||||
pub use run_curate_fx::{
|
||||
format_curate_fx_report, run_curate_fx_1d, CurateFx1dArgs, CurateFx1dRunReport,
|
||||
RunCurateFxError, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE,
|
||||
format_curate_fx_report, is_supported_te_symbol, run_curate_fx_1d, CurateFx1dArgs,
|
||||
CurateFx1dRunReport, RunCurateFxError, ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL,
|
||||
EOD_CAD_FOREX_CODE,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -17,10 +17,10 @@
|
|||
//! and post-EOD tail), read-only 1% overlap cross-check, conservative `23:59:59.999999 UTC`
|
||||
//! `ts`/`known_at` stamping, and atomic Zstd Parquet publication unchanged to
|
||||
//! [`curate_and_write_fx_1d`].
|
||||
//! - **Fail-closed safety:** invalid `--out`, blank `--te-symbol`, unreadable input files,
|
||||
//! corrupt/truncated BSON framing or element bytes, and zero decoded bars across both sources
|
||||
//! each return a typed [`RunCurateFxError`] before touching `args.out_dir`, leaving any
|
||||
//! pre-existing `<out_dir>/fx_1d/part.parquet` byte-identical.
|
||||
//! - **Fail-closed safety:** invalid `--out`, unsupported/blank `--te-symbol`, unreadable input
|
||||
//! files, corrupt/truncated BSON framing or element bytes, zero decoded bars across both
|
||||
//! sources, and zero publishable rows after FX curation each return a typed [`RunCurateFxError`]
|
||||
//! without modifying any pre-existing `<out_dir>/fx_1d/part.parquet`.
|
||||
//!
|
||||
//! # Counter Conservation Invariants
|
||||
//! Every successful [`CurateFx1dRunReport`] satisfies:
|
||||
|
|
@ -60,6 +60,18 @@ use crate::parquet_fx::{
|
|||
pub const EOD_CAD_FOREX_CODE: &str = "CAD.FOREX";
|
||||
/// Default `--te-symbol` matched (ASCII case-insensitive) against `teMarketData.teSymbol`.
|
||||
pub const DEFAULT_TE_SYMBOL: &str = "USDCAD";
|
||||
/// Verified USD/CAD `teMarketData.teSymbol` selectors accepted by `curate-fx-1d`
|
||||
/// (matched ASCII case-insensitively).
|
||||
pub const ALLOWED_TE_SYMBOLS: &[&str] = &[DEFAULT_TE_SYMBOL];
|
||||
|
||||
/// Returns `true` if `te_symbol` is an allowed USD/CAD `teMarketData` selector
|
||||
/// (ASCII case-insensitive match against [`ALLOWED_TE_SYMBOLS`]).
|
||||
#[inline]
|
||||
pub fn is_supported_te_symbol(te_symbol: &str) -> bool {
|
||||
ALLOWED_TE_SYMBOLS
|
||||
.iter()
|
||||
.any(|allowed| te_symbol.eq_ignore_ascii_case(allowed))
|
||||
}
|
||||
|
||||
/// Parsed arguments for the `curate-fx-1d` CLI command.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
@ -143,6 +155,12 @@ pub enum RunCurateFxError {
|
|||
te_path: PathBuf,
|
||||
te_symbol: String,
|
||||
},
|
||||
NoCuratedRows {
|
||||
eod_path: PathBuf,
|
||||
te_path: PathBuf,
|
||||
eod_bars_in: usize,
|
||||
te_bars_in: usize,
|
||||
},
|
||||
CurateWrite {
|
||||
out_dir: PathBuf,
|
||||
source: CurateFxWriteError,
|
||||
|
|
@ -158,7 +176,7 @@ impl fmt::Display for RunCurateFxError {
|
|||
Self::InvalidTeSymbol { value } => {
|
||||
write!(
|
||||
f,
|
||||
"invalid --te-symbol '{value}': must not be empty or whitespace-only"
|
||||
"invalid --te-symbol '{value}': only USD/CAD selector '{DEFAULT_TE_SYMBOL}' (case-insensitive) is supported for fx_1d"
|
||||
)
|
||||
}
|
||||
Self::OpenInput {
|
||||
|
|
@ -199,6 +217,17 @@ impl fmt::Display for RunCurateFxError {
|
|||
eod_path.display(),
|
||||
te_path.display()
|
||||
),
|
||||
Self::NoCuratedRows {
|
||||
eod_path,
|
||||
te_path,
|
||||
eod_bars_in,
|
||||
te_bars_in,
|
||||
} => write!(
|
||||
f,
|
||||
"no publishable fx_1d rows survived curation (eod_bars_in={eod_bars_in} from '{}', te_bars_in={te_bars_in} from '{}')",
|
||||
eod_path.display(),
|
||||
te_path.display()
|
||||
),
|
||||
Self::CurateWrite { out_dir, source } => {
|
||||
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
||||
}
|
||||
|
|
@ -216,7 +245,8 @@ impl Error for RunCurateFxError {
|
|||
Self::CurateWrite { source, .. } => Some(source),
|
||||
Self::InvalidOutDir { .. }
|
||||
| Self::InvalidTeSymbol { .. }
|
||||
| Self::NoDecodedBars { .. } => None,
|
||||
| Self::NoDecodedBars { .. }
|
||||
| Self::NoCuratedRows { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -232,7 +262,7 @@ fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateFxError> {
|
|||
}
|
||||
|
||||
fn validate_te_symbol(te_symbol: &str) -> Result<(), RunCurateFxError> {
|
||||
if te_symbol.trim().is_empty() {
|
||||
if !is_supported_te_symbol(te_symbol) {
|
||||
return Err(RunCurateFxError::InvalidTeSymbol {
|
||||
value: te_symbol.to_string(),
|
||||
});
|
||||
|
|
@ -420,6 +450,14 @@ pub fn run_curate_fx_1d(args: &CurateFx1dArgs) -> Result<CurateFx1dRunReport, Ru
|
|||
out_dir: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
if write_report.curate_stats.rows_out == 0 {
|
||||
return Err(RunCurateFxError::NoCuratedRows {
|
||||
eod_path: args.eod_prices.clone(),
|
||||
te_path: args.te_market_data.clone(),
|
||||
eod_bars_in: decoded.eod_cad_forex_kept,
|
||||
te_bars_in: decoded.te_decode.points_decoded,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(CurateFx1dRunReport {
|
||||
eod_docs_framed: decoded.eod_docs_framed,
|
||||
|
|
@ -488,6 +526,14 @@ pub(crate) fn run_curate_fx_1d_timed(
|
|||
}
|
||||
})?;
|
||||
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
||||
if curated.rows.is_empty() {
|
||||
return Err(RunCurateFxError::NoCuratedRows {
|
||||
eod_path: args.eod_prices.clone(),
|
||||
te_path: args.te_market_data.clone(),
|
||||
eod_bars_in: decoded.eod_cad_forex_kept,
|
||||
te_bars_in: decoded.te_decode.points_decoded,
|
||||
});
|
||||
}
|
||||
|
||||
let checksum = compute_rows_checksum(&curated.rows);
|
||||
|
||||
|
|
|
|||
|
|
@ -224,7 +224,7 @@ fn end_to_end_curation_precedence_gap_tail_and_permutation_invariance() {
|
|||
te_doc_2.append(cstr!("daily"), te_daily_2);
|
||||
te_doc_2.append(cstr!("teSymbol"), "usdcad");
|
||||
|
||||
let te_docs = vec![
|
||||
let te_docs = [
|
||||
other_te_doc.as_bytes().to_vec(),
|
||||
te_doc_1.as_bytes().to_vec(),
|
||||
te_doc_2.as_bytes().to_vec(),
|
||||
|
|
@ -297,9 +297,30 @@ fn end_to_end_curation_precedence_gap_tail_and_permutation_invariance() {
|
|||
// d4 TE tail fill
|
||||
assert_eq!(rows[3].close.to_bits(), 1.385_f64.to_bits());
|
||||
|
||||
// Write run B in reversed doc order -> byte-identical Parquet and identical report (sans timing)
|
||||
// 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<u8> = eod_docs.into_iter().rev().flatten().collect();
|
||||
let te_rev: Vec<u8> = te_docs.into_iter().rev().flatten().collect();
|
||||
let te_rev: Vec<u8> = 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();
|
||||
|
|
@ -308,7 +329,7 @@ fn end_to_end_curation_precedence_gap_tail_and_permutation_invariance() {
|
|||
let args_b = CurateFx1dArgs {
|
||||
eod_prices: eod_rev_path,
|
||||
te_market_data: te_rev_path,
|
||||
te_symbol: DEFAULT_TE_SYMBOL.to_string(),
|
||||
te_symbol: "usdcad".to_string(),
|
||||
out_dir: out_b.clone(),
|
||||
};
|
||||
let report_b = run_curate_fx_1d(&args_b).expect("run B succeeds");
|
||||
|
|
@ -470,16 +491,21 @@ fn failure_modes_return_typed_errors_and_preserve_existing_parquet() {
|
|||
assert!(matches!(err, RunCurateFxError::InvalidOutDir { .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
|
||||
// 8. Blank te_symbol
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
te_market_data: valid_te.clone(),
|
||||
te_symbol: " ".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::InvalidTeSymbol { .. }), "{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");
|
||||
|
|
@ -495,11 +521,146 @@ fn failure_modes_return_typed_errors_and_preserve_existing_parquet() {
|
|||
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,
|
||||
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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1080,6 +1080,17 @@ fn curate_fx_1d_cli_flag_errors_exit_nonzero_with_usage() {
|
|||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--te-market-data",
|
||||
"t.bson",
|
||||
"--te-symbol",
|
||||
"EURUSD",
|
||||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue