T-141: M2.3d — tools/curate-etl: zero-copy eodIntraday1M BSON decoder + chunked stream decode into EodIntradayBar (pure, no new crates, no live Mongo/QuestDB)
This commit is contained in:
parent
0e5074c5f4
commit
d43d987416
6 changed files with 1737 additions and 5 deletions
|
|
@ -1566,6 +1566,14 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code
|
|||
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
|
||||
- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks).
|
||||
|
||||
## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`)
|
||||
|
||||
`src/bson_eod_intraday.rs` decodes raw `eodIntraday1M` MongoDB BSON documents in a single zero-copy forward pass (`RawEodIntradayBar<'a>`, `decode_eod_intraday_doc`, `decode_eod_intraday_bytes`, `decode_eod_intraday_buffer`, `BsonEodIntradayError`, `BsonEodIntradayDecodeStats`) with bounded-memory streaming helpers in `src/bson_stream.rs` (`decode_eod_intraday_chunks`, `decode_eod_intraday_stream`):
|
||||
|
||||
- **Timestamp units:** `timestamp` is bar-start **UTC Unix seconds** (accepted in BSON `Int32`, `Int64`, or finite integral `Double` within `0..=i64::MAX / 1_000_000`) converted to UTC microseconds (`ts: i64`) via checked multiplication by `1_000_000`. It is bar start only (not a publication / `known_at` timestamp).
|
||||
- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`.
|
||||
- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar<K>`.
|
||||
|
||||
## Exporting Input Files (`data-pipeline`)
|
||||
|
||||
All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`:
|
||||
|
|
|
|||
655
tools/curate-etl/src/bson_eod_intraday.rs
Normal file
655
tools/curate-etl/src/bson_eod_intraday.rs
Normal file
|
|
@ -0,0 +1,655 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `eodIntraday1M` documents (`M2.3d`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawEodIntradayBar`] views without allocating a `String` or `bson::Document` per row.
|
||||
//! Callers convert borrowed views into [`crate::bars_1m::EodIntradayBar<K>`] via a caller-supplied
|
||||
//! key mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an
|
||||
//! interned integer symbol ID), keeping the 3.40B-document path free of per-row `String`
|
||||
//! allocations.
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! Field names and semantics are grounded in the repository's ingestion writer, historical reader,
|
||||
//! and empirical data contract:
|
||||
//! - `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts:565-585` (`fetchIntraday`
|
||||
//! writes `symbol`, `exchange`, `eodSearchCode`, `datetime`, `timestamp`, `gmtoffset`, `open`,
|
||||
//! `high`, `low`, `close`, `volume`, `source` into `eodIntraday1M`, keyed by
|
||||
//! `['timestamp', 'eodSearchCode']`)
|
||||
//! - `libs/trading-runtime/src/historical-storage.ts:265-298` (`timestamp` is bar-start **UTC
|
||||
//! Unix seconds**, not a local `datetime` label and not a publication / `known_at` time)
|
||||
//! - `design/DATA-CONTRACTS.md` §1: `eodIntraday1M` (~3.40B docs) stores retroactively
|
||||
//! split-adjusted OHLC and volume. This decoder passes those split-adjusted values through
|
||||
//! untouched; split un-adjustment happens downstream in [`crate::bars_1m::build_bars_1m`].
|
||||
//!
|
||||
//! # Accepted BSON Representations & Daily-Decoder Conventions
|
||||
//!
|
||||
//! Where a rule is ambiguous, this module follows [`crate::bson_eod_prices`]:
|
||||
//! - `eodSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or
|
||||
//! whitespace-only strings are rejected as [`BsonEodIntradayError::EmptyField`]; non-string
|
||||
//! values (including BSON `Null`) are rejected as [`BsonEodIntradayError::WrongType`].
|
||||
//! - `timestamp`: bar-start UTC Unix seconds in BSON `Int32`, `Int64`, or finite integral `Double`
|
||||
//! within `0..=i64::MAX / 1_000_000`, converted to UTC microseconds via checked multiplication
|
||||
//! by `1_000_000`. Non-numeric types (including `Null` and `DateTime`) are rejected as
|
||||
//! [`BsonEodIntradayError::WrongType`]; negative, fractional, non-finite, or microsecond-overflow
|
||||
//! values are rejected as [`BsonEodIntradayError::InvalidTimestamp`].
|
||||
//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and
|
||||
//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as
|
||||
//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected
|
||||
//! as [`BsonEodIntradayError::InvalidNumber`].
|
||||
//! - `volume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is
|
||||
//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as
|
||||
//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as
|
||||
//! [`BsonEodIntradayError::InvalidNumber`].
|
||||
//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, nested
|
||||
//! objects/arrays, etc.) are skipped without calling `elem.value()`.
|
||||
//! - Error precedence: retains the first semantic error while continuing to scan remaining
|
||||
//! top-level elements so any malformed BSON bytes surface immediately as `CorruptBson`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bars_1m::EodIntradayBar;
|
||||
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
|
||||
|
||||
const MICROS_PER_SECOND: i64 = 1_000_000;
|
||||
/// Largest whole Unix-second timestamp that fits in signed `i64` microseconds (`9_223_372_036_854`).
|
||||
pub(crate) const MAX_TIMESTAMP_SECONDS: i64 = i64::MAX / MICROS_PER_SECOND;
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `eodIntraday1M` BSON document.
|
||||
///
|
||||
/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `open`, `high`, `low`, `close`, and `volume` are passed through as the provider's
|
||||
/// split-adjusted values so [`crate::bars_1m::build_bars_1m`] can apply split un-adjustment.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawEodIntradayBar<'a> {
|
||||
pub eod_search_code: &'a str,
|
||||
/// Bar start timestamp in UTC microseconds since the Unix epoch.
|
||||
pub ts: i64,
|
||||
pub open: f64,
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub close: f64,
|
||||
pub volume: f64,
|
||||
}
|
||||
|
||||
impl<'a> RawEodIntradayBar<'a> {
|
||||
/// Converts this borrowed view into an [`EodIntradayBar<K>`] using a caller-supplied key
|
||||
/// mapper.
|
||||
///
|
||||
/// `map_key` receives `(eod_search_code, ts)` (provider code and UTC bar-start microseconds)
|
||||
/// so callers can resolve an integer `listing_id` or interned key without allocating a per-row
|
||||
/// `String`.
|
||||
#[inline]
|
||||
pub fn into_eod_intraday_bar<K, F>(self, map_key: F) -> EodIntradayBar<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i64) -> K,
|
||||
{
|
||||
EodIntradayBar {
|
||||
key: map_key(self.eod_search_code, self.ts),
|
||||
ts: self.ts,
|
||||
open: self.open,
|
||||
high: self.high,
|
||||
low: self.low,
|
||||
close: self.close,
|
||||
volume: self.volume,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible conversion into [`EodIntradayBar<K>`] using a caller-supplied key resolver.
|
||||
#[inline]
|
||||
pub fn try_into_eod_intraday_bar<K, F>(self, map_key: F) -> Option<EodIntradayBar<K>>
|
||||
where
|
||||
F: FnOnce(&'a str, i64) -> Option<K>,
|
||||
{
|
||||
let key = map_key(self.eod_search_code, self.ts)?;
|
||||
Some(EodIntradayBar {
|
||||
key,
|
||||
ts: self.ts,
|
||||
open: self.open,
|
||||
high: self.high,
|
||||
low: self.low,
|
||||
close: self.close,
|
||||
volume: self.volume,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `eodIntraday1M` BSON documents or length-prefixed
|
||||
/// buffers.
|
||||
///
|
||||
/// Every field-level error names the offending BSON field in both its structure and `Display`
|
||||
/// output; framing errors carry byte offsets; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonEodIntradayError {
|
||||
/// A required field was absent from the document.
|
||||
MissingField { field: &'static str },
|
||||
/// A required string field was empty or contained only whitespace.
|
||||
EmptyField { field: &'static str },
|
||||
/// A required field had an unexpected BSON element type (including `Null`).
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// `timestamp` was negative, non-integral, non-finite, or overflowed `i64` microseconds.
|
||||
InvalidTimestamp { field: &'static str },
|
||||
/// An OHLC field was non-finite or `<= 0.0`, or `volume` was non-finite or `< 0.0`.
|
||||
InvalidNumber { field: &'static str, value: f64 },
|
||||
/// 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 BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonEodIntradayError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "eodIntraday1M BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(
|
||||
f,
|
||||
"eodIntraday1M BSON field '{field}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"eodIntraday1M BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::InvalidTimestamp { field } => {
|
||||
write!(
|
||||
f,
|
||||
"eodIntraday1M BSON field '{field}' is not a valid non-negative integral Unix-seconds timestamp within i64 microsecond range"
|
||||
)
|
||||
}
|
||||
Self::InvalidNumber { field, value } => {
|
||||
if *field == "volume" {
|
||||
write!(
|
||||
f,
|
||||
"eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0"
|
||||
)
|
||||
} else {
|
||||
write!(
|
||||
f,
|
||||
"eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and > 0"
|
||||
)
|
||||
}
|
||||
}
|
||||
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 BsonEodIntradayError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonEodIntradayError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonEodIntradayError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonEodIntradayError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonEodIntradayError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonEodIntradayError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonEodIntradayError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonEodIntradayError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => {
|
||||
BsonEodIntradayError::InvalidTimestamp { field }
|
||||
}
|
||||
BsonEodPriceError::InvalidNumber { field, value } => {
|
||||
BsonEodIntradayError::InvalidNumber { field, value }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_eod_intraday_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonEodIntradayDecodeStats {
|
||||
pub docs_seen: usize,
|
||||
pub rows_decoded: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_invalid_timestamp: usize,
|
||||
pub rejected_invalid_number: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonEodIntradayDecodeStats {
|
||||
/// Total number of rejected documents across all error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_missing_field
|
||||
+ self.rejected_empty_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_invalid_timestamp
|
||||
+ self.rejected_invalid_number
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonEodIntradayError) {
|
||||
match err {
|
||||
BsonEodIntradayError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonEodIntradayError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonEodIntradayError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonEodIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1,
|
||||
BsonEodIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
|
||||
BsonEodIntradayError::TruncatedDocument { .. }
|
||||
| BsonEodIntradayError::CorruptDocumentLength { .. }
|
||||
| BsonEodIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_seen += other.docs_seen;
|
||||
self.rows_decoded += other.rows_decoded;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_invalid_timestamp += other.rejected_invalid_timestamp;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonEodIntradayDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonEodIntradayError> {
|
||||
elem.value().map_err(|err| BsonEodIntradayError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_timestamp_seconds_to_micros(val: RawBsonRef<'_>) -> Result<i64, BsonEodIntradayError> {
|
||||
let secs = match val {
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" });
|
||||
}
|
||||
i64::from(v)
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" });
|
||||
}
|
||||
v
|
||||
}
|
||||
RawBsonRef::Double(v) => {
|
||||
// `MAX_TIMESTAMP_SECONDS` (9_223_372_036_854 < 2^44) is well within `f64`'s exact
|
||||
// 53-bit integer range, so both the upper bound and the cast are exact.
|
||||
if !v.is_finite()
|
||||
|| v < 0.0
|
||||
|| v.fract() != 0.0
|
||||
|| v > MAX_TIMESTAMP_SECONDS as f64
|
||||
{
|
||||
return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" });
|
||||
}
|
||||
v as i64
|
||||
}
|
||||
other => {
|
||||
return Err(BsonEodIntradayError::WrongType {
|
||||
field: "timestamp",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
secs.checked_mul(MICROS_PER_SECOND)
|
||||
.ok_or(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_positive_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonEodIntradayError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v <= 0.0 {
|
||||
return Err(BsonEodIntradayError::InvalidNumber { field, value: v });
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonEodIntradayError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonEodIntradayError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonEodIntradayError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_negative_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonEodIntradayError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v < 0.0 {
|
||||
return Err(BsonEodIntradayError::InvalidNumber { field, value: v });
|
||||
}
|
||||
if v == 0.0 {
|
||||
Ok(0.0)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonEodIntradayError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonEodIntradayError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonEodIntradayError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_eod_intraday_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawEodIntradayBar<'a>, BsonEodIntradayError> {
|
||||
let mut eod_search_code: Option<&'a str> = None;
|
||||
let mut ts: Option<i64> = None;
|
||||
let mut open: Option<f64> = None;
|
||||
let mut high: Option<f64> = None;
|
||||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
let mut volume: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonEodIntradayError> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonEodIntradayError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key();
|
||||
|
||||
if key == cstr!("eodSearchCode") {
|
||||
match decode_element_value("eodSearchCode", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodIntradayError::EmptyField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
eod_search_code = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodIntradayError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("timestamp") {
|
||||
let val = decode_element_value("timestamp", elem, offset)?;
|
||||
match decode_timestamp_seconds_to_micros(val) {
|
||||
Ok(micros) => ts = Some(micros),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("open") {
|
||||
let val = decode_element_value("open", elem, offset)?;
|
||||
match decode_positive_number("open", val) {
|
||||
Ok(v) => open = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("high") {
|
||||
let val = decode_element_value("high", elem, offset)?;
|
||||
match decode_positive_number("high", val) {
|
||||
Ok(v) => high = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("low") {
|
||||
let val = decode_element_value("low", elem, offset)?;
|
||||
match decode_positive_number("low", val) {
|
||||
Ok(v) => low = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("close") {
|
||||
let val = decode_element_value("close", elem, offset)?;
|
||||
match decode_positive_number("close", val) {
|
||||
Ok(v) => close = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("volume") {
|
||||
let val = decode_element_value("volume", elem, offset)?;
|
||||
match decode_non_negative_number("volume", val) {
|
||||
Ok(v) => volume = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`,
|
||||
// etc.) are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(eod_search_code) = eod_search_code else {
|
||||
return Err(BsonEodIntradayError::MissingField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
};
|
||||
let Some(ts) = ts else {
|
||||
return Err(BsonEodIntradayError::MissingField { field: "timestamp" });
|
||||
};
|
||||
let Some(open) = open else {
|
||||
return Err(BsonEodIntradayError::MissingField { field: "open" });
|
||||
};
|
||||
let Some(high) = high else {
|
||||
return Err(BsonEodIntradayError::MissingField { field: "high" });
|
||||
};
|
||||
let Some(low) = low else {
|
||||
return Err(BsonEodIntradayError::MissingField { field: "low" });
|
||||
};
|
||||
let Some(close) = close else {
|
||||
return Err(BsonEodIntradayError::MissingField { field: "close" });
|
||||
};
|
||||
let Some(volume) = volume else {
|
||||
return Err(BsonEodIntradayError::MissingField { field: "volume" });
|
||||
};
|
||||
|
||||
Ok(RawEodIntradayBar {
|
||||
eod_search_code,
|
||||
ts,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing an `eodIntraday1M` MongoDB document in one forward
|
||||
/// pass without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_eod_intraday_doc<'a>(
|
||||
doc: &'a RawDocument,
|
||||
) -> Result<RawEodIntradayBar<'a>, BsonEodIntradayError> {
|
||||
decode_eod_intraday_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodIntradayBar`].
|
||||
pub fn decode_eod_intraday_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodIntradayBar<'a>, BsonEodIntradayError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_eod_intraday_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_intraday_doc`],
|
||||
/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected
|
||||
/// document without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`.
|
||||
pub fn decode_eod_intraday_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonEodIntradayDecodeStats
|
||||
where
|
||||
F: FnMut(RawEodIntradayBar<'a>),
|
||||
E: FnMut(usize, BsonEodIntradayError),
|
||||
{
|
||||
let mut stats = BsonEodIntradayDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_seen += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_eod_intraday_doc_at(doc, doc_offset) {
|
||||
Ok(bar) => {
|
||||
stats.rows_decoded += 1;
|
||||
on_bar(bar);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_eod_intraday_tests.rs"]
|
||||
mod tests;
|
||||
817
tools/curate-etl/src/bson_eod_intraday_tests.rs
Normal file
817
tools/curate-etl/src/bson_eod_intraday_tests.rs
Normal file
|
|
@ -0,0 +1,817 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::bars_1m::{build_bars_1m, IntradaySession, BARS_1M_SOURCE_EOD};
|
||||
use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_valid_doc(
|
||||
code: &str,
|
||||
timestamp_sec: i64,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("timestamp"), timestamp_sec);
|
||||
doc.append(cstr!("open"), open);
|
||||
doc.append(cstr!("high"), high);
|
||||
doc.append(cstr!("low"), low);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), volume);
|
||||
doc
|
||||
}
|
||||
|
||||
fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc.append(cstr!("timestamp"), timestamp);
|
||||
doc.append(cstr!("open"), 120.15_f64);
|
||||
doc.append(cstr!("high"), 120.42_f64);
|
||||
doc.append(cstr!("low"), 120.05_f64);
|
||||
doc.append(cstr!("close"), 120.38_f64);
|
||||
doc.append(cstr!("volume"), 842_500.0_f64);
|
||||
doc
|
||||
}
|
||||
|
||||
fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) {
|
||||
let diff = (actual - expected).abs();
|
||||
let scale = expected.abs().max(1.0);
|
||||
assert!(
|
||||
diff <= rel_tol * scale,
|
||||
"actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_nvda_fixture_across_int32_int64_double_timestamps_and_ignores_metadata() {
|
||||
const TS_SEC: i32 = 1_717_767_000;
|
||||
const EXPECTED_TS_MICROS: i64 = 1_717_767_000_000_000;
|
||||
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "eodhd");
|
||||
nested.append(cstr!("interval"), "1m");
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("us");
|
||||
tags.push("intraday");
|
||||
|
||||
let mut doc_i32 = RawDocumentBuf::new();
|
||||
doc_i32.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
doc_i32.append(cstr!("symbol"), "NVDA");
|
||||
doc_i32.append(cstr!("exchange"), "US");
|
||||
doc_i32.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc_i32.append(cstr!("datetime"), "2024-06-07 13:30:00");
|
||||
doc_i32.append(cstr!("timestamp"), TS_SEC);
|
||||
doc_i32.append(cstr!("gmtoffset"), 0_i32);
|
||||
doc_i32.append(cstr!("open"), 119.77_f64);
|
||||
doc_i32.append(cstr!("high"), 121.692_f64);
|
||||
doc_i32.append(cstr!("low"), 118.022_f64);
|
||||
doc_i32.append(cstr!("close"), 120.888_f64);
|
||||
doc_i32.append(cstr!("volume"), 412_390.0_f64);
|
||||
doc_i32.append(cstr!("source"), "eod");
|
||||
doc_i32.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
doc_i32.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let bar_i32 = decode_eod_intraday_doc(&doc_i32).unwrap();
|
||||
assert_eq!(bar_i32.eod_search_code, "NVDA.US");
|
||||
assert_eq!(bar_i32.ts, EXPECTED_TS_MICROS);
|
||||
assert_eq!(bar_i32.open.to_bits(), 119.77_f64.to_bits());
|
||||
assert_eq!(bar_i32.high.to_bits(), 121.692_f64.to_bits());
|
||||
assert_eq!(bar_i32.low.to_bits(), 118.022_f64.to_bits());
|
||||
assert_eq!(bar_i32.close.to_bits(), 120.888_f64.to_bits());
|
||||
assert_eq!(bar_i32.volume.to_bits(), 412_390.0_f64.to_bits());
|
||||
|
||||
// decode_eod_intraday_bytes matches decode_eod_intraday_doc bit-for-bit.
|
||||
let from_bytes = decode_eod_intraday_bytes(doc_i32.as_bytes()).unwrap();
|
||||
assert_eq!(from_bytes, bar_i32);
|
||||
|
||||
// Same document with timestamp as Int64 and as integral Double decodes identically.
|
||||
let mut doc_i64 = RawDocumentBuf::new();
|
||||
doc_i64.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc_i64.append(cstr!("timestamp"), i64::from(TS_SEC));
|
||||
doc_i64.append(cstr!("open"), 119.77_f64);
|
||||
doc_i64.append(cstr!("high"), 121.692_f64);
|
||||
doc_i64.append(cstr!("low"), 118.022_f64);
|
||||
doc_i64.append(cstr!("close"), 120.888_f64);
|
||||
doc_i64.append(cstr!("volume"), 412_390.0_f64);
|
||||
|
||||
let mut doc_f64 = RawDocumentBuf::new();
|
||||
doc_f64.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc_f64.append(cstr!("timestamp"), f64::from(TS_SEC));
|
||||
doc_f64.append(cstr!("open"), 119.77_f64);
|
||||
doc_f64.append(cstr!("high"), 121.692_f64);
|
||||
doc_f64.append(cstr!("low"), 118.022_f64);
|
||||
doc_f64.append(cstr!("close"), 120.888_f64);
|
||||
doc_f64.append(cstr!("volume"), 412_390.0_f64);
|
||||
|
||||
let bar_i64 = decode_eod_intraday_doc(&doc_i64).unwrap();
|
||||
let bar_f64 = decode_eod_intraday_doc(&doc_f64).unwrap();
|
||||
assert_eq!(bar_i64, bar_i32);
|
||||
assert_eq!(bar_f64, bar_i32);
|
||||
|
||||
// Verify into_eod_intraday_bar and try_into_eod_intraday_bar pass exact (code, ts).
|
||||
let mut seen_into: Option<(&str, i64)> = None;
|
||||
let mapped = bar_i32.into_eod_intraday_bar(|code, ts| {
|
||||
seen_into = Some((code, ts));
|
||||
42_u64
|
||||
});
|
||||
assert_eq!(seen_into, Some(("NVDA.US", EXPECTED_TS_MICROS)));
|
||||
assert_eq!(mapped.key, 42_u64);
|
||||
assert_eq!(mapped.ts, EXPECTED_TS_MICROS);
|
||||
assert_eq!(mapped.close.to_bits(), 120.888_f64.to_bits());
|
||||
|
||||
let mut seen_try_some: Option<(&str, i64)> = None;
|
||||
let try_some = bar_i32.try_into_eod_intraday_bar(|code, ts| {
|
||||
seen_try_some = Some((code, ts));
|
||||
Some(99_u64)
|
||||
});
|
||||
assert_eq!(seen_try_some, Some(("NVDA.US", EXPECTED_TS_MICROS)));
|
||||
assert_eq!(try_some.unwrap().key, 99_u64);
|
||||
|
||||
let try_none: Option<EodIntradayBar<u64>> = bar_i32.try_into_eod_intraday_bar(|code, ts| {
|
||||
assert_eq!(code, "NVDA.US");
|
||||
assert_eq!(ts, EXPECTED_TS_MICROS);
|
||||
None
|
||||
});
|
||||
assert!(try_none.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrows_eod_search_code_zero_copy_from_input_buffer() {
|
||||
let doc = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0);
|
||||
let bytes = doc.as_bytes();
|
||||
let buf_start = bytes.as_ptr() as usize;
|
||||
let buf_end = buf_start + bytes.len();
|
||||
|
||||
let bar = decode_eod_intraday_bytes(bytes).unwrap();
|
||||
let code_start = bar.eod_search_code.as_ptr() as usize;
|
||||
let code_end = code_start + bar.eod_search_code.len();
|
||||
assert!(
|
||||
code_start >= buf_start && code_end <= buf_end,
|
||||
"expected eod_search_code pointer {code_start:#x}..{code_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}"
|
||||
);
|
||||
assert_eq!(bar.eod_search_code, "NVDA.US");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_mixed_numeric_types_zero_volume_and_timestamp_boundaries() {
|
||||
let mut mixed = RawDocumentBuf::new();
|
||||
mixed.append(cstr!("eodSearchCode"), "SHOP.TO");
|
||||
mixed.append(cstr!("timestamp"), 0_i32);
|
||||
mixed.append(cstr!("open"), 100_i32);
|
||||
mixed.append(cstr!("high"), 105_i64);
|
||||
mixed.append(cstr!("low"), 99.5_f64);
|
||||
mixed.append(cstr!("close"), 104_i32);
|
||||
mixed.append(cstr!("volume"), 5_000_000_000_i64);
|
||||
|
||||
let bar = decode_eod_intraday_doc(&mixed).unwrap();
|
||||
assert_eq!(bar.eod_search_code, "SHOP.TO");
|
||||
assert_eq!(bar.ts, 0);
|
||||
assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits());
|
||||
assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits());
|
||||
assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits());
|
||||
assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits());
|
||||
assert_eq!(bar.volume.to_bits(), 5_000_000_000.0_f64.to_bits());
|
||||
|
||||
// Epoch zero in Int32, Int64, Double (+0.0 and -0.0).
|
||||
for zero_ts in [
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int64(0),
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
] {
|
||||
let doc = make_doc_with_timestamp(zero_ts);
|
||||
let decoded = decode_eod_intraday_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.ts, 0);
|
||||
}
|
||||
|
||||
// Largest accepted whole second in Int64 and Double.
|
||||
let expected_max_micros = MAX_TIMESTAMP_SECONDS * 1_000_000;
|
||||
for max_ts in [
|
||||
RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS),
|
||||
RawBsonRef::Double(MAX_TIMESTAMP_SECONDS as f64),
|
||||
] {
|
||||
let doc = make_doc_with_timestamp(max_ts);
|
||||
let decoded = decode_eod_intraday_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.ts, expected_max_micros);
|
||||
}
|
||||
|
||||
// Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) normalizes to +0.0.
|
||||
for zero_vol in [
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int64(0),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
doc.append(cstr!("open"), 10.0_f64);
|
||||
doc.append(cstr!("high"), 11.0_f64);
|
||||
doc.append(cstr!("low"), 9.5_f64);
|
||||
doc.append(cstr!("close"), 10.5_f64);
|
||||
doc.append(cstr!("volume"), zero_vol);
|
||||
|
||||
let decoded = decode_eod_intraday_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_eod_search_code_variants_with_matching_stats() {
|
||||
// Missing eodSearchCode
|
||||
let mut missing = RawDocumentBuf::new();
|
||||
missing.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
missing.append(cstr!("open"), 10.0_f64);
|
||||
missing.append(cstr!("high"), 11.0_f64);
|
||||
missing.append(cstr!("low"), 9.0_f64);
|
||||
missing.append(cstr!("close"), 10.5_f64);
|
||||
missing.append(cstr!("volume"), 100.0_f64);
|
||||
let err = decode_eod_intraday_doc(&missing).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::MissingField {
|
||||
field: "eodSearchCode"
|
||||
}
|
||||
);
|
||||
let mut stats = BsonEodIntradayDecodeStats::default();
|
||||
stats.record_error(&err);
|
||||
assert_eq!(stats.rejected_missing_field, 1);
|
||||
assert_eq!(stats.rejected_total(), 1);
|
||||
|
||||
// Empty and whitespace-only keys
|
||||
for blank in ["", " ", "\t\n\r "] {
|
||||
let doc = make_valid_doc(blank, 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::EmptyField {
|
||||
field: "eodSearchCode"
|
||||
}
|
||||
);
|
||||
let mut s = BsonEodIntradayDecodeStats::default();
|
||||
s.record_error(&err);
|
||||
assert_eq!(s.rejected_empty_field, 1);
|
||||
assert_eq!(s.rejected_total(), 1);
|
||||
}
|
||||
|
||||
// Wrong BSON types for eodSearchCode
|
||||
let wrong_types: [(RawBsonRef<'_>, ElementType); 3] = [
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::Int32(123), ElementType::Int32),
|
||||
(RawBsonRef::Boolean(true), ElementType::Boolean),
|
||||
];
|
||||
for (val, expected_type) in wrong_types {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), val);
|
||||
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
doc.append(cstr!("open"), 10.0_f64);
|
||||
doc.append(cstr!("high"), 11.0_f64);
|
||||
doc.append(cstr!("low"), 9.0_f64);
|
||||
doc.append(cstr!("close"), 10.5_f64);
|
||||
doc.append(cstr!("volume"), 100.0_f64);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: expected_type,
|
||||
}
|
||||
);
|
||||
let mut s = BsonEodIntradayDecodeStats::default();
|
||||
s.record_error(&err);
|
||||
assert_eq!(s.rejected_wrong_type, 1);
|
||||
assert_eq!(s.rejected_total(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_timestamp_variants_with_matching_stats() {
|
||||
// Missing timestamp
|
||||
let mut missing = RawDocumentBuf::new();
|
||||
missing.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
missing.append(cstr!("open"), 10.0_f64);
|
||||
missing.append(cstr!("high"), 11.0_f64);
|
||||
missing.append(cstr!("low"), 9.0_f64);
|
||||
missing.append(cstr!("close"), 10.5_f64);
|
||||
missing.append(cstr!("volume"), 100.0_f64);
|
||||
let err = decode_eod_intraday_doc(&missing).unwrap_err();
|
||||
assert_eq!(err, BsonEodIntradayError::MissingField { field: "timestamp" });
|
||||
let mut stats = BsonEodIntradayDecodeStats::default();
|
||||
stats.record_error(&err);
|
||||
assert_eq!(stats.rejected_missing_field, 1);
|
||||
assert_eq!(stats.rejected_total(), 1);
|
||||
|
||||
// Wrong BSON types for timestamp
|
||||
let wrong_types: [(RawBsonRef<'_>, ElementType); 4] = [
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::String("1717767000"), ElementType::String),
|
||||
(
|
||||
RawBsonRef::DateTime(DateTime::from_millis(1_717_767_000_000)),
|
||||
ElementType::DateTime,
|
||||
),
|
||||
(RawBsonRef::Boolean(false), ElementType::Boolean),
|
||||
];
|
||||
for (val, expected_type) in wrong_types {
|
||||
let doc = make_doc_with_timestamp(val);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::WrongType {
|
||||
field: "timestamp",
|
||||
actual: expected_type,
|
||||
}
|
||||
);
|
||||
let mut s = BsonEodIntradayDecodeStats::default();
|
||||
s.record_error(&err);
|
||||
assert_eq!(s.rejected_wrong_type, 1);
|
||||
assert_eq!(s.rejected_total(), 1);
|
||||
}
|
||||
|
||||
// Invalid numeric timestamps: fractional, NaN, inf, -inf, negative, overflowing
|
||||
let invalid_timestamps: [RawBsonRef<'_>; 11] = [
|
||||
RawBsonRef::Double(1_717_767_000.5),
|
||||
RawBsonRef::Double(0.25),
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-1),
|
||||
RawBsonRef::Double(-1.0),
|
||||
RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS + 1),
|
||||
RawBsonRef::Int64(i64::MAX),
|
||||
RawBsonRef::Double((MAX_TIMESTAMP_SECONDS + 1) as f64),
|
||||
];
|
||||
for bad_ts in invalid_timestamps {
|
||||
let doc = make_doc_with_timestamp(bad_ts);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }
|
||||
);
|
||||
let mut s = BsonEodIntradayDecodeStats::default();
|
||||
s.record_error(&err);
|
||||
assert_eq!(s.rejected_invalid_timestamp, 1);
|
||||
assert_eq!(s.rejected_total(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_ohlc_and_volume_variants_with_matching_stats() {
|
||||
let ohlc_fields = ["open", "high", "low", "close"];
|
||||
|
||||
for target in ohlc_fields {
|
||||
// Missing field
|
||||
let mut missing = RawDocumentBuf::new();
|
||||
missing.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
missing.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
for (f, key) in [
|
||||
("open", cstr!("open")),
|
||||
("high", cstr!("high")),
|
||||
("low", cstr!("low")),
|
||||
("close", cstr!("close")),
|
||||
("volume", cstr!("volume")),
|
||||
] {
|
||||
if f != target {
|
||||
missing.append(key, 10.0_f64);
|
||||
}
|
||||
}
|
||||
let err = decode_eod_intraday_doc(&missing).unwrap_err();
|
||||
assert_eq!(err, BsonEodIntradayError::MissingField { field: target });
|
||||
let mut s = BsonEodIntradayDecodeStats::default();
|
||||
s.record_error(&err);
|
||||
assert_eq!(s.rejected_missing_field, 1);
|
||||
assert_eq!(s.rejected_total(), 1);
|
||||
|
||||
let build_with_field = |val: RawBsonRef<'_>| {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
for (name, key) in [
|
||||
("open", cstr!("open")),
|
||||
("high", cstr!("high")),
|
||||
("low", cstr!("low")),
|
||||
("close", cstr!("close")),
|
||||
("volume", cstr!("volume")),
|
||||
] {
|
||||
if name == target {
|
||||
doc.append(key, val);
|
||||
} else {
|
||||
doc.append(key, 10.0_f64);
|
||||
}
|
||||
}
|
||||
doc
|
||||
};
|
||||
|
||||
// Null and wrong types -> WrongType
|
||||
for (val, expected_type) in [
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::String("10.0"), ElementType::String),
|
||||
(RawBsonRef::Boolean(true), ElementType::Boolean),
|
||||
] {
|
||||
let doc = build_with_field(val);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::WrongType {
|
||||
field: target,
|
||||
actual: expected_type,
|
||||
}
|
||||
);
|
||||
let mut st = BsonEodIntradayDecodeStats::default();
|
||||
st.record_error(&err);
|
||||
assert_eq!(st.rejected_wrong_type, 1);
|
||||
assert_eq!(st.rejected_total(), 1);
|
||||
}
|
||||
|
||||
// Non-finite, zero, and negative -> InvalidNumber
|
||||
for bad_num in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Double(-1.25),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int32(-5),
|
||||
RawBsonRef::Int64(0),
|
||||
RawBsonRef::Int64(-5),
|
||||
] {
|
||||
let doc = build_with_field(bad_num);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
match &err {
|
||||
BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target),
|
||||
other => panic!("expected InvalidNumber for {target}, got {other:?}"),
|
||||
}
|
||||
let mut st = BsonEodIntradayDecodeStats::default();
|
||||
st.record_error(&err);
|
||||
assert_eq!(st.rejected_invalid_number, 1);
|
||||
assert_eq!(st.rejected_total(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Volume: missing, Null/wrong-type, negative/NaN/inf
|
||||
let mut missing_vol = RawDocumentBuf::new();
|
||||
missing_vol.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
missing_vol.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
missing_vol.append(cstr!("open"), 10.0_f64);
|
||||
missing_vol.append(cstr!("high"), 11.0_f64);
|
||||
missing_vol.append(cstr!("low"), 9.0_f64);
|
||||
missing_vol.append(cstr!("close"), 10.5_f64);
|
||||
let err = decode_eod_intraday_doc(&missing_vol).unwrap_err();
|
||||
assert_eq!(err, BsonEodIntradayError::MissingField { field: "volume" });
|
||||
|
||||
let build_with_vol = |val: RawBsonRef<'_>| {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
doc.append(cstr!("timestamp"), 1_717_767_000_i64);
|
||||
doc.append(cstr!("open"), 10.0_f64);
|
||||
doc.append(cstr!("high"), 11.0_f64);
|
||||
doc.append(cstr!("low"), 9.0_f64);
|
||||
doc.append(cstr!("close"), 10.5_f64);
|
||||
doc.append(cstr!("volume"), val);
|
||||
doc
|
||||
};
|
||||
|
||||
for (val, expected_type) in [
|
||||
(RawBsonRef::Null, ElementType::Null),
|
||||
(RawBsonRef::String("100"), ElementType::String),
|
||||
(RawBsonRef::Boolean(false), ElementType::Boolean),
|
||||
] {
|
||||
let doc = build_with_vol(val);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonEodIntradayError::WrongType {
|
||||
field: "volume",
|
||||
actual: expected_type,
|
||||
}
|
||||
);
|
||||
let mut st = BsonEodIntradayDecodeStats::default();
|
||||
st.record_error(&err);
|
||||
assert_eq!(st.rejected_wrong_type, 1);
|
||||
assert_eq!(st.rejected_total(), 1);
|
||||
}
|
||||
|
||||
for bad_vol in [
|
||||
RawBsonRef::Double(-0.01),
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-1),
|
||||
] {
|
||||
let doc = build_with_vol(bad_vol);
|
||||
let err = decode_eod_intraday_doc(&doc).unwrap_err();
|
||||
match &err {
|
||||
BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, "volume"),
|
||||
other => panic!("expected InvalidNumber for volume, got {other:?}"),
|
||||
}
|
||||
let mut st = BsonEodIntradayDecodeStats::default();
|
||||
st.record_error(&err);
|
||||
assert_eq!(st.rejected_invalid_number, 1);
|
||||
assert_eq!(st.rejected_total(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_and_corrupt_single_doc_bytes_without_panicking() {
|
||||
// Truncated header (< 4 bytes)
|
||||
assert_eq!(
|
||||
decode_eod_intraday_bytes(&[0x10, 0x00]),
|
||||
Err(BsonEodIntradayError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 2,
|
||||
declared_len: None,
|
||||
})
|
||||
);
|
||||
|
||||
// Declared length < 5
|
||||
assert_eq!(
|
||||
decode_eod_intraday_bytes(&[4, 0, 0, 0]),
|
||||
Err(BsonEodIntradayError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4,
|
||||
})
|
||||
);
|
||||
|
||||
// Truncated body (declared_len > remaining)
|
||||
let valid = make_valid_doc("NVDA.US", 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0);
|
||||
let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3];
|
||||
assert_eq!(
|
||||
decode_eod_intraday_bytes(truncated),
|
||||
Err(BsonEodIntradayError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: truncated.len(),
|
||||
declared_len: Some(valid.as_bytes().len() as i32),
|
||||
})
|
||||
);
|
||||
|
||||
// Trailing extra bytes on single-doc decode -> CorruptDocumentLength
|
||||
let mut with_trailing = valid.as_bytes().to_vec();
|
||||
with_trailing.push(0x00);
|
||||
assert_eq!(
|
||||
decode_eod_intraday_bytes(&with_trailing),
|
||||
Err(BsonEodIntradayError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: valid.as_bytes().len() as i32,
|
||||
})
|
||||
);
|
||||
|
||||
// Malformed BSON (missing trailing null terminator)
|
||||
let mut bad_term = valid.as_bytes().to_vec();
|
||||
*bad_term.last_mut().unwrap() = 0xFF;
|
||||
match decode_eod_intraday_bytes(&bad_term) {
|
||||
Err(BsonEodIntradayError::CorruptBson { offset: 0, .. }) => {}
|
||||
other => panic!("expected CorruptBson, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_mixed_buffer_preserving_order_recovering_past_corrupt_frame_and_merging_stats() {
|
||||
let valid1 = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0);
|
||||
let empty_key = make_valid_doc(" ", 1_717_767_060, 120.5, 121.0, 120.0, 120.8, 500.0);
|
||||
let bad_ts = make_doc_with_timestamp(RawBsonRef::Double(1_717_767_120.5));
|
||||
let bad_price = make_valid_doc("NVDA.US", 1_717_767_180, 0.0, 121.0, 119.0, 120.0, 200.0);
|
||||
|
||||
let mut wrong_type = RawDocumentBuf::new();
|
||||
wrong_type.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
wrong_type.append(cstr!("timestamp"), 1_717_767_240_i64);
|
||||
wrong_type.append(cstr!("open"), RawBsonRef::Null);
|
||||
wrong_type.append(cstr!("high"), 121.0_f64);
|
||||
wrong_type.append(cstr!("low"), 119.0_f64);
|
||||
wrong_type.append(cstr!("close"), 120.0_f64);
|
||||
wrong_type.append(cstr!("volume"), 200.0_f64);
|
||||
|
||||
let mut missing_field = RawDocumentBuf::new();
|
||||
missing_field.append(cstr!("eodSearchCode"), "NVDA.US");
|
||||
missing_field.append(cstr!("timestamp"), 1_717_767_300_i64);
|
||||
missing_field.append(cstr!("open"), 120.0_f64);
|
||||
missing_field.append(cstr!("high"), 121.0_f64);
|
||||
missing_field.append(cstr!("low"), 119.0_f64);
|
||||
missing_field.append(cstr!("close"), 120.0_f64);
|
||||
|
||||
// Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer
|
||||
// iteration recovers and decodes valid2 after it.
|
||||
let mut corrupt_framed = valid1.as_bytes().to_vec();
|
||||
*corrupt_framed.last_mut().unwrap() = 0xAA;
|
||||
|
||||
let valid2 = make_valid_doc("AAPL.US", 1_717_767_360, 195.0, 196.0, 194.5, 195.5, 0.0);
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(valid1.as_bytes());
|
||||
let off_empty = buf.len();
|
||||
buf.extend_from_slice(empty_key.as_bytes());
|
||||
let off_bad_ts = buf.len();
|
||||
buf.extend_from_slice(bad_ts.as_bytes());
|
||||
let off_bad_price = buf.len();
|
||||
buf.extend_from_slice(bad_price.as_bytes());
|
||||
let off_wrong_type = buf.len();
|
||||
buf.extend_from_slice(wrong_type.as_bytes());
|
||||
let off_missing = buf.len();
|
||||
buf.extend_from_slice(missing_field.as_bytes());
|
||||
let off_corrupt = buf.len();
|
||||
buf.extend_from_slice(&corrupt_framed);
|
||||
buf.extend_from_slice(valid2.as_bytes());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_eod_intraday_buffer(
|
||||
&buf,
|
||||
|bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close, bar.volume)),
|
||||
|offset, err| errors.push((offset, err)),
|
||||
);
|
||||
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(rows[0], ("NVDA.US".to_owned(), 1_717_767_000_000_000, 120.5, 1000.0));
|
||||
assert_eq!(rows[1], ("AAPL.US".to_owned(), 1_717_767_360_000_000, 195.5, 0.0));
|
||||
|
||||
assert_eq!(stats.docs_seen, 8);
|
||||
assert_eq!(stats.rows_decoded, 2);
|
||||
assert_eq!(stats.rejected_empty_field, 1);
|
||||
assert_eq!(stats.rejected_invalid_timestamp, 1);
|
||||
assert_eq!(stats.rejected_invalid_number, 1);
|
||||
assert_eq!(stats.rejected_wrong_type, 1);
|
||||
assert_eq!(stats.rejected_missing_field, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.rejected_total(), 6);
|
||||
assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total());
|
||||
|
||||
assert_eq!(errors.len(), 6);
|
||||
assert_eq!(errors[0].0, off_empty);
|
||||
assert_eq!(errors[1].0, off_bad_ts);
|
||||
assert_eq!(errors[2].0, off_bad_price);
|
||||
assert_eq!(errors[3].0, off_wrong_type);
|
||||
assert_eq!(errors[4].0, off_missing);
|
||||
assert_eq!(errors[5].0, off_corrupt);
|
||||
assert!(matches!(
|
||||
errors[5].1,
|
||||
BsonEodIntradayError::CorruptBson { offset, .. } if offset == off_corrupt
|
||||
));
|
||||
|
||||
// Verify BsonEodIntradayDecodeStats::merge sums every counter.
|
||||
let mut merged = BsonEodIntradayDecodeStats {
|
||||
docs_seen: 10,
|
||||
rows_decoded: 4,
|
||||
rejected_missing_field: 1,
|
||||
rejected_empty_field: 1,
|
||||
rejected_wrong_type: 1,
|
||||
rejected_invalid_timestamp: 1,
|
||||
rejected_invalid_number: 1,
|
||||
rejected_corrupt_document: 1,
|
||||
};
|
||||
merged.merge(&stats);
|
||||
assert_eq!(
|
||||
merged,
|
||||
BsonEodIntradayDecodeStats {
|
||||
docs_seen: 18,
|
||||
rows_decoded: 6,
|
||||
rejected_missing_field: 2,
|
||||
rejected_empty_field: 2,
|
||||
rejected_wrong_type: 2,
|
||||
rejected_invalid_timestamp: 2,
|
||||
rejected_invalid_number: 2,
|
||||
rejected_corrupt_document: 2,
|
||||
}
|
||||
);
|
||||
assert_eq!(merged.docs_seen, merged.rows_decoded + merged.rejected_total());
|
||||
|
||||
// Truncated tail stops cleanly and still maintains conservation invariant.
|
||||
let mut with_trunc = buf.clone();
|
||||
let trunc_off = with_trunc.len();
|
||||
with_trunc.extend_from_slice(&valid2.as_bytes()[..10]);
|
||||
let mut trunc_errs = Vec::new();
|
||||
let trunc_stats = decode_eod_intraday_buffer(
|
||||
&with_trunc,
|
||||
|_| {},
|
||||
|off, err| trunc_errs.push((off, err)),
|
||||
);
|
||||
assert_eq!(trunc_stats.docs_seen, 9);
|
||||
assert_eq!(trunc_stats.rows_decoded, 2);
|
||||
assert_eq!(trunc_stats.rejected_corrupt_document, 2);
|
||||
assert_eq!(
|
||||
trunc_stats.docs_seen,
|
||||
trunc_stats.rows_decoded + trunc_stats.rejected_total()
|
||||
);
|
||||
assert_eq!(trunc_errs.last().unwrap().0, trunc_off);
|
||||
assert!(matches!(
|
||||
trunc_errs.last().unwrap().1,
|
||||
BsonEodIntradayError::TruncatedDocument { offset, remaining: 10, declared_len: Some(_) }
|
||||
if offset == trunc_off
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_nvda_bars_feed_build_bars_1m_end_to_end_with_10_for_1_split() {
|
||||
// NVDA 10:1 split ex-date: 2024-06-10.
|
||||
// Bar 1: 2024-06-07 15:59 ET (EDT, UTC-4) = 2024-06-07 19:59:00 UTC = 1_717_790_340 s.
|
||||
// Bar 2: 2024-06-10 09:30 ET (EDT, UTC-4) = 2024-06-10 13:30:00 UTC = 1_718_026_200 s.
|
||||
const PRE_SPLIT_TS_SEC: i64 = 1_717_790_340;
|
||||
const EX_DATE_TS_SEC: i64 = 1_718_026_200;
|
||||
|
||||
// Provider's retroactively split-adjusted 1m values.
|
||||
let pre_split_doc = make_valid_doc(
|
||||
"NVDA.US",
|
||||
PRE_SPLIT_TS_SEC,
|
||||
120.80,
|
||||
121.05,
|
||||
120.72,
|
||||
120.888,
|
||||
2_500_000.0,
|
||||
);
|
||||
let ex_date_doc = make_valid_doc(
|
||||
"NVDA.US",
|
||||
EX_DATE_TS_SEC,
|
||||
120.37,
|
||||
121.10,
|
||||
120.15,
|
||||
120.95,
|
||||
1_800_000.0,
|
||||
);
|
||||
|
||||
let mut raw_buf = Vec::new();
|
||||
raw_buf.extend_from_slice(pre_split_doc.as_bytes());
|
||||
raw_buf.extend_from_slice(ex_date_doc.as_bytes());
|
||||
|
||||
let splits = SplitTable::from_events([(
|
||||
"NVDA.US".to_owned(),
|
||||
SplitEvent {
|
||||
ex_date: day(2024, 6, 10),
|
||||
ratio: 10.0,
|
||||
},
|
||||
)])
|
||||
.unwrap();
|
||||
let empty_splits = SplitTable::<String>::default();
|
||||
|
||||
let run_once = |table: &SplitTable<String>| {
|
||||
let mut bars = Vec::new();
|
||||
let mut decode_errors = Vec::new();
|
||||
let decode_stats = decode_eod_intraday_buffer(
|
||||
&raw_buf,
|
||||
|raw| bars.push(raw.into_eod_intraday_bar(|code, _ts| code.to_owned())),
|
||||
|off, err| decode_errors.push((off, err)),
|
||||
);
|
||||
assert!(decode_errors.is_empty());
|
||||
assert_eq!(decode_stats.docs_seen, 2);
|
||||
assert_eq!(decode_stats.rows_decoded, 2);
|
||||
let built = build_bars_1m(bars, table);
|
||||
(decode_stats, built)
|
||||
};
|
||||
|
||||
let (stats_split, built_split) = run_once(&splits);
|
||||
let (stats_empty, built_empty) = run_once(&empty_splits);
|
||||
let (stats_replay, built_replay) = run_once(&splits);
|
||||
|
||||
// Deterministic replay produces identical rows and stats.
|
||||
assert_eq!(stats_split, stats_replay);
|
||||
assert_eq!(built_split.rows, built_replay.rows);
|
||||
assert_eq!(built_split.stats, built_replay.stats);
|
||||
assert_eq!(stats_split, stats_empty);
|
||||
|
||||
assert_eq!(built_split.rows.len(), 2);
|
||||
assert_eq!(built_empty.rows.len(), 2);
|
||||
|
||||
// Pre-split bar: OHLC * 10, volume / 10, dollar volume (close * volume) conserved.
|
||||
let pre_split = &built_split.rows[0];
|
||||
let pre_empty = &built_empty.rows[0];
|
||||
assert_eq!(pre_split.key, "NVDA.US");
|
||||
assert_eq!(pre_split.ts, PRE_SPLIT_TS_SEC * 1_000_000);
|
||||
assert_eq!(pre_split.session_date, day(2024, 6, 7));
|
||||
assert_eq!(pre_split.session, IntradaySession::Rth);
|
||||
assert_eq!(pre_split.source, BARS_1M_SOURCE_EOD);
|
||||
assert_rel_eq(pre_split.open, pre_empty.open * 10.0, 1e-12);
|
||||
assert_rel_eq(pre_split.high, pre_empty.high * 10.0, 1e-12);
|
||||
assert_rel_eq(pre_split.low, pre_empty.low * 10.0, 1e-12);
|
||||
assert_rel_eq(pre_split.close, pre_empty.close * 10.0, 1e-12);
|
||||
assert_rel_eq(pre_split.volume, pre_empty.volume / 10.0, 1e-12);
|
||||
assert_rel_eq(
|
||||
pre_split.close * pre_split.volume,
|
||||
pre_empty.close * pre_empty.volume,
|
||||
1e-12,
|
||||
);
|
||||
|
||||
// Ex-date bar: unchanged by the 2024-06-10 split (strict ex_date > session_date boundary).
|
||||
let ex_split = &built_split.rows[1];
|
||||
let ex_empty = &built_empty.rows[1];
|
||||
assert_eq!(ex_split.ts, EX_DATE_TS_SEC * 1_000_000);
|
||||
assert_eq!(ex_split.session_date, day(2024, 6, 10));
|
||||
assert_eq!(ex_split.session, IntradaySession::Rth);
|
||||
assert_eq!(ex_split.open.to_bits(), ex_empty.open.to_bits());
|
||||
assert_eq!(ex_split.high.to_bits(), ex_empty.high.to_bits());
|
||||
assert_eq!(ex_split.low.to_bits(), ex_empty.low.to_bits());
|
||||
assert_eq!(ex_split.close.to_bits(), ex_empty.close.to_bits());
|
||||
assert_eq!(ex_split.volume.to_bits(), ex_empty.volume.to_bits());
|
||||
}
|
||||
|
|
@ -24,6 +24,10 @@ use std::io;
|
|||
use crate::bson_ceo_shorts::{
|
||||
decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
|
||||
};
|
||||
use crate::bson_eod_intraday::{
|
||||
decode_eod_intraday_buffer, BsonEodIntradayDecodeStats, BsonEodIntradayError,
|
||||
RawEodIntradayBar,
|
||||
};
|
||||
use crate::bson_eod_prices::{
|
||||
decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar,
|
||||
};
|
||||
|
|
@ -531,6 +535,84 @@ fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError {
|
|||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_eod_intraday_error(base: u64, err: BsonEodIntradayError) -> BsonEodIntradayError {
|
||||
match err {
|
||||
BsonEodIntradayError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonEodIntradayError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodIntradayError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonEodIntradayError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonEodIntradayError::CorruptBson { offset, detail } => {
|
||||
BsonEodIntradayError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
}
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_intraday_buffer`],
|
||||
/// accumulating [`BsonEodIntradayDecodeStats`] and rebasing per-document error offsets to
|
||||
/// absolute stream byte offsets.
|
||||
pub fn decode_eod_intraday_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonEodIntradayDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawEodIntradayBar<'a>),
|
||||
E: FnMut(u64, BsonEodIntradayError),
|
||||
{
|
||||
let mut total = BsonEodIntradayDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_eod_intraday_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_bar,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_eod_intraday_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `eodIntraday1M` [`std::io::Read`] source through
|
||||
/// [`decode_eod_intraday_buffer`] with bounded memory.
|
||||
///
|
||||
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
|
||||
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
|
||||
pub fn decode_eod_intraday_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_bar: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonEodIntradayDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawEodIntradayBar<'a>),
|
||||
E: FnMut(u64, BsonEodIntradayError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error)
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`],
|
||||
/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream
|
||||
/// byte offsets.
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ use std::io::{self, Cursor, Read};
|
|||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
|
||||
use crate::bson_eod_intraday::{
|
||||
decode_eod_intraday_buffer, BsonEodIntradayError,
|
||||
};
|
||||
use crate::bson_eod_prices::{
|
||||
decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats,
|
||||
};
|
||||
|
|
@ -12,9 +15,10 @@ use crate::bson_qm_actions::{
|
|||
};
|
||||
use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError};
|
||||
use crate::bson_stream::{
|
||||
decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_price_stream,
|
||||
decode_qm_split_stream, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
|
||||
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream,
|
||||
decode_qm_dividend_stream, decode_qm_price_stream, decode_qm_split_stream, BsonStreamError,
|
||||
BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES,
|
||||
MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
|
|
@ -2113,3 +2117,164 @@ fn decode_qm_price_stream_matches_buffer_rebases_offsets_and_fails_on_framing()
|
|||
.unwrap_err();
|
||||
assert!(matches!(err, BsonStreamError::TruncatedDocument { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() {
|
||||
let make_doc = |code: &str, ts: i64, open: f64, close: f64, vol: f64| -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("timestamp"), ts);
|
||||
doc.append(cstr!("open"), open);
|
||||
doc.append(cstr!("high"), open.max(close) + 0.5);
|
||||
doc.append(cstr!("low"), open.min(close) - 0.5);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), vol);
|
||||
doc.into_bytes()
|
||||
};
|
||||
|
||||
let mut fixture = Vec::new();
|
||||
fixture.extend_from_slice(&make_doc("NVDA.US", 1_717_767_000, 120.0, 120.5, 1000.0));
|
||||
fixture.extend_from_slice(&make_doc("AAPL.US", 1_717_767_060, 195.0, 195.25, 0.0));
|
||||
|
||||
// Semantic error: invalid timestamp (negative)
|
||||
let bad_ts_offset = fixture.len() as u64;
|
||||
fixture.extend_from_slice(&make_doc("NVDA.US", -60, 120.0, 120.5, 100.0));
|
||||
|
||||
// Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset
|
||||
let mut corrupt_bytes = make_doc("MSFT.US", 1_717_767_120, 420.0, 421.0, 500.0);
|
||||
*corrupt_bytes.last_mut().unwrap() = 0xEE;
|
||||
let corrupt_offset = fixture.len() as u64;
|
||||
fixture.extend_from_slice(&corrupt_bytes);
|
||||
|
||||
fixture.extend_from_slice(&make_doc("SHOP.TO", 1_717_767_180, 88.0, 88.4, 2500.0));
|
||||
|
||||
let mut expected_rows = Vec::new();
|
||||
let mut expected_errs = Vec::new();
|
||||
let expected_stats = decode_eod_intraday_buffer(
|
||||
&fixture,
|
||||
|b| {
|
||||
expected_rows.push((
|
||||
b.eod_search_code.to_owned(),
|
||||
b.ts,
|
||||
b.open.to_bits(),
|
||||
b.high.to_bits(),
|
||||
b.low.to_bits(),
|
||||
b.close.to_bits(),
|
||||
b.volume.to_bits(),
|
||||
))
|
||||
},
|
||||
|off, err| expected_errs.push((off as u64, err)),
|
||||
);
|
||||
assert_eq!(expected_stats.docs_seen, 5);
|
||||
assert_eq!(expected_stats.rows_decoded, 3);
|
||||
assert_eq!(expected_stats.rejected_invalid_timestamp, 1);
|
||||
assert_eq!(expected_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(expected_stats.rejected_total(), 2);
|
||||
|
||||
// Exercise decode_eod_intraday_stream across small capacities and short reads splitting
|
||||
// length prefixes and document bodies.
|
||||
for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] {
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: cap,
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut got_rows = Vec::new();
|
||||
let mut got_errs = Vec::new();
|
||||
let got_stats = decode_eod_intraday_stream(
|
||||
FixedStepReader::new(&fixture, step),
|
||||
opts,
|
||||
|b| {
|
||||
got_rows.push((
|
||||
b.eod_search_code.to_owned(),
|
||||
b.ts,
|
||||
b.open.to_bits(),
|
||||
b.high.to_bits(),
|
||||
b.low.to_bits(),
|
||||
b.close.to_bits(),
|
||||
b.volume.to_bits(),
|
||||
))
|
||||
},
|
||||
|off, err| got_errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(got_stats, expected_stats);
|
||||
assert_eq!(got_rows, expected_rows);
|
||||
assert_eq!(got_errs, expected_errs);
|
||||
assert_eq!(got_errs[0].0, bad_ts_offset);
|
||||
assert!(matches!(
|
||||
got_errs[1],
|
||||
(off, BsonEodIntradayError::CorruptBson { offset, .. })
|
||||
if off == corrupt_offset && offset as u64 == corrupt_offset
|
||||
));
|
||||
}
|
||||
|
||||
// Exercise decode_eod_intraday_chunks directly with random read sizes and EINTR interrupts.
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut chunk_reader =
|
||||
RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x141, true), opts)
|
||||
.unwrap();
|
||||
let mut chunk_rows = Vec::new();
|
||||
let mut chunk_errs = Vec::new();
|
||||
let chunk_stats = decode_eod_intraday_chunks(
|
||||
&mut chunk_reader,
|
||||
|b| {
|
||||
chunk_rows.push((
|
||||
b.eod_search_code.to_owned(),
|
||||
b.ts,
|
||||
b.open.to_bits(),
|
||||
b.high.to_bits(),
|
||||
b.low.to_bits(),
|
||||
b.close.to_bits(),
|
||||
b.volume.to_bits(),
|
||||
))
|
||||
},
|
||||
|off, err| chunk_errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(chunk_stats, expected_stats);
|
||||
assert_eq!(chunk_rows, expected_rows);
|
||||
assert_eq!(chunk_errs, expected_errs);
|
||||
|
||||
// Truncated trailing document must deliver the complete prefix first and then return
|
||||
// BsonStreamError::TruncatedDocument at the exact tail offset.
|
||||
let mut truncated = fixture.clone();
|
||||
let trunc_offset = truncated.len() as u64;
|
||||
truncated.extend_from_slice(&120_i32.to_le_bytes());
|
||||
truncated.extend_from_slice(&[0x02, b'a', 0x00]);
|
||||
let mut prefix_rows = Vec::new();
|
||||
let mut prefix_errs = Vec::new();
|
||||
let err = decode_eod_intraday_stream(
|
||||
FixedStepReader::new(&truncated, 5),
|
||||
BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 4096,
|
||||
},
|
||||
|b| {
|
||||
prefix_rows.push((
|
||||
b.eod_search_code.to_owned(),
|
||||
b.ts,
|
||||
b.open.to_bits(),
|
||||
b.high.to_bits(),
|
||||
b.low.to_bits(),
|
||||
b.close.to_bits(),
|
||||
b.volume.to_bits(),
|
||||
))
|
||||
},
|
||||
|off, e| prefix_errs.push((off, e)),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(prefix_rows, expected_rows);
|
||||
assert_eq!(prefix_errs, expected_errs);
|
||||
assert!(matches!(
|
||||
err,
|
||||
BsonStreamError::TruncatedDocument {
|
||||
offset,
|
||||
remaining: 7,
|
||||
declared_len: Some(120),
|
||||
} if offset == trunc_offset
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ pub mod bars;
|
|||
pub mod bars_1m;
|
||||
pub mod bench;
|
||||
pub mod bson_ceo_shorts;
|
||||
pub mod bson_eod_intraday;
|
||||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod bson_qm_events;
|
||||
|
|
@ -50,6 +51,10 @@ pub use bson_ceo_shorts::{
|
|||
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
|
||||
DEFAULT_REPORT_DATE_FIELD,
|
||||
};
|
||||
pub use bson_eod_intraday::{
|
||||
decode_eod_intraday_buffer, decode_eod_intraday_bytes, decode_eod_intraday_doc,
|
||||
BsonEodIntradayDecodeStats, BsonEodIntradayError, RawEodIntradayBar,
|
||||
};
|
||||
pub use bson_eod_prices::{
|
||||
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
|
||||
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
|
||||
|
|
@ -73,8 +78,8 @@ pub use bson_qm_prices::{
|
|||
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,
|
||||
};
|
||||
pub use bson_stream::{
|
||||
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks,
|
||||
decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
|
||||
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_intraday_chunks,
|
||||
decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
|
||||
decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks,
|
||||
decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream,
|
||||
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue