T-168: M2.2k — tools/curate-etl: zero-copy raw BSON decoder for MongoDB qmFinancials (bson_qm_financials.rs → FinancialObservation<&str>, caller-supplied dotted field paths, fail-closed fiscal-period/date handling) with tests (no new crates, no CLI/bench/stream changes, no live Mongo)

This commit is contained in:
Studio 2026-12-02 11:58:50 -05:00
parent 811f006e2f
commit 49098cc195
4 changed files with 1760 additions and 0 deletions

View file

@ -1649,3 +1649,11 @@ All `curate-*` commands read local TSV and concatenated raw-BSON files produced
- **MongoDB concatenated raw-BSON files (`<collection>.bson`):** `apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts`
See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.md#read-only-raw-bson-exporter-export-raw-bsonts) for flags, read-only safety guards, and the full M1 Step 2 execution order (`run-export-curate-inputs.ts` → `run-export-raw-bson.ts` → `curate-etl curate-*`).
## Zero-Copy `qmFinancials` BSON Decoder (`M2.2k`)
`src/bson_qm_financials.rs` (tested in `src/bson_qm_financials_tests.rs`) decodes raw `qmFinancials` / `qmFinancials-old` MongoDB BSON documents without allocating a `bson::Document`, emitting `FinancialObservation<&str>` rows (key borrowed verbatim from the input BSON slice; owned `currency` allocated only on emission) through `decode_qm_financials_doc`, `decode_qm_financials_bytes`, and `decode_qm_financials_buffer`:
- **Unverified live schema (explicit caller configuration):** Only the four repo-evidenced top-level field names have defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`, available via `QmFinancialsFieldNames::with_verified_defaults`). Live inner field names under `BalanceSheet`, `CashFlow`, and `IncomeStatement`, the currency path, `reportPeriod` token strings, and date BSON types are **unverified against a live dump**, so callers must supply the dotted `currency` path, explicit `Option<&str>` dotted paths for the six `FundamentalsFields` metrics, and `QmFinancialsFiscalPeriod` (`ByTokens { quarterly, annual }` or `Fixed(FiscalPeriod)`). Empty paths, empty/blank dotted segments, blank tokens, and overlapping token lists fail closed before decoding.
- **Fail-closed dates, periods & BSON framing:** Every document is structurally validated (nested documents/arrays/JS-with-scope up to depth `128`) before semantic skips run so corrupt BSON always returns `Err(BsonQmFinancialsError::CorruptBson)` with the failing byte offset (in buffer mode, callbacks may have already fired for earlier valid documents). `periodEndDate` (required) and `reportDate` (optional) accept BSON `DateTime` (UTC epoch day) or strict `YYYY-MM-DD` strings within `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE`; only an absent or BSON `Null` `reportDate` emits `None` (present-but-invalid vintage dates skip the document rather than silently dropping the vintage). Numeric paths accept `Double`, `Int32`, `Int64`, and trimmed numeric strings (`f64`), counting missing paths, wrong types, unparsable strings, and non-finite values on emitted rows while leaving unconfigured (`None`) paths and BSON `Null` leaves uncounted.
- **Accounting invariant & ownership boundary:** `BsonQmFinancialsDecodeStats` satisfies `docs_in == rows_out + skipped_total()`. QuoteMedia owns the source statement inputs; `build_fundamentals_rows` owns filing linkage and `known_at` derivation, while this decoder preserves the supplied `report_date` vintage and `currency`. Chunked streaming (`bson_stream`), file-to-file runner, and CLI wiring are deferred to follow-up tasks.

View file

@ -0,0 +1,939 @@
//! Zero-copy raw BSON decoder for MongoDB `qmFinancials` (and `qmFinancials-old`) documents (`M2.2k`).
//!
//! Decodes `&bson::RawDocument` slices without allocating a `bson::Document`, emitting
//! [`FinancialObservation<&str>`] rows (borrowing `key` verbatim from the input BSON slice and
//! allocating the owned `currency: String` only when a row is emitted) via a caller-supplied
//! callback.
//!
//! # Unverified Live Schema & Caller-Supplied Paths
//!
//! QuoteMedia owns the source statement inputs; the existing builder
//! ([`crate::fundamentals::build_fundamentals_rows`]) owns filing linkage and `known_at`
//! derivation, while this decoder preserves the supplied `report_date` vintage and `currency`.
//!
//! Field defaults are restricted strictly to names established by in-repo evidence
//! (`apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts` and
//! `design/DATA-CONTRACTS.md` §1):
//! - Verified defaults: `key = "qmSearchCode"` ([`DEFAULT_QM_FINANCIALS_KEY_FIELD`]),
//! `period_end = "periodEndDate"` ([`DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD`]),
//! `report_date = "reportDate"` ([`DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD`]),
//! `report_period = "reportPeriod"` ([`DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD`]).
//! - **Unverified against a live dump:** the inner field names under `BalanceSheet`, `CashFlow`,
//! and `IncomeStatement`, the currency field path, the exact `reportPeriod` token strings, and
//! the live MongoDB BSON types of `periodEndDate` / `reportDate` have **not** been verified
//! against a live `qmFinancials` dump. Callers must therefore explicitly supply:
//! - `currency` path and each of the six numeric value paths (`Option<&str>`, dotted paths such
//! as `"IncomeStatement.totalRevenue"` or `None` to leave a field unconfigured) in
//! [`QmFinancialsFieldNames`];
//! - [`QmFinancialsFiscalPeriod`] (`ByTokens` with explicit quarterly/annual string lists, or
//! `Fixed` for a caller-known uniform input).
//!
//! # Decoding & Validation Rules
//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each
//! [`RawDocument`] is structurally validated to completion before semantic skip checks run, so
//! structural BSON corruption always returns `Err(BsonQmFinancialsError::CorruptBson)` rather
//! than being masked by an earlier semantic skip.
//! - Deterministic semantic skip priority:
//! `key` → `period_end` → `fiscal_period` (`report_period`) → `report_date` → `currency`.
//! - `key` and `currency`: required non-blank UTF-8 BSON `String`s passed verbatim (no trimming).
//! Missing, wrong-typed (including non-document intermediate segments), or blank values skip the
//! document under their respective counters.
//! - `period_end`: required BSON `DateTime` (UTC epoch day via
//! `timestamp_millis().div_euclid(86_400_000)` with checked `i32` conversion) or strict
//! `YYYY-MM-DD` UTF-8 BSON `String`, validated inclusively against
//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`).
//! - `fiscal_period`: under [`QmFinancialsFiscalPeriod::ByTokens`], `report_period` must be a
//! UTF-8 `String` matching an exact configured quarterly or annual token; missing, wrong-typed,
//! or unmapped values skip the document (fail closed). Under
//! [`QmFinancialsFiscalPeriod::Fixed`], the supplied [`FiscalPeriod`] is used without consulting
//! `fields.report_period`.
//! - `report_date` (**point-in-time vintage guard, fail closed**): only an absent path (or null
//! intermediate) or BSON `Null` emits `None`. A present but wrong-typed, malformed/blank, or
//! out-of-range `report_date` skips the document rather than silently dropping a vintage date.
//! - Numeric fields (`FundamentalsFields`): decoded only on rows that pass all skip checks.
//! Unconfigured (`None`) paths emit `None` without incrementing any null counter. Configured
//! (`Some(path)`) paths accept BSON `Double`, `Int32`, `Int64`, and UTF-8 `String`s parsed as
//! finite `f64` (trimmed before parsing); BSON `Null` emits `None` cleanly. Missing paths
//! (including missing or null intermediate subdocuments), wrong types (including non-document
//! intermediates), unparsable strings, and non-finite doubles/strings emit `None` and increment
//! `nulled_missing_path`, `nulled_wrong_type`, `nulled_unparsable_string`, or
//! `nulled_non_finite` respectively.
//! - Buffer error semantics: if [`decode_qm_financials_buffer`] encounters a framing or BSON
//! corruption error after one or more valid documents, `on_row` has already been invoked for
//! those earlier valid documents and the error carries the failing document's byte offset.
//! - Conservation invariant on [`BsonQmFinancialsDecodeStats`]:
//! `docs_in == rows_out + skipped_total()`.
use std::error::Error;
use std::fmt;
use bson::raw::{RawBsonRef, RawDocument};
use crate::bson_eod_prices::{
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
MILLIS_PER_DAY,
};
use crate::fundamentals::{FinancialObservation, FiscalPeriod, FundamentalsFields};
use crate::shorts::{MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE};
/// Verified default BSON field name for the `qmFinancials` security key (`financials.action.ts`).
pub const DEFAULT_QM_FINANCIALS_KEY_FIELD: &str = "qmSearchCode";
/// Verified default BSON field name for `qmFinancials.periodEndDate` (`design/DATA-CONTRACTS.md` §1).
pub const DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD: &str = "periodEndDate";
/// Verified default BSON field name for `qmFinancials.reportDate` (`financials.action.ts`, `DATA-CONTRACTS.md` §1).
pub const DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD: &str = "reportDate";
/// Verified default BSON field name for `qmFinancials.reportPeriod` (`financials.action.ts`).
pub const DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD: &str = "reportPeriod";
/// Borrowed dotted BSON field-path configuration for decoding `qmFinancials` documents.
///
/// Intentionally has no `Default`: live inner field names under `BalanceSheet`, `CashFlow`, and
/// `IncomeStatement` and the currency path are unverified against a live dump. Use
/// [`Self::with_verified_defaults`] to populate only the four repo-evidenced top-level defaults
/// while explicitly supplying `currency` and any desired numeric value paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QmFinancialsFieldNames<'a> {
pub key: &'a str,
pub period_end: &'a str,
pub report_date: &'a str,
pub report_period: &'a str,
pub currency: &'a str,
pub revenue: Option<&'a str>,
pub net_income: Option<&'a str>,
pub operating_cash_flow: Option<&'a str>,
pub total_assets: Option<&'a str>,
pub total_equity: Option<&'a str>,
pub shares_outstanding: Option<&'a str>,
}
impl<'a> QmFinancialsFieldNames<'a> {
/// Constructs a configuration pre-populated with the four repo-evidenced defaults
/// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the caller-supplied
/// `currency` path, and all six numeric value paths left unconfigured (`None`).
#[inline]
pub const fn with_verified_defaults(currency: &'a str) -> Self {
Self {
key: DEFAULT_QM_FINANCIALS_KEY_FIELD,
period_end: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD,
report_date: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD,
report_period: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD,
currency,
revenue: None,
net_income: None,
operating_cash_flow: None,
total_assets: None,
total_equity: None,
shares_outstanding: None,
}
}
/// Validates that every configured dotted field path is non-empty/non-blank and contains no
/// empty or whitespace-only segments (rejecting leading, trailing, or consecutive dots).
pub fn validate(&self) -> Result<(), BsonQmFinancialsError> {
let roles: [(&'static str, Option<&str>); 11] = [
("key", Some(self.key)),
("period_end", Some(self.period_end)),
("report_date", Some(self.report_date)),
("report_period", Some(self.report_period)),
("currency", Some(self.currency)),
("revenue", self.revenue),
("net_income", self.net_income),
("operating_cash_flow", self.operating_cash_flow),
("total_assets", self.total_assets),
("total_equity", self.total_equity),
("shares_outstanding", self.shares_outstanding),
];
for &(role, path_opt) in &roles {
if let Some(path) = path_opt {
validate_dotted_path(role, path)?;
}
}
Ok(())
}
}
fn validate_dotted_path(role: &'static str, path: &str) -> Result<(), BsonQmFinancialsError> {
if path.is_empty() || path.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFieldNames {
detail: format!("field path for '{role}' must not be empty or blank"),
});
}
for segment in path.split('.') {
if segment.is_empty() || segment.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFieldNames {
detail: format!(
"field path '{path}' for '{role}' contains an empty or blank segment"
),
});
}
}
Ok(())
}
/// Explicit fiscal-period resolution policy for `qmFinancials` documents.
///
/// Intentionally has no `Default`: the live `reportPeriod` token strings in MongoDB are
/// unverified in the repository, so callers must either supply explicit token lists or a fixed
/// [`FiscalPeriod`] override for a caller-known uniform input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QmFinancialsFiscalPeriod<'a> {
/// Map exact UTF-8 BSON `String` values of `fields.report_period` against caller-supplied
/// quarterly and annual token slices. Missing, wrong-typed, or unmapped values skip the
/// document (fail closed).
ByTokens {
quarterly: &'a [&'a str],
annual: &'a [&'a str],
},
/// Assign a fixed [`FiscalPeriod`] to every decoded document without consulting
/// `fields.report_period`.
Fixed(FiscalPeriod),
}
impl<'a> QmFinancialsFiscalPeriod<'a> {
/// Validates token-mode configuration, rejecting empty/blank tokens and any token present in
/// both `quarterly` and `annual`.
pub fn validate(&self) -> Result<(), BsonQmFinancialsError> {
match *self {
Self::Fixed(_) => Ok(()),
Self::ByTokens { quarterly, annual } => {
for &tok in quarterly {
if tok.is_empty() || tok.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig {
detail: "quarterly report_period token must not be empty or blank"
.to_string(),
});
}
}
for &tok in annual {
if tok.is_empty() || tok.trim().is_empty() {
return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig {
detail: "annual report_period token must not be empty or blank"
.to_string(),
});
}
}
for &q_tok in quarterly {
if annual.contains(&q_tok) {
return Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig {
detail: format!(
"report_period token '{q_tok}' cannot appear in both quarterly and annual lists"
),
});
}
}
Ok(())
}
}
}
}
/// Typed errors returned while validating configuration or decoding raw `qmFinancials` BSON.
///
/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset;
/// every variant's `Display` output is a single line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BsonQmFinancialsError {
/// Invalid [`QmFinancialsFieldNames`] configuration (empty/blank path or segment).
InvalidFieldNames { detail: String },
/// Invalid [`QmFinancialsFiscalPeriod`] configuration (blank token or overlapping token lists).
InvalidFiscalPeriodConfig { detail: String },
/// Buffer ended before a complete 4-byte length prefix or declared document body.
TruncatedDocument {
offset: u64,
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: u64, declared_len: i32 },
/// Underlying BSON framing or element bytes were malformed.
CorruptBson { offset: u64, detail: String },
}
impl fmt::Display for BsonQmFinancialsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFieldNames { detail } => {
write!(f, "invalid qmFinancials field configuration: {detail}")
}
Self::InvalidFiscalPeriodConfig { detail } => {
write!(
f,
"invalid qmFinancials fiscal period configuration: {detail}"
)
}
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}")
}
}
}
}
impl Error for BsonQmFinancialsError {}
#[inline]
fn map_framing_error(err: BsonEodPriceError) -> BsonQmFinancialsError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonQmFinancialsError::TruncatedDocument {
offset: offset as u64,
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonQmFinancialsError::CorruptDocumentLength {
offset: offset as u64,
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => BsonQmFinancialsError::CorruptBson {
offset: offset as u64,
detail,
},
other => BsonQmFinancialsError::CorruptBson {
offset: 0,
detail: other.to_string(),
},
}
}
/// Per-batch decode accounting for `qmFinancials`.
///
/// Conservation invariant:
/// `docs_in == rows_out + skipped_total()`
///
/// Numeric null counters (`nulled_missing_path`, `nulled_wrong_type`,
/// `nulled_unparsable_string`, `nulled_non_finite`) are incremented only on emitted rows and are
/// excluded from [`Self::skipped_total`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BsonQmFinancialsDecodeStats {
pub docs_in: usize,
pub rows_out: usize,
pub skipped_missing_key: usize,
pub skipped_wrong_key_type: usize,
pub skipped_empty_key: usize,
pub skipped_missing_period_end: usize,
pub skipped_wrong_period_end_type: usize,
pub skipped_invalid_period_end: usize,
pub skipped_period_end_out_of_range: usize,
pub skipped_missing_report_period: usize,
pub skipped_wrong_report_period_type: usize,
pub skipped_unmapped_report_period: usize,
pub skipped_wrong_report_date_type: usize,
pub skipped_invalid_report_date: usize,
pub skipped_report_date_out_of_range: usize,
pub skipped_missing_currency: usize,
pub skipped_wrong_currency_type: usize,
pub skipped_empty_currency: usize,
pub nulled_missing_path: usize,
pub nulled_wrong_type: usize,
pub nulled_unparsable_string: usize,
pub nulled_non_finite: usize,
}
impl BsonQmFinancialsDecodeStats {
/// Total number of semantically skipped `qmFinancials` documents across all skip categories.
#[inline]
pub fn skipped_total(&self) -> usize {
self.skipped_missing_key
+ self.skipped_wrong_key_type
+ self.skipped_empty_key
+ self.skipped_missing_period_end
+ self.skipped_wrong_period_end_type
+ self.skipped_invalid_period_end
+ self.skipped_period_end_out_of_range
+ self.skipped_missing_report_period
+ self.skipped_wrong_report_period_type
+ self.skipped_unmapped_report_period
+ self.skipped_wrong_report_date_type
+ self.skipped_invalid_report_date
+ self.skipped_report_date_out_of_range
+ self.skipped_missing_currency
+ self.skipped_wrong_currency_type
+ self.skipped_empty_currency
}
/// Accumulates counters from another batch into `self`.
#[inline]
pub fn merge(&mut self, other: &Self) {
self.docs_in += other.docs_in;
self.rows_out += other.rows_out;
self.skipped_missing_key += other.skipped_missing_key;
self.skipped_wrong_key_type += other.skipped_wrong_key_type;
self.skipped_empty_key += other.skipped_empty_key;
self.skipped_missing_period_end += other.skipped_missing_period_end;
self.skipped_wrong_period_end_type += other.skipped_wrong_period_end_type;
self.skipped_invalid_period_end += other.skipped_invalid_period_end;
self.skipped_period_end_out_of_range += other.skipped_period_end_out_of_range;
self.skipped_missing_report_period += other.skipped_missing_report_period;
self.skipped_wrong_report_period_type += other.skipped_wrong_report_period_type;
self.skipped_unmapped_report_period += other.skipped_unmapped_report_period;
self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type;
self.skipped_invalid_report_date += other.skipped_invalid_report_date;
self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range;
self.skipped_missing_currency += other.skipped_missing_currency;
self.skipped_wrong_currency_type += other.skipped_wrong_currency_type;
self.skipped_empty_currency += other.skipped_empty_currency;
self.nulled_missing_path += other.nulled_missing_path;
self.nulled_wrong_type += other.nulled_wrong_type;
self.nulled_unparsable_string += other.nulled_unparsable_string;
self.nulled_non_finite += other.nulled_non_finite;
}
}
impl std::ops::AddAssign for BsonQmFinancialsDecodeStats {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.merge(&rhs);
}
}
/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays.
const MAX_BSON_VALIDATION_DEPTH: usize = 128;
#[inline]
fn is_exact_array_index(key: &str, expected: usize) -> bool {
let bytes = key.as_bytes();
if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') {
return false;
}
let mut parsed: usize = 0;
for &b in bytes {
if !b.is_ascii_digit() {
return false;
}
let digit = usize::from(b - b'0');
match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) {
Some(next) => parsed = next,
None => return false,
}
}
parsed == expected
}
fn validate_raw_bson_value(
val: RawBsonRef<'_>,
doc_offset: u64,
field_name: &str,
depth: usize,
) -> Result<(), BsonQmFinancialsError> {
match val {
RawBsonRef::Document(subdoc) => {
validate_raw_document(subdoc, doc_offset, field_name, depth + 1)
}
RawBsonRef::Array(arr) => {
if depth >= MAX_BSON_VALIDATION_DEPTH {
return Err(BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
),
});
}
for (expected_idx, elem_res) in arr.iter_elements().enumerate() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
let key = elem.key().as_str();
if !is_exact_array_index(key, expected_idx) {
return Err(BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}"
),
});
}
let item = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?;
}
Ok(())
}
RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => {
validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1)
}
_ => Ok(()),
}
}
fn validate_raw_document(
doc: &RawDocument,
doc_offset: u64,
field_name: &str,
depth: usize,
) -> Result<(), BsonQmFinancialsError> {
if depth > MAX_BSON_VALIDATION_DEPTH {
return Err(BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!(
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
),
});
}
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
let val = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{field_name}': {err}"),
})?;
validate_raw_bson_value(val, doc_offset, field_name, depth)?;
}
Ok(())
}
fn validate_top_level_document(
doc: &RawDocument,
doc_offset: u64,
) -> Result<(), BsonQmFinancialsError> {
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
})?;
let name = elem.key().as_str();
let val = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{name}': {err}"),
})?;
validate_raw_bson_value(val, doc_offset, name, 0)?;
}
Ok(())
}
enum PathLookup<'a> {
Found(RawBsonRef<'a>),
Missing,
NonDocumentIntermediate,
}
fn lookup_dotted_path<'a>(
doc: &'a RawDocument,
path: &str,
doc_offset: u64,
) -> Result<PathLookup<'a>, BsonQmFinancialsError> {
let mut current_doc = doc;
let mut segments = path.split('.').peekable();
while let Some(seg) = segments.next() {
let is_last = segments.peek().is_none();
let mut matched: Option<RawBsonRef<'a>> = None;
for elem_res in current_doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
})?;
if elem.key().as_str() == seg {
let val = elem
.value()
.map_err(|err| BsonQmFinancialsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{path}': {err}"),
})?;
matched = Some(val);
}
}
let Some(val) = matched else {
return Ok(PathLookup::Missing);
};
if is_last {
return Ok(PathLookup::Found(val));
}
match val {
RawBsonRef::Document(subdoc) => {
current_doc = subdoc;
}
RawBsonRef::Null => return Ok(PathLookup::Missing),
_ => return Ok(PathLookup::NonDocumentIntermediate),
}
}
Ok(PathLookup::Missing)
}
#[inline]
fn is_supported_date(epoch_day: i32) -> bool {
(MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day)
}
enum DateParseResult {
Valid(i32),
WrongType,
Invalid,
OutOfRange,
}
#[inline]
fn decode_date_value(val: RawBsonRef<'_>) -> DateParseResult {
match val {
RawBsonRef::DateTime(dt) => {
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
match i32::try_from(days) {
Ok(d) if is_supported_date(d) => DateParseResult::Valid(d),
_ => DateParseResult::OutOfRange,
}
}
RawBsonRef::String(s) => match parse_ymd_strict_days(s) {
Some(d) if is_supported_date(d) => DateParseResult::Valid(d),
Some(_) => DateParseResult::OutOfRange,
None => DateParseResult::Invalid,
},
_ => DateParseResult::WrongType,
}
}
fn decode_numeric_field(
doc: &RawDocument,
path_opt: Option<&str>,
doc_offset: u64,
stats: &mut BsonQmFinancialsDecodeStats,
) -> Result<Option<f64>, BsonQmFinancialsError> {
let Some(path) = path_opt else {
return Ok(None);
};
match lookup_dotted_path(doc, path, doc_offset)? {
PathLookup::Missing => {
stats.nulled_missing_path += 1;
Ok(None)
}
PathLookup::NonDocumentIntermediate => {
stats.nulled_wrong_type += 1;
Ok(None)
}
PathLookup::Found(val) => match val {
RawBsonRef::Null => Ok(None),
RawBsonRef::Double(v) => {
if v.is_finite() {
Ok(Some(v))
} else {
stats.nulled_non_finite += 1;
Ok(None)
}
}
RawBsonRef::Int32(v) => Ok(Some(f64::from(v))),
RawBsonRef::Int64(v) => Ok(Some(v as f64)),
RawBsonRef::String(s) => {
let trimmed = s.trim();
match trimmed.parse::<f64>() {
Ok(v) if v.is_finite() => Ok(Some(v)),
Ok(_) => {
stats.nulled_non_finite += 1;
Ok(None)
}
Err(_) => {
stats.nulled_unparsable_string += 1;
Ok(None)
}
}
}
_ => {
stats.nulled_wrong_type += 1;
Ok(None)
}
},
}
}
fn decode_qm_financials_doc_at<'a, F>(
doc: &'a RawDocument,
doc_offset: u64,
fields: &QmFinancialsFieldNames<'_>,
fiscal_period_cfg: QmFinancialsFiscalPeriod<'_>,
mut on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
// Validate the entire raw document structurally first so BSON corruption always returns
// `Err(BsonQmFinancialsError::CorruptBson)` rather than being masked by a semantic skip.
validate_top_level_document(doc, doc_offset)?;
let mut stats = BsonQmFinancialsDecodeStats {
docs_in: 1,
..BsonQmFinancialsDecodeStats::default()
};
// 1. Key (required non-blank UTF-8 string, borrowed verbatim).
let key = match lookup_dotted_path(doc, fields.key, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_key += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_key_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::String(s)) => {
if s.trim().is_empty() {
stats.skipped_empty_key += 1;
return Ok(stats);
}
s
}
PathLookup::Found(_) => {
stats.skipped_wrong_key_type += 1;
return Ok(stats);
}
};
// 2. Period end date (required DateTime or strict YYYY-MM-DD within supported calendar bounds).
let period_end = match lookup_dotted_path(doc, fields.period_end, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_period_end += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_period_end_type += 1;
return Ok(stats);
}
PathLookup::Found(val) => match decode_date_value(val) {
DateParseResult::Valid(d) => d,
DateParseResult::WrongType => {
stats.skipped_wrong_period_end_type += 1;
return Ok(stats);
}
DateParseResult::Invalid => {
stats.skipped_invalid_period_end += 1;
return Ok(stats);
}
DateParseResult::OutOfRange => {
stats.skipped_period_end_out_of_range += 1;
return Ok(stats);
}
},
};
// 3. Fiscal period (explicit token mapping or fixed override; fail closed in token mode).
let fiscal_period = match fiscal_period_cfg {
QmFinancialsFiscalPeriod::Fixed(fp) => fp,
QmFinancialsFiscalPeriod::ByTokens { quarterly, annual } => {
match lookup_dotted_path(doc, fields.report_period, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_report_period += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_report_period_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::String(s)) => {
if quarterly.contains(&s) {
FiscalPeriod::Quarterly
} else if annual.contains(&s) {
FiscalPeriod::Annual
} else {
stats.skipped_unmapped_report_period += 1;
return Ok(stats);
}
}
PathLookup::Found(_) => {
stats.skipped_wrong_report_period_type += 1;
return Ok(stats);
}
}
}
};
// 4. Report date (optional vintage date: only absent or BSON Null -> None; invalid skips row).
let report_date = match lookup_dotted_path(doc, fields.report_date, doc_offset)? {
PathLookup::Missing => None,
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_report_date_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::Null) => None,
PathLookup::Found(val) => match decode_date_value(val) {
DateParseResult::Valid(d) => Some(d),
DateParseResult::WrongType => {
stats.skipped_wrong_report_date_type += 1;
return Ok(stats);
}
DateParseResult::Invalid => {
stats.skipped_invalid_report_date += 1;
return Ok(stats);
}
DateParseResult::OutOfRange => {
stats.skipped_report_date_out_of_range += 1;
return Ok(stats);
}
},
};
// 5. Currency (required non-blank UTF-8 string; owned String allocated only on emission).
let currency_str = match lookup_dotted_path(doc, fields.currency, doc_offset)? {
PathLookup::Missing => {
stats.skipped_missing_currency += 1;
return Ok(stats);
}
PathLookup::NonDocumentIntermediate => {
stats.skipped_wrong_currency_type += 1;
return Ok(stats);
}
PathLookup::Found(RawBsonRef::String(s)) => {
if s.trim().is_empty() {
stats.skipped_empty_currency += 1;
return Ok(stats);
}
s
}
PathLookup::Found(_) => {
stats.skipped_wrong_currency_type += 1;
return Ok(stats);
}
};
// Row passed all skip checks: decode configured numeric statement fields and emit.
let statement_fields = FundamentalsFields {
revenue: decode_numeric_field(doc, fields.revenue, doc_offset, &mut stats)?,
net_income: decode_numeric_field(doc, fields.net_income, doc_offset, &mut stats)?,
operating_cash_flow: decode_numeric_field(
doc,
fields.operating_cash_flow,
doc_offset,
&mut stats,
)?,
total_assets: decode_numeric_field(doc, fields.total_assets, doc_offset, &mut stats)?,
total_equity: decode_numeric_field(doc, fields.total_equity, doc_offset, &mut stats)?,
shares_outstanding: decode_numeric_field(
doc,
fields.shares_outstanding,
doc_offset,
&mut stats,
)?,
};
stats.rows_out += 1;
on_row(FinancialObservation {
key,
period_end,
fiscal_period,
currency: currency_str.to_owned(),
report_date,
fields: statement_fields,
});
Ok(stats)
}
/// Decodes a single `&RawDocument` representing a `qmFinancials` MongoDB document without
/// allocating a `bson::Document`.
///
/// Validates `fields` and `fiscal_period` before inspecting the document.
pub fn decode_qm_financials_doc<'a, F>(
doc: &'a RawDocument,
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
decode_qm_financials_doc_at(doc, 0, fields, fiscal_period, on_row)
}
/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmFinancials`
/// document.
///
/// Validates `fields` and `fiscal_period` before inspecting the bytes.
pub fn decode_qm_financials_bytes<'a, F>(
bytes: &'a [u8],
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
decode_qm_financials_doc_at(doc, 0, fields, fiscal_period, on_row)
}
/// Streams a concatenated length-prefixed BSON buffer of `qmFinancials` documents through
/// [`decode_qm_financials_doc`], emitting every valid [`FinancialObservation<&str>`] to `on_row`
/// and failing closed on the first structural BSON framing or element corruption.
///
/// Validates `fields` and `fiscal_period` once before reading the buffer. If an error occurs after
/// one or more valid documents, `on_row` has already been invoked for those earlier documents and
/// the returned error reports the failing document's byte offset.
///
/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`.
pub fn decode_qm_financials_buffer<'a, F>(
buf: &'a [u8],
fields: &QmFinancialsFieldNames<'_>,
fiscal_period: QmFinancialsFiscalPeriod<'_>,
mut on_row: F,
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsError>
where
F: FnMut(FinancialObservation<&'a str>),
{
fields.validate()?;
fiscal_period.validate()?;
let mut total = BsonQmFinancialsDecodeStats::default();
let mut iter = iter_raw_bson_docs(buf);
while let Some(item) = iter.next_with_offset() {
match item {
Ok((offset, doc)) => {
let doc_stats = decode_qm_financials_doc_at(
doc,
offset as u64,
fields,
fiscal_period,
&mut on_row,
)?;
total += doc_stats;
}
Err((_, err)) => return Err(map_framing_error(err)),
}
}
Ok(total)
}
#[cfg(test)]
#[path = "bson_qm_financials_tests.rs"]
mod tests;

View file

@ -0,0 +1,805 @@
use std::collections::BTreeMap;
use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf};
use bson::DateTime as BsonDateTime;
use super::*;
use crate::events::{parse_filing_timefiled, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP};
use crate::fundamentals::{build_fundamentals_rows, StatutoryLagVenue};
use crate::shorts::epoch_days_to_ymd;
use crate::split::ymd_to_epoch_days;
fn assert_conservation(stats: &BsonQmFinancialsDecodeStats) {
assert_eq!(
stats.docs_in,
stats.rows_out + stats.skipped_total(),
"conservation invariant failed: {stats:?}"
);
}
fn full_test_fields() -> QmFinancialsFieldNames<'static> {
QmFinancialsFieldNames {
revenue: Some("IncomeStatement.totalRevenue"),
net_income: Some("IncomeStatement.netIncome"),
operating_cash_flow: Some("CashFlow.operatingCashFlow"),
total_assets: Some("BalanceSheet.totalAssets"),
total_equity: Some("BalanceSheet.totalEquity"),
shares_outstanding: Some("BalanceSheet.commonSharesOutstanding"),
..QmFinancialsFieldNames::with_verified_defaults("currency")
}
}
const QUARTERLY_TOKENS: &[&str] = &["Q", "Q1", "Q2", "Q3", "Q4"];
const ANNUAL_TOKENS: &[&str] = &["A", "FY"];
fn token_period_cfg() -> QmFinancialsFiscalPeriod<'static> {
QmFinancialsFiscalPeriod::ByTokens {
quarterly: QUARTERLY_TOKENS,
annual: ANNUAL_TOKENS,
}
}
fn make_nested_doc(
key: &str,
period_end: RawBson,
report_period: &str,
report_date: Option<RawBson>,
currency: &str,
statements: (RawDocumentBuf, RawDocumentBuf, RawDocumentBuf),
) -> RawDocumentBuf {
let (income, balance, cash_flow) = statements;
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), key);
doc.append(cstr!("periodEndDate"), period_end);
doc.append(cstr!("reportPeriod"), report_period);
if let Some(rd) = report_date {
doc.append(cstr!("reportDate"), rd);
}
doc.append(cstr!("currency"), currency);
doc.append(cstr!("IncomeStatement"), income);
doc.append(cstr!("BalanceSheet"), balance);
doc.append(cstr!("CashFlow"), cash_flow);
doc
}
fn make_valid_doc(key: &str) -> RawDocumentBuf {
let mut income = RawDocumentBuf::new();
income.append(cstr!("totalRevenue"), 1_250_000.5_f64);
income.append(cstr!("netIncome"), 125_000_i32);
let mut balance = RawDocumentBuf::new();
balance.append(cstr!("totalAssets"), 9_000_000_000_i64);
balance.append(cstr!("totalEquity"), "4500000.25");
balance.append(cstr!("commonSharesOutstanding"), " 100000000 ");
let mut cash_flow = RawDocumentBuf::new();
cash_flow.append(cstr!("operatingCashFlow"), 300_000.75_f64);
make_nested_doc(
key,
RawBson::String("2024-06-30".to_string()),
"Q2",
Some(RawBson::String("2024-08-02".to_string())),
"USD",
(income, balance, cash_flow),
)
}
#[test]
fn decodes_nested_statements_all_entry_points_date_and_numeric_types() {
let fields = full_test_fields();
let period_cfg = token_period_cfg();
// Doc 1: String dates + Double, Int32, Int64, numeric String (with spaces).
let doc1 = make_valid_doc("AAPL:US");
// Doc 2: BSON DateTime dates (mid-day UTC) + Annual token + negative numeric string.
let pe_day = ymd_to_epoch_days(2024, 12, 31).unwrap();
let rd_day = ymd_to_epoch_days(2025, 2, 14).unwrap();
let mut income2 = RawDocumentBuf::new();
income2.append(cstr!("totalRevenue"), 5_000_000_i64);
income2.append(cstr!("netIncome"), "-42500.5");
let mut balance2 = RawDocumentBuf::new();
balance2.append(cstr!("totalAssets"), 20_000_000_i32);
balance2.append(cstr!("totalEquity"), 12_500_000.0_f64);
balance2.append(cstr!("commonSharesOutstanding"), 50_000_000_i64);
let mut cash2 = RawDocumentBuf::new();
cash2.append(cstr!("operatingCashFlow"), -10_000_i32);
let doc2 = make_nested_doc(
"SHOP:CA",
RawBson::DateTime(BsonDateTime::from_millis(
i64::from(pe_day) * MILLIS_PER_DAY + 43_200_000,
)),
"FY",
Some(RawBson::DateTime(BsonDateTime::from_millis(
i64::from(rd_day) * MILLIS_PER_DAY + 3_600_000,
))),
"CAD",
(income2, balance2, cash2),
);
// 1. decode_qm_financials_doc (zero-copy check on borrowed key)
let raw_doc1: &RawDocument = doc1.as_ref();
let raw_bytes1 = raw_doc1.as_bytes();
let range1 = raw_bytes1.as_ptr() as usize..raw_bytes1.as_ptr() as usize + raw_bytes1.len();
let mut rows_doc = Vec::new();
let stats_doc = decode_qm_financials_doc(raw_doc1, &fields, period_cfg, |obs| {
let key_ptr = obs.key.as_ptr() as usize;
assert!(
range1.contains(&key_ptr),
"expected key to borrow directly from input RawDocument slice"
);
rows_doc.push(obs);
})
.unwrap();
assert_conservation(&stats_doc);
assert_eq!(stats_doc.docs_in, 1);
assert_eq!(stats_doc.rows_out, 1);
assert_eq!(rows_doc.len(), 1);
assert_eq!(
rows_doc[0],
FinancialObservation {
key: "AAPL:US",
period_end: ymd_to_epoch_days(2024, 6, 30).unwrap(),
fiscal_period: FiscalPeriod::Quarterly,
currency: "USD".to_string(),
report_date: Some(ymd_to_epoch_days(2024, 8, 2).unwrap()),
fields: FundamentalsFields {
revenue: Some(1_250_000.5),
net_income: Some(125_000.0),
operating_cash_flow: Some(300_000.75),
total_assets: Some(9_000_000_000.0),
total_equity: Some(4_500_000.25),
shares_outstanding: Some(100_000_000.0),
},
}
);
// 2. decode_qm_financials_bytes
let bytes2 = doc2.as_bytes();
let mut rows_bytes = Vec::new();
let stats_bytes = decode_qm_financials_bytes(bytes2, &fields, period_cfg, |obs| {
rows_bytes.push(obs);
})
.unwrap();
assert_conservation(&stats_bytes);
assert_eq!(stats_bytes.docs_in, 1);
assert_eq!(stats_bytes.rows_out, 1);
assert_eq!(
rows_bytes[0],
FinancialObservation {
key: "SHOP:CA",
period_end: pe_day,
fiscal_period: FiscalPeriod::Annual,
currency: "CAD".to_string(),
report_date: Some(rd_day),
fields: FundamentalsFields {
revenue: Some(5_000_000.0),
net_income: Some(-42_500.5),
operating_cash_flow: Some(-10_000.0),
total_assets: Some(20_000_000.0),
total_equity: Some(12_500_000.0),
shares_outstanding: Some(50_000_000.0),
},
}
);
// 3. decode_qm_financials_buffer
let mut buf = Vec::new();
buf.extend_from_slice(doc1.as_bytes());
buf.extend_from_slice(doc2.as_bytes());
let mut rows_buf = Vec::new();
let stats_buf = decode_qm_financials_buffer(&buf, &fields, period_cfg, |obs| {
rows_buf.push(obs);
})
.unwrap();
assert_conservation(&stats_buf);
assert_eq!(stats_buf.docs_in, 2);
assert_eq!(stats_buf.rows_out, 2);
assert_eq!(rows_buf, vec![rows_doc[0].clone(), rows_bytes[0].clone()]);
}
#[test]
fn rejects_invalid_field_paths_and_fiscal_period_configs_before_decoding() {
let base = full_test_fields();
let bad_field_configs = [
QmFinancialsFieldNames { key: "", ..base },
QmFinancialsFieldNames { key: " ", ..base },
QmFinancialsFieldNames {
period_end: ".periodEndDate",
..base
},
QmFinancialsFieldNames {
report_date: "reportDate.",
..base
},
QmFinancialsFieldNames {
report_period: "a..b",
..base
},
QmFinancialsFieldNames {
currency: "",
..base
},
QmFinancialsFieldNames {
currency: "meta. .currency",
..base
},
QmFinancialsFieldNames {
revenue: Some(""),
..base
},
QmFinancialsFieldNames {
net_income: Some(".netIncome"),
..base
},
QmFinancialsFieldNames {
operating_cash_flow: Some("CashFlow."),
..base
},
QmFinancialsFieldNames {
total_assets: Some("BalanceSheet..totalAssets"),
..base
},
QmFinancialsFieldNames {
total_equity: Some("BalanceSheet. \t .totalEquity"),
..base
},
QmFinancialsFieldNames {
shares_outstanding: Some("."),
..base
},
];
let doc = make_valid_doc("AAPL:US");
for cfg in bad_field_configs {
let err = cfg.validate().unwrap_err();
assert!(
matches!(err, BsonQmFinancialsError::InvalidFieldNames { .. }),
"expected InvalidFieldNames for {cfg:?}, got {err:?}"
);
assert!(!err.to_string().contains('\n'));
let mut called = false;
assert!(matches!(
decode_qm_financials_doc(doc.as_ref(), &cfg, token_period_cfg(), |_| called = true),
Err(BsonQmFinancialsError::InvalidFieldNames { .. })
));
assert!(matches!(
decode_qm_financials_bytes(doc.as_bytes(), &cfg, token_period_cfg(), |_| called = true),
Err(BsonQmFinancialsError::InvalidFieldNames { .. })
));
assert!(matches!(
decode_qm_financials_buffer(doc.as_bytes(), &cfg, token_period_cfg(), |_| called =
true),
Err(BsonQmFinancialsError::InvalidFieldNames { .. })
));
assert!(!called);
}
let bad_period_configs = [
QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q", "BOTH"],
annual: &["FY", "BOTH"],
},
QmFinancialsFiscalPeriod::ByTokens {
quarterly: &[""],
annual: &["FY"],
},
QmFinancialsFiscalPeriod::ByTokens {
quarterly: &["Q"],
annual: &[" "],
},
];
for pcfg in bad_period_configs {
let err = pcfg.validate().unwrap_err();
assert!(
matches!(err, BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }),
"expected InvalidFiscalPeriodConfig for {pcfg:?}, got {err:?}"
);
assert!(!err.to_string().contains('\n'));
let mut called = false;
assert!(matches!(
decode_qm_financials_doc(doc.as_ref(), &base, pcfg, |_| called = true),
Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
));
assert!(matches!(
decode_qm_financials_bytes(doc.as_bytes(), &base, pcfg, |_| called = true),
Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
));
assert!(matches!(
decode_qm_financials_buffer(doc.as_bytes(), &base, pcfg, |_| called = true),
Err(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
));
assert!(!called);
}
}
#[test]
fn covers_each_skip_counter_and_inclusive_date_bounds() {
let fields = full_test_fields();
let pcfg = token_period_cfg();
// Helper to decode a single doc and assert zero rows emitted.
let decode_skipped = |doc: &RawDocumentBuf| -> BsonQmFinancialsDecodeStats {
let mut count = 0usize;
let stats = decode_qm_financials_doc(doc.as_ref(), &fields, pcfg, |_| count += 1).unwrap();
assert_eq!(count, 0);
assert_eq!(stats.rows_out, 0);
assert_conservation(&stats);
stats
};
// --- Key skips ---
let mut missing_key = RawDocumentBuf::new();
missing_key.append(cstr!("periodEndDate"), "2024-06-30");
missing_key.append(cstr!("reportPeriod"), "Q");
missing_key.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&missing_key).skipped_missing_key, 1);
let mut wrong_key = RawDocumentBuf::new();
wrong_key.append(cstr!("qmSearchCode"), 12345_i32);
wrong_key.append(cstr!("periodEndDate"), "2024-06-30");
wrong_key.append(cstr!("reportPeriod"), "Q");
wrong_key.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&wrong_key).skipped_wrong_key_type, 1);
let mut empty_key = RawDocumentBuf::new();
empty_key.append(cstr!("qmSearchCode"), " \t ");
empty_key.append(cstr!("periodEndDate"), "2024-06-30");
empty_key.append(cstr!("reportPeriod"), "Q");
empty_key.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&empty_key).skipped_empty_key, 1);
// --- periodEndDate skips ---
let mut missing_pe = RawDocumentBuf::new();
missing_pe.append(cstr!("qmSearchCode"), "AAPL:US");
missing_pe.append(cstr!("reportPeriod"), "Q");
missing_pe.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&missing_pe).skipped_missing_period_end, 1);
let mut wrong_pe = RawDocumentBuf::new();
wrong_pe.append(cstr!("qmSearchCode"), "AAPL:US");
wrong_pe.append(cstr!("periodEndDate"), 20240630_i32);
wrong_pe.append(cstr!("reportPeriod"), "Q");
wrong_pe.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&wrong_pe).skipped_wrong_period_end_type, 1);
let mut invalid_pe = RawDocumentBuf::new();
invalid_pe.append(cstr!("qmSearchCode"), "AAPL:US");
invalid_pe.append(cstr!("periodEndDate"), "2024-02-30");
invalid_pe.append(cstr!("reportPeriod"), "Q");
invalid_pe.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&invalid_pe).skipped_invalid_period_end, 1);
let mut oor_pe_low = RawDocumentBuf::new();
oor_pe_low.append(cstr!("qmSearchCode"), "AAPL:US");
oor_pe_low.append(cstr!("periodEndDate"), "2007-12-31");
oor_pe_low.append(cstr!("reportPeriod"), "Q");
oor_pe_low.append(cstr!("currency"), "USD");
assert_eq!(
decode_skipped(&oor_pe_low).skipped_period_end_out_of_range,
1
);
let mut oor_pe_high_dt = RawDocumentBuf::new();
oor_pe_high_dt.append(cstr!("qmSearchCode"), "AAPL:US");
oor_pe_high_dt.append(
cstr!("periodEndDate"),
BsonDateTime::from_millis(i64::from(MAX_SUPPORTED_DATE + 1) * MILLIS_PER_DAY),
);
oor_pe_high_dt.append(cstr!("reportPeriod"), "Q");
oor_pe_high_dt.append(cstr!("currency"), "USD");
assert_eq!(
decode_skipped(&oor_pe_high_dt).skipped_period_end_out_of_range,
1
);
// --- reportPeriod skips ---
let mut missing_rp = RawDocumentBuf::new();
missing_rp.append(cstr!("qmSearchCode"), "AAPL:US");
missing_rp.append(cstr!("periodEndDate"), "2024-06-30");
missing_rp.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&missing_rp).skipped_missing_report_period, 1);
let mut wrong_rp = RawDocumentBuf::new();
wrong_rp.append(cstr!("qmSearchCode"), "AAPL:US");
wrong_rp.append(cstr!("periodEndDate"), "2024-06-30");
wrong_rp.append(cstr!("reportPeriod"), 4_i32);
wrong_rp.append(cstr!("currency"), "USD");
assert_eq!(
decode_skipped(&wrong_rp).skipped_wrong_report_period_type,
1
);
let mut unmapped_rp = RawDocumentBuf::new();
unmapped_rp.append(cstr!("qmSearchCode"), "AAPL:US");
unmapped_rp.append(cstr!("periodEndDate"), "2024-06-30");
unmapped_rp.append(cstr!("reportPeriod"), "TTM");
unmapped_rp.append(cstr!("currency"), "USD");
assert_eq!(
decode_skipped(&unmapped_rp).skipped_unmapped_report_period,
1
);
// --- reportDate skips (present-but-invalid fails closed) ---
let mut wrong_rd = RawDocumentBuf::new();
wrong_rd.append(cstr!("qmSearchCode"), "AAPL:US");
wrong_rd.append(cstr!("periodEndDate"), "2024-06-30");
wrong_rd.append(cstr!("reportPeriod"), "Q");
wrong_rd.append(cstr!("reportDate"), true);
wrong_rd.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&wrong_rd).skipped_wrong_report_date_type, 1);
let mut invalid_rd = RawDocumentBuf::new();
invalid_rd.append(cstr!("qmSearchCode"), "AAPL:US");
invalid_rd.append(cstr!("periodEndDate"), "2024-06-30");
invalid_rd.append(cstr!("reportPeriod"), "Q");
invalid_rd.append(cstr!("reportDate"), "08/02/2024");
invalid_rd.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&invalid_rd).skipped_invalid_report_date, 1);
let mut blank_rd = RawDocumentBuf::new();
blank_rd.append(cstr!("qmSearchCode"), "AAPL:US");
blank_rd.append(cstr!("periodEndDate"), "2024-06-30");
blank_rd.append(cstr!("reportPeriod"), "Q");
blank_rd.append(cstr!("reportDate"), " ");
blank_rd.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&blank_rd).skipped_invalid_report_date, 1);
let mut oor_rd = RawDocumentBuf::new();
oor_rd.append(cstr!("qmSearchCode"), "AAPL:US");
oor_rd.append(cstr!("periodEndDate"), "2024-06-30");
oor_rd.append(cstr!("reportPeriod"), "Q");
oor_rd.append(cstr!("reportDate"), "2031-01-01");
oor_rd.append(cstr!("currency"), "USD");
assert_eq!(decode_skipped(&oor_rd).skipped_report_date_out_of_range, 1);
// --- currency skips ---
let mut missing_ccy = RawDocumentBuf::new();
missing_ccy.append(cstr!("qmSearchCode"), "AAPL:US");
missing_ccy.append(cstr!("periodEndDate"), "2024-06-30");
missing_ccy.append(cstr!("reportPeriod"), "Q");
assert_eq!(decode_skipped(&missing_ccy).skipped_missing_currency, 1);
let mut wrong_ccy = RawDocumentBuf::new();
wrong_ccy.append(cstr!("qmSearchCode"), "AAPL:US");
wrong_ccy.append(cstr!("periodEndDate"), "2024-06-30");
wrong_ccy.append(cstr!("reportPeriod"), "Q");
wrong_ccy.append(cstr!("currency"), 840_i32);
assert_eq!(decode_skipped(&wrong_ccy).skipped_wrong_currency_type, 1);
let mut empty_ccy = RawDocumentBuf::new();
empty_ccy.append(cstr!("qmSearchCode"), "AAPL:US");
empty_ccy.append(cstr!("periodEndDate"), "2024-06-30");
empty_ccy.append(cstr!("reportPeriod"), "Q");
empty_ccy.append(cstr!("currency"), " ");
assert_eq!(decode_skipped(&empty_ccy).skipped_empty_currency, 1);
// --- Inclusive date bounds + absent/Null reportDate ---
let (min_y, min_m, min_d) = epoch_days_to_ymd(MIN_SUPPORTED_DATE);
let (max_y, max_m, max_d) = epoch_days_to_ymd(MAX_SUPPORTED_DATE);
let min_str = format!("{min_y:04}-{min_m:02}-{min_d:02}");
let max_str = format!("{max_y:04}-{max_m:02}-{max_d:02}");
let mut min_bound_absent_rd = RawDocumentBuf::new();
min_bound_absent_rd.append(cstr!("qmSearchCode"), "AAPL:US");
min_bound_absent_rd.append(cstr!("periodEndDate"), min_str.as_str());
min_bound_absent_rd.append(cstr!("reportPeriod"), "Q");
min_bound_absent_rd.append(cstr!("currency"), "USD");
let mut max_bound_null_rd = RawDocumentBuf::new();
max_bound_null_rd.append(cstr!("qmSearchCode"), "AAPL:US");
max_bound_null_rd.append(cstr!("periodEndDate"), max_str.as_str());
max_bound_null_rd.append(cstr!("reportPeriod"), "FY");
max_bound_null_rd.append(cstr!("reportDate"), RawBson::Null);
max_bound_null_rd.append(cstr!("currency"), "USD");
let minimal_fields = QmFinancialsFieldNames::with_verified_defaults("currency");
let mut emitted = Vec::new();
let mut buf = Vec::new();
buf.extend_from_slice(min_bound_absent_rd.as_bytes());
buf.extend_from_slice(max_bound_null_rd.as_bytes());
let stats = decode_qm_financials_buffer(&buf, &minimal_fields, pcfg, |obs| {
emitted.push(obs);
})
.unwrap();
assert_conservation(&stats);
assert_eq!(stats.rows_out, 2);
assert_eq!(emitted[0].period_end, MIN_SUPPORTED_DATE);
assert_eq!(emitted[0].report_date, None);
assert_eq!(emitted[1].period_end, MAX_SUPPORTED_DATE);
assert_eq!(emitted[1].report_date, None);
}
#[test]
fn fixed_fiscal_period_override_ignores_report_period_field() {
let fields = QmFinancialsFieldNames::with_verified_defaults("currency");
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), "MSFT:US");
doc.append(cstr!("periodEndDate"), "2024-09-30");
// Wrong-typed reportPeriod would fail in ByTokens mode, but Fixed mode ignores it.
doc.append(cstr!("reportPeriod"), 999_i32);
doc.append(cstr!("currency"), "USD");
let mut rows = Vec::new();
let stats = decode_qm_financials_doc(
doc.as_ref(),
&fields,
QmFinancialsFiscalPeriod::Fixed(FiscalPeriod::Annual),
|obs| rows.push(obs),
)
.unwrap();
assert_conservation(&stats);
assert_eq!(stats.rows_out, 1);
assert_eq!(rows[0].fiscal_period, FiscalPeriod::Annual);
}
#[test]
fn numeric_null_counters_and_unconfigured_paths() {
// Configure 5 of 6 paths; leave `shares_outstanding` unconfigured (`None`).
let fields = QmFinancialsFieldNames {
revenue: Some("IncomeStatement.totalRevenue"), // missing sub-document
net_income: Some("BalanceSheet.netIncome"), // wrong type (boolean)
operating_cash_flow: Some("CashFlow.ocf"), // unparsable string
total_assets: Some("BalanceSheet.assets"), // non-finite double (NaN)
total_equity: Some("BalanceSheet.equity"), // non-finite string ("inf")
shares_outstanding: None, // unconfigured -> no null counter
..QmFinancialsFieldNames::with_verified_defaults("meta.currency")
};
let mut meta = RawDocumentBuf::new();
meta.append(cstr!("currency"), "CAD");
let mut balance = RawDocumentBuf::new();
balance.append(cstr!("netIncome"), true);
balance.append(cstr!("assets"), f64::NAN);
balance.append(cstr!("equity"), "inf");
let mut cash = RawDocumentBuf::new();
cash.append(cstr!("ocf"), "N/A");
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), "RY:CA");
doc.append(cstr!("periodEndDate"), "2024-10-31");
doc.append(cstr!("reportPeriod"), "FY");
doc.append(cstr!("meta"), meta);
// IncomeStatement intentionally omitted -> nulled_missing_path
doc.append(cstr!("BalanceSheet"), balance);
doc.append(cstr!("CashFlow"), cash);
let mut rows = Vec::new();
let stats = decode_qm_financials_doc(doc.as_ref(), &fields, token_period_cfg(), |obs| {
rows.push(obs);
})
.unwrap();
assert_conservation(&stats);
assert_eq!(stats.rows_out, 1);
assert_eq!(stats.nulled_missing_path, 1);
assert_eq!(stats.nulled_wrong_type, 1);
assert_eq!(stats.nulled_unparsable_string, 1);
assert_eq!(stats.nulled_non_finite, 2);
assert_eq!(rows[0].currency, "CAD");
assert_eq!(rows[0].fields, FundamentalsFields::default());
// BSON Null on a configured numeric leaf emits None cleanly without incrementing null counters.
let mut income_null = RawDocumentBuf::new();
income_null.append(cstr!("totalRevenue"), RawBson::Null);
let mut doc_null = RawDocumentBuf::new();
doc_null.append(cstr!("qmSearchCode"), "RY:CA");
doc_null.append(cstr!("periodEndDate"), "2024-10-31");
doc_null.append(cstr!("reportPeriod"), "FY");
doc_null.append(cstr!("currency"), "CAD");
doc_null.append(cstr!("IncomeStatement"), income_null);
let single_field = QmFinancialsFieldNames {
revenue: Some("IncomeStatement.totalRevenue"),
..QmFinancialsFieldNames::with_verified_defaults("currency")
};
let mut rows_null = Vec::new();
let stats_null =
decode_qm_financials_doc(doc_null.as_ref(), &single_field, token_period_cfg(), |obs| {
rows_null.push(obs);
})
.unwrap();
assert_eq!(stats_null.rows_out, 1);
assert_eq!(stats_null.nulled_missing_path, 0);
assert_eq!(stats_null.nulled_wrong_type, 0);
assert_eq!(stats_null.nulled_unparsable_string, 0);
assert_eq!(stats_null.nulled_non_finite, 0);
assert_eq!(rows_null[0].fields.revenue, None);
}
#[test]
fn mixed_buffer_reconciles_stats_and_framing_errors_fail_closed_with_offset() {
let fields = full_test_fields();
let pcfg = token_period_cfg();
let good = make_valid_doc("AAPL:US");
let mut bad_key = RawDocumentBuf::new();
bad_key.append(cstr!("periodEndDate"), "2024-06-30");
bad_key.append(cstr!("reportPeriod"), "Q");
bad_key.append(cstr!("currency"), "USD");
let mut bad_period = RawDocumentBuf::new();
bad_period.append(cstr!("qmSearchCode"), "AAPL:US");
bad_period.append(cstr!("periodEndDate"), "2024-06-30");
bad_period.append(cstr!("reportPeriod"), "UNKNOWN");
bad_period.append(cstr!("currency"), "USD");
let mut bad_rd = RawDocumentBuf::new();
bad_rd.append(cstr!("qmSearchCode"), "AAPL:US");
bad_rd.append(cstr!("periodEndDate"), "2024-06-30");
bad_rd.append(cstr!("reportPeriod"), "Q");
bad_rd.append(cstr!("reportDate"), "not-a-date");
bad_rd.append(cstr!("currency"), "USD");
let mut mixed = Vec::new();
mixed.extend_from_slice(good.as_bytes());
mixed.extend_from_slice(bad_key.as_bytes());
mixed.extend_from_slice(bad_period.as_bytes());
mixed.extend_from_slice(bad_rd.as_bytes());
let mut emitted = Vec::new();
let stats = decode_qm_financials_buffer(&mixed, &fields, pcfg, |obs| emitted.push(obs)).unwrap();
assert_eq!(stats.docs_in, 4);
assert_eq!(stats.rows_out, 1);
assert_eq!(stats.skipped_missing_key, 1);
assert_eq!(stats.skipped_unmapped_report_period, 1);
assert_eq!(stats.skipped_invalid_report_date, 1);
assert_eq!(stats.skipped_total(), 3);
assert_conservation(&stats);
assert_eq!(emitted.len(), 1);
// 1. Truncated length prefix after a valid document.
let prefix_len = good.as_bytes().len() as u64;
let mut truncated_hdr = good.as_bytes().to_vec();
truncated_hdr.extend_from_slice(&[0x10, 0x00]);
let mut seen = 0usize;
let err = decode_qm_financials_buffer(&truncated_hdr, &fields, pcfg, |_| seen += 1).unwrap_err();
assert_eq!(seen, 1);
assert_eq!(
err,
BsonQmFinancialsError::TruncatedDocument {
offset: prefix_len,
remaining: 2,
declared_len: None,
}
);
// 2. Truncated document body after a valid document.
let mut truncated_body = good.as_bytes().to_vec();
truncated_body.extend_from_slice(&good.as_bytes()[..10]);
let err = decode_qm_financials_buffer(&truncated_body, &fields, pcfg, |_| {}).unwrap_err();
assert!(matches!(
err,
BsonQmFinancialsError::TruncatedDocument {
offset,
remaining: 10,
declared_len: Some(_),
} if offset == prefix_len
));
// 3. Invalid declared document length (< 5).
let mut bad_len = good.as_bytes().to_vec();
bad_len.extend_from_slice(&3_i32.to_le_bytes());
bad_len.push(0x00);
let err = decode_qm_financials_buffer(&bad_len, &fields, pcfg, |_| {}).unwrap_err();
assert_eq!(
err,
BsonQmFinancialsError::CorruptDocumentLength {
offset: prefix_len,
declared_len: 3,
}
);
// 4. Malformed nested BSON (invalid UTF-8 inside an unused nested subdocument) in a document
// that ALSO lacks a key: must return CorruptBson rather than silently skipping!
let mut nested = RawDocumentBuf::new();
nested.append(cstr!("note"), "AAAA");
let mut nested_bytes = nested.into_bytes();
// Corrupt the 4-byte ASCII payload "AAAA" into invalid UTF-8 bytes.
let pos = nested_bytes
.windows(4)
.position(|w| w == b"AAAA")
.expect("marker present");
nested_bytes[pos] = 0xFF;
nested_bytes[pos + 1] = 0xFE;
// Build outer doc containing no key (would skip) + the corrupt nested subdoc.
let mut outer = Vec::new();
let placeholder_len = 0_i32;
outer.extend_from_slice(&placeholder_len.to_le_bytes());
outer.push(0x03); // Embedded Document element type
outer.extend_from_slice(b"extra\0");
outer.extend_from_slice(&nested_bytes);
outer.push(0x00); // Document terminator
let total_len = i32::try_from(outer.len()).unwrap();
outer[..4].copy_from_slice(&total_len.to_le_bytes());
let mut with_prefix = good.as_bytes().to_vec();
with_prefix.extend_from_slice(&outer);
let err = decode_qm_financials_buffer(&with_prefix, &fields, pcfg, |_| {}).unwrap_err();
assert!(
matches!(err, BsonQmFinancialsError::CorruptBson { offset, .. } if offset == prefix_len),
"expected CorruptBson at offset {prefix_len}, got {err:?}"
);
// 5. Corrupt array index inside a nested array fails closed.
let mut bad_arr = RawArrayBuf::new();
bad_arr.push(1_i32);
let mut arr_bytes = bad_arr.as_bytes().to_vec();
// Replace key "0" with "1" so array index validation rejects it.
let zero_pos = arr_bytes
.windows(2)
.position(|w| w == b"0\0")
.expect("index 0 key present");
arr_bytes[zero_pos] = b'1';
let mut outer_arr = Vec::new();
outer_arr.extend_from_slice(&0_i32.to_le_bytes());
outer_arr.push(0x04); // Array element type
outer_arr.extend_from_slice(b"arr\0");
outer_arr.extend_from_slice(&arr_bytes);
outer_arr.push(0x00);
let arr_total_len = i32::try_from(outer_arr.len()).unwrap();
outer_arr[..4].copy_from_slice(&arr_total_len.to_le_bytes());
let err = decode_qm_financials_bytes(&outer_arr, &fields, pcfg, |_| {}).unwrap_err();
assert!(matches!(err, BsonQmFinancialsError::CorruptBson { offset: 0, .. }));
}
#[test]
fn decoded_observation_feeds_build_fundamentals_rows_with_filing_timestamp() {
let fields = full_test_fields();
let doc = make_valid_doc("AAPL:US");
let mut observations: Vec<FinancialObservation<&str>> = Vec::new();
let decode_stats =
decode_qm_financials_bytes(doc.as_bytes(), &fields, token_period_cfg(), |obs| {
observations.push(obs);
})
.unwrap();
assert_conservation(&decode_stats);
assert_eq!(observations.len(), 1);
let timefiled = "2024-08-02T16:30:15 EDT";
let expected_micros = parse_filing_timefiled(timefiled).unwrap().utc_micros;
let filings = vec![QmFiling {
key: "AAPL:US",
timefiled: timefiled.to_string(),
form_type: "10-Q".to_string(),
filing_id: Some("0000320193-24-000081".to_string()),
url: None,
}];
let mut venues = BTreeMap::new();
venues.insert("AAPL:US", StatutoryLagVenue::UsTsx);
let build = build_fundamentals_rows(observations, filings, &venues);
assert_eq!(build.stats.observations_in, 1);
assert_eq!(build.stats.rows_out, 1);
assert_eq!(build.stats.rows_linked_to_filing, 1);
assert_eq!(build.stats.rows_statutory_lag_estimate, 0);
assert_eq!(build.rows.len(), 1);
let row = &build.rows[0];
assert_eq!(row.key, "AAPL:US");
assert_eq!(row.period_end, ymd_to_epoch_days(2024, 6, 30).unwrap());
assert_eq!(row.fiscal_period, FiscalPeriod::Quarterly);
assert_eq!(row.currency, "USD");
assert_eq!(row.known_at_utc_micros, expected_micros);
assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP);
assert_eq!(row.fields.revenue, Some(1_250_000.5));
assert_eq!(row.fields.net_income, Some(125_000.0));
assert_eq!(row.fields.operating_cash_flow, Some(300_000.75));
assert_eq!(row.fields.total_assets, Some(9_000_000_000.0));
assert_eq!(row.fields.total_equity, Some(4_500_000.25));
assert_eq!(row.fields.shares_outstanding, Some(100_000_000.0));
}

View file

@ -10,6 +10,7 @@ pub mod bson_eod_intraday;
pub mod bson_eod_prices;
pub mod bson_qm_actions;
pub mod bson_qm_events;
pub mod bson_qm_financials;
pub mod bson_qm_intraday;
pub mod bson_qm_prices;
pub mod bson_stream;
@ -82,6 +83,13 @@ pub use bson_qm_events::{
DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD,
DEFAULT_FILINGS_TIMEFILED_FIELD,
};
pub use bson_qm_financials::{
decode_qm_financials_buffer, decode_qm_financials_bytes, decode_qm_financials_doc,
BsonQmFinancialsDecodeStats, BsonQmFinancialsError, QmFinancialsFieldNames,
QmFinancialsFiscalPeriod, DEFAULT_QM_FINANCIALS_KEY_FIELD,
DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD,
DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD,
};
pub use bson_qm_prices::{
decode_qm_price_buffer, decode_qm_price_bytes, decode_qm_price_doc, BsonQmPriceDecodeStats,
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,