T-174: M2.2p — tools/curate-etl: zero-copy raw BSON decoder for MongoDB teData (bson_te_data.rs → TeDataPoint<&str>, data only, forecast never read, fail-closed d/v handling) with tests (no new crates, no CLI/bench/stream changes, no live Mongo)
This commit is contained in:
parent
f2ae15e0b3
commit
f72f1f552f
4 changed files with 1752 additions and 0 deletions
|
|
@ -1674,3 +1674,11 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m
|
|||
- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`).
|
||||
- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
|
||||
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: `teData` BSON decoding, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access.
|
||||
|
||||
## Zero-Copy `teData` BSON Decoder (`M2.2p`)
|
||||
|
||||
`src/bson_te_data.rs` (tested in `src/bson_te_data_tests.rs`) decodes raw `teData` MongoDB BSON documents in a single forward pass without allocating a `bson::Document` or per-point heap memory, emitting borrowed `TeDataPoint<'a>` views through `decode_te_data_doc`, `decode_te_data_bytes`, and `decode_te_data_buffer`.
|
||||
|
||||
- **History-only (zero forecast leakage):** Reads only `data` (`[{ d: "YYYY-MM-DD", v: number }]`) and skips `forecast`, descriptive metadata, timestamps, and unknown fields without calling `elem.value()`.
|
||||
- **Writer-derived schema & no hardcoded mappings:** Field names (`teSymbol`, `country`, `category`, `data`, `forecast`, `d`, `v`) come from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts` and are not verified against a live `mongodump`. Provider `te_symbol`, `country`, and `category` strings are preserved verbatim; downstream runners own country/indicator/lag mapping into `build_macro_rows`.
|
||||
- **Fail-closed accounting:** Rejects missing/empty/non-string `teSymbol`, `country`, or `category`, and missing/non-array `data` before emitting any point; rejects malformed/non-string `d` and non-numeric `v` per point while passing finite and non-finite `Double` values through unchanged. `BsonTeDataDecodeStats` maintains `docs_in == docs_accepted + docs_rejected_total()` and `points_in == points_decoded + rejected_total()`.
|
||||
|
|
|
|||
854
tools/curate-etl/src/bson_te_data.rs
Normal file
854
tools/curate-etl/src/bson_te_data.rs
Normal file
|
|
@ -0,0 +1,854 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `teData` documents (`M2.2p`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
|
||||
//! allocating a `bson::Document` or per-point heap memory, emitting borrowed [`TeDataPoint`]
|
||||
//! values via a caller-supplied callback.
|
||||
//!
|
||||
//! # Empirical Field Contract & Unverified Assumptions
|
||||
//!
|
||||
//! - Field names are derived strictly from the ingestion writer in
|
||||
//! `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts:87-156`
|
||||
//! (`teSymbol`, `name`, `unit`, `source`, `frequency`, `country`, `category`, `data`, `forecast`,
|
||||
//! `lastUpdated`, `createdAt`; `data: [{ d: "YYYY-MM-DD", v: number }]`; `forecast: [{ d, v }]`),
|
||||
//! and isolated in the `pub const FIELD_*` constants below. They have **not** been verified
|
||||
//! against a live `mongodump` of `teData`.
|
||||
//! - **History-only (zero forecast leakage):** `forecast` stores forward-looking provider
|
||||
//! forecasts. `forecast`, descriptive metadata (`name`, `unit`, `source`, `frequency`),
|
||||
//! timestamps (`lastUpdated`, `createdAt`), and all unknown fields are skipped by key without
|
||||
//! calling `elem.value()`, so forecast observations can never leak into research inputs.
|
||||
//! - **Ownership & no hardcoded mappings:** `TeDataPoint` preserves the verbatim provider
|
||||
//! `te_symbol`, `country`, and `category` strings. No country-to-ISO, indicator-name, or
|
||||
//! publication-lag mapping is hardcoded here: Quant Research owns the coarse regime-use policy,
|
||||
//! and the downstream caller/runner owns all explicit mapping into [`crate::macro_series`].
|
||||
//! - **Observation dates & provenance:** `period_date` is the provider observation date parsed from
|
||||
//! strict `YYYY-MM-DD`. Because `teData` carries final-revised values without verified
|
||||
//! first-release vintages, downstream availability begins strictly at the builder's estimated
|
||||
//! `known_at` ([`crate::macro_series::build_macro_rows`]).
|
||||
//! - **Lazy `data` capture:** `data` is retained as a raw [`RawElement`] during the top-level
|
||||
//! scan and only decoded after `teSymbol`, `country`, and `category` pass validation, so raw
|
||||
//! BSON field ordering (`data` before metadata) does not affect output or rejection accounting.
|
||||
//! - **Non-finite doubles:** `v` accepts BSON `Double`, `Int32`, and `Int64` only. Finite and
|
||||
//! non-finite (`NaN`, `±inf`) doubles are passed through unchanged so the downstream
|
||||
//! [`crate::macro_series::build_macro_rows`] builder can account for them in
|
||||
//! `skipped_non_finite_value`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
};
|
||||
|
||||
/// MongoDB field name for the TradingEconomics symbol key (`data-fetch.action.ts:94`).
|
||||
pub const FIELD_TE_SYMBOL: &str = "teSymbol";
|
||||
/// MongoDB field name for the provider country label (`data-fetch.action.ts:99`).
|
||||
pub const FIELD_COUNTRY: &str = "country";
|
||||
/// MongoDB field name for the provider category/indicator label (`data-fetch.action.ts:100`).
|
||||
pub const FIELD_CATEGORY: &str = "category";
|
||||
/// MongoDB field name for the historical observation array (`data-fetch.action.ts:101`).
|
||||
pub const FIELD_DATA: &str = "data";
|
||||
/// MongoDB field name for the forward-looking forecast array, never read (`data-fetch.action.ts:102`).
|
||||
pub const FIELD_FORECAST: &str = "forecast";
|
||||
/// Point field name for the `YYYY-MM-DD` observation date string (`data-fetch.action.ts:78`).
|
||||
pub const FIELD_POINT_D: &str = "d";
|
||||
/// Point field name for the numeric observation value (`data-fetch.action.ts:78`).
|
||||
pub const FIELD_POINT_V: &str = "v";
|
||||
|
||||
/// Borrowed zero-copy view of a single historical `teData.data` observation.
|
||||
///
|
||||
/// `te_symbol`, `country`, and `category` are borrowed verbatim from the underlying
|
||||
/// `&RawDocument` byte slice with zero per-point heap allocation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TeDataPoint<'a> {
|
||||
pub te_symbol: &'a str,
|
||||
pub country: &'a str,
|
||||
pub category: &'a str,
|
||||
/// Observation period date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub period_date: i32,
|
||||
pub value: f64,
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `teData` BSON documents or length-prefixed buffers.
|
||||
///
|
||||
/// Every variant's `Display` output is a single line; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonTeDataError {
|
||||
/// Required top-level `teSymbol` field was absent.
|
||||
MissingSymbol,
|
||||
/// Top-level `teSymbol` string was empty or whitespace-only.
|
||||
EmptySymbol,
|
||||
/// Top-level `teSymbol` had an unexpected BSON element type.
|
||||
WrongSymbolType { actual: ElementType },
|
||||
/// Required top-level `country` field was absent.
|
||||
MissingCountry,
|
||||
/// Top-level `country` string was empty or whitespace-only.
|
||||
EmptyCountry,
|
||||
/// Top-level `country` had an unexpected BSON element type.
|
||||
WrongCountryType { actual: ElementType },
|
||||
/// Required top-level `category` field was absent.
|
||||
MissingCategory,
|
||||
/// Top-level `category` string was empty or whitespace-only.
|
||||
EmptyCategory,
|
||||
/// Top-level `category` had an unexpected BSON element type.
|
||||
WrongCategoryType { actual: ElementType },
|
||||
/// Required top-level `data` field was absent.
|
||||
MissingData,
|
||||
/// Top-level `data` field was not a BSON array.
|
||||
DataNotArray { actual: ElementType },
|
||||
/// An element inside `data` was not an embedded BSON document.
|
||||
PointNotDocument {
|
||||
point_index: usize,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A required field (`d` or `v`) was absent from a `data` point document.
|
||||
MissingPointField {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
},
|
||||
/// A required field (`d` or `v`) in a `data` point document had an unexpected BSON type.
|
||||
WrongPointFieldType {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// Point date `d` was not a strict, valid Gregorian `YYYY-MM-DD` string.
|
||||
InvalidPointDate { point_index: usize },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying top-level BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
/// Underlying BSON bytes inside a `data` array or point document were malformed.
|
||||
CorruptPointBson {
|
||||
offset: usize,
|
||||
point_index: usize,
|
||||
detail: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonTeDataError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingSymbol => {
|
||||
write!(f, "teData BSON missing required field '{FIELD_TE_SYMBOL}'")
|
||||
}
|
||||
Self::EmptySymbol => {
|
||||
write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongSymbolType { actual } => write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::MissingCountry => {
|
||||
write!(f, "teData BSON missing required field '{FIELD_COUNTRY}'")
|
||||
}
|
||||
Self::EmptyCountry => {
|
||||
write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_COUNTRY}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongCountryType { actual } => write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_COUNTRY}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::MissingCategory => {
|
||||
write!(f, "teData BSON missing required field '{FIELD_CATEGORY}'")
|
||||
}
|
||||
Self::EmptyCategory => {
|
||||
write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_CATEGORY}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongCategoryType { actual } => write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_CATEGORY}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::MissingData => {
|
||||
write!(f, "teData BSON missing required field '{FIELD_DATA}'")
|
||||
}
|
||||
Self::DataNotArray { actual } => write!(
|
||||
f,
|
||||
"teData BSON field '{FIELD_DATA}' has unexpected BSON type {actual:?} (expected Array)"
|
||||
),
|
||||
Self::PointNotDocument {
|
||||
point_index,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"teData BSON '{FIELD_DATA}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)"
|
||||
),
|
||||
Self::MissingPointField { point_index, field } => write!(
|
||||
f,
|
||||
"teData BSON '{FIELD_DATA}[{point_index}]' missing required field '{field}'"
|
||||
),
|
||||
Self::WrongPointFieldType {
|
||||
point_index,
|
||||
field,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"teData BSON '{FIELD_DATA}[{point_index}].{field}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::InvalidPointDate { point_index } => write!(
|
||||
f,
|
||||
"teData BSON '{FIELD_DATA}[{point_index}].{FIELD_POINT_D}' is not a valid strict YYYY-MM-DD date"
|
||||
),
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
Self::CorruptPointBson {
|
||||
offset,
|
||||
point_index,
|
||||
detail,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON bytes in '{FIELD_DATA}[{point_index}]' at byte offset {offset}: {detail}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonTeDataError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonTeDataError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonTeDataError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonTeDataError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonTeDataError::CorruptBson { offset, detail }
|
||||
}
|
||||
other => BsonTeDataError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: other.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch document and point decode accounting for `teData`.
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `docs_in == docs_accepted + docs_rejected_total()`
|
||||
/// - `points_in == points_decoded + rejected_total()`
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonTeDataDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub docs_accepted: usize,
|
||||
pub rejected_missing_symbol: usize,
|
||||
pub rejected_empty_symbol: usize,
|
||||
pub rejected_wrong_symbol_type: usize,
|
||||
pub rejected_missing_country: usize,
|
||||
pub rejected_empty_country: usize,
|
||||
pub rejected_wrong_country_type: usize,
|
||||
pub rejected_missing_category: usize,
|
||||
pub rejected_empty_category: usize,
|
||||
pub rejected_wrong_category_type: usize,
|
||||
pub rejected_data_missing: usize,
|
||||
pub rejected_data_not_array: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
pub points_in: usize,
|
||||
pub points_decoded: usize,
|
||||
pub rejected_point_not_document: usize,
|
||||
pub rejected_invalid_date: usize,
|
||||
pub rejected_invalid_value: usize,
|
||||
pub rejected_corrupt_point: usize,
|
||||
}
|
||||
|
||||
impl BsonTeDataDecodeStats {
|
||||
/// Total number of document-level rejects across all document error categories.
|
||||
#[inline]
|
||||
pub fn docs_rejected_total(&self) -> usize {
|
||||
self.rejected_missing_symbol
|
||||
+ self.rejected_empty_symbol
|
||||
+ self.rejected_wrong_symbol_type
|
||||
+ self.rejected_missing_country
|
||||
+ self.rejected_empty_country
|
||||
+ self.rejected_wrong_country_type
|
||||
+ self.rejected_missing_category
|
||||
+ self.rejected_empty_category
|
||||
+ self.rejected_wrong_category_type
|
||||
+ self.rejected_data_missing
|
||||
+ self.rejected_data_not_array
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Total number of point-level rejects across all point error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_point_not_document
|
||||
+ self.rejected_invalid_date
|
||||
+ self.rejected_invalid_value
|
||||
+ self.rejected_corrupt_point
|
||||
}
|
||||
|
||||
/// Increments the document-level rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
fn record_doc_error(&mut self, err: &BsonTeDataError) {
|
||||
match err {
|
||||
BsonTeDataError::MissingSymbol => self.rejected_missing_symbol += 1,
|
||||
BsonTeDataError::EmptySymbol => self.rejected_empty_symbol += 1,
|
||||
BsonTeDataError::WrongSymbolType { .. } => self.rejected_wrong_symbol_type += 1,
|
||||
BsonTeDataError::MissingCountry => self.rejected_missing_country += 1,
|
||||
BsonTeDataError::EmptyCountry => self.rejected_empty_country += 1,
|
||||
BsonTeDataError::WrongCountryType { .. } => self.rejected_wrong_country_type += 1,
|
||||
BsonTeDataError::MissingCategory => self.rejected_missing_category += 1,
|
||||
BsonTeDataError::EmptyCategory => self.rejected_empty_category += 1,
|
||||
BsonTeDataError::WrongCategoryType { .. } => self.rejected_wrong_category_type += 1,
|
||||
BsonTeDataError::MissingData => self.rejected_data_missing += 1,
|
||||
BsonTeDataError::DataNotArray { .. } => self.rejected_data_not_array += 1,
|
||||
_ => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Increments the point-level rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
fn record_point_error(&mut self, err: &BsonTeDataError) {
|
||||
match err {
|
||||
BsonTeDataError::PointNotDocument { .. } => {
|
||||
self.rejected_point_not_document += 1;
|
||||
}
|
||||
BsonTeDataError::InvalidPointDate { .. } => {
|
||||
self.rejected_invalid_date += 1;
|
||||
}
|
||||
BsonTeDataError::MissingPointField { field, .. }
|
||||
| BsonTeDataError::WrongPointFieldType { field, .. } => {
|
||||
if *field == FIELD_POINT_D {
|
||||
self.rejected_invalid_date += 1;
|
||||
} else if *field == FIELD_POINT_V {
|
||||
self.rejected_invalid_value += 1;
|
||||
} else {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
}
|
||||
BsonTeDataError::CorruptPointBson { .. } => {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
_ => {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.docs_accepted += other.docs_accepted;
|
||||
self.rejected_missing_symbol += other.rejected_missing_symbol;
|
||||
self.rejected_empty_symbol += other.rejected_empty_symbol;
|
||||
self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type;
|
||||
self.rejected_missing_country += other.rejected_missing_country;
|
||||
self.rejected_empty_country += other.rejected_empty_country;
|
||||
self.rejected_wrong_country_type += other.rejected_wrong_country_type;
|
||||
self.rejected_missing_category += other.rejected_missing_category;
|
||||
self.rejected_empty_category += other.rejected_empty_category;
|
||||
self.rejected_wrong_category_type += other.rejected_wrong_category_type;
|
||||
self.rejected_data_missing += other.rejected_data_missing;
|
||||
self.rejected_data_not_array += other.rejected_data_not_array;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
self.points_in += other.points_in;
|
||||
self.points_decoded += other.points_decoded;
|
||||
self.rejected_point_not_document += other.rejected_point_not_document;
|
||||
self.rejected_invalid_date += other.rejected_invalid_date;
|
||||
self.rejected_invalid_value += other.rejected_invalid_value;
|
||||
self.rejected_corrupt_point += other.rejected_corrupt_point;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonTeDataDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_point_d(point_index: usize, val: RawBsonRef<'_>) -> Result<i32, BsonTeDataError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
parse_ymd_strict_days(s).ok_or(BsonTeDataError::InvalidPointDate { point_index })
|
||||
}
|
||||
other => Err(BsonTeDataError::WrongPointFieldType {
|
||||
point_index,
|
||||
field: FIELD_POINT_D,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_point_v(point_index: usize, val: RawBsonRef<'_>) -> Result<f64, BsonTeDataError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => Ok(v),
|
||||
RawBsonRef::Int32(v) => Ok(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => Ok(v as f64),
|
||||
other => Err(BsonTeDataError::WrongPointFieldType {
|
||||
point_index,
|
||||
field: FIELD_POINT_V,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_point_doc(
|
||||
point_doc: &RawDocument,
|
||||
doc_offset: usize,
|
||||
point_index: usize,
|
||||
) -> Result<(i32, f64), BsonTeDataError> {
|
||||
let mut period_date: Option<i32> = None;
|
||||
let mut value: Option<f64> = None;
|
||||
let mut d_err: Option<BsonTeDataError> = None;
|
||||
let mut v_err: Option<BsonTeDataError> = None;
|
||||
|
||||
for elem_res in point_doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonTeDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_POINT_D {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_D}': {err}"),
|
||||
})?;
|
||||
match decode_point_d(point_index, val) {
|
||||
Ok(d) => period_date = Some(d),
|
||||
Err(err) => {
|
||||
if d_err.is_none() {
|
||||
d_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_V {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_V}': {err}"),
|
||||
})?;
|
||||
match decode_point_v(point_index, val) {
|
||||
Ok(v) => value = Some(v),
|
||||
Err(err) => {
|
||||
if v_err.is_none() {
|
||||
v_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown point fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = d_err {
|
||||
return Err(err);
|
||||
}
|
||||
let Some(period_date) = period_date else {
|
||||
return Err(BsonTeDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_D,
|
||||
});
|
||||
};
|
||||
if let Some(err) = v_err {
|
||||
return Err(err);
|
||||
}
|
||||
let Some(value) = value else {
|
||||
return Err(BsonTeDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_V,
|
||||
});
|
||||
};
|
||||
|
||||
Ok((period_date, value))
|
||||
}
|
||||
|
||||
fn decode_te_data_doc_at<'a, F, E>(
|
||||
doc: &'a RawDocument,
|
||||
doc_offset: usize,
|
||||
mut on_point: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeDataDecodeStats
|
||||
where
|
||||
F: FnMut(TeDataPoint<'a>),
|
||||
E: FnMut(BsonTeDataError),
|
||||
{
|
||||
let mut stats = BsonTeDataDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonTeDataDecodeStats::default()
|
||||
};
|
||||
|
||||
let mut te_symbol: Option<&'a str> = None;
|
||||
let mut te_symbol_err: Option<BsonTeDataError> = None;
|
||||
let mut country: Option<&'a str> = None;
|
||||
let mut country_err: Option<BsonTeDataError> = None;
|
||||
let mut category: Option<&'a str> = None;
|
||||
let mut category_err: Option<BsonTeDataError> = None;
|
||||
let mut data_elem: Option<RawElement<'a>> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = match elem_res {
|
||||
Ok(elem) => elem,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: err.to_string(),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
let key = elem.key().as_str();
|
||||
if key == FIELD_TE_SYMBOL {
|
||||
let val = match elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_TE_SYMBOL}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if te_symbol_err.is_none() {
|
||||
te_symbol_err = Some(BsonTeDataError::EmptySymbol);
|
||||
}
|
||||
} else {
|
||||
te_symbol = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if te_symbol_err.is_none() {
|
||||
te_symbol_err = Some(BsonTeDataError::WrongSymbolType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_COUNTRY {
|
||||
let val = match elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_COUNTRY}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if country_err.is_none() {
|
||||
country_err = Some(BsonTeDataError::EmptyCountry);
|
||||
}
|
||||
} else {
|
||||
country = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if country_err.is_none() {
|
||||
country_err = Some(BsonTeDataError::WrongCountryType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_CATEGORY {
|
||||
let val = match elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_CATEGORY}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if category_err.is_none() {
|
||||
category_err = Some(BsonTeDataError::EmptyCategory);
|
||||
}
|
||||
} else {
|
||||
category = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if category_err.is_none() {
|
||||
category_err = Some(BsonTeDataError::WrongCategoryType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_DATA {
|
||||
data_elem = Some(elem);
|
||||
}
|
||||
// `FIELD_FORECAST`, `name`, `unit`, `source`, `frequency`, `lastUpdated`, `createdAt`,
|
||||
// and all other top-level fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
// Deterministic top-level validation order: `teSymbol`, `country`, `category`, then `data`.
|
||||
if let Some(err) = te_symbol_err {
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
}
|
||||
let Some(te_symbol) = te_symbol else {
|
||||
let err = BsonTeDataError::MissingSymbol;
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
};
|
||||
|
||||
if let Some(err) = country_err {
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
}
|
||||
let Some(country) = country else {
|
||||
let err = BsonTeDataError::MissingCountry;
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
};
|
||||
|
||||
if let Some(err) = category_err {
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
}
|
||||
let Some(category) = category else {
|
||||
let err = BsonTeDataError::MissingCategory;
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
};
|
||||
|
||||
let Some(data_elem) = data_elem else {
|
||||
let err = BsonTeDataError::MissingData;
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
};
|
||||
|
||||
let data_val = match data_elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_DATA}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
|
||||
let data_arr = match data_val {
|
||||
RawBsonRef::Array(arr) => arr,
|
||||
other => {
|
||||
let err = BsonTeDataError::DataNotArray {
|
||||
actual: other.element_type(),
|
||||
};
|
||||
stats.record_doc_error(&err);
|
||||
on_error(err);
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
|
||||
stats.docs_accepted += 1;
|
||||
|
||||
for (point_index, item_res) in data_arr.into_iter().enumerate() {
|
||||
stats.points_in += 1;
|
||||
let item = match item_res {
|
||||
Ok(item) => item,
|
||||
Err(err) => {
|
||||
let err = BsonTeDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: err.to_string(),
|
||||
};
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
let point_doc = match item {
|
||||
RawBsonRef::Document(point_doc) => point_doc,
|
||||
other => {
|
||||
let err = BsonTeDataError::PointNotDocument {
|
||||
point_index,
|
||||
actual: other.element_type(),
|
||||
};
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
match decode_point_doc(point_doc, doc_offset, point_index) {
|
||||
Ok((period_date, value)) => {
|
||||
stats.points_decoded += 1;
|
||||
on_point(TeDataPoint {
|
||||
te_symbol,
|
||||
country,
|
||||
category,
|
||||
period_date,
|
||||
value,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `teData` MongoDB document in one forward pass
|
||||
/// without allocating a `bson::Document` or per-point heap memory.
|
||||
///
|
||||
/// Emits each valid historical `data` point as a borrowed [`TeDataPoint`] via `on_point` and
|
||||
/// reports document- or point-level errors to `on_error` without panicking. `forecast` is never
|
||||
/// read or emitted.
|
||||
#[inline]
|
||||
pub fn decode_te_data_doc<'a, F, E>(
|
||||
doc: &'a RawDocument,
|
||||
on_point: F,
|
||||
on_error: E,
|
||||
) -> BsonTeDataDecodeStats
|
||||
where
|
||||
F: FnMut(TeDataPoint<'a>),
|
||||
E: FnMut(BsonTeDataError),
|
||||
{
|
||||
decode_te_data_doc_at(doc, 0, on_point, on_error)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice representing a `teData` document.
|
||||
pub fn decode_te_data_bytes<'a, F, E>(
|
||||
bytes: &'a [u8],
|
||||
on_point: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeDataDecodeStats
|
||||
where
|
||||
F: FnMut(TeDataPoint<'a>),
|
||||
E: FnMut(BsonTeDataError),
|
||||
{
|
||||
match parse_single_raw_doc(bytes) {
|
||||
Ok(doc) => decode_te_data_doc_at(doc, 0, on_point, on_error),
|
||||
Err(err) => {
|
||||
let mut stats = BsonTeDataDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonTeDataDecodeStats::default()
|
||||
};
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(map_framing_error(err));
|
||||
stats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_data_doc`], emitting
|
||||
/// every valid historical [`TeDataPoint`] to `on_point` and reporting document- or point-level
|
||||
/// errors to `on_error(byte_offset, err)` without aborting on per-document semantic errors.
|
||||
///
|
||||
/// Always maintains:
|
||||
/// - `stats.docs_in == stats.docs_accepted + stats.docs_rejected_total()`
|
||||
/// - `stats.points_in == stats.points_decoded + stats.rejected_total()`
|
||||
pub fn decode_te_data_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_point: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeDataDecodeStats
|
||||
where
|
||||
F: FnMut(TeDataPoint<'a>),
|
||||
E: FnMut(usize, BsonTeDataError),
|
||||
{
|
||||
let mut stats = BsonTeDataDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => {
|
||||
let doc_stats = decode_te_data_doc_at(doc, doc_offset, &mut on_point, |err| {
|
||||
on_error(doc_offset, err)
|
||||
});
|
||||
stats += doc_stats;
|
||||
}
|
||||
Err((doc_offset, err)) => {
|
||||
stats.docs_in += 1;
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(doc_offset, map_framing_error(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_te_data_tests.rs"]
|
||||
mod tests;
|
||||
885
tools/curate-etl/src/bson_te_data_tests.rs
Normal file
885
tools/curate-etl/src/bson_te_data_tests.rs
Normal file
|
|
@ -0,0 +1,885 @@
|
|||
use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn assert_stats_conserved(stats: &BsonTeDataDecodeStats) {
|
||||
assert_eq!(
|
||||
stats.docs_in,
|
||||
stats.docs_accepted + stats.docs_rejected_total(),
|
||||
"doc conservation failed: {stats:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stats.points_in,
|
||||
stats.points_decoded + stats.rejected_total(),
|
||||
"point conservation failed: {stats:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct OwnedPoint {
|
||||
te_symbol: String,
|
||||
country: String,
|
||||
category: String,
|
||||
period_date: i32,
|
||||
value_bits: u64,
|
||||
}
|
||||
|
||||
impl From<TeDataPoint<'_>> for OwnedPoint {
|
||||
fn from(p: TeDataPoint<'_>) -> Self {
|
||||
Self {
|
||||
te_symbol: p.te_symbol.to_owned(),
|
||||
country: p.country.to_owned(),
|
||||
category: p.category.to_owned(),
|
||||
period_date: p.period_date,
|
||||
value_bits: p.value.to_bits(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_point_f64(d: &str, v: f64) -> RawDocumentBuf {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("d"), d);
|
||||
pt.append(cstr!("v"), v);
|
||||
pt
|
||||
}
|
||||
|
||||
fn make_writer_order_doc(
|
||||
te_symbol: &str,
|
||||
country: &str,
|
||||
category: &str,
|
||||
data: RawArrayBuf,
|
||||
forecast: Option<RawArrayBuf>,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
// Exact field order from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts:93-105`
|
||||
doc.append(cstr!("teSymbol"), te_symbol);
|
||||
doc.append(cstr!("name"), "United States Fed Funds Interest Rate");
|
||||
doc.append(cstr!("unit"), "percent");
|
||||
doc.append(cstr!("source"), "Federal Reserve");
|
||||
doc.append(cstr!("frequency"), "Daily");
|
||||
doc.append(cstr!("country"), country);
|
||||
doc.append(cstr!("category"), category);
|
||||
doc.append(cstr!("data"), data);
|
||||
if let Some(fc) = forecast {
|
||||
doc.append(cstr!("forecast"), fc);
|
||||
}
|
||||
doc.append(cstr!("lastUpdated"), DateTime::from_millis(1_710_000_000_000));
|
||||
doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000));
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_writer_order_document_across_all_three_entry_points() {
|
||||
let mut data = RawArrayBuf::new();
|
||||
data.push(make_point_f64("2024-02-29", 5.5_f64));
|
||||
data.push(make_point_f64("2024-03-31", -0.25_f64));
|
||||
data.push(make_point_f64("1970-01-01", 0.0_f64));
|
||||
|
||||
let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None);
|
||||
|
||||
let expected = vec![
|
||||
OwnedPoint {
|
||||
te_symbol: "FDTR".to_owned(),
|
||||
country: "United States".to_owned(),
|
||||
category: "Interest Rate".to_owned(),
|
||||
period_date: 19_782, // 2024-02-29
|
||||
value_bits: 5.5_f64.to_bits(),
|
||||
},
|
||||
OwnedPoint {
|
||||
te_symbol: "FDTR".to_owned(),
|
||||
country: "United States".to_owned(),
|
||||
category: "Interest Rate".to_owned(),
|
||||
period_date: day(2024, 3, 31),
|
||||
value_bits: (-0.25_f64).to_bits(),
|
||||
},
|
||||
OwnedPoint {
|
||||
te_symbol: "FDTR".to_owned(),
|
||||
country: "United States".to_owned(),
|
||||
category: "Interest Rate".to_owned(),
|
||||
period_date: 0,
|
||||
value_bits: 0.0_f64.to_bits(),
|
||||
},
|
||||
];
|
||||
|
||||
// 1. decode_te_data_doc (verify zero-copy borrowed slices directly)
|
||||
let mut doc_points: Vec<TeDataPoint<'_>> = Vec::new();
|
||||
let mut doc_errs = Vec::new();
|
||||
let doc_stats = decode_te_data_doc(&doc, |p| doc_points.push(p), |e| doc_errs.push(e));
|
||||
assert_stats_conserved(&doc_stats);
|
||||
assert!(doc_errs.is_empty(), "unexpected errors: {doc_errs:?}");
|
||||
assert_eq!(doc_stats.docs_in, 1);
|
||||
assert_eq!(doc_stats.docs_accepted, 1);
|
||||
assert_eq!(doc_stats.points_in, 3);
|
||||
assert_eq!(doc_stats.points_decoded, 3);
|
||||
let doc_owned: Vec<OwnedPoint> = doc_points.into_iter().map(OwnedPoint::from).collect();
|
||||
assert_eq!(doc_owned, expected);
|
||||
|
||||
// 2. decode_te_data_bytes
|
||||
let mut bytes_points = Vec::new();
|
||||
let mut bytes_errs = Vec::new();
|
||||
let bytes_stats = decode_te_data_bytes(
|
||||
doc.as_bytes(),
|
||||
|p| bytes_points.push(OwnedPoint::from(p)),
|
||||
|e| bytes_errs.push(e),
|
||||
);
|
||||
assert_stats_conserved(&bytes_stats);
|
||||
assert!(bytes_errs.is_empty(), "unexpected errors: {bytes_errs:?}");
|
||||
assert_eq!(bytes_stats, doc_stats);
|
||||
assert_eq!(bytes_points, expected);
|
||||
|
||||
// 3. decode_te_data_buffer
|
||||
let mut buf_points = Vec::new();
|
||||
let mut buf_errs = Vec::new();
|
||||
let buf_stats = decode_te_data_buffer(
|
||||
doc.as_bytes(),
|
||||
|p| buf_points.push(OwnedPoint::from(p)),
|
||||
|off, e| buf_errs.push((off, e)),
|
||||
);
|
||||
assert_stats_conserved(&buf_stats);
|
||||
assert!(buf_errs.is_empty(), "unexpected errors: {buf_errs:?}");
|
||||
assert_eq!(buf_stats, doc_stats);
|
||||
assert_eq!(buf_points, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_data_array_accepts_document_and_emits_zero_points() {
|
||||
let doc = make_writer_order_doc("CACPI", "Canada", "Inflation Rate", RawArrayBuf::new(), None);
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e));
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errs.is_empty(), "unexpected errors: {errs:?}");
|
||||
assert!(points.is_empty());
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.docs_accepted, 1);
|
||||
assert_eq!(stats.points_in, 0);
|
||||
assert_eq!(stats.points_decoded, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_before_metadata_decodes_identically_to_writer_order() {
|
||||
let make_data = || {
|
||||
let mut data = RawArrayBuf::new();
|
||||
data.push(make_point_f64("2024-02-29", 4.75_f64));
|
||||
data.push(make_point_f64("2025-01-15", 3.25_f64));
|
||||
data
|
||||
};
|
||||
|
||||
let writer_doc = make_writer_order_doc(
|
||||
"CABOC",
|
||||
"Canada",
|
||||
"Interest Rate",
|
||||
make_data(),
|
||||
None,
|
||||
);
|
||||
|
||||
let mut reordered_doc = RawDocumentBuf::new();
|
||||
reordered_doc.append(cstr!("data"), make_data());
|
||||
reordered_doc.append(cstr!("category"), "Interest Rate");
|
||||
reordered_doc.append(cstr!("country"), "Canada");
|
||||
reordered_doc.append(cstr!("teSymbol"), "CABOC");
|
||||
|
||||
let mut writer_points = Vec::new();
|
||||
let mut writer_errs = Vec::new();
|
||||
let writer_stats = decode_te_data_doc(
|
||||
&writer_doc,
|
||||
|p| writer_points.push(OwnedPoint::from(p)),
|
||||
|e| writer_errs.push(e),
|
||||
);
|
||||
|
||||
let mut reordered_points = Vec::new();
|
||||
let mut reordered_errs = Vec::new();
|
||||
let reordered_stats = decode_te_data_doc(
|
||||
&reordered_doc,
|
||||
|p| reordered_points.push(OwnedPoint::from(p)),
|
||||
|e| reordered_errs.push(e),
|
||||
);
|
||||
|
||||
assert_stats_conserved(&writer_stats);
|
||||
assert_stats_conserved(&reordered_stats);
|
||||
assert!(writer_errs.is_empty());
|
||||
assert!(reordered_errs.is_empty());
|
||||
assert_eq!(reordered_stats, writer_stats);
|
||||
assert_eq!(reordered_points, writer_points);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forecast_is_never_read_or_emitted_before_after_or_when_corrupted() {
|
||||
let make_data = || {
|
||||
let mut data = RawArrayBuf::new();
|
||||
data.push(make_point_f64("2024-02-29", 3.1_f64));
|
||||
data.push(make_point_f64("2024-03-31", 3.2_f64));
|
||||
data
|
||||
};
|
||||
|
||||
let make_forecast = || {
|
||||
let mut fc = RawArrayBuf::new();
|
||||
fc.push(make_point_f64("2026-06-30", 2.0_f64));
|
||||
fc.push("not-even-a-document");
|
||||
let mut bad_pt = RawDocumentBuf::new();
|
||||
bad_pt.append(cstr!("d"), "invalid-date");
|
||||
bad_pt.append(cstr!("v"), RawBson::Null);
|
||||
fc.push(bad_pt);
|
||||
fc
|
||||
};
|
||||
|
||||
// Baseline: data-only
|
||||
let baseline_doc = make_writer_order_doc("USCPI", "United States", "Inflation Rate", make_data(), None);
|
||||
let mut base_points = Vec::new();
|
||||
let mut base_errs = Vec::new();
|
||||
let base_stats = decode_te_data_doc(
|
||||
&baseline_doc,
|
||||
|p| base_points.push(OwnedPoint::from(p)),
|
||||
|e| base_errs.push(e),
|
||||
);
|
||||
assert_stats_conserved(&base_stats);
|
||||
assert!(base_errs.is_empty());
|
||||
assert_eq!(base_points.len(), 2);
|
||||
|
||||
// Variant 1: populated forecast AFTER data (writer order)
|
||||
let after_doc = make_writer_order_doc(
|
||||
"USCPI",
|
||||
"United States",
|
||||
"Inflation Rate",
|
||||
make_data(),
|
||||
Some(make_forecast()),
|
||||
);
|
||||
let mut after_points = Vec::new();
|
||||
let mut after_errs = Vec::new();
|
||||
let after_stats = decode_te_data_doc(
|
||||
&after_doc,
|
||||
|p| after_points.push(OwnedPoint::from(p)),
|
||||
|e| after_errs.push(e),
|
||||
);
|
||||
assert_eq!(after_stats, base_stats);
|
||||
assert_eq!(after_points, base_points);
|
||||
assert!(after_errs.is_empty());
|
||||
|
||||
// Variant 2: populated forecast BEFORE data
|
||||
let mut before_doc = RawDocumentBuf::new();
|
||||
before_doc.append(cstr!("forecast"), make_forecast());
|
||||
before_doc.append(cstr!("teSymbol"), "USCPI");
|
||||
before_doc.append(cstr!("country"), "United States");
|
||||
before_doc.append(cstr!("category"), "Inflation Rate");
|
||||
before_doc.append(cstr!("data"), make_data());
|
||||
|
||||
let mut before_points = Vec::new();
|
||||
let mut before_errs = Vec::new();
|
||||
let before_stats = decode_te_data_doc(
|
||||
&before_doc,
|
||||
|p| before_points.push(OwnedPoint::from(p)),
|
||||
|e| before_errs.push(e),
|
||||
);
|
||||
assert_eq!(before_stats, base_stats);
|
||||
assert_eq!(before_points, base_points);
|
||||
assert!(before_errs.is_empty());
|
||||
|
||||
// Variant 3: corrupt a byte inside the `forecast` array payload while preserving the
|
||||
// enclosing array length and document terminator. If `elem.value()` or array iteration ever
|
||||
// inspected `forecast`, this would fail with a corrupt BSON error.
|
||||
let mut corrupt_fc_bytes = before_doc.as_bytes().to_vec();
|
||||
// Locate the array element `\x04forecast\0`, then advance past its 4-byte length prefix
|
||||
// into the first inner array element's type byte (`0x03` EmbeddedDocument) and corrupt it
|
||||
// to `0xFF`.
|
||||
let fc_header = b"\x04forecast\0";
|
||||
let fc_pos = corrupt_fc_bytes
|
||||
.windows(fc_header.len())
|
||||
.position(|w| w == fc_header)
|
||||
.expect("find forecast array element");
|
||||
let first_inner_elem_type_pos = fc_pos + fc_header.len() + 4;
|
||||
assert_eq!(
|
||||
corrupt_fc_bytes[first_inner_elem_type_pos], 0x03,
|
||||
"expected EmbeddedDocument type byte for forecast[0]"
|
||||
);
|
||||
corrupt_fc_bytes[first_inner_elem_type_pos] = 0xFF;
|
||||
|
||||
let mut corrupt_fc_points = Vec::new();
|
||||
let mut corrupt_fc_errs = Vec::new();
|
||||
let corrupt_fc_stats = decode_te_data_bytes(
|
||||
&corrupt_fc_bytes,
|
||||
|p| corrupt_fc_points.push(OwnedPoint::from(p)),
|
||||
|e| corrupt_fc_errs.push(e),
|
||||
);
|
||||
assert_stats_conserved(&corrupt_fc_stats);
|
||||
assert_eq!(corrupt_fc_stats, base_stats);
|
||||
assert_eq!(corrupt_fc_points, base_points);
|
||||
assert!(
|
||||
corrupt_fc_errs.is_empty(),
|
||||
"corrupt forecast payload must never be read, got: {corrupt_fc_errs:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_empty_and_wrong_type_required_top_level_fields() {
|
||||
let valid_data = || {
|
||||
let mut data = RawArrayBuf::new();
|
||||
data.push(make_point_f64("2024-02-29", 1.0_f64));
|
||||
data
|
||||
};
|
||||
|
||||
// Helper to assert a single rejected doc emits zero points and exact error + counter.
|
||||
let check_reject = |doc: RawDocumentBuf,
|
||||
expected_err: BsonTeDataError,
|
||||
check_counter: fn(&BsonTeDataDecodeStats) -> usize| {
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(points.is_empty(), "rejected doc must emit zero points");
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.docs_accepted, 0);
|
||||
assert_eq!(stats.docs_rejected_total(), 1);
|
||||
assert_eq!(check_counter(&stats), 1, "wrong counter for {expected_err:?}: {stats:?}");
|
||||
assert_eq!(errs, vec![expected_err]);
|
||||
let msg = errs[0].to_string();
|
||||
assert!(!msg.contains('\n'), "multiline error display: {msg}");
|
||||
};
|
||||
|
||||
// --- teSymbol ---
|
||||
// Missing
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::MissingSymbol, |s| s.rejected_missing_symbol);
|
||||
|
||||
// Empty ("")
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::EmptySymbol, |s| s.rejected_empty_symbol);
|
||||
|
||||
// Whitespace-only (" \t ")
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), " \t ");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::EmptySymbol, |s| s.rejected_empty_symbol);
|
||||
|
||||
// Non-string
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), 42_i32);
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(
|
||||
d,
|
||||
BsonTeDataError::WrongSymbolType {
|
||||
actual: ElementType::Int32,
|
||||
},
|
||||
|s| s.rejected_wrong_symbol_type,
|
||||
);
|
||||
|
||||
// --- country ---
|
||||
// Missing
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::MissingCountry, |s| s.rejected_missing_country);
|
||||
|
||||
// Empty ("")
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::EmptyCountry, |s| s.rejected_empty_country);
|
||||
|
||||
// Whitespace-only
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), " ");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::EmptyCountry, |s| s.rejected_empty_country);
|
||||
|
||||
// Non-string
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), RawBson::Null);
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(
|
||||
d,
|
||||
BsonTeDataError::WrongCountryType {
|
||||
actual: ElementType::Null,
|
||||
},
|
||||
|s| s.rejected_wrong_country_type,
|
||||
);
|
||||
|
||||
// --- category ---
|
||||
// Missing
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::MissingCategory, |s| s.rejected_missing_category);
|
||||
|
||||
// Empty ("")
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "");
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(d, BsonTeDataError::EmptyCategory, |s| s.rejected_empty_category);
|
||||
|
||||
// Non-string
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), true);
|
||||
d.append(cstr!("data"), valid_data());
|
||||
check_reject(
|
||||
d,
|
||||
BsonTeDataError::WrongCategoryType {
|
||||
actual: ElementType::Boolean,
|
||||
},
|
||||
|s| s.rejected_wrong_category_type,
|
||||
);
|
||||
|
||||
// --- data ---
|
||||
// Missing
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
check_reject(d, BsonTeDataError::MissingData, |s| s.rejected_data_missing);
|
||||
|
||||
// Document-valued `data`
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), RawDocumentBuf::new());
|
||||
check_reject(
|
||||
d,
|
||||
BsonTeDataError::DataNotArray {
|
||||
actual: ElementType::EmbeddedDocument,
|
||||
},
|
||||
|s| s.rejected_data_not_array,
|
||||
);
|
||||
|
||||
// Scalar `data`
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("teSymbol"), "CAGDP");
|
||||
d.append(cstr!("country"), "Canada");
|
||||
d.append(cstr!("category"), "GDP");
|
||||
d.append(cstr!("data"), "not-an-array");
|
||||
check_reject(
|
||||
d,
|
||||
BsonTeDataError::DataNotArray {
|
||||
actual: ElementType::String,
|
||||
},
|
||||
|s| s.rejected_data_not_array,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_level_validation_numeric_types_and_non_finite_passthrough() {
|
||||
let mut data = RawArrayBuf::new();
|
||||
|
||||
// [0] Valid Double
|
||||
data.push(make_point_f64("2024-02-29", 5.25_f64));
|
||||
|
||||
// [1] Invalid date: non-existent Feb 30
|
||||
data.push(make_point_f64("2024-02-30", 1.0_f64));
|
||||
// [2] Invalid date: non-leap year Feb 29
|
||||
data.push(make_point_f64("2023-02-29", 1.0_f64));
|
||||
// [3] Invalid date: non-padded month/day
|
||||
data.push(make_point_f64("2024-2-1", 1.0_f64));
|
||||
// [4] Invalid date: leading whitespace (no trimming)
|
||||
data.push(make_point_f64(" 2024-01-01", 1.0_f64));
|
||||
// [5] Invalid date: compact YYYYMMDD
|
||||
data.push(make_point_f64("20240101", 1.0_f64));
|
||||
// [6] Invalid date: non-string (`Int32`)
|
||||
let mut pt_int_d = RawDocumentBuf::new();
|
||||
pt_int_d.append(cstr!("d"), 20240101_i32);
|
||||
pt_int_d.append(cstr!("v"), 1.0_f64);
|
||||
data.push(pt_int_d);
|
||||
// [7] Missing `d`
|
||||
let mut pt_no_d = RawDocumentBuf::new();
|
||||
pt_no_d.append(cstr!("v"), 1.0_f64);
|
||||
data.push(pt_no_d);
|
||||
|
||||
// [8] Valid Int32 `v` (interleaved after bad dates to prove continuation)
|
||||
let mut pt_i32 = RawDocumentBuf::new();
|
||||
pt_i32.append(cstr!("d"), "2024-03-01");
|
||||
pt_i32.append(cstr!("v"), -7_i32);
|
||||
data.push(pt_i32);
|
||||
|
||||
// [9] Invalid `v`: Null
|
||||
let mut pt_null_v = RawDocumentBuf::new();
|
||||
pt_null_v.append(cstr!("d"), "2024-03-02");
|
||||
pt_null_v.append(cstr!("v"), RawBson::Null);
|
||||
data.push(pt_null_v);
|
||||
// [10] Invalid `v`: String
|
||||
let mut pt_str_v = RawDocumentBuf::new();
|
||||
pt_str_v.append(cstr!("d"), "2024-03-03");
|
||||
pt_str_v.append(cstr!("v"), "5.25");
|
||||
data.push(pt_str_v);
|
||||
// [11] Invalid `v`: Bool
|
||||
let mut pt_bool_v = RawDocumentBuf::new();
|
||||
pt_bool_v.append(cstr!("d"), "2024-03-04");
|
||||
pt_bool_v.append(cstr!("v"), false);
|
||||
data.push(pt_bool_v);
|
||||
// [12] Missing `v`
|
||||
let mut pt_no_v = RawDocumentBuf::new();
|
||||
pt_no_v.append(cstr!("d"), "2024-03-05");
|
||||
data.push(pt_no_v);
|
||||
|
||||
// [13] Non-document array element
|
||||
data.push("scalar-item");
|
||||
|
||||
// [14] Valid Int64 `v`
|
||||
let mut pt_i64 = RawDocumentBuf::new();
|
||||
pt_i64.append(cstr!("d"), "2024-03-06");
|
||||
pt_i64.append(cstr!("v"), 1_000_000_000_000_i64);
|
||||
data.push(pt_i64);
|
||||
|
||||
// [15] Signed zero (-0.0) passed through bit-identically
|
||||
data.push(make_point_f64("2024-03-07", -0.0_f64));
|
||||
// [16] Payload-bearing NaN passed through bit-identically
|
||||
let payload_nan = f64::from_bits(0x7ff8_0000_0000_1234);
|
||||
assert!(payload_nan.is_nan());
|
||||
data.push(make_point_f64("2024-03-08", payload_nan));
|
||||
// [17] +Infinity passed through bit-identically
|
||||
data.push(make_point_f64("2024-03-09", f64::INFINITY));
|
||||
// [18] -Infinity passed through bit-identically
|
||||
data.push(make_point_f64("2024-03-10", f64::NEG_INFINITY));
|
||||
|
||||
let doc = make_writer_order_doc("TEST", "United States", "CPI", data, None);
|
||||
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_doc(&doc, |p| points.push(p), |e| errs.push(e));
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.docs_accepted, 1);
|
||||
assert_eq!(stats.points_in, 19);
|
||||
assert_eq!(stats.points_decoded, 7);
|
||||
assert_eq!(stats.rejected_invalid_date, 7);
|
||||
assert_eq!(stats.rejected_invalid_value, 4);
|
||||
assert_eq!(stats.rejected_point_not_document, 1);
|
||||
assert_eq!(stats.rejected_corrupt_point, 0);
|
||||
assert_eq!(errs.len(), 12);
|
||||
|
||||
assert_eq!(points.len(), 7);
|
||||
assert_eq!(points[0].period_date, 19_782);
|
||||
assert_eq!(points[0].value.to_bits(), 5.25_f64.to_bits());
|
||||
|
||||
assert_eq!(points[1].period_date, day(2024, 3, 1));
|
||||
assert_eq!(points[1].value.to_bits(), (-7.0_f64).to_bits());
|
||||
|
||||
assert_eq!(points[2].period_date, day(2024, 3, 6));
|
||||
assert_eq!(points[2].value.to_bits(), 1_000_000_000_000.0_f64.to_bits());
|
||||
|
||||
assert_eq!(points[3].period_date, day(2024, 3, 7));
|
||||
assert_eq!(points[3].value.to_bits(), (-0.0_f64).to_bits());
|
||||
|
||||
assert_eq!(points[4].period_date, day(2024, 3, 8));
|
||||
assert_eq!(points[4].value.to_bits(), payload_nan.to_bits());
|
||||
|
||||
assert_eq!(points[5].period_date, day(2024, 3, 9));
|
||||
assert_eq!(points[5].value.to_bits(), f64::INFINITY.to_bits());
|
||||
|
||||
assert_eq!(points[6].period_date, day(2024, 3, 10));
|
||||
assert_eq!(points[6].value.to_bits(), f64::NEG_INFINITY.to_bits());
|
||||
|
||||
// Spot-check error variants and single-line Display
|
||||
assert!(errs.iter().any(|e| matches!(e, BsonTeDataError::InvalidPointDate { point_index: 1 })));
|
||||
assert!(errs.iter().any(|e| matches!(
|
||||
e,
|
||||
BsonTeDataError::WrongPointFieldType {
|
||||
point_index: 6,
|
||||
field: FIELD_POINT_D,
|
||||
actual: ElementType::Int32
|
||||
}
|
||||
)));
|
||||
assert!(errs.iter().any(|e| matches!(
|
||||
e,
|
||||
BsonTeDataError::MissingPointField {
|
||||
point_index: 7,
|
||||
field: FIELD_POINT_D
|
||||
}
|
||||
)));
|
||||
assert!(errs.iter().any(|e| matches!(
|
||||
e,
|
||||
BsonTeDataError::WrongPointFieldType {
|
||||
point_index: 9,
|
||||
field: FIELD_POINT_V,
|
||||
actual: ElementType::Null
|
||||
}
|
||||
)));
|
||||
assert!(errs.iter().any(|e| matches!(
|
||||
e,
|
||||
BsonTeDataError::MissingPointField {
|
||||
point_index: 12,
|
||||
field: FIELD_POINT_V
|
||||
}
|
||||
)));
|
||||
assert!(errs.iter().any(|e| matches!(
|
||||
e,
|
||||
BsonTeDataError::PointNotDocument {
|
||||
point_index: 13,
|
||||
actual: ElementType::String
|
||||
}
|
||||
)));
|
||||
|
||||
for err in &errs {
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "multiline error display: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_doc_buffer_conservation_and_chunk_merge_parity() {
|
||||
// Chunk 1: good doc + rejected doc (missing country) + mixed valid/invalid points doc
|
||||
let mut chunk1 = Vec::new();
|
||||
|
||||
let mut d1_data = RawArrayBuf::new();
|
||||
d1_data.push(make_point_f64("2024-01-31", 4.5_f64));
|
||||
d1_data.push(make_point_f64("2024-02-29", 4.5_f64));
|
||||
let doc1 = make_writer_order_doc("FDTR", "United States", "Interest Rate", d1_data, None);
|
||||
chunk1.extend_from_slice(doc1.as_bytes());
|
||||
|
||||
let mut doc2_missing_country = RawDocumentBuf::new();
|
||||
doc2_missing_country.append(cstr!("teSymbol"), "BAD1");
|
||||
doc2_missing_country.append(cstr!("category"), "GDP");
|
||||
doc2_missing_country.append(cstr!("data"), RawArrayBuf::new());
|
||||
chunk1.extend_from_slice(doc2_missing_country.as_bytes());
|
||||
|
||||
let mut d3_data = RawArrayBuf::new();
|
||||
d3_data.push(make_point_f64("2023-02-29", 1.0_f64)); // invalid date
|
||||
d3_data.push(make_point_f64("2024-03-31", 2.9_f64)); // valid
|
||||
let doc3 = make_writer_order_doc("CACPI", "Canada", "Inflation Rate", d3_data, None);
|
||||
chunk1.extend_from_slice(doc3.as_bytes());
|
||||
|
||||
// Chunk 2: rejected doc (data not array) + empty-data doc + valid doc with bad v
|
||||
let mut chunk2 = Vec::new();
|
||||
|
||||
let mut doc4_bad_data = RawDocumentBuf::new();
|
||||
doc4_bad_data.append(cstr!("teSymbol"), "BAD2");
|
||||
doc4_bad_data.append(cstr!("country"), "Canada");
|
||||
doc4_bad_data.append(cstr!("category"), "GDP");
|
||||
doc4_bad_data.append(cstr!("data"), 99_i32);
|
||||
chunk2.extend_from_slice(doc4_bad_data.as_bytes());
|
||||
|
||||
let doc5_empty = make_writer_order_doc("EMPTY", "Canada", "GDP", RawArrayBuf::new(), None);
|
||||
chunk2.extend_from_slice(doc5_empty.as_bytes());
|
||||
|
||||
let mut d6_data = RawArrayBuf::new();
|
||||
d6_data.push(123_i32); // PointNotDocument
|
||||
let mut bad_v = RawDocumentBuf::new();
|
||||
bad_v.append(cstr!("d"), "2024-04-30");
|
||||
bad_v.append(cstr!("v"), "NaN");
|
||||
d6_data.push(bad_v);
|
||||
d6_data.push(make_point_f64("2024-05-31", 1.75_f64));
|
||||
let doc6 = make_writer_order_doc("CAGDP", "Canada", "GDP Growth Rate", d6_data, None);
|
||||
chunk2.extend_from_slice(doc6.as_bytes());
|
||||
|
||||
let mut full_buf = Vec::with_capacity(chunk1.len() + chunk2.len());
|
||||
full_buf.extend_from_slice(&chunk1);
|
||||
full_buf.extend_from_slice(&chunk2);
|
||||
|
||||
// Decode concatenated buffer
|
||||
let mut full_points = Vec::new();
|
||||
let mut full_errs = Vec::new();
|
||||
let full_stats = decode_te_data_buffer(
|
||||
&full_buf,
|
||||
|p| full_points.push(OwnedPoint::from(p)),
|
||||
|off, e| full_errs.push((off, e)),
|
||||
);
|
||||
assert_stats_conserved(&full_stats);
|
||||
|
||||
// Decode chunk 1 and chunk 2 separately and merge
|
||||
let mut split_points = Vec::new();
|
||||
let stats1 = decode_te_data_buffer(
|
||||
&chunk1,
|
||||
|p| split_points.push(OwnedPoint::from(p)),
|
||||
|_, _| {},
|
||||
);
|
||||
assert_stats_conserved(&stats1);
|
||||
|
||||
let stats2 = decode_te_data_buffer(
|
||||
&chunk2,
|
||||
|p| split_points.push(OwnedPoint::from(p)),
|
||||
|_, _| {},
|
||||
);
|
||||
assert_stats_conserved(&stats2);
|
||||
|
||||
let mut merged = stats1;
|
||||
merged.merge(&stats2);
|
||||
assert_stats_conserved(&merged);
|
||||
|
||||
assert_eq!(merged, full_stats);
|
||||
assert_eq!(split_points, full_points);
|
||||
assert_eq!(full_stats.docs_in, 6);
|
||||
assert_eq!(full_stats.docs_accepted, 4);
|
||||
assert_eq!(full_stats.docs_rejected_total(), 2);
|
||||
assert_eq!(full_stats.points_in, 7);
|
||||
assert_eq!(full_stats.points_decoded, 4);
|
||||
assert_eq!(full_stats.rejected_total(), 3);
|
||||
assert_eq!(full_errs.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framed_corrupt_doc_recovery_and_truncated_tail_offsets() {
|
||||
// 1. decode_te_data_bytes on truncated input
|
||||
let mut trunc_errs = Vec::new();
|
||||
let trunc_stats = decode_te_data_bytes(&[10, 0, 0, 0, 1], |_| {}, |e| trunc_errs.push(e));
|
||||
assert_stats_conserved(&trunc_stats);
|
||||
assert_eq!(trunc_stats.docs_in, 1);
|
||||
assert_eq!(trunc_stats.rejected_corrupt_document, 1);
|
||||
assert!(matches!(
|
||||
trunc_errs.as_slice(),
|
||||
[BsonTeDataError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 5,
|
||||
declared_len: Some(10)
|
||||
}]
|
||||
));
|
||||
|
||||
// 2. Buffer: [recoverably corrupt framed doc] + [valid doc] + [truncated tail]
|
||||
// Valid 4-byte length prefix (12 bytes) with invalid element type byte 0xFF and trailing NUL
|
||||
let bad_framed_doc: [u8; 12] = [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0];
|
||||
|
||||
let mut good_data = RawArrayBuf::new();
|
||||
good_data.push(make_point_f64("2024-02-29", 3.5_f64));
|
||||
let good_doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", good_data, None);
|
||||
|
||||
let truncated_tail: [u8; 3] = [20, 0, 0];
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(&bad_framed_doc);
|
||||
let good_offset = buf.len();
|
||||
buf.extend_from_slice(good_doc.as_bytes());
|
||||
let tail_offset = buf.len();
|
||||
buf.extend_from_slice(&truncated_tail);
|
||||
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_buffer(
|
||||
&buf,
|
||||
|p| points.push(OwnedPoint::from(p)),
|
||||
|off, e| errs.push((off, e)),
|
||||
);
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert_eq!(good_offset, 12);
|
||||
assert_eq!(stats.docs_in, 3);
|
||||
assert_eq!(stats.docs_accepted, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 2);
|
||||
assert_eq!(stats.points_in, 1);
|
||||
assert_eq!(stats.points_decoded, 1);
|
||||
assert_eq!(points.len(), 1);
|
||||
assert_eq!(points[0].te_symbol, "FDTR");
|
||||
assert_eq!(points[0].period_date, 19_782);
|
||||
assert_eq!(points[0].value_bits, 3.5_f64.to_bits());
|
||||
|
||||
assert_eq!(errs.len(), 2);
|
||||
assert_eq!(errs[0].0, 0);
|
||||
assert!(matches!(
|
||||
errs[0].1,
|
||||
BsonTeDataError::CorruptBson { offset: 0, .. }
|
||||
));
|
||||
assert_eq!(errs[1].0, tail_offset);
|
||||
assert!(matches!(
|
||||
errs[1].1,
|
||||
BsonTeDataError::TruncatedDocument {
|
||||
offset,
|
||||
remaining: 3,
|
||||
declared_len: None
|
||||
} if offset == tail_offset
|
||||
));
|
||||
|
||||
// 3. CorruptDocumentLength (< 5) terminates cleanly
|
||||
let bad_len_buf: [u8; 8] = [4, 0, 0, 0, 0, 0, 0, 0];
|
||||
let mut bad_len_errs = Vec::new();
|
||||
let bad_len_stats =
|
||||
decode_te_data_buffer(&bad_len_buf, |_| panic!("no points expected"), |off, e| {
|
||||
bad_len_errs.push((off, e))
|
||||
});
|
||||
assert_stats_conserved(&bad_len_stats);
|
||||
assert_eq!(bad_len_stats.docs_in, 1);
|
||||
assert_eq!(bad_len_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
bad_len_errs,
|
||||
vec![(
|
||||
0,
|
||||
BsonTeDataError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
}
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_corruption_after_semantic_reject_takes_precedence() {
|
||||
// 1. Point with invalid `d` followed by corrupt element type byte on `v`.
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("d"), "2024-02-30");
|
||||
pt.append(cstr!("v"), 1.25_f64);
|
||||
|
||||
let mut data = RawArrayBuf::new();
|
||||
data.push(pt);
|
||||
let doc = make_writer_order_doc("FDTR", "United States", "Interest Rate", data, None);
|
||||
let mut bytes = doc.as_bytes().to_vec();
|
||||
let v_elem_pos = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == b"\x01v\0")
|
||||
.expect("find double element 'v'");
|
||||
bytes[v_elem_pos] = 0xFF;
|
||||
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_bytes(&bytes, |p| points.push(p), |e| errs.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(points.is_empty());
|
||||
assert_eq!(stats.points_in, 1);
|
||||
assert_eq!(stats.rejected_corrupt_point, 1);
|
||||
assert_eq!(stats.rejected_invalid_date, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
errs.as_slice(),
|
||||
[BsonTeDataError::CorruptPointBson { point_index: 0, .. }]
|
||||
),
|
||||
"expected CorruptPointBson to take precedence over InvalidPointDate, got {errs:?}"
|
||||
);
|
||||
|
||||
// 2. Top-level doc with empty `teSymbol` followed by corrupt element type byte on `data`.
|
||||
let mut bad_top = RawDocumentBuf::new();
|
||||
bad_top.append(cstr!("teSymbol"), "");
|
||||
bad_top.append(cstr!("country"), "Canada");
|
||||
bad_top.append(cstr!("category"), "GDP");
|
||||
bad_top.append(cstr!("data"), RawArrayBuf::new());
|
||||
let mut doc_bytes = bad_top.as_bytes().to_vec();
|
||||
let data_elem_pos = doc_bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"\x04data\0")
|
||||
.expect("find array element 'data'");
|
||||
doc_bytes[data_elem_pos] = 0xFF;
|
||||
|
||||
let mut top_errs = Vec::new();
|
||||
let top_stats = decode_te_data_bytes(&doc_bytes, |_| {}, |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(), [BsonTeDataError::CorruptBson { .. }]),
|
||||
"expected CorruptBson to take precedence over EmptySymbol, got {top_errs:?}"
|
||||
);
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ pub mod bson_qm_financials;
|
|||
pub mod bson_qm_intraday;
|
||||
pub mod bson_qm_prices;
|
||||
pub mod bson_stream;
|
||||
pub mod bson_te_data;
|
||||
pub mod bson_te_market_data;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
|
|
@ -109,6 +110,10 @@ pub use bson_stream::{
|
|||
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk,
|
||||
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
pub use bson_te_data::{
|
||||
decode_te_data_buffer, decode_te_data_bytes, decode_te_data_doc, BsonTeDataDecodeStats,
|
||||
BsonTeDataError, TeDataPoint,
|
||||
};
|
||||
pub use bson_te_market_data::{
|
||||
decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc,
|
||||
te_epoch_i64_to_session_date, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, FIELD_DAILY,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue