From 0204f2eff695f3cfe4e5d740c24f29c652e09916 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:38:56 -0500 Subject: [PATCH 01/10] =?UTF-8?q?T-150:=20M2.3i=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20zero-copy=20raw=20BSON=20decoder=20for=20`qmIntraday`?= =?UTF-8?q?=20raw=20`1m`=20bars=20(`bson=5Fqm=5Fintraday.rs`,=20pure,=20wi?= =?UTF-8?q?th=20tests;=20no=20new=20crates,=20no=20CLI/bench=20changes,=20?= =?UTF-8?q?no=20live=20Mongo/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bson_qm_intraday.rs | 641 +++++++++++++++ .../curate-etl/src/bson_qm_intraday_tests.rs | 757 ++++++++++++++++++ tools/curate-etl/src/lib.rs | 1 + 3 files changed, 1399 insertions(+) create mode 100644 tools/curate-etl/src/bson_qm_intraday.rs create mode 100644 tools/curate-etl/src/bson_qm_intraday_tests.rs diff --git a/tools/curate-etl/src/bson_qm_intraday.rs b/tools/curate-etl/src/bson_qm_intraday.rs new file mode 100644 index 00000000..491d4138 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_intraday.rs @@ -0,0 +1,641 @@ +//! Zero-copy raw BSON decoder for MongoDB `qmIntraday` documents (`M2.3i`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into +//! borrowed [`RawQmIntradayBar`] views without allocating a `String` or `bson::Document` per row. +//! Callers can convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a +//! caller-supplied key mapper without per-row `String` allocations, keeping in mind that +//! `qmIntraday` raw fields are already un-adjusted (see [`RawQmIntradayBar::into_eod_intraday_bar`]). +//! +//! # Empirical Field Contract & Cited Sources +//! +//! Field names and semantics are grounded in the repository's ingestion writer and empirical data +//! contract: +//! - `apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts:119-131,165-173` +//! (requests 1-minute bars via `interval: '1'`, spreads the provider bar payload, adds +//! `qmSearchCode`, `symbol`, `exchange`, and +//! `timestamp: new Date(bar.startdatetime || bar.date || bar.datetime)`, and upserts into +//! `qmIntraday` keyed by `['qmSearchCode', 'timestamp']`) +//! - `design/DATA-CONTRACTS.md:16` (§1 row `qmIntraday`, ~173.3M docs): stores **both** raw +//! (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`) +//! fields. This decoder reads the raw fields only; all adjusted fields are validated as borrowed +//! `RawBsonRef` payloads and otherwise ignored. +//! +//! `ts` is decoded as bar-start UTC microseconds (`DateTime` milliseconds × `1_000`). Downstream +//! research/curation owns availability (`known_at`) decisions. +//! +//! # Accepted BSON Representations & Decoder Conventions +//! +//! Following [`crate::bson_eod_intraday`] and [`crate::bson_qm_prices`]: +//! - `qmSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or +//! whitespace-only strings are rejected as [`BsonQmIntradayError::EmptyField`]; non-string +//! values (including BSON `Null`) are rejected as [`BsonQmIntradayError::WrongType`]. +//! - `timestamp`: BSON `DateTime` (UTC milliseconds since Unix epoch), converted to UTC +//! microseconds via checked multiplication by `1_000`. Non-`DateTime` types (including `Null`, +//! integers, doubles, strings, and BSON `Timestamp`) are rejected as +//! [`BsonQmIntradayError::WrongType`]; negative millisecond values or values overflowing `i64` +//! microseconds are rejected as [`BsonQmIntradayError::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 +//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected +//! as [`BsonQmIntradayError::InvalidNumber`]. +//! - `sharevolume`: 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 +//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as +//! [`BsonQmIntradayError::InvalidNumber`]. +//! - All other top-level fields (`_id`, `symbol`, `exchange`, `adjustedopen`, `adjustedhigh`, +//! `adjustedlow`, `adjustedclose`, `avolume`, `startdatetime`, nested objects/arrays, etc.) are +//! validated as borrowed `RawBsonRef` views (zero allocation) and otherwise ignored, so malformed +//! bytes in skipped fields still surface as [`BsonQmIntradayError::CorruptBson`]. +//! - Duplicate fields and error precedence: later valid duplicates replace earlier valid values, +//! the first semantic error is retained (a later valid duplicate cannot clear an earlier semantic +//! error), and malformed BSON bytes take precedence immediately as `CorruptBson`. After the scan, +//! the first semantic error is returned, or else the first missing required field in +//! `qmSearchCode`, `timestamp`, `open`, `high`, `low`, `close`, `sharevolume` order. + +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}; + +/// MongoDB field name for the QuoteMedia security key (`intraday-crawl.action.ts:167,173`). +pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; +/// MongoDB field name for the bar-start BSON `DateTime` (`intraday-crawl.action.ts:170,173`). +pub const FIELD_TIMESTAMP: &str = "timestamp"; +/// MongoDB field name for raw bar open price (`DATA-CONTRACTS.md:16`). +pub const FIELD_OPEN: &str = "open"; +/// MongoDB field name for raw bar high price (`DATA-CONTRACTS.md:16`). +pub const FIELD_HIGH: &str = "high"; +/// MongoDB field name for raw bar low price (`DATA-CONTRACTS.md:16`). +pub const FIELD_LOW: &str = "low"; +/// MongoDB field name for raw bar close price (`DATA-CONTRACTS.md:16`). +pub const FIELD_CLOSE: &str = "close"; +/// MongoDB field name for raw bar share volume (`DATA-CONTRACTS.md:16`). +pub const FIELD_SHARE_VOLUME: &str = "sharevolume"; + +const MICROS_PER_MILLI: i64 = 1_000; +/// Largest UTC millisecond timestamp that fits in signed `i64` microseconds (`9_223_372_036_854_775`). +#[cfg(test)] +pub(crate) const MAX_TIMESTAMP_MILLIS: i64 = i64::MAX / MICROS_PER_MILLI; + +/// Borrowed zero-copy view of a single decoded `qmIntraday` BSON document. +/// +/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. +/// `open`, `high`, `low`, `close`, and `volume` are the provider's already-raw values +/// (`open..close`, `sharevolume`); adjusted fields are ignored. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawQmIntradayBar<'a> { + pub qm_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> RawQmIntradayBar<'a> { + /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key + /// mapper. + /// + /// `map_key` receives `(qm_search_code, ts)` (provider code and UTC bar-start microseconds) + /// and this method only maps the key and copies the raw OHLCV fields verbatim. + /// + /// **Important:** [`crate::bars_1m::build_bars_1m`] applies split un-adjustment to + /// [`EodIntradayBar`] inputs (which is required for retroactively split-adjusted + /// `eodIntraday1M` bars). Passing already-raw `qmIntraday` bars through a split-unadjusting + /// path with non-empty splits would distort raw prices and volumes; downstream `qmIntraday` + /// curation must ingest raw values without split un-adjustment. + #[inline] + pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar + where + F: FnOnce(&'a str, i64) -> K, + { + EodIntradayBar { + key: map_key(self.qm_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`] using a caller-supplied key resolver. + /// + /// Maps `(qm_search_code, ts)` and copies the raw OHLCV fields verbatim without applying any + /// split adjustment. See [`Self::into_eod_intraday_bar`] for the split un-adjustment caveat. + #[inline] + pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> + where + F: FnOnce(&'a str, i64) -> Option, + { + let key = map_key(self.qm_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 `qmIntraday` BSON documents or length-prefixed +/// buffers. +/// +/// Every field-level error names the offending BSON field in both its structure and `Display` +/// output; malformed and truncated BSON framing errors report `CorruptBson` with byte offset and +/// framing detail; no input path panics. +#[derive(Debug, Clone, PartialEq)] +pub enum BsonQmIntradayError { + /// 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` BSON `DateTime` was negative or overflowed `i64` microseconds. + InvalidTimestamp { field: &'static str }, + /// An OHLC field was non-finite or `<= 0.0`, or `sharevolume` was non-finite or `< 0.0`. + InvalidNumber { field: &'static str, value: f64 }, + /// Underlying BSON framing, truncation, document length, or element bytes were malformed. + CorruptBson { offset: usize, detail: String }, +} + +impl fmt::Display for BsonQmIntradayError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingField { field } => { + write!(f, "qmIntraday BSON missing required field '{field}'") + } + Self::EmptyField { field } => { + write!( + f, + "qmIntraday BSON field '{field}' must not be empty or blank" + ) + } + Self::WrongType { field, actual } => { + write!( + f, + "qmIntraday BSON field '{field}' has unexpected BSON type {actual:?}" + ) + } + Self::InvalidTimestamp { field } => { + write!( + f, + "qmIntraday BSON field '{field}' is not a valid non-negative DateTime within i64 microsecond range" + ) + } + Self::InvalidNumber { field, value } => { + if *field == FIELD_SHARE_VOLUME { + write!( + f, + "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" + ) + } else { + write!( + f, + "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" + ) + } + } + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonQmIntradayError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonQmIntradayError { + match err { + BsonEodPriceError::TruncatedDocument { offset, .. } + | BsonEodPriceError::CorruptDocumentLength { offset, .. } => { + BsonQmIntradayError::CorruptBson { + offset, + detail: err.to_string(), + } + } + BsonEodPriceError::CorruptBson { offset, detail } => { + BsonQmIntradayError::CorruptBson { offset, detail } + } + BsonEodPriceError::MissingField { field } => BsonQmIntradayError::MissingField { field }, + BsonEodPriceError::EmptyField { field } => BsonQmIntradayError::EmptyField { field }, + BsonEodPriceError::WrongType { field, actual } => { + BsonQmIntradayError::WrongType { field, actual } + } + BsonEodPriceError::MalformedDate { field } => { + BsonQmIntradayError::InvalidTimestamp { field } + } + BsonEodPriceError::InvalidNumber { field, value } => { + BsonQmIntradayError::InvalidNumber { field, value } + } + } +} + +/// Per-batch decode and rejection accounting for [`decode_qm_intraday_buffer`]. +/// +/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonQmIntradayDecodeStats { + 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 BsonQmIntradayDecodeStats { + /// 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: &BsonQmIntradayError) { + match err { + BsonQmIntradayError::MissingField { .. } => self.rejected_missing_field += 1, + BsonQmIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, + BsonQmIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, + BsonQmIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, + BsonQmIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, + BsonQmIntradayError::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 BsonQmIntradayDecodeStats { + #[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, BsonQmIntradayError> { + elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { + offset, + detail: format!("field '{field}': {err}"), + }) +} + +#[inline] +fn decode_timestamp_datetime_to_micros(val: RawBsonRef<'_>) -> Result { + match val { + RawBsonRef::DateTime(dt) => { + let millis = dt.timestamp_millis(); + if millis < 0 { + return Err(BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP, + }); + } + millis + .checked_mul(MICROS_PER_MILLI) + .ok_or(BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP, + }) + } + other => Err(BsonQmIntradayError::WrongType { + field: FIELD_TIMESTAMP, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_positive_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v <= 0.0 { + return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); + } + Ok(v) + } + RawBsonRef::Int32(v) => { + if v <= 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v <= 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonQmIntradayError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_non_negative_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v < 0.0 { + return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); + } + if v == 0.0 { + Ok(0.0) + } else { + Ok(v) + } + } + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonQmIntradayError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonQmIntradayError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +fn decode_qm_intraday_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonQmIntradayError> { + let mut qm_search_code: Option<&'a str> = None; + let mut ts: Option = None; + let mut open: Option = None; + let mut high: Option = None; + let mut low: Option = None; + let mut close: Option = None; + let mut volume: Option = None; + let mut first_semantic_err: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmIntradayError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key(); + + if key == cstr!("qmSearchCode") { + match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE, + }); + } + } else { + qm_search_code = Some(s); + } + } + other => { + if first_semantic_err.is_none() { + first_semantic_err = Some(BsonQmIntradayError::WrongType { + field: FIELD_QM_SEARCH_CODE, + actual: other.element_type(), + }); + } + } + } + } else if key == cstr!("timestamp") { + let val = decode_element_value(FIELD_TIMESTAMP, elem, offset)?; + match decode_timestamp_datetime_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(FIELD_OPEN, elem, offset)?; + match decode_positive_number(FIELD_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(FIELD_HIGH, elem, offset)?; + match decode_positive_number(FIELD_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(FIELD_LOW, elem, offset)?; + match decode_positive_number(FIELD_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(FIELD_CLOSE, elem, offset)?; + match decode_positive_number(FIELD_CLOSE, val) { + Ok(v) => close = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else if key == cstr!("sharevolume") { + let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?; + match decode_non_negative_number(FIELD_SHARE_VOLUME, val) { + Ok(v) => volume = Some(v), + Err(err) => { + if first_semantic_err.is_none() { + first_semantic_err = Some(err); + } + } + } + } else { + // Validate skipped top-level payloads (including adjustedopen..adjustedclose and + // avolume) via borrowed `RawBsonRef` views (zero allocation) so malformed bytes still + // reject the document as `CorruptBson` at its frame offset. + elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { + offset, + detail: format!("field '{}': {err}", key.as_str()), + })?; + } + } + + if let Some(err) = first_semantic_err { + return Err(err); + } + + let Some(qm_search_code) = qm_search_code else { + return Err(BsonQmIntradayError::MissingField { + field: FIELD_QM_SEARCH_CODE, + }); + }; + let Some(ts) = ts else { + return Err(BsonQmIntradayError::MissingField { + field: FIELD_TIMESTAMP, + }); + }; + let Some(open) = open else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_OPEN }); + }; + let Some(high) = high else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_HIGH }); + }; + let Some(low) = low else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_LOW }); + }; + let Some(close) = close else { + return Err(BsonQmIntradayError::MissingField { field: FIELD_CLOSE }); + }; + let Some(volume) = volume else { + return Err(BsonQmIntradayError::MissingField { + field: FIELD_SHARE_VOLUME, + }); + }; + + Ok(RawQmIntradayBar { + qm_search_code, + ts, + open, + high, + low, + close, + volume, + }) +} + +/// Decodes a single `&RawDocument` representing a `qmIntraday` MongoDB document in one forward +/// pass without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_qm_intraday_doc<'a>( + doc: &'a RawDocument, +) -> Result, BsonQmIntradayError> { + decode_qm_intraday_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawQmIntradayBar`]. +pub fn decode_qm_intraday_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonQmIntradayError> { + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_qm_intraday_doc_at(doc, 0) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_intraday_doc`], +/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected +/// document without aborting the stream on recoverable per-document errors. +/// +/// Stops at an unrecoverable frame length or truncated tail and counts it once. +/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. +pub fn decode_qm_intraday_buffer<'a, F, E>( + buf: &'a [u8], + mut on_bar: F, + mut on_error: E, +) -> BsonQmIntradayDecodeStats +where + F: FnMut(RawQmIntradayBar<'a>), + E: FnMut(usize, BsonQmIntradayError), +{ + let mut stats = BsonQmIntradayDecodeStats::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_qm_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_qm_intraday_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_qm_intraday_tests.rs b/tools/curate-etl/src/bson_qm_intraday_tests.rs new file mode 100644 index 00000000..e9c78fe3 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_intraday_tests.rs @@ -0,0 +1,757 @@ +use bson::oid::ObjectId; +use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::{DateTime, Timestamp}; + +use super::*; + +fn make_valid_doc( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(timestamp_ms)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), sharevolume); + doc +} + +fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), timestamp); + doc.append(cstr!("open"), 84.10_f64); + doc.append(cstr!("high"), 84.55_f64); + doc.append(cstr!("low"), 84.02_f64); + doc.append(cstr!("close"), 84.40_f64); + doc.append(cstr!("sharevolume"), 12_500.0_f64); + doc +} + +#[test] +fn decodes_raw_fields_ignoring_differing_adjusted_fields_with_zero_copy_key_and_mappers() { + // 2024-06-07T13:30:00.375Z (nonzero milliseconds to verify exact * 1_000 scaling) + const TS_MS: i64 = 1_717_767_000_375; + const EXPECTED_TS_MICROS: i64 = 1_717_767_000_375_000; + const VERBATIM_KEY: &str = " SHOP:CA "; + + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("provider"), "quotemedia"); + nested.append(cstr!("interval"), 1_i32); + + let mut tags = RawArrayBuf::new(); + tags.push("ca"); + tags.push("1m"); + + let mut doc = RawDocumentBuf::new(); + doc.append( + cstr!("_id"), + ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ); + doc.append(cstr!("symbol"), "SHOP"); + doc.append(cstr!("exchange"), "TSX"); + doc.append(cstr!("qmSearchCode"), VERBATIM_KEY); + doc.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); + doc.append(cstr!("timestamp"), DateTime::from_millis(TS_MS)); + // Mixed numeric encodings for raw fields: + doc.append(cstr!("open"), 84_i32); + doc.append(cstr!("high"), 85_i64); + doc.append(cstr!("low"), 83.75_f64); + doc.append(cstr!("close"), 84.50_f64); + doc.append(cstr!("sharevolume"), 12_500_i64); + // Deliberately different adjusted fields that must be ignored: + doc.append(cstr!("adjustedopen"), 8.40_f64); + doc.append(cstr!("adjustedhigh"), 8.50_f64); + doc.append(cstr!("adjustedlow"), 8.375_f64); + doc.append(cstr!("adjustedclose"), 8.45_f64); + doc.append(cstr!("avolume"), 125_000.0_f64); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let bytes = doc.as_bytes(); + let buf_start = bytes.as_ptr() as usize; + let buf_end = buf_start + bytes.len(); + + let from_doc = decode_qm_intraday_doc(&doc).unwrap(); + let from_bytes = decode_qm_intraday_bytes(bytes).unwrap(); + assert_eq!(from_doc, from_bytes); + + for bar in [from_doc, from_bytes] { + assert_eq!(bar.qm_search_code, VERBATIM_KEY); + assert_eq!(bar.ts, EXPECTED_TS_MICROS); + assert_eq!(bar.open.to_bits(), 84.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 85.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 83.75_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 84.50_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 12_500.0_f64.to_bits()); + + // Zero-copy proof: borrowed key slice points inside the input BSON buffer. + let key_start = bar.qm_search_code.as_ptr() as usize; + let key_end = key_start + bar.qm_search_code.len(); + assert!( + key_start >= buf_start && key_end <= buf_end, + "expected qm_search_code pointer {key_start:#x}..{key_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" + ); + } + + // Verify into_eod_intraday_bar and try_into_eod_intraday_bar preserve raw OHLCV verbatim. + let mut seen_into: Option<(&str, i64)> = None; + let mapped = from_doc.into_eod_intraday_bar(|code, ts| { + seen_into = Some((code, ts)); + 42_u64 + }); + assert_eq!(seen_into, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); + assert_eq!(mapped.key, 42_u64); + assert_eq!(mapped.ts, EXPECTED_TS_MICROS); + assert_eq!(mapped.open.to_bits(), 84.0_f64.to_bits()); + assert_eq!(mapped.high.to_bits(), 85.0_f64.to_bits()); + assert_eq!(mapped.low.to_bits(), 83.75_f64.to_bits()); + assert_eq!(mapped.close.to_bits(), 84.50_f64.to_bits()); + assert_eq!(mapped.volume.to_bits(), 12_500.0_f64.to_bits()); + + let mut seen_try_some: Option<(&str, i64)> = None; + let try_some = from_doc.try_into_eod_intraday_bar(|code, ts| { + seen_try_some = Some((code, ts)); + Some(99_u64) + }); + assert_eq!(seen_try_some, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); + let try_some = try_some.unwrap(); + assert_eq!(try_some.key, 99_u64); + assert_eq!(try_some.ts, EXPECTED_TS_MICROS); + assert_eq!(try_some.open.to_bits(), 84.0_f64.to_bits()); + assert_eq!(try_some.high.to_bits(), 85.0_f64.to_bits()); + assert_eq!(try_some.low.to_bits(), 83.75_f64.to_bits()); + assert_eq!(try_some.close.to_bits(), 84.50_f64.to_bits()); + assert_eq!(try_some.volume.to_bits(), 12_500.0_f64.to_bits()); + + let try_none: Option> = from_doc.try_into_eod_intraday_bar(|code, ts| { + assert_eq!(code, VERBATIM_KEY); + assert_eq!(ts, EXPECTED_TS_MICROS); + None + }); + assert!(try_none.is_none()); +} + +#[test] +fn table_tests_all_seven_required_fields_for_omission_null_and_wrong_type() { + const ALL_FIELDS: [&str; 7] = [ + FIELD_QM_SEARCH_CODE, + FIELD_TIMESTAMP, + FIELD_OPEN, + FIELD_HIGH, + FIELD_LOW, + FIELD_CLOSE, + FIELD_SHARE_VOLUME, + ]; + + let append_valid = |doc: &mut RawDocumentBuf, field: &str| match field { + FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), "SHOP:CA"), + FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)), + FIELD_OPEN => doc.append(cstr!("open"), 10.0_f64), + FIELD_HIGH => doc.append(cstr!("high"), 11.0_f64), + FIELD_LOW => doc.append(cstr!("low"), 9.5_f64), + FIELD_CLOSE => doc.append(cstr!("close"), 10.5_f64), + FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), 100.0_f64), + other => unreachable!("unexpected field {other}"), + }; + + let append_override = |doc: &mut RawDocumentBuf, field: &str, val: RawBsonRef<'_>| match field { + FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), val), + FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), val), + FIELD_OPEN => doc.append(cstr!("open"), val), + FIELD_HIGH => doc.append(cstr!("high"), val), + FIELD_LOW => doc.append(cstr!("low"), val), + FIELD_CLOSE => doc.append(cstr!("close"), val), + FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), val), + other => unreachable!("unexpected field {other}"), + }; + + for target in ALL_FIELDS { + // 1. Omission -> MissingField + let mut missing = RawDocumentBuf::new(); + for f in ALL_FIELDS { + if f != target { + append_valid(&mut missing, f); + } + } + let err = decode_qm_intraday_doc(&missing).unwrap_err(); + assert_eq!(err, BsonQmIntradayError::MissingField { field: target }); + assert!(err.to_string().contains(target)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_missing_field, 1); + assert_eq!(st.rejected_total(), 1); + + // 2. Null -> WrongType(Null) + let mut with_null = RawDocumentBuf::new(); + for f in ALL_FIELDS { + if f == target { + append_override(&mut with_null, f, RawBsonRef::Null); + } else { + append_valid(&mut with_null, f); + } + } + let err = decode_qm_intraday_doc(&with_null).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::WrongType { + field: target, + actual: ElementType::Null, + } + ); + assert!(err.to_string().contains(target)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_wrong_type, 1); + assert_eq!(st.rejected_total(), 1); + + // 3. Another inappropriate BSON type -> WrongType + let (bad_val, expected_type) = match target { + FIELD_QM_SEARCH_CODE => (RawBsonRef::Int32(123), ElementType::Int32), + FIELD_TIMESTAMP => (RawBsonRef::Boolean(true), ElementType::Boolean), + _ => (RawBsonRef::String("10.0"), ElementType::String), + }; + let mut with_wrong = RawDocumentBuf::new(); + for f in ALL_FIELDS { + if f == target { + append_override(&mut with_wrong, f, bad_val); + } else { + append_valid(&mut with_wrong, f); + } + } + let err = decode_qm_intraday_doc(&with_wrong).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::WrongType { + field: target, + actual: expected_type, + } + ); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_wrong_type, 1); + assert_eq!(st.rejected_total(), 1); + } + + // Empty document checks missing-field order starts at qmSearchCode. + let empty_doc = RawDocumentBuf::new(); + assert_eq!( + decode_qm_intraday_doc(&empty_doc).unwrap_err(), + BsonQmIntradayError::MissingField { + field: FIELD_QM_SEARCH_CODE + } + ); +} + +#[test] +fn rejects_empty_and_whitespace_only_qm_search_code() { + for blank in ["", " ", " ", "\t\n\r "] { + let doc = make_valid_doc(blank, 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_empty_field, 1); + assert_eq!(st.rejected_total(), 1); + } +} + +#[test] +fn validates_timestamp_datetime_boundaries_and_rejects_substitutes() { + // Epoch zero is valid. + let epoch_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(0))); + assert_eq!(decode_qm_intraday_doc(&epoch_doc).unwrap().ts, 0); + + // Largest in-range millisecond timestamp (i64::MAX / 1_000) is valid. + let max_doc = + make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(MAX_TIMESTAMP_MILLIS))); + assert_eq!( + decode_qm_intraday_doc(&max_doc).unwrap().ts, + MAX_TIMESTAMP_MILLIS * 1_000 + ); + + // Negative and overflowing DateTime values -> InvalidTimestamp. + for bad_ms in [-1_i64, i64::MIN, MAX_TIMESTAMP_MILLIS + 1, i64::MAX] { + let doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(bad_ms))); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP + } + ); + assert!(err.to_string().contains(FIELD_TIMESTAMP)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_timestamp, 1); + assert_eq!(st.rejected_total(), 1); + } + + // Numeric, string, and BSON Timestamp substitutes -> WrongType. + let wrong_ts: [(RawBsonRef<'_>, ElementType); 6] = [ + (RawBsonRef::Int32(1_717_767_000), ElementType::Int32), + (RawBsonRef::Int64(1_717_767_000_000), ElementType::Int64), + (RawBsonRef::Double(1_717_767_000_000.0), ElementType::Double), + ( + RawBsonRef::String("2024-06-07T13:30:00Z"), + ElementType::String, + ), + ( + RawBsonRef::Timestamp(Timestamp { + time: 1_717_767_000, + increment: 1, + }), + ElementType::Timestamp, + ), + (RawBsonRef::Null, ElementType::Null), + ]; + for (val, expected_type) in wrong_ts { + let doc = make_doc_with_timestamp(val); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmIntradayError::WrongType { + field: FIELD_TIMESTAMP, + actual: expected_type, + } + ); + } +} + +#[test] +fn validates_ohlc_and_sharevolume_domains_and_normalizes_negative_zero_volume() { + let ohlc_fields = [FIELD_OPEN, FIELD_HIGH, FIELD_LOW, FIELD_CLOSE]; + + for target in ohlc_fields { + let build_with = |val: RawBsonRef<'_>| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + for (name, key) in [ + (FIELD_OPEN, cstr!("open")), + (FIELD_HIGH, cstr!("high")), + (FIELD_LOW, cstr!("low")), + (FIELD_CLOSE, cstr!("close")), + (FIELD_SHARE_VOLUME, cstr!("sharevolume")), + ] { + if name == target { + doc.append(key, val); + } else { + doc.append(key, 10.0_f64); + } + } + doc + }; + + for bad_num in [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Double(-1.25), + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Int32(0), + RawBsonRef::Int32(-5), + RawBsonRef::Int64(0), + RawBsonRef::Int64(-5), + ] { + let doc = build_with(bad_num); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + match &err { + BsonQmIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), + other => panic!("expected InvalidNumber for {target}, got {other:?}"), + } + assert!(err.to_string().contains(target)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_number, 1); + assert_eq!(st.rejected_total(), 1); + } + } + + let build_with_vol = |val: RawBsonRef<'_>| { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + 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!("sharevolume"), val); + doc + }; + + // Zero sharevolume in +0.0, -0.0, Int32(0), Int64(0) canonicalizes to +0.0. + for zero_vol in [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Int32(0), + RawBsonRef::Int64(0), + ] { + let doc = build_with_vol(zero_vol); + let decoded = decode_qm_intraday_doc(&doc).unwrap(); + assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); + } + + // Negative and non-finite sharevolume -> InvalidNumber. + 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_qm_intraday_doc(&doc).unwrap_err(); + match &err { + BsonQmIntradayError::InvalidNumber { field, .. } => { + assert_eq!(*field, FIELD_SHARE_VOLUME) + } + other => panic!("expected InvalidNumber for sharevolume, got {other:?}"), + } + assert!(err.to_string().contains(FIELD_SHARE_VOLUME)); + let mut st = BsonQmIntradayDecodeStats::default(); + st.record_error(&err); + assert_eq!(st.rejected_invalid_number, 1); + assert_eq!(st.rejected_total(), 1); + } +} + +#[test] +fn duplicate_fields_and_semantic_vs_corrupt_precedence() { + // 1. All duplicate occurrences valid -> last valid value wins. + let mut dup_valid = RawDocumentBuf::new(); + dup_valid.append(cstr!("qmSearchCode"), "FIRST:CA"); + dup_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); + dup_valid.append(cstr!("open"), 10.0_f64); + dup_valid.append(cstr!("high"), 11.0_f64); + dup_valid.append(cstr!("low"), 9.0_f64); + dup_valid.append(cstr!("close"), 10.5_f64); + dup_valid.append(cstr!("sharevolume"), 100.0_f64); + dup_valid.append(cstr!("qmSearchCode"), "SECOND:CA"); + dup_valid.append(cstr!("timestamp"), DateTime::from_millis(2_500)); + dup_valid.append(cstr!("open"), 20.0_f64); + dup_valid.append(cstr!("high"), 22.0_f64); + dup_valid.append(cstr!("low"), 19.0_f64); + dup_valid.append(cstr!("close"), 21.5_f64); + dup_valid.append(cstr!("sharevolume"), 250_i32); + + let bar = decode_qm_intraday_doc(&dup_valid).unwrap(); + assert_eq!(bar.qm_search_code, "SECOND:CA"); + assert_eq!(bar.ts, 2_500_000); + assert_eq!(bar.open.to_bits(), 20.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 22.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 19.0_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 21.5_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 250.0_f64.to_bits()); + + // 2. A valid duplicate cannot erase an earlier semantic error. + let mut err_then_valid = RawDocumentBuf::new(); + err_then_valid.append(cstr!("qmSearchCode"), " "); + err_then_valid.append(cstr!("qmSearchCode"), "SHOP:CA"); + err_then_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); + err_then_valid.append(cstr!("open"), 10.0_f64); + err_then_valid.append(cstr!("high"), 11.0_f64); + err_then_valid.append(cstr!("low"), 9.0_f64); + err_then_valid.append(cstr!("close"), 10.5_f64); + err_then_valid.append(cstr!("sharevolume"), 100.0_f64); + assert_eq!( + decode_qm_intraday_doc(&err_then_valid).unwrap_err(), + BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + + // 3. First semantic error survives a second semantic error. + let mut two_errors = RawDocumentBuf::new(); + two_errors.append(cstr!("qmSearchCode"), "SHOP:CA"); + two_errors.append(cstr!("timestamp"), DateTime::from_millis(-1)); + two_errors.append(cstr!("open"), -5.0_f64); + two_errors.append(cstr!("high"), RawBsonRef::Null); + two_errors.append(cstr!("low"), 9.0_f64); + two_errors.append(cstr!("close"), 10.5_f64); + two_errors.append(cstr!("sharevolume"), 100.0_f64); + assert_eq!( + decode_qm_intraday_doc(&two_errors).unwrap_err(), + BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP + } + ); + + // 4. Malformed UTF-8 in a later skipped field overrides an earlier semantic error as CorruptBson. + const MARKER: &[u8] = b"2024-06-07 09:30:00"; + let mut semantic_then_corrupt = RawDocumentBuf::new(); + semantic_then_corrupt.append(cstr!("qmSearchCode"), " "); // earlier EmptyField + semantic_then_corrupt.append(cstr!("timestamp"), DateTime::from_millis(-5)); // second semantic err + semantic_then_corrupt.append(cstr!("open"), 10.0_f64); + semantic_then_corrupt.append(cstr!("high"), 11.0_f64); + semantic_then_corrupt.append(cstr!("low"), 9.0_f64); + semantic_then_corrupt.append(cstr!("close"), 10.5_f64); + semantic_then_corrupt.append(cstr!("sharevolume"), 100.0_f64); + semantic_then_corrupt.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); + + let mut corrupt_bytes = semantic_then_corrupt.as_bytes().to_vec(); + let pos = corrupt_bytes + .windows(MARKER.len()) + .position(|w| w == MARKER) + .expect("startdatetime marker must exist"); + corrupt_bytes[pos + 4] = 0xFF; + + match decode_qm_intraday_bytes(&corrupt_bytes) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!( + detail.contains("startdatetime"), + "expected offending skipped field name in detail, got: {detail}" + ); + } + other => panic!("expected CorruptBson overriding earlier semantic error, got {other:?}"), + } +} + +#[test] +fn rejects_truncated_corrupt_and_trailing_single_doc_bytes_as_corrupt_bson() { + // Truncated header (< 4 bytes) + match decode_qm_intraday_bytes(&[0x10, 0x00]) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains("truncated"), "detail={detail}"); + } + other => panic!("expected CorruptBson for truncated header, got {other:?}"), + } + + // Declared length < 5 + match decode_qm_intraday_bytes(&[4, 0, 0, 0]) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains('4'), "detail={detail}"); + } + other => panic!("expected CorruptBson for length < 5, got {other:?}"), + } + + let valid = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); + + // Truncated body + let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; + match decode_qm_intraday_bytes(truncated) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains("truncated"), "detail={detail}"); + } + other => panic!("expected CorruptBson for truncated body, got {other:?}"), + } + + // Trailing extra bytes on single-doc decode + let mut with_trailing = valid.as_bytes().to_vec(); + with_trailing.push(0x00); + match decode_qm_intraday_bytes(&with_trailing) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains("length"), "detail={detail}"); + } + other => panic!("expected CorruptBson for trailing bytes, got {other:?}"), + } + + // Malformed BSON (bad trailing NUL terminator) + let mut bad_term = valid.as_bytes().to_vec(); + *bad_term.last_mut().unwrap() = 0xFF; + match decode_qm_intraday_bytes(&bad_term) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} + other => panic!("expected CorruptBson for bad terminator, got {other:?}"), + } +} + +#[test] +fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges_stats() { + // Empty buffer -> zero stats and no callbacks. + let mut empty_rows = 0usize; + let mut empty_errs = 0usize; + let empty_stats = decode_qm_intraday_buffer(&[], |_| empty_rows += 1, |_, _| empty_errs += 1); + assert_eq!(empty_stats, BsonQmIntradayDecodeStats::default()); + assert_eq!(empty_stats.rejected_total(), 0); + assert_eq!(empty_rows, 0); + assert_eq!(empty_errs, 0); + + let valid1 = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); + let empty_key = make_valid_doc(" ", 1_717_767_060_000, 84.5, 85.0, 84.0, 84.8, 500.0); + let bad_ts = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(-10))); + let bad_price = make_valid_doc("SHOP:CA", 1_717_767_180_000, 0.0, 85.0, 83.0, 84.0, 200.0); + + let mut wrong_type = RawDocumentBuf::new(); + wrong_type.append(cstr!("qmSearchCode"), "SHOP:CA"); + wrong_type.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_240_000)); + wrong_type.append(cstr!("open"), RawBsonRef::Null); + wrong_type.append(cstr!("high"), 85.0_f64); + wrong_type.append(cstr!("low"), 83.0_f64); + wrong_type.append(cstr!("close"), 84.0_f64); + wrong_type.append(cstr!("sharevolume"), 200.0_f64); + + let mut missing_field = RawDocumentBuf::new(); + missing_field.append(cstr!("qmSearchCode"), "SHOP:CA"); + missing_field.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_300_000)); + missing_field.append(cstr!("open"), 84.0_f64); + missing_field.append(cstr!("high"), 85.0_f64); + missing_field.append(cstr!("low"), 83.0_f64); + missing_field.append(cstr!("close"), 84.0_f64); + + // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer + // iteration recovers past the known frame boundary 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("X:CA", 1_717_767_360_000, 39.5, 40.0, 39.25, 39.75, -0.0); + + let mut batch1 = Vec::new(); + batch1.extend_from_slice(valid1.as_bytes()); + let off_empty = batch1.len(); + batch1.extend_from_slice(empty_key.as_bytes()); + let off_bad_ts = batch1.len(); + batch1.extend_from_slice(bad_ts.as_bytes()); + let off_bad_price = batch1.len(); + batch1.extend_from_slice(bad_price.as_bytes()); + + let mut batch2 = Vec::new(); + batch2.extend_from_slice(wrong_type.as_bytes()); + batch2.extend_from_slice(missing_field.as_bytes()); + batch2.extend_from_slice(&corrupt_framed); + batch2.extend_from_slice(valid2.as_bytes()); + + let mut full_buf = Vec::new(); + full_buf.extend_from_slice(&batch1); + let off_wrong_type = full_buf.len(); + full_buf.extend_from_slice(wrong_type.as_bytes()); + let off_missing = full_buf.len(); + full_buf.extend_from_slice(missing_field.as_bytes()); + let off_corrupt = full_buf.len(); + full_buf.extend_from_slice(&corrupt_framed); + full_buf.extend_from_slice(valid2.as_bytes()); + let off_trunc = full_buf.len(); + // Truncated tail: stops cleanly and is counted once. + full_buf.extend_from_slice(&valid2.as_bytes()[..10]); + + let run_once = |buf: &[u8]| { + let mut rows = Vec::new(); + let mut errors = Vec::new(); + let stats = decode_qm_intraday_buffer( + buf, + |bar| { + rows.push(( + bar.qm_search_code.to_owned(), + bar.ts, + bar.close.to_bits(), + bar.volume.to_bits(), + )) + }, + |offset, err| errors.push((offset, err)), + ); + (rows, errors, stats) + }; + + let (rows_a, errs_a, stats_a) = run_once(&full_buf); + let (rows_b, errs_b, stats_b) = run_once(&full_buf); + + // Deterministic replay produces identical rows, errors, offsets, and stats. + assert_eq!(rows_a, rows_b); + assert_eq!(errs_a, errs_b); + assert_eq!(stats_a, stats_b); + + assert_eq!( + rows_a, + vec![ + ( + "SHOP:CA".to_owned(), + 1_717_767_000_000_000, + 84.5_f64.to_bits(), + 1000.0_f64.to_bits(), + ), + ( + "X:CA".to_owned(), + 1_717_767_360_000_000, + 39.75_f64.to_bits(), + 0.0_f64.to_bits(), + ), + ] + ); + + assert_eq!(stats_a.docs_seen, 9); + assert_eq!(stats_a.rows_decoded, 2); + assert_eq!(stats_a.rejected_empty_field, 1); + assert_eq!(stats_a.rejected_invalid_timestamp, 1); + assert_eq!(stats_a.rejected_invalid_number, 1); + assert_eq!(stats_a.rejected_wrong_type, 1); + assert_eq!(stats_a.rejected_missing_field, 1); + assert_eq!(stats_a.rejected_corrupt_document, 2); // corrupt_framed + truncated tail + assert_eq!(stats_a.rejected_total(), 7); + assert_eq!(stats_a.docs_seen, stats_a.rows_decoded + stats_a.rejected_total()); + + assert_eq!(errs_a.len(), 7); + assert_eq!(errs_a[0].0, off_empty); + assert_eq!( + errs_a[0].1, + BsonQmIntradayError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert_eq!(errs_a[1].0, off_bad_ts); + assert_eq!( + errs_a[1].1, + BsonQmIntradayError::InvalidTimestamp { + field: FIELD_TIMESTAMP + } + ); + assert_eq!(errs_a[2].0, off_bad_price); + assert!(matches!( + errs_a[2].1, + BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, .. } + )); + assert_eq!(errs_a[3].0, off_wrong_type); + assert_eq!( + errs_a[3].1, + BsonQmIntradayError::WrongType { + field: FIELD_OPEN, + actual: ElementType::Null, + } + ); + assert_eq!(errs_a[4].0, off_missing); + assert_eq!( + errs_a[4].1, + BsonQmIntradayError::MissingField { + field: FIELD_SHARE_VOLUME + } + ); + assert_eq!(errs_a[5].0, off_corrupt); + assert!(matches!( + &errs_a[5].1, + BsonQmIntradayError::CorruptBson { offset, .. } if *offset == off_corrupt + )); + assert_eq!(errs_a[6].0, off_trunc); + assert!(matches!( + &errs_a[6].1, + BsonQmIntradayError::CorruptBson { offset, detail } + if *offset == off_trunc && detail.contains("truncated") + )); + + // Verify merge and AddAssign match decoding frame-aligned batches separately. + let mut batch2_with_trunc = batch2.clone(); + batch2_with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); + let s1 = decode_qm_intraday_buffer(&batch1, |_| {}, |_, _| {}); + let s2 = decode_qm_intraday_buffer(&batch2_with_trunc, |_| {}, |_, _| {}); + let mut merged = s1; + merged.merge(&s2); + assert_eq!(merged, stats_a); + + let mut added = s1; + added += s2; + assert_eq!(added, stats_a); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6b795fef..e853e210 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -9,6 +9,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_intraday; pub mod bson_qm_prices; pub mod bson_stream; pub mod bson_te_market_data; From 60f972bd53bb82b0ac9e4c2616344424bbb73d97 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:44:56 -0500 Subject: [PATCH 02/10] T-150: tests --- .../curate-etl/src/bson_qm_intraday_tests.rs | 343 +++++++++++++++++- 1 file changed, 339 insertions(+), 4 deletions(-) diff --git a/tools/curate-etl/src/bson_qm_intraday_tests.rs b/tools/curate-etl/src/bson_qm_intraday_tests.rs index e9c78fe3..b4638271 100644 --- a/tools/curate-etl/src/bson_qm_intraday_tests.rs +++ b/tools/curate-etl/src/bson_qm_intraday_tests.rs @@ -278,8 +278,9 @@ fn validates_timestamp_datetime_boundaries_and_rejects_substitutes() { assert_eq!(decode_qm_intraday_doc(&epoch_doc).unwrap().ts, 0); // Largest in-range millisecond timestamp (i64::MAX / 1_000) is valid. - let max_doc = - make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(MAX_TIMESTAMP_MILLIS))); + let max_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis( + MAX_TIMESTAMP_MILLIS, + ))); assert_eq!( decode_qm_intraday_doc(&max_doc).unwrap().ts, MAX_TIMESTAMP_MILLIS * 1_000 @@ -693,7 +694,10 @@ fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges assert_eq!(stats_a.rejected_missing_field, 1); assert_eq!(stats_a.rejected_corrupt_document, 2); // corrupt_framed + truncated tail assert_eq!(stats_a.rejected_total(), 7); - assert_eq!(stats_a.docs_seen, stats_a.rows_decoded + stats_a.rejected_total()); + assert_eq!( + stats_a.docs_seen, + stats_a.rows_decoded + stats_a.rejected_total() + ); assert_eq!(errs_a.len(), 7); assert_eq!(errs_a[0].0, off_empty); @@ -713,7 +717,10 @@ fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges assert_eq!(errs_a[2].0, off_bad_price); assert!(matches!( errs_a[2].1, - BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, .. } + BsonQmIntradayError::InvalidNumber { + field: FIELD_OPEN, + .. + } )); assert_eq!(errs_a[3].0, off_wrong_type); assert_eq!( @@ -755,3 +762,331 @@ fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges added += s2; assert_eq!(added, stats_a); } + +// --- QA edge cases (T-150) ------------------------------------------------------------------- + +fn find_marker(bytes: &[u8], marker: &[u8]) -> usize { + bytes + .windows(marker.len()) + .position(|w| w == marker) + .expect("marker must exist in fixture bytes") +} + +#[test] +fn corrupt_bytes_inside_an_adjusted_field_reject_the_document_as_corrupt_bson() { + // Proves adjusted fields are validated (not blindly skipped) even though they are never read: + // flip `adjustedclose` from Double (0x01) to String (0x02) so its 8 payload bytes are read as a + // bogus string length. + let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); + doc.append(cstr!("adjustedclose"), 8.45_f64); + doc.append(cstr!("avolume"), 10_000.0_f64); + let mut bytes = doc.as_bytes().to_vec(); + let key_pos = find_marker(&bytes, b"adjustedclose\0"); + assert_eq!( + bytes[key_pos - 1], + 0x01, + "fixture: element type byte precedes key" + ); + bytes[key_pos - 1] = 0x02; + + match decode_qm_intraday_bytes(&bytes) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} + other => panic!("expected CorruptBson for corrupt adjustedclose, got {other:?}"), + } +} + +#[test] +fn adjusted_fields_of_any_type_or_value_do_not_affect_raw_decode() { + // Adjusted fields that would fail raw validation (Null, negative, NaN, string) must be ignored. + let mut doc = make_valid_doc( + "RY:CA", + 1_717_767_000_000, + 130.0, + 131.0, + 129.5, + 130.5, + 2_000.0, + ); + doc.append(cstr!("adjustedopen"), RawBsonRef::Null); + doc.append(cstr!("adjustedhigh"), -1.0_f64); + doc.append(cstr!("adjustedlow"), f64::NAN); + doc.append(cstr!("adjustedclose"), "n/a"); + doc.append(cstr!("avolume"), -5_i64); + + let bar = decode_qm_intraday_doc(&doc).unwrap(); + assert_eq!(bar.qm_search_code, "RY:CA"); + assert_eq!(bar.ts, 1_717_767_000_000_000); + assert_eq!(bar.open.to_bits(), 130.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 131.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 129.5_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 130.5_f64.to_bits()); + assert_eq!(bar.volume.to_bits(), 2_000.0_f64.to_bits()); +} + +#[test] +fn adjusted_only_document_is_missing_raw_fields_not_silently_substituted() { + // A doc carrying only adjusted prices/volume must not fall back to them. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("adjustedopen"), 8.4_f64); + doc.append(cstr!("adjustedhigh"), 8.5_f64); + doc.append(cstr!("adjustedlow"), 8.3_f64); + doc.append(cstr!("adjustedclose"), 8.45_f64); + doc.append(cstr!("avolume"), 125_000.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { field: FIELD_OPEN } + ); + + // Same with only `volume`/`avolume` instead of `sharevolume`. + let mut doc = make_doc_without_sharevolume(); + doc.append(cstr!("volume"), 100.0_f64); + doc.append(cstr!("avolume"), 100.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { + field: FIELD_SHARE_VOLUME + } + ); +} + +fn make_doc_without_sharevolume() -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + 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 +} + +#[test] +fn field_names_match_case_sensitively() { + // `Open` / `QmSearchCode` are unknown fields, so the real ones are reported missing. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("QmSearchCode"), "SHOP:CA"); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + 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!("sharevolume"), 1.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { field: FIELD_OPEN } + ); +} + +#[test] +fn field_order_does_not_change_the_decoded_bar() { + let forward = make_valid_doc( + "SHOP:CA", + 1_717_767_000_123, + 84.0, + 85.0, + 83.5, + 84.5, + 1_000.0, + ); + + let mut reversed = RawDocumentBuf::new(); + reversed.append(cstr!("sharevolume"), 1_000.0_f64); + reversed.append(cstr!("close"), 84.5_f64); + reversed.append(cstr!("low"), 83.5_f64); + reversed.append(cstr!("high"), 85.0_f64); + reversed.append(cstr!("open"), 84.0_f64); + reversed.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_123)); + reversed.append(cstr!("qmSearchCode"), "SHOP:CA"); + + assert_eq!( + decode_qm_intraday_doc(&forward).unwrap(), + decode_qm_intraday_doc(&reversed).unwrap() + ); +} + +#[test] +fn missing_field_precedence_follows_declared_order_and_semantic_error_beats_missing() { + // close and sharevolume both missing -> close (earlier in declared order) is reported. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "SHOP:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + assert_eq!( + decode_qm_intraday_doc(&doc).unwrap_err(), + BsonQmIntradayError::MissingField { field: FIELD_CLOSE } + ); + + // A semantic error on a late field wins over an earlier-ordered missing field. + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + doc.append(cstr!("sharevolume"), -1.0_f64); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert!( + matches!( + err, + BsonQmIntradayError::InvalidNumber { + field: FIELD_SHARE_VOLUME, + .. + } + ), + "got {err:?}" + ); +} + +#[test] +fn invalid_duplicate_after_valid_value_still_rejects_the_document() { + // Valid open followed by an invalid duplicate open: the semantic error must be kept. + let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + doc.append(cstr!("open"), 0.0_f64); + let err = decode_qm_intraday_doc(&doc).unwrap_err(); + assert!( + matches!(err, BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, value } if value == 0.0), + "got {err:?}" + ); +} + +#[test] +fn malformed_utf8_in_qm_search_code_is_corrupt_bson_naming_the_field() { + let doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let mut bytes = doc.as_bytes().to_vec(); + let pos = find_marker(&bytes, b"SHOP:CA"); + bytes[pos + 1] = 0xFF; + match decode_qm_intraday_bytes(&bytes) { + Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { + assert!(detail.contains(FIELD_QM_SEARCH_CODE), "detail={detail}"); + } + other => panic!("expected CorruptBson for invalid UTF-8 key, got {other:?}"), + } +} + +#[test] +fn non_ascii_and_large_integer_values_are_preserved_exactly() { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "BCE.PR.Ä:CA"); + doc.append(cstr!("timestamp"), DateTime::from_millis(1_735_689_599_999)); + doc.append(cstr!("open"), 1_i32); + doc.append(cstr!("high"), i32::MAX); + doc.append(cstr!("low"), 1_i64); + doc.append(cstr!("close"), 9_007_199_254_740_992_i64); // 2^53, exact in f64 + doc.append(cstr!("sharevolume"), i64::MAX); + + let bar = decode_qm_intraday_doc(&doc).unwrap(); + assert_eq!(bar.qm_search_code, "BCE.PR.Ä:CA"); + assert_eq!(bar.ts, 1_735_689_599_999_000); + assert_eq!(bar.open, 1.0); + assert_eq!(bar.high, f64::from(i32::MAX)); + assert_eq!(bar.low, 1.0); + assert_eq!(bar.close, 9_007_199_254_740_992.0); + assert_eq!(bar.volume, i64::MAX as f64); + assert!(bar.volume.is_finite()); +} + +#[test] +fn display_messages_name_field_and_domain() { + let vol = BsonQmIntradayError::InvalidNumber { + field: FIELD_SHARE_VOLUME, + value: -1.0, + } + .to_string(); + assert!(vol.contains("sharevolume") && vol.contains(">= 0"), "{vol}"); + let price = BsonQmIntradayError::InvalidNumber { + field: FIELD_HIGH, + value: 0.0, + } + .to_string(); + assert!( + price.contains("high") && price.contains("> 0") && !price.contains(">= 0"), + "{price}" + ); + let corrupt = BsonQmIntradayError::CorruptBson { + offset: 77, + detail: "x".into(), + } + .to_string(); + assert!(corrupt.contains("77"), "{corrupt}"); +} + +#[test] +fn buffer_stops_at_unrecoverable_frame_length_counting_it_once_and_keeps_earlier_rows() { + let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); + let c = make_valid_doc("C:CA", 1_717_767_120_000, 30.0, 31.0, 29.0, 30.5, 300.0); + + let mut buf = Vec::new(); + buf.extend_from_slice(a.as_bytes()); + buf.extend_from_slice(b.as_bytes()); + let bad_off = buf.len(); + buf.extend_from_slice(&3_i32.to_le_bytes()); // declared length < 5: no boundary known + buf.extend_from_slice(c.as_bytes()); // must NOT be decoded (cannot resync safely) + + let mut codes = Vec::new(); + let mut errors = Vec::new(); + let stats = decode_qm_intraday_buffer( + &buf, + |bar| codes.push(bar.qm_search_code), + |off, err| errors.push((off, err)), + ); + + assert_eq!(codes, vec!["A:CA", "B:CA"]); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, bad_off); + assert!(matches!( + &errors[0].1, + BsonQmIntradayError::CorruptBson { offset, .. } if *offset == bad_off + )); + assert_eq!(stats.docs_seen, 3); + assert_eq!(stats.rows_decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); +} + +#[test] +fn buffer_rows_borrow_keys_from_the_input_buffer() { + let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); + let mut buf = Vec::new(); + buf.extend_from_slice(a.as_bytes()); + buf.extend_from_slice(b.as_bytes()); + let range = buf.as_ptr_range(); + + let mut ptrs = Vec::new(); + let stats = decode_qm_intraday_buffer( + &buf, + |bar| ptrs.push(bar.qm_search_code.as_ptr()), + |_, err| panic!("unexpected error {err:?}"), + ); + assert_eq!(stats.rows_decoded, 2); + assert_eq!(ptrs.len(), 2); + for p in ptrs { + assert!( + range.contains(&p), + "key pointer {p:?} outside input buffer {range:?}" + ); + } +} + +#[test] +fn single_valid_doc_buffer_with_short_trailing_bytes_decodes_row_then_counts_truncated_tail() { + let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); + let mut buf = a.as_bytes().to_vec(); + let tail_off = buf.len(); + buf.extend_from_slice(&[0x00, 0x00]); + + let mut rows = 0usize; + let mut errors = Vec::new(); + let stats = decode_qm_intraday_buffer(&buf, |_| rows += 1, |off, err| errors.push((off, err))); + assert_eq!(rows, 1); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].0, tail_off); + assert!(matches!( + errors[0].1, + BsonQmIntradayError::CorruptBson { .. } + )); + assert_eq!(stats.docs_seen, 2); + assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); +} From b49bbd59b405211910eeb7cfdafb1a42ddf3c423 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:17:04 -0500 Subject: [PATCH 03/10] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 340 +++++- libs/research/test/mcp-analyze-signal.test.ts | 1081 ++++++++++++++++- libs/research/test/mcp-copilot-server.test.ts | 220 +++- 3 files changed, 1554 insertions(+), 87 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 090e9e32..8a803e12 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -14,10 +14,14 @@ import { type TableRow, type VaultFenceContext, } from '../../market-data-store'; -import { UNIVERSE_REFS } from '../../market-data-store-duckdb'; +import { + FUNDAMENTALS_PIT_VALUE_FIELDS, + type FundamentalsPitValueField, + UNIVERSE_REFS, +} from '../../market-data-store-duckdb'; import { SHORTS_SIGNAL_FIELDS, - type ShortsSignalField, + type SignalObservation, type SignalPanelDiagnostics, SignalPanelError, type SignalPanelErrorCode, @@ -44,8 +48,8 @@ import { UNIVERSE_MARKETS, type UniverseMarket, } from '../../trial-ledger'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; +import type { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server'; import { EXCLUSIVE_LISTING_SELECTOR_MESSAGE, MCP_MAX_LISTING_IDS, @@ -53,6 +57,7 @@ import { createUniverseFieldSchema, fenceVaultQueryBounds, formatMappedStoreError, + formatUtcIsoWithMicros, hasExclusiveListingSelector, isValidUtcBoundString, resolvePreStartUniverseDate, @@ -69,6 +74,9 @@ export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252; /** Maximum number of latest dated observations exposed in the tool response preview. */ export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; +/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ +export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; + const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const AGENT_PRINCIPAL_RE = /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; @@ -84,22 +92,37 @@ const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC const shortsSignalSpecSchema = z .object({ - source: z.literal('shorts').describe('Signal data source (currently "shorts").'), + source: z.literal('shorts').describe('Signal data source ("shorts").'), field: z .enum(SHORTS_SIGNAL_FIELDS) .describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'), }) .strict() - .describe('Discriminated signal source and field specification.'); + .describe('Short-interest signal specification.'); -/** - * Strict Zod input schema for the `analyze_signal` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and - * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them - * or any other unknown top-level or nested key. - */ -export const analyzeSignalInputSchema = z +const fundamentalsSignalSpecSchema = z + .object({ + source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'), + field: z + .enum(FUNDAMENTALS_PIT_VALUE_FIELDS) + .describe( + 'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).' + ), + allowEstimatedLag: z + .boolean() + .default(false) + .describe( + 'Whether to include fundamentals snapshots with estimated publication lag (default false).' + ), + }) + .strict() + .describe('Point-in-time fundamentals signal specification.'); + +const signalSpecSchema = z + .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) + .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); + +const analyzeSignalSharedFieldsSchema = z .object({ listingIds: createListingIdsFieldSchema( 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' @@ -118,7 +141,6 @@ export const analyzeSignalInputSchema = z .describe( 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' ), - signal: shortsSignalSpecSchema, horizonSessions: z .number() .int() @@ -159,6 +181,19 @@ export const analyzeSignalInputSchema = z .default('raw') .describe('Bar price adjustment mode (default raw).'), }) + .strict(); + +/** + * Strict Zod input schema for the `analyze_signal` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and + * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them + * or any other unknown top-level or nested key. + */ +export const analyzeSignalInputSchema = analyzeSignalSharedFieldsSchema + .extend({ + signal: signalSpecSchema, + }) .strict() .superRefine((data, ctx) => { if (!hasExclusiveListingSelector(data)) { @@ -185,18 +220,62 @@ export const analyzeSignalInputSchema = z message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, }); } - } else if (data.signal.source === 'shorts' && data.universeMarket === 'FX') { + } else if (data.universeMarket === 'FX') { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['universeMarket'], message: - 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', + data.signal.source === 'shorts' + ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' + : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', }); } }); export type AnalyzeSignalInput = z.infer; +function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { + const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); + const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); + const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); + const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { + type: 'boolean' as const, + default: false, + }; + const signalProperty: JsonSchemaProperty = { + type: 'object', + description: signalSpecSchema.description, + properties: { + source: { + type: 'string', + enum: ['shorts', 'fundamentals'], + description: 'Signal data source ("shorts" or "fundamentals").', + }, + field: { + type: 'string', + enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], + description: 'Signal field name valid for the chosen source.', + }, + allowEstimatedLag: allowEstimatedLagProp, + }, + required: ['source', 'field'], + additionalProperties: false, + anyOf: [shortsBranch, fundamentalsBranch], + }; + + return { + type: 'object', + properties: { + ...sharedSchema.properties, + signal: signalProperty, + }, + required: [...(sharedSchema.required ?? []), 'signal'], + additionalProperties: false, + }; +} + +const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema(); + /** Server-side injected configuration for {@link createAnalyzeSignalTool}. */ export interface AnalyzeSignalToolOptions { readonly store: MarketDataStore; @@ -250,10 +329,7 @@ interface AnalyzeSignalResultBase { readonly scope: 'vault_fenced'; readonly vaultCutoffTs: number; readonly vaultCutoffDate: string; - readonly signal: { - readonly source: 'shorts'; - readonly field: ShortsSignalField; - }; + readonly signal: AnalyzeSignalInput['signal']; readonly horizonSessions: number; readonly adjustment: 'raw' | 'split' | 'total'; readonly universeMarket: UniverseMarket; @@ -463,6 +539,127 @@ function filterEligibleShortsTable( }; } +function deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] { + const latestByMonth = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + const sessionDate = utcDateOf(bar.ts); + const monthKey = sessionDate.slice(0, 7); + const prev = latestByMonth.get(monthKey); + if (prev === undefined || sessionDate > prev) { + latestByMonth.set(monthKey, sessionDate); + } + } + return [...latestByMonth.values()].sort(); +} + +function resolveSnapshotAsOf( + snapshotDate: string, + fencedAsOfMs: number, + canonicalAsOf: string +): { readonly asOf: string; readonly asOfMs: number } { + const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`); + if (fencedAsOfMs <= snapshotDayEndMs) { + return { + asOf: canonicalAsOf, + asOfMs: fencedAsOfMs, + }; + } + return { + asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999), + asOfMs: snapshotDayEndMs, + }; +} + +function appendEligibleFundamentalsObservations(params: { + readonly table: Table; + readonly field: FundamentalsPitValueField; + readonly listingIdSet: ReadonlySet; + readonly snapshotAsOfMs: number; + readonly fencedAsOfMs: number; + readonly vaultCutoffTs: number; + readonly seenKeys: Set; + readonly out: SignalObservation[]; +}): void { + const { + table, + field, + listingIdSet, + snapshotAsOfMs, + fencedAsOfMs, + vaultCutoffTs, + seenKeys, + out, + } = params; + + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + throw new SignalPanelError( + 'invalid_input', + 'Expected a fundamentals Table object with array columns and rows.' + ); + } + + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null) { + continue; + } + + const listingId = row.listing_id; + if ( + typeof listingId !== 'number' || + !Number.isSafeInteger(listingId) || + !listingIdSet.has(listingId) + ) { + continue; + } + + const knownAt = row.effective_known_at; + if ( + typeof knownAt !== 'number' || + !Number.isFinite(knownAt) || + !Number.isSafeInteger(knownAt) + ) { + continue; + } + if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) { + continue; + } + + const rawValue = row[field]; + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + continue; + } + + const normalizedListingId = listingId === 0 ? 0 : listingId; + const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; + const normalizedValue = rawValue === 0 ? 0 : rawValue; + const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; + if (seenKeys.has(dedupeKey)) { + continue; + } + seenKeys.add(dedupeKey); + out.push({ + listingId: normalizedListingId, + knownAt: normalizedKnownAt, + value: normalizedValue, + }); + } +} + function buildCanonicalStudyExpression(params: { readonly input: AnalyzeSignalInput; readonly listingIds: readonly number[]; @@ -479,6 +676,9 @@ function buildCanonicalStudyExpression(params: { version: 1, signalSource: input.signal.source, signalField: input.signal.field, + ...(input.signal.source === 'fundamentals' + ? { allowEstimatedLag: input.signal.allowEstimatedLag } + : {}), horizonSessions: input.horizonSessions, maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, adjustment: input.adjustment, @@ -553,10 +753,11 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { options.store === null || typeof options.store.bars !== 'function' || typeof options.store.shortsAsOf !== 'function' || + typeof options.store.fundamentalsAsOf !== 'function' || typeof options.store.universe !== 'function' ) { throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, and `universe`.', + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.', 'store' ); } @@ -602,8 +803,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT return defineMcpTool({ name: 'analyze_signal', description: - 'Run a Vault-fenced cross-sectional short-interest signal study and record eligible trials to trial_ledger.', + 'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', inputSchema: analyzeSignalInputSchema, + jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, async handler(input: AnalyzeSignalInput): Promise { try { const fenced = fenceVaultQueryBounds( @@ -633,14 +835,23 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT listingIds = sortAndDedupeListingIds(input.listingIds ?? []); } + const signalEcho: AnalyzeSignalInput['signal'] = + input.signal.source === 'shorts' + ? { + source: 'shorts', + field: input.signal.field, + } + : { + source: 'fundamentals', + field: input.signal.field, + allowEstimatedLag: input.signal.allowEstimatedLag, + }; + const basePayloadFields = { scope: 'vault_fenced' as const, vaultCutoffTs, vaultCutoffDate: fenced.vaultCutoffDate, - signal: { - source: input.signal.source, - field: input.signal.field, - }, + signal: signalEcho, horizonSessions: input.horizonSessions, adjustment: input.adjustment, universeMarket: input.universeMarket, @@ -684,13 +895,6 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT }) ); - const rawShortsTable = await store.shortsAsOf({ - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - const listingIdSet = new Set(listingIds); const eligibleBars = filterEligibleBars( rawBars, @@ -702,17 +906,65 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT fenced.vaultCutoffDate ); - const eligibleShortsTable = filterEligibleShortsTable( - rawShortsTable, - listingIdSet, - utcDateOf(fenced.fromMs), - utcDateOf(fenced.toMs), - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); + let signals: SignalObservation[]; + if (input.signal.source === 'shorts') { + const rawShortsTable = await store.shortsAsOf({ + listingIds, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + asOf: fenced.canonicalAsOf, + }); + const eligibleShortsTable = filterEligibleShortsTable( + rawShortsTable, + listingIdSet, + utcDateOf(fenced.fromMs), + utcDateOf(fenced.toMs), + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); + } else { + const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); + if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { + return { + content: [ + { + type: 'text', + text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`, + }, + ], + isError: true, + }; + } + + signals = []; + const seenKeys = new Set(); + for (const snapshotDate of snapshotDates) { + const snapshot = resolveSnapshotAsOf( + snapshotDate, + fenced.asOfMs, + fenced.canonicalAsOf + ); + const rawTable = await store.fundamentalsAsOf({ + listingIds, + fields: [input.signal.field], + asOf: snapshot.asOf, + allowEstimatedLag: input.signal.allowEstimatedLag, + }); + appendEligibleFundamentalsObservations({ + table: rawTable, + field: input.signal.field, + listingIdSet, + snapshotAsOfMs: snapshot.asOfMs, + fencedAsOfMs: fenced.asOfMs, + vaultCutoffTs, + seenKeys, + out: signals, + }); + } + } - const signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); const built = buildForwardReturnPanel({ bars: eligibleBars, signals, diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index e7840a38..40c52efd 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -10,11 +10,14 @@ import { } from '../src/market-data-store'; import { type BarsQuery, + FUNDAMENTALS_PIT_VALUE_FIELDS, + type FundamentalsAsOfQuery, MarketDataStoreNotImplementedError, type ShortsAsOfQuery, type UniverseQuery, } from '../src/market-data-store-duckdb'; import { + ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS, ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS, ANALYZE_SIGNAL_MAX_LISTING_IDS, ANALYZE_SIGNAL_MAX_SERIES_POINTS, @@ -23,9 +26,13 @@ import { createMcpServer, createQueryDataTool, } from '../src/mcp/index'; -import { buildForwardReturnPanel, shortsTableToSignalRows } from '../src/signal-panel'; +import { + type SignalObservation, + buildForwardReturnPanel, + shortsTableToSignalRows, +} from '../src/signal-panel'; import { analyzeSignal } from '../src/signal-study'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; +import { type TrialLedgerExecutor, canonicalExpressionHash } from '../src/trial-ledger'; const SEED = 20261129; const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; @@ -280,6 +287,7 @@ function buildCeoShortsFixture(options?: { interface FakeStoreState { readonly barsCalls: BarsQuery[]; readonly shortsCalls: ShortsAsOfQuery[]; + readonly fundamentalsCalls: FundamentalsAsOfQuery[]; readonly universeCalls: UniverseQuery[]; readonly store: MarketDataStore; } @@ -287,15 +295,18 @@ interface FakeStoreState { function createFakeStore(options?: { bars?: readonly BarRecord[]; shortsTable?: Table; + fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise; universeIds?: readonly number[]; universeResolver?: (q: UniverseQuery) => number[]; leaky?: boolean; barsError?: Error; shortsError?: Error; + fundamentalsError?: Error; universeError?: Error; }): FakeStoreState { const barsCalls: BarsQuery[] = []; const shortsCalls: ShortsAsOfQuery[] = []; + const fundamentalsCalls: FundamentalsAsOfQuery[] = []; const universeCalls: UniverseQuery[] = []; const allBars = options?.bars ?? []; @@ -394,7 +405,14 @@ function createFakeStore(options?: { crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, - fundamentalsAsOf() { + async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ + fundamentalsCalls.push(q); + if (options?.fundamentalsError !== undefined) { + throw options.fundamentalsError; + } + if (options?.fundamentalsResolver !== undefined) { + return options.fundamentalsResolver(q); + } throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); }, events() { @@ -408,7 +426,7 @@ function createFakeStore(options?: { }, }; - return { barsCalls, shortsCalls, universeCalls, store }; + return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; } async function callAnalyzeSignal(params: { @@ -1593,3 +1611,1058 @@ describe('MCP analyze_signal tool', () => { expect(dsrFailLedger.rows).toHaveLength(1); }); }); + +interface FundamentalsPitFixtureRow { + readonly listing_id: number; + readonly effective_known_at: number; + readonly known_at_source: string; + readonly has_estimated_lag: boolean; + readonly period_end: string; + readonly fiscal_period: string; + readonly currency: string; + readonly period_known_at: number; + readonly revenue: number | null; + readonly net_income: number | null; + readonly operating_cash_flow: number | null; + readonly total_assets: number | null; + readonly total_equity: number | null; + readonly shares_outstanding: number | null; + readonly ttm_revenue: number | null; + readonly ttm_net_income: number | null; + readonly ttm_operating_cash_flow: number | null; + readonly ttm_period_end: string | null; + readonly ttm_currency: string | null; + readonly ttm_has_estimated_lag: boolean; +} + +const FUNDAMENTALS_TTM_FIELDS = new Set([ + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +]); + +function queryFundamentalsFixtureRows( + rows: readonly FundamentalsPitFixtureRow[], + q: FundamentalsAsOfQuery +): Table { + const idSet = new Set(q.listingIds); + const asOfMs = Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf); + const allowEstimatedLag = q.allowEstimatedLag ?? false; + + const latestByListing = new Map(); + for (const row of rows) { + if (!idSet.has(row.listing_id) || row.effective_known_at > asOfMs) { + continue; + } + const prev = latestByListing.get(row.listing_id); + if (prev === undefined || row.effective_known_at > prev.effective_known_at) { + latestByListing.set(row.listing_id, row); + } + } + + const hasTtm = q.fields.some(f => FUNDAMENTALS_TTM_FIELDS.has(f)); + const columns: string[] = [ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + ...q.fields, + ...(hasTtm ? ['ttm_period_end', 'ttm_currency', 'ttm_has_estimated_lag'] : []), + ]; + + const outRows: TableRow[] = []; + const sortedIds = [...latestByListing.keys()].sort((a, b) => a - b); + for (const lid of sortedIds) { + const selected = latestByListing.get(lid)!; + if (!allowEstimatedLag && selected.has_estimated_lag) { + continue; + } + const projected: Record = { + listing_id: selected.listing_id, + effective_known_at: selected.effective_known_at, + known_at_source: selected.known_at_source, + has_estimated_lag: selected.has_estimated_lag, + period_end: selected.period_end, + fiscal_period: selected.fiscal_period, + currency: selected.currency, + period_known_at: selected.period_known_at, + }; + for (const field of q.fields) { + const val = selected[field as keyof FundamentalsPitFixtureRow] as number | null; + if (FUNDAMENTALS_TTM_FIELDS.has(field)) { + projected[field] = allowEstimatedLag || !selected.ttm_has_estimated_lag ? val : null; + } else { + projected[field] = val; + } + } + if (hasTtm) { + projected.ttm_period_end = + allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_period_end : null; + projected.ttm_currency = + allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_currency : null; + projected.ttm_has_estimated_lag = selected.ttm_has_estimated_lag; + } + outRows.push(projected); + } + + return { columns, rows: outRows }; +} + +function makeFundamentalsRow(params: { + listingId: number; + effectiveKnownAt: number; + periodEnd: string; + fiscalPeriod: string; + revenue: number; + ttmRevenue: number; + hasEstimatedLag?: boolean; + ttmHasEstimatedLag?: boolean; +}): FundamentalsPitFixtureRow { + const hasEstimatedLag = params.hasEstimatedLag ?? false; + const ttmHasEstimatedLag = params.ttmHasEstimatedLag ?? false; + return { + listing_id: params.listingId, + effective_known_at: params.effectiveKnownAt, + known_at_source: hasEstimatedLag ? 'estimated_lag' : 'sec_edgar_filing', + has_estimated_lag: hasEstimatedLag, + period_end: params.periodEnd, + fiscal_period: params.fiscalPeriod, + currency: 'USD', + period_known_at: params.effectiveKnownAt, + revenue: params.revenue, + net_income: Number((params.revenue * 0.15).toFixed(2)), + operating_cash_flow: Number((params.revenue * 0.2).toFixed(2)), + total_assets: Number((params.revenue * 4.0).toFixed(2)), + total_equity: Number((params.revenue * 1.8).toFixed(2)), + shares_outstanding: 10_000_000, + ttm_revenue: params.ttmRevenue, + ttm_net_income: Number((params.ttmRevenue * 0.15).toFixed(2)), + ttm_operating_cash_flow: Number((params.ttmRevenue * 0.2).toFixed(2)), + ttm_period_end: params.periodEnd, + ttm_currency: 'USD', + ttm_has_estimated_lag: ttmHasEstimatedLag, + }; +} + +// Seeded fundamentals study fixture metadata (pinned for reproducibility): +// - Dataset ID: `synthetic:mcp-analyze-signal-fundamentals:seed-20261202:v1` +// - Tool version: `mcp:analyze_signal:v1` +// - Seed: `20261202` (Mulberry32 PRNG) +// - Universe: 12 synthetic US equity listings (`70001..70012`, USD, 21:00 UTC close) +// - Pre-Vault window: 2023-01-02..2023-06-30 (130 business sessions), Vault cutoff: 2023-07-03T00:00:00.000Z +// - Adjustment: `raw`, horizon: `5` sessions, modeled execution/transaction costs: `0` +// - Ownership: Quant research owns evidence; Director owns adoption. +const FUNDAMENTALS_FIXTURE_SEED = 20261202; + +function buildFundamentalsStudyFixture(): { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly preCutoffSessions: number; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: BarRecord[]; + readonly fundamentalsRows: FundamentalsPitFixtureRow[]; +} { + const rand = createSeededRng(FUNDAMENTALS_FIXTURE_SEED); + const listingCount = 12; + const preCutoffSessions = 130; + const postCutoffSessions = 10; + const allDates = makeBusinessDates('2023-01-02', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); + + const fundamentalsRows: FundamentalsPitFixtureRow[] = []; + // Monthly PIT releases across 6 pre-cutoff months + 1 post-cutoff release + const releaseDates = [ + { date: '2023-01-10', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, + { date: '2023-02-15', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, + { date: '2023-04-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, + { date: '2023-05-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, + { date: vaultCutoffDate, periodEnd: '2023-06-30', fiscalPeriod: 'Q2' }, + ]; + + const activeScore = new Float64Array(listingCount); + for (let rIdx = 0; rIdx < releaseDates.length; rIdx += 1) { + const rel = releaseDates[rIdx]!; + const knownAt = makeUtcMs(rel.date, 13); // 08:00 ET pre-close + for (let l = 0; l < listingCount; l += 1) { + const rev = 100 + l * 25 + rIdx * 10 + Math.round((rand() * 2 - 1) * 40); + const ttm = rev * 4 + (l % 3) * 15; + fundamentalsRows.push( + makeFundamentalsRow({ + listingId: listingIds[l]!, + effectiveKnownAt: knownAt, + periodEnd: rel.periodEnd, + fiscalPeriod: rel.fiscalPeriod, + revenue: rev, + ttmRevenue: ttm, + }) + ); + } + } + + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 20 + l * 3; + } + + const bars: BarRecord[] = []; + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingCount; l += 1) { + activeScore[l] = (l - listingCount / 2) / listingCount; + const dailyRet = 0.002 * activeScore[l]! + (rand() * 2 - 1) * 0.01; + prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 80_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + preCutoffSessions, + vaultCutoffDate, + vaultCutoffTs, + bars, + fundamentalsRows, + }; +} + +describe('MCP analyze_signal tool — fundamentals source', () => { + test('tools/list advertises strict signal discriminated branches and rejects invalid fundamentals inputs with zero store/ledger calls', async () => { + const cutoffTs = makeUtcMs('2025-03-31', 0); + const fakeStore = createFakeStore(); + const fakeLedger = createFakeTrialLedger(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultContext: { vaultCutoffTs: cutoffTs }, + principalId: AGENT_PRINCIPAL, + }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 'list-fund', method: 'tools/list' }) + ); + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + properties: { + signal: { + type: string; + additionalProperties: boolean; + properties: Record; + anyOf: { + additionalProperties: boolean; + properties: Record; + }[]; + }; + }; + }; + }[]; + }; + }; + + const tool = listParsed.result.tools[0]!; + expect(tool.description).toContain('fundamentals'); + expect(tool.description).toContain('short-interest'); + + const signalSchema = tool.inputSchema.properties.signal; + expect(signalSchema.type).toBe('object'); + expect(signalSchema.additionalProperties).toBe(false); + expect(Object.keys(signalSchema.properties).sort()).toEqual([ + 'allowEstimatedLag', + 'field', + 'source', + ]); + expect(signalSchema.anyOf).toHaveLength(2); + expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); + expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); + expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); + expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); + expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); + + const validBase = { + listingIds: [70_001, 70_002], + from: '2023-01-02', + to: '2023-06-30', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const invalidCases: readonly [string, Record][] = [ + ['unknown fundamentals field', { ...validBase, signal: { source: 'fundamentals', field: 'ebitda_fake' } }], + ['shorts field on fundamentals source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], + ['fundamentals field on shorts source', { ...validBase, signal: { source: 'shorts', field: 'ttm_revenue' } }], + ['unknown signal.source', { ...validBase, signal: { source: 'macro', field: 'ttm_revenue' } }], + [ + 'unknown nested key in fundamentals signal', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', extraKey: true } }, + ], + [ + 'allowEstimatedLag on shorts source', + { ...validBase, signal: { source: 'shorts', field: 'net_change', allowEstimatedLag: false } }, + ], + [ + 'non-boolean allowEstimatedLag string', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 'true' } }, + ], + [ + 'non-boolean allowEstimatedLag number', + { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 1 } }, + ], + ['fundamentals study with FX universeMarket', { ...validBase, universeMarket: 'FX' }], + ]; + + for (const [_label, args] of invalidCases) { + const store = createFakeStore(); + const ledger = createFakeTrialLedger(); + const res = await callAnalyzeSignal({ + store: store.store, + ledger: ledger.executor, + vaultCutoffTs: cutoffTs, + args, + }); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); + expect(store.barsCalls).toHaveLength(0); + expect(store.shortsCalls).toHaveLength(0); + expect(store.fundamentalsCalls).toHaveLength(0); + expect(store.universeCalls).toHaveLength(0); + expect(ledger.insertCalls).toBe(0); + } + }); + + test('executes fundamentals study, records canonical fundamentals expressionHash, forwards allowEstimatedLag verbatim, and preserves identity on append-only retry', async () => { + const fixture = buildFundamentalsStudyFixture(); + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.preCutoffSessions - 1]!; + + const store = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const sharedLedger = createFakeTrialLedger(); + + const baseArgs = { + listingIds: fixture.listingIds, + from, + to, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + }; + + const res1 = await callAnalyzeSignal({ + store: store.store, + ledger: sharedLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: baseArgs, + }); + expect(res1.isError).toBe(false); + const payload1 = JSON.parse(res1.text) as AnalyzeSignalResultPayload; + expect(payload1.status).toBe('ok'); + if (payload1.status !== 'ok') { + return; + } + + expect(payload1.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + expect(sharedLedger.rows).toHaveLength(1); + expect(sharedLedger.rows[0]?.stage).toBe('signal_ic'); + expect(sharedLedger.rows[0]?.principal_id).toBe(AGENT_PRINCIPAL); + + // Verify canonical expression prefix `mcp:analyze_signal:v1:fundamentals:` via canonicalExpressionHash + const expectedHash = canonicalExpressionHash({ + expression: 'mcp:analyze_signal:v1:fundamentals:ttm_revenue', + params: { + version: 1, + signalSource: 'fundamentals', + signalField: 'ttm_revenue', + allowEstimatedLag: false, + horizonSessions: 5, + maxSignalAgeSessions: null, + adjustment: 'raw', + ledgerSeries: 'rank_ic', + effectiveFrom: payload1.effectiveFrom, + effectiveTo: payload1.effectiveTo, + effectiveAsOf: payload1.effectiveAsOf, + }, + universe: { + kind: 'listingIds', + listingIds: fixture.listingIds, + }, + horizon: '5d', + sampleStart: payload1.trial.sampleStart, + sampleEnd: payload1.trial.sampleEnd, + }); + expect(payload1.trial.expressionHash).toBe(expectedHash); + expect(sharedLedger.rows[0]?.expression_hash).toBe(expectedHash); + + // Default allowEstimatedLag === false forwarded verbatim to every fundamentalsAsOf call + expect(store.fundamentalsCalls.length).toBeGreaterThan(0); + expect(store.shortsCalls).toHaveLength(0); + for (const call of store.fundamentalsCalls) { + expect(call.fields).toEqual(['ttm_revenue']); + expect(call.allowEstimatedLag).toBe(false); + } + + // Re-running identical request against the SAME ledger appends under append-only rules with one distinct expression_hash + const res2 = await callAnalyzeSignal({ + store: store.store, + ledger: sharedLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: baseArgs, + }); + expect(res2.isError).toBe(false); + const payload2 = JSON.parse(res2.text) as AnalyzeSignalResultPayload; + expect(payload2.status).toBe('ok'); + if (payload2.status !== 'ok') { + return; + } + expect(payload2.trial.expressionHash).toBe(payload1.trial.expressionHash); + expect(new Set(sharedLedger.rows.map(r => r.expression_hash)).size).toBe(1); + + // Explicit allowEstimatedLag: false and reordered/duplicated listingIds preserve identity + const explicitFalseStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const explicitFalseLedger = createFakeTrialLedger(); + const reorderedIds = [...fixture.listingIds].reverse(); + reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[2]!); + const resExplicitFalse = await callAnalyzeSignal({ + store: explicitFalseStore.store, + ledger: explicitFalseLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + listingIds: reorderedIds, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: false }, + }, + }); + const payloadExplicitFalse = JSON.parse(resExplicitFalse.text) as AnalyzeSignalResultPayload; + expect(payloadExplicitFalse.status).toBe('ok'); + if (payloadExplicitFalse.status === 'ok') { + expect(payloadExplicitFalse.trial.expressionHash).toBe(payload1.trial.expressionHash); + } + expect(explicitFalseStore.fundamentalsCalls.every(c => c.allowEstimatedLag === false)).toBe(true); + + // allowEstimatedLag: true forwards true verbatim and changes expressionHash + const lagTrueStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const lagTrueLedger = createFakeTrialLedger(); + const resLagTrue = await callAnalyzeSignal({ + store: lagTrueStore.store, + ledger: lagTrueLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + }, + }); + const payloadLagTrue = JSON.parse(resLagTrue.text) as AnalyzeSignalResultPayload; + expect(payloadLagTrue.status).toBe('ok'); + if (payloadLagTrue.status === 'ok') { + expect(payloadLagTrue.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: true, + }); + expect(payloadLagTrue.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + expect(lagTrueStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + + // Different field changes expressionHash + const otherFieldStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const otherFieldLedger = createFakeTrialLedger(); + const resOtherField = await callAnalyzeSignal({ + store: otherFieldStore.store, + ledger: otherFieldLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'fundamentals', field: 'revenue' }, + }, + }); + const payloadOtherField = JSON.parse(resOtherField.text) as AnalyzeSignalResultPayload; + expect(payloadOtherField.status).toBe('ok'); + if (payloadOtherField.status === 'ok') { + expect(payloadOtherField.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + + // Shorts study over the same window/listings produces a distinct expressionHash + const shortsRows: TableRow[] = fixture.listingIds.map((lid, i) => ({ + listing_id: lid, + report_date: from, + known_at: makeUtcMs(from, 12), + shares_short: 100_000 + i * 5_000, + net_change: (i - 5) * 1_000, + pct_float: 0.03 + i * 0.005, + source: 'ceoShorts', + })); + const shortsStore = createFakeStore({ + bars: fixture.bars, + shortsTable: { columns: SHORTS_COLUMNS, rows: shortsRows }, + }); + const shortsLedger = createFakeTrialLedger(); + const resShorts = await callAnalyzeSignal({ + store: shortsStore.store, + ledger: shortsLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + ...baseArgs, + signal: { source: 'shorts', field: 'net_change' }, + }, + }); + const payloadShorts = JSON.parse(resShorts.text) as AnalyzeSignalResultPayload; + expect(payloadShorts.status).toBe('ok'); + if (payloadShorts.status === 'ok') { + expect(payloadShorts.trial.expressionHash).not.toBe(payload1.trial.expressionHash); + } + }); + + test('queries month-end snapshots in ascending order from unsorted bars, preserves earlier explicit asOf, enforces 120-snapshot cap, and handles empty bars', async () => { + // 1. Unsorted bars spanning 3 UTC months (2 full + 1 partial final month) with earlier intraday asOf + const janDates = ['2023-01-10', '2023-01-31']; + const febDates = ['2023-02-14', '2023-02-28']; + const marDates = ['2023-03-08', '2023-03-15']; + const unsortedDates = [...marDates, ...janDates, ...febDates].reverse(); + const bars: BarRecord[] = []; + for (const date of unsortedDates) { + const ts = makeUtcMs(date, 21); + for (const lid of [101, 102]) { + bars.push({ + listingId: lid, + ts, + open: 10, + high: 10, + low: 10, + close: 10, + volume: 100, + vwap: 10, + knownAt: ts, + }); + } + } + + const cutoffTs = makeUtcMs('2023-04-01', 0); + const storeOrder = createFakeStore({ + bars, + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const ledgerOrder = createFakeTrialLedger(); + + // Earlier explicit asOf on 2023-03-15T22:30:00.123456Z (after 21:00 bar close, before day end) + const explicitAsOf = '2023-03-15T22:30:00.123456Z'; + const orderRes = await callAnalyzeSignal({ + store: storeOrder.store, + ledger: ledgerOrder.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [102, 101], + from: '2023-01-01', + to: '2023-03-31', + asOf: explicitAsOf, + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(orderRes.isError).toBe(false); + expect(storeOrder.fundamentalsCalls.map(c => c.asOf)).toEqual([ + '2023-01-31T23:59:59.999999Z', + '2023-02-28T23:59:59.999999Z', + explicitAsOf, + ]); + expect(storeOrder.fundamentalsCalls.every(c => c.listingIds[0] === 101 && c.listingIds[1] === 102)).toBe(true); + + // 2. Empty eligible bar sample -> 0 fundamentalsAsOf calls, insufficient_data, 0 ledger writes + const emptyBarsStore = createFakeStore({ + bars: [], + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const emptyBarsLedger = createFakeTrialLedger(); + const emptyRes = await callAnalyzeSignal({ + store: emptyBarsStore.store, + ledger: emptyBarsLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [101, 102], + from: '2023-01-01', + to: '2023-03-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(emptyRes.isError).toBe(false); + const emptyPayload = JSON.parse(emptyRes.text) as AnalyzeSignalResultPayload; + expect(emptyPayload.status).toBe('insufficient_data'); + if (emptyPayload.status === 'insufficient_data') { + expect(emptyPayload.reason).toBe('too_few_observations'); + } + expect(emptyBarsStore.fundamentalsCalls).toHaveLength(0); + expect(emptyBarsLedger.rows).toHaveLength(0); + + // 3. Exactly 120 eligible UTC months is accepted; 121 is rejected with 0 fundamentals calls and 0 ledger inserts + function makeMonthlyBars(monthCount: number): BarRecord[] { + const out: BarRecord[] = []; + for (let m = 0; m < monthCount; m += 1) { + const year = 2010 + Math.floor(m / 12); + const month = (m % 12) + 1; + const date = `${year}-${String(month).padStart(2, '0')}-15`; + const ts = makeUtcMs(date, 21); + out.push({ + listingId: 101, + ts, + open: 10, + high: 10, + low: 10, + close: 10, + volume: 100, + vwap: 10, + knownAt: ts, + }); + } + return out; + } + + const capCutoffTs = makeUtcMs('2025-01-01', 0); + const exactCapStore = createFakeStore({ + bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const exactCapLedger = createFakeTrialLedger(); + const exactCapRes = await callAnalyzeSignal({ + store: exactCapStore.store, + ledger: exactCapLedger.executor, + vaultCutoffTs: capCutoffTs, + args: { + listingIds: [101], + from: '2010-01-01', + to: '2024-12-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(exactCapRes.isError).toBe(false); + expect(exactCapStore.fundamentalsCalls).toHaveLength(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS); + + const overCapStore = createFakeStore({ + bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS + 1), + fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + }); + const overCapLedger = createFakeTrialLedger(); + const overCapRes = await callAnalyzeSignal({ + store: overCapStore.store, + ledger: overCapLedger.executor, + vaultCutoffTs: capCutoffTs, + args: { + listingIds: [101], + from: '2010-01-01', + to: '2024-12-31', + signal: { source: 'fundamentals', field: 'revenue' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(overCapRes.isError).toBe(true); + expect(overCapRes.text).toBe( + `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.` + ); + expect(overCapStore.fundamentalsCalls).toHaveLength(0); + expect(overCapLedger.insertCalls).toBe(0); + expect(overCapLedger.rows).toHaveLength(0); + }); + + test('restatement replay prevents look-ahead: dates before Q1 restatement use originally known values and appending a future revision leaves prior output unchanged', async () => { + // Explicit deterministic restatement fixture: + // - 6 listings across 2023-01-02..2023-05-31 (108 sessions), Vault cutoff 2023-06-01T00:00:00Z + // - Original Q1 known 2023-01-12T13:00Z (period_end 2022-12-31) + // - Original Q2 known 2023-02-15T13:00Z (period_end 2023-01-31) + // - Q1 restatement known 2023-04-12T13:00Z (AFTER Q2!): period_end stays 2023-01-31 (Q2), + // while ttm_revenue flips cross-sectional ordering for listings 0..5. + // - Unchanged months (March, May) re-emit identical (listing_id, effective_known_at) -> deduped cleanly. + const listingIds = [80_001, 80_002, 80_003, 80_004, 80_005, 80_006]; + const allDates = makeBusinessDates('2023-01-02', 112); + const preCutoffDates = allDates.filter(d => d < '2023-06-01'); + const vaultCutoffDate = '2023-06-01'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const q1KnownAt = makeUtcMs('2023-01-12', 13); + const q2KnownAt = makeUtcMs('2023-02-15', 13); + const q1RestatedKnownAt = makeUtcMs('2023-04-12', 13); + const futureRevisionKnownAt = makeUtcMs('2023-06-15', 13); // post-cutoff + + const rand = createSeededRng(20261203); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(50); + for (let t = 0; t < preCutoffDates.length; t += 1) { + const date = preCutoffDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.0015 + (rand() * 2 - 1) * 0.008; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 25_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const basePitRows: FundamentalsPitFixtureRow[] = []; + const expectedDirectObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + const q1Val = 100 + l * 20; + const q2Val = 120 + l * 25; + // Restatement reverses cross-sectional rank ordering after 2023-04-12 + const restatedVal = 300 - l * 30; + + basePitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q1KnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: q1Val / 4, + ttmRevenue: q1Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q2KnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: q2Val / 4, + ttmRevenue: q2Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: q1RestatedKnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: q2Val / 4, + ttmRevenue: restatedVal, + }) + ); + + expectedDirectObs.push( + { listingId: lid, knownAt: q1KnownAt, value: q1Val }, + { listingId: lid, knownAt: q2KnownAt, value: q2Val }, + { listingId: lid, knownAt: q1RestatedKnownAt, value: restatedVal } + ); + } + + // 1. Direct baseline using independently specified eligible observations + const directLedger = createFakeTrialLedger(); + const directBuilt = buildForwardReturnPanel({ + bars, + signals: expectedDirectObs, + horizonSessions: 5, + vaultCutoffDate, + }); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_restatement_baseline', + params: { field: 'ttm_revenue', horizonSessions: 5 }, + universe: listingIds, + horizon: '5d', + }, + panel: directBuilt.panel, + vaultCutoffDate, + }); + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // 2. MCP handler run on base rows (before future revision is appended) + const args = { + listingIds, + from: preCutoffDates[0]!, + to: preCutoffDates[preCutoffDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(basePitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity between MCP handler and direct baseline (dates, rankIc, ledger daily_series) + expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); + expect(mcpPayload.trial.sampleStart).toBe(directStudy.trial.sampleStart); + expect(mcpPayload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); + // Forward return endpoint remains strictly before vaultCutoffDate + const sampleEndIdx = preCutoffDates.indexOf(mcpPayload.trial.sampleEnd); + expect(sampleEndIdx).toBeGreaterThanOrEqual(0); + expect(sampleEndIdx + 5).toBeLessThan(preCutoffDates.length); + expect(preCutoffDates[sampleEndIdx + 5]! < vaultCutoffDate).toBe(true); + + // Confirm pre-restatement dates (between 2023-02-15 and 2023-04-11) actually differ from a look-ahead study + // that wrongly substitutes the restated values onto Q2's earlier known_at! + const lookAheadObs = expectedDirectObs.map(o => + o.knownAt === q2KnownAt + ? { ...o, value: 300 - (o.listingId - 80_001) * 30 } + : o + ); + const lookAheadBuilt = buildForwardReturnPanel({ + bars, + signals: lookAheadObs, + horizonSessions: 5, + vaultCutoffDate, + }); + const lookAheadLedger = createFakeTrialLedger(); + const lookAheadStudy = await analyzeSignal(lookAheadLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'look_ahead_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 5 }, + universe: listingIds, + horizon: '5d', + }, + panel: lookAheadBuilt.panel, + vaultCutoffDate, + }); + expect(lookAheadStudy.status).toBe('ok'); + expect(mcpLedger.rows[0]?.daily_series).not.toEqual(lookAheadLedger.rows[0]?.daily_series); + + // 3. Append a future revision (post-cutoff) and verify all prior dated outputs & ledger rows remain bit-identical + const rowsWithFutureRevision: FundamentalsPitFixtureRow[] = [ + ...basePitRows, + ...listingIds.map((lid, l) => + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: futureRevisionKnownAt, + periodEnd: '2023-01-31', + fiscalPeriod: 'Q2', + revenue: 999, + ttmRevenue: 9_999 + l, + }) + ), + ]; + const futureStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(rowsWithFutureRevision, q), + }); + const futureLedger = createFakeTrialLedger(); + const futureRes = await callAnalyzeSignal({ + store: futureStore.store, + ledger: futureLedger.executor, + vaultCutoffTs, + args, + }); + expect(futureRes.isError).toBe(false); + expect(futureRes.text).toBe(mcpRes.text); + expect(futureLedger.rows).toEqual(mcpLedger.rows); + }); + + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { + const fixture = buildFundamentalsStudyFixture(); + const from = fixture.allDates[0]!; + const postCutoffDate = fixture.allDates[fixture.allDates.length - 1]!; + + const cleanStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), + }); + const leakyStore = createFakeStore({ + bars: fixture.bars, + leaky: true, + fundamentalsResolver: q => { + const cleanTable = queryFundamentalsFixtureRows(fixture.fundamentalsRows, q); + const snapAsOfMs = Date.parse(q.asOf); + const poisonedRows: TableRow[] = [ + // 1. effective_known_at strictly after individual snapshot asOf (but before vaultCutoffTs) + { + listing_id: fixture.listingIds[0]!, + effective_known_at: snapAsOfMs + 60_000, + ttm_revenue: 999_999, + }, + // 2. effective_known_at at exact vaultCutoffTs + { + listing_id: fixture.listingIds[1]!, + effective_known_at: fixture.vaultCutoffTs, + ttm_revenue: 888_888, + }, + // 3. effective_known_at after vaultCutoffTs + { + listing_id: fixture.listingIds[2]!, + effective_known_at: fixture.vaultCutoffTs + 86_400_000, + ttm_revenue: 777_777, + }, + // 4. unrequested listing_id + { + listing_id: 999_999, + effective_known_at: makeUtcMs(from, 12), + ttm_revenue: 666_666, + }, + // 5. non-safe-integer effective_known_at (float & NaN) + { + listing_id: fixture.listingIds[3]!, + effective_known_at: makeUtcMs(from, 12) + 0.5, + ttm_revenue: 555_555, + }, + { + listing_id: fixture.listingIds[3]!, + effective_known_at: Number.NaN, + ttm_revenue: 555_555, + }, + // 6. null, NaN, and Infinity field values + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12), + ttm_revenue: null, + }, + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12) + 1_000, + ttm_revenue: Number.NaN, + }, + { + listing_id: fixture.listingIds[4]!, + effective_known_at: makeUtcMs(from, 12) + 2_000, + ttm_revenue: Number.POSITIVE_INFINITY, + }, + ]; + return { + columns: cleanTable.columns, + rows: [...cleanTable.rows, ...poisonedRows], + }; + }, + }); + + const cleanLedger = createFakeTrialLedger(); + const leakyLedger = createFakeTrialLedger(); + const args = { + listingIds: fixture.listingIds, + from, + to: postCutoffDate, + asOf: postCutoffDate, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const cleanRes = await callAnalyzeSignal({ + store: cleanStore.store, + ledger: cleanLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + const leakyRes = await callAnalyzeSignal({ + store: leakyStore.store, + ledger: leakyLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + + expect(cleanRes.isError).toBe(false); + expect(leakyRes.isError).toBe(false); + expect(leakyRes.text).toBe(cleanRes.text); + expect(leakyLedger.rows).toEqual(cleanLedger.rows); + + // Every fundamentalsAsOf call's asOf is strictly before vaultCutoffTs + expect(cleanStore.fundamentalsCalls.length).toBeGreaterThan(0); + for (const call of [...cleanStore.fundamentalsCalls, ...leakyStore.fundamentalsCalls]) { + expect(Date.parse(call.asOf)).toBeLessThan(fixture.vaultCutoffTs); + } + + // Malformed fundamentals table -> sanitized SignalPanelError with zero ledger writes + const badTableStore = createFakeStore({ + bars: fixture.bars, + fundamentalsResolver: () => ({ columns: null, rows: null } as unknown as Table), + }); + const badTableLedger = createFakeTrialLedger(); + const badTableRes = await callAnalyzeSignal({ + store: badTableStore.store, + ledger: badTableLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + expect(badTableRes.isError).toBe(true); + expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); + expect(badTableLedger.rows).toHaveLength(0); + }); +}); diff --git a/libs/research/test/mcp-copilot-server.test.ts b/libs/research/test/mcp-copilot-server.test.ts index 2bc4ab24..8bd18a11 100644 --- a/libs/research/test/mcp-copilot-server.test.ts +++ b/libs/research/test/mcp-copilot-server.test.ts @@ -217,6 +217,7 @@ interface CopilotStudyFixture { readonly postCutoffDate: string; readonly bars: readonly BarRecord[]; readonly shortsTable: Table; + readonly fundamentalsRows: readonly TableRow[]; readonly eventsTable: Table; readonly symbols: readonly SymbolSearchRow[]; readonly exchangeCalendars: EventStudyExchangeCalendars; @@ -238,8 +239,42 @@ function buildCopilotStudyFixture(): CopilotStudyFixture { const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); const bars: BarRecord[] = []; const shortsRows: TableRow[] = []; + const fundamentalsRows: TableRow[] = []; const eventRows: TableRow[] = []; + const fundamentalReleaseIndices = [0, 22, 44, 64]; + for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) { + const t = fundamentalReleaseIndices[rIdx]!; + const relDate = allDates[t]!; + const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close + for (let l = 0; l < listingCount; l += 1) { + const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15; + const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25; + fundamentalsRows.push({ + listing_id: listingIds[l]!, + effective_known_at: effectiveKnownAt, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: relDate, + fiscal_period: `Q${(rIdx % 4) + 1}`, + currency: 'USD', + period_known_at: effectiveKnownAt, + revenue, + net_income: Number((revenue * 0.14).toFixed(2)), + operating_cash_flow: Number((revenue * 0.19).toFixed(2)), + total_assets: Number((revenue * 3.8).toFixed(2)), + total_equity: Number((revenue * 1.7).toFixed(2)), + shares_outstanding: 10_000_000, + ttm_revenue: ttmRevenue, + ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)), + ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)), + ttm_period_end: relDate, + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + } + } + const eventDayIndices = [12, 20, 28, 38, 48, 58]; const eventSet = new Set(); for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { @@ -362,6 +397,7 @@ function buildCopilotStudyFixture(): CopilotStudyFixture { columns: [...SHORTS_COLUMNS], rows: shortsRows, }, + fundamentalsRows, eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows, @@ -378,6 +414,7 @@ interface FakeMarketDataStoreHandle { readonly store: MarketDataStore; readonly getBarsCalls: () => number; readonly getShortsCalls: () => number; + readonly getFundamentalsCalls: () => number; readonly getEventsCalls: () => number; readonly getUniverseCalls: () => number; } @@ -391,6 +428,7 @@ function createFakeMarketDataStore( const leaky = options?.leakyVaultRows ?? false; let barsCalls = 0; let shortsCalls = 0; + let fundamentalsCalls = 0; let eventsCalls = 0; let universeCalls = 0; @@ -537,8 +575,63 @@ function createFakeMarketDataStore( async crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + async fundamentalsAsOf(q): Promise
{ + fundamentalsCalls += 1; + const idSet = new Set(q.listingIds); + const asOfMs = parseBoundMs(q.asOf, true); + const allowEstimatedLag = q.allowEstimatedLag ?? false; + const latestByListing = new Map(); + + for (const row of fixture.fundamentalsRows) { + const listingId = row.listing_id as number; + const knownAt = row.effective_known_at as number; + if (!idSet.has(listingId) || knownAt > asOfMs) { + continue; + } + const prev = latestByListing.get(listingId); + if (prev === undefined || knownAt > (prev.effective_known_at as number)) { + latestByListing.set(listingId, row); + } + } + + const rows: TableRow[] = []; + for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) { + const row = latestByListing.get(lid)!; + if (!allowEstimatedLag && row.has_estimated_lag === true) { + continue; + } + rows.push(row); + } + + if (leaky) { + rows.push({ + listing_id: fixture.listingIds[0]!, + effective_known_at: fixture.vaultCutoffTs, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: fixture.vaultCutoffDate, + fiscal_period: 'Q4', + currency: 'USD', + period_known_at: fixture.vaultCutoffTs, + revenue: 999_999, + ttm_revenue: 999_999, + }); + } + + return { + columns: [ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + ...q.fields, + ], + rows, + }; }, async macroAsOf() { throw new MarketDataStoreNotImplementedError('macroAsOf'); @@ -552,6 +645,7 @@ function createFakeMarketDataStore( store, getBarsCalls: () => barsCalls, getShortsCalls: () => shortsCalls, + getFundamentalsCalls: () => fundamentalsCalls, getEventsCalls: () => eventsCalls, getUniverseCalls: () => universeCalls, }; @@ -763,13 +857,14 @@ describe('createResearchCopilotMcpServer', () => { } }); - test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { + test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { const fixture = buildCopilotStudyFixture(); - const { serverOptions, ledger, findings } = buildComposedServerOptions(fixture); + const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture); const server = createResearchCopilotMcpServer(serverOptions); const sink = createMemoryOutput(); - let signalTrialRef = ''; + let shortsTrialRef = ''; + let fundamentalsTrialRef = ''; async function* requestStream(): AsyncGenerator { yield `${JSON.stringify({ @@ -839,6 +934,25 @@ describe('createResearchCopilotMcpServer', () => { jsonrpc: '2.0', id: 6, method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 7, + method: 'tools/call', params: { name: 'event_study', arguments: { @@ -858,7 +972,7 @@ describe('createResearchCopilotMcpServer', () => { yield `${JSON.stringify({ jsonrpc: '2.0', - id: 7, + id: 8, method: 'tools/call', params: { name: 'read_knowledge', @@ -866,28 +980,36 @@ describe('createResearchCopilotMcpServer', () => { }, })}\n`; - // Decode the earlier analyze_signal response written by runStdioServer before - // constructing the file_finding call so the trialRef is dynamically linked. - expect(sink.lines.length).toBeGreaterThanOrEqual(5); - const signalResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; - const signalPayload = decodeToolJson(signalResp); - expect(signalPayload.status).toBe('ok'); - if (signalPayload.status !== 'ok') { - throw new Error('Expected analyze_signal status to be ok.'); + // Decode both earlier analyze_signal responses written by runStdioServer before + // constructing the file_finding call so both trialRefs are dynamically linked. + expect(sink.lines.length).toBeGreaterThanOrEqual(6); + const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; + const shortsPayload = decodeToolJson(shortsResp); + expect(shortsPayload.status).toBe('ok'); + if (shortsPayload.status !== 'ok') { + throw new Error('Expected shorts analyze_signal status to be ok.'); } - signalTrialRef = String(signalPayload.trial.trialId); + shortsTrialRef = String(shortsPayload.trial.trialId); + + const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope; + const fundamentalsPayload = decodeToolJson(fundamentalsResp); + expect(fundamentalsPayload.status).toBe('ok'); + if (fundamentalsPayload.status !== 'ok') { + throw new Error('Expected fundamentals analyze_signal status to be ok.'); + } + fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId); yield `${JSON.stringify({ jsonrpc: '2.0', - id: 8, + id: 9, method: 'tools/call', params: { name: 'file_finding', arguments: { kind: 'finding', - title: 'Short-interest net_change study on synthetic US_EQ panel', + title: 'Short-interest and fundamentals signal studies on synthetic US_EQ panel', summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`, - trialRefs: [signalTrialRef], + trialRefs: [shortsTrialRef, fundamentalsTrialRef], evidenceRefs: [FIXTURE_DATASET_ID], idempotencyKey: 'copilot-e2e-finding-1', }, @@ -899,10 +1021,10 @@ describe('createResearchCopilotMcpServer', () => { const rawOut = sink.text(); expect(rawOut.endsWith('\n')).toBe(true); - expect(sink.lines).toHaveLength(8); + expect(sink.lines).toHaveLength(9); const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope); - expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); for (const resp of responses) { expect(resp.error).toBeUndefined(); } @@ -933,16 +1055,34 @@ describe('createResearchCopilotMcpServer', () => { expect(queryPayload.truncated).toBe(true); expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true); - // 5. analyze_signal - const signalPayload = decodeToolJson(responses[4]!); - expect(signalPayload.status).toBe('ok'); - if (signalPayload.status !== 'ok') { - throw new Error('Expected analyze_signal status to be ok.'); + // 5. analyze_signal (shorts) + const shortsSignalPayload = decodeToolJson(responses[4]!); + expect(shortsSignalPayload.status).toBe('ok'); + if (shortsSignalPayload.status !== 'ok') { + throw new Error('Expected shorts analyze_signal status to be ok.'); } - expect(String(signalPayload.trial.trialId)).toBe(signalTrialRef); + expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' }); + expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef); - // 6. event_study - const eventPayload = decodeToolJson(responses[5]!); + // 6. analyze_signal (fundamentals) + const fundamentalsSignalPayload = decodeToolJson(responses[5]!); + expect(fundamentalsSignalPayload.status).toBe('ok'); + if (fundamentalsSignalPayload.status !== 'ok') { + throw new Error('Expected fundamentals analyze_signal status to be ok.'); + } + expect(fundamentalsSignalPayload.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef); + expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe( + shortsSignalPayload.trial.expressionHash + ); + expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0); + + // 7. event_study + const eventPayload = decodeToolJson(responses[6]!); expect(eventPayload.status).toBe('ok'); if (eventPayload.status !== 'ok') { throw new Error('Expected event_study status to be ok.'); @@ -950,27 +1090,29 @@ describe('createResearchCopilotMcpServer', () => { expect(eventPayload.benchmark).toBe('equal_weight'); expect(eventPayload.study.hasBenchmark).toBe(true); - // 7. read_knowledge - const knowledgePayload = decodeToolJson(responses[6]!); + // 8. read_knowledge + const knowledgePayload = decodeToolJson(responses[7]!); expect(knowledgePayload.rowCount).toBe(1); expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01'); - // 8. file_finding - const findingPayload = decodeToolJson(responses[7]!); + // 9. file_finding + const findingPayload = decodeToolJson(responses[8]!); expect(findingPayload).toEqual({ id: FIXED_FINDING_ID, createdAt: FIXED_NOW_ISO, created: true, }); - // Verify trial_ledger recorded both stages under AGENT_PRINCIPAL and matches responses. - expect(ledger.rows).toHaveLength(2); - expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); + // Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL. + expect(ledger.rows).toHaveLength(3); + expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']); expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true); - expect(ledger.rows[0]?.trial_id).toBe(String(signalPayload.trial.trialId)); - expect(ledger.rows[1]?.trial_id).toBe(String(eventPayload.trial.trialId)); + expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId)); + expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId)); + expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId)); + expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash); - // Verify FindingWritePort recorded exactly one pending_review finding referencing signal trial. + // Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials. expect(findings.appendCalls).toHaveLength(1); expect(findings.stored).toHaveLength(1); expect(findings.stored[0]).toMatchObject({ @@ -978,7 +1120,7 @@ describe('createResearchCopilotMcpServer', () => { createdAt: findingPayload.createdAt, kind: 'finding', status: 'pending_review', - trialRefs: [signalTrialRef], + trialRefs: [shortsTrialRef, fundamentalsTrialRef], evidenceRefs: [FIXTURE_DATASET_ID], }); }); From 1d9a8fc63414a7c394df17613d1148ee076f549f Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:30:22 -0500 Subject: [PATCH 04/10] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 162 ++++++++++- libs/research/test/mcp-analyze-signal.test.ts | 259 ++++++++++++++++++ 2 files changed, 418 insertions(+), 3 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index 8a803e12..ef4ca71c 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -579,6 +579,69 @@ function resolveSnapshotAsOf( }; } +function buildBarTimestampsByListing(bars: readonly BarRecord[]): Map { + const byListing = new Map(); + for (let i = 0; i < bars.length; i += 1) { + const bar = bars[i]; + if ( + typeof bar !== 'object' || + bar === null || + typeof bar.listingId !== 'number' || + !Number.isSafeInteger(bar.listingId) || + typeof bar.ts !== 'number' || + !Number.isFinite(bar.ts) + ) { + continue; + } + let list = byListing.get(bar.listingId); + if (list === undefined) { + list = []; + byListing.set(bar.listingId, list); + } + list.push(bar.ts); + } + for (const [lid, list] of byListing) { + list.sort((a, b) => a - b); + let write = 0; + for (let i = 0; i < list.length; i += 1) { + const ts = list[i] as number; + if (write === 0 || list[write - 1] !== ts) { + list[write] = ts; + write += 1; + } + } + list.length = write; + byListing.set(lid, list); + } + return byListing; +} + +function findLatestBarBefore( + sortedTs: readonly number[] | undefined, + upperExclusiveMs: number, + lowerExclusiveMs: number +): number | null { + if (sortedTs === undefined || sortedTs.length === 0) { + return null; + } + let lo = 0; + let hi = sortedTs.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sortedTs[mid] as number) < upperExclusiveMs) { + lo = mid + 1; + } else { + hi = mid; + } + } + const idx = lo - 1; + if (idx < 0) { + return null; + } + const candidate = sortedTs[idx] as number; + return candidate > lowerExclusiveMs ? candidate : null; +} + function appendEligibleFundamentalsObservations(params: { readonly table: Table; readonly field: FundamentalsPitValueField; @@ -588,7 +651,7 @@ function appendEligibleFundamentalsObservations(params: { readonly vaultCutoffTs: number; readonly seenKeys: Set; readonly out: SignalObservation[]; -}): void { +}): Map { const { table, field, @@ -612,6 +675,8 @@ function appendEligibleFundamentalsObservations(params: { ); } + const latestKnownAtByListing = new Map(); + for (let i = 0; i < table.rows.length; i += 1) { const row = table.rows[i]; if (typeof row !== 'object' || row === null) { @@ -640,12 +705,22 @@ function appendEligibleFundamentalsObservations(params: { } const rawValue = row[field]; - if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { + const isFiniteValue = typeof rawValue === 'number' && Number.isFinite(rawValue); + if (!isFiniteValue && rawValue !== null) { continue; } const normalizedListingId = listingId === 0 ? 0 : listingId; const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; + const prevLatest = latestKnownAtByListing.get(normalizedListingId); + if (prevLatest === undefined || normalizedKnownAt > prevLatest) { + latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); + } + + if (!isFiniteValue) { + continue; + } + const normalizedValue = rawValue === 0 ? 0 : rawValue; const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; if (seenKeys.has(dedupeKey)) { @@ -658,6 +733,8 @@ function appendEligibleFundamentalsObservations(params: { value: normalizedValue, }); } + + return latestKnownAtByListing; } function buildCanonicalStudyExpression(params: { @@ -940,6 +1017,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT signals = []; const seenKeys = new Set(); + const barTimestampsByListing = buildBarTimestampsByListing(eligibleBars); + let windowFloorMs = Number.NEGATIVE_INFINITY; + for (const snapshotDate of snapshotDates) { const snapshot = resolveSnapshotAsOf( snapshotDate, @@ -952,7 +1032,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT asOf: snapshot.asOf, allowEstimatedLag: input.signal.allowEstimatedLag, }); - appendEligibleFundamentalsObservations({ + const latestKnownByListing = appendEligibleFundamentalsObservations({ table: rawTable, field: input.signal.field, listingIdSet, @@ -962,6 +1042,82 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT seenKeys, out: signals, }); + + // Backfill vintages superseded earlier within this month (or prior + // to the first eligible bar for the initial month) by stepping to + // the latest uncovered eligible bar strictly before each returned + // vintage. Listings sharing a target bar timestamp are batched. + const pendingByBarTs = new Map(); + const enqueueBackfill = ( + knownByListing: ReadonlyMap, + upperBoundExclusiveMs?: number + ): void => { + for (const [lid, knownAt] of knownByListing) { + const upperExclusive = + upperBoundExclusiveMs !== undefined + ? Math.min(knownAt, upperBoundExclusiveMs) + : knownAt; + const prevBarTs = findLatestBarBefore( + barTimestampsByListing.get(lid), + upperExclusive, + windowFloorMs + ); + if (prevBarTs !== null) { + let bucket = pendingByBarTs.get(prevBarTs); + if (bucket === undefined) { + bucket = []; + pendingByBarTs.set(prevBarTs, bucket); + } + bucket.push(lid); + } + } + }; + + enqueueBackfill(latestKnownByListing); + + while (pendingByBarTs.size > 0) { + // Pop the highest bar timestamp first so earlier buckets merge + // newly discovered listings landing on the same session. + let nextBarTs = Number.NEGATIVE_INFINITY; + for (const ts of pendingByBarTs.keys()) { + if (ts > nextBarTs) { + nextBarTs = ts; + } + } + const batchListingIds = sortAndDedupeListingIds(pendingByBarTs.get(nextBarTs) ?? []); + pendingByBarTs.delete(nextBarTs); + if (batchListingIds.length === 0) { + continue; + } + + const batchAsOfMs = Math.min(nextBarTs, fenced.asOfMs); + const batchAsOf = + batchAsOfMs === fenced.asOfMs + ? fenced.canonicalAsOf + : formatUtcIsoWithMicros(batchAsOfMs, 0); + const batchListingIdSet = new Set(batchListingIds); + + const backfillTable = await store.fundamentalsAsOf({ + listingIds: batchListingIds, + fields: [input.signal.field], + asOf: batchAsOf, + allowEstimatedLag: input.signal.allowEstimatedLag, + }); + const backfillKnownByListing = appendEligibleFundamentalsObservations({ + table: backfillTable, + field: input.signal.field, + listingIdSet: batchListingIdSet, + snapshotAsOfMs: batchAsOfMs, + fencedAsOfMs: fenced.asOfMs, + vaultCutoffTs, + seenKeys, + out: signals, + }); + + enqueueBackfill(backfillKnownByListing, nextBarTs); + } + + windowFloorMs = snapshot.asOfMs; } } diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 40c52efd..8176615e 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -2537,6 +2537,265 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(futureLedger.rows).toEqual(mcpLedger.rows); }); + test('same-month restatement replay retains earlier intra-month vintage through the day before the amendment', async () => { + // Regression fixture for intra-month superseded vintages: + // - Dataset ID: `synthetic:mcp-analyze-signal-same-month-restatement:seed-20261204:v1` + // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z + // - March 10: initial Q1 release (listings 0..4 only; listing 5 has NO prior release before April 5) + // - April 5: Q2 release for all 6 listings (strictly ascending ttm_revenue across listings) + // - April 18: Q1 restatement (SAME month as Q2!) keeping Q2 as latest period while reversing + // ttm_revenue cross-sectional ordering. + // Under latest-only month-end reads, the April 30 snapshot returns only the April 18 vintage + // and erases April 5 from April 5..17 (falling back to March for listings 0..4 and dropping + // listing 5 completely). With intra-month backfill, April 5..17 uses the original April 5 Q2 + // values and April 18+ uses the restated values. + const listingIds = [81_001, 81_002, 81_003, 81_004, 81_005, 81_006]; + const allDates = makeBusinessDates('2023-03-01', 53); + const vaultCutoffDate = '2023-05-15'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const marKnownAt = makeUtcMs('2023-03-10', 13); + const aprQ2KnownAt = makeUtcMs('2023-04-05', 13); + const aprRestatedKnownAt = makeUtcMs('2023-04-18', 13); + + const rand = createSeededRng(20261204); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(40); + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 30_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const pitRows: FundamentalsPitFixtureRow[] = []; + const expectedAllVintagesObs: SignalObservation[] = []; + const brokenMonthEndOnlyObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + // March ordering: alternating/scrambled; April 5 Q2: strictly ascending; April 18 restated: strictly descending + const marVal = 200 + ((l * 3) % listingIds.length) * 25; + const aprQ2Val = 100 + l * 40; + const aprRestatedVal = 400 - l * 45; + + if (l < 5) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: marKnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: marVal / 4, + ttmRevenue: marVal, + }) + ); + expectedAllVintagesObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + } + + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprQ2KnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprQ2Val / 4, + ttmRevenue: aprQ2Val, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprRestatedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprQ2Val / 4, + ttmRevenue: aprRestatedVal, + }) + ); + + expectedAllVintagesObs.push( + { listingId: lid, knownAt: aprQ2KnownAt, value: aprQ2Val }, + { listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal } + ); + // Month-end-only baseline misses the April 5 vintage completely + brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal }); + } + + // 1. Direct baseline with all eligible vintages (including April 5 Q2) + const directBuilt = buildForwardReturnPanel({ + bars, + signals: expectedAllVintagesObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const directLedger = createFakeTrialLedger(); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_same_month_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: directBuilt.panel, + vaultCutoffDate, + }); + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // 2. Broken month-end-only counterfactual (omits April 5 Q2) + const brokenBuilt = buildForwardReturnPanel({ + bars, + signals: brokenMonthEndOnlyObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const brokenLedger = createFakeTrialLedger(); + const brokenStudy = await analyzeSignal(brokenLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'broken_month_end_only_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: brokenBuilt.panel, + vaultCutoffDate, + }); + expect(brokenStudy.status).toBe('ok'); + + // 3. MCP handler over multi-month window (March..May) + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity with the full-vintage direct baseline across all dates (including April 5..17) + expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); + + // Specifically verify April 5..17 dated points match direct baseline and differ from month-end-only + const aprilPreAmendmentDates = mcpPayload.analysis.ledgerSeries.points + .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') + .map(p => p.date); + expect(aprilPreAmendmentDates.length).toBeGreaterThan(0); + expect(aprilPreAmendmentDates[0]).toBe('2023-04-05'); + expect(aprilPreAmendmentDates[aprilPreAmendmentDates.length - 1]).toBe('2023-04-17'); + + const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); + const brokenByDate = new Map( + brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) + ); + let aprilDiffCount = 0; + for (const d of aprilPreAmendmentDates) { + if (mcpByDate.get(d) !== brokenByDate.get(d)) { + aprilDiffCount += 1; + } + } + expect(aprilDiffCount).toBeGreaterThan(0); + + // Every fundamentalsAsOf call (month-end + backfill) stays strictly below Vault cutoff and forwards allowEstimatedLag + for (const call of mcpStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 4. Single-month window starting in April (2023-04-03..2023-04-28): + // must retain March prior (for Apr 3..4), April 5 Q2 (for Apr 5..17), and April 18 restatement (Apr 18..28). + const aprilOnlyBars = bars.filter(b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23)); + const aprilDirectBuilt = buildForwardReturnPanel({ + bars: aprilOnlyBars, + signals: expectedAllVintagesObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const aprilDirectLedger = createFakeTrialLedger(); + const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_april_only_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3 }, + universe: listingIds, + horizon: '3d', + }, + panel: aprilDirectBuilt.panel, + vaultCutoffDate, + }); + expect(aprilDirectStudy.status).toBe('ok'); + + const aprilMcpStore = createFakeStore({ + bars: aprilOnlyBars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const aprilMcpLedger = createFakeTrialLedger(); + const aprilMcpRes = await callAnalyzeSignal({ + store: aprilMcpStore.store, + ledger: aprilMcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: '2023-04-03', + to: '2023-04-28', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(aprilMcpRes.isError).toBe(false); + const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; + expect(aprilMcpPayload.status).toBe('ok'); + if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { + expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); + expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); + expect(aprilMcpPayload.trial.sampleStart).toBe('2023-04-03'); + } + }); + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { const fixture = buildFundamentalsStudyFixture(); const from = fixture.allDates[0]!; From ee826bdef4bab9873e9d01d34505470b1044f8b3 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:39:37 -0500 Subject: [PATCH 05/10] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 41 +- libs/research/test/mcp-analyze-signal.test.ts | 368 +++++++++++++++++- 2 files changed, 392 insertions(+), 17 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index ef4ca71c..eaa43c40 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -1002,6 +1002,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ); signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); } else { + const { field: fundamentalsField, allowEstimatedLag } = input.signal; const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { return { @@ -1028,13 +1029,13 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ); const rawTable = await store.fundamentalsAsOf({ listingIds, - fields: [input.signal.field], + fields: [fundamentalsField], asOf: snapshot.asOf, - allowEstimatedLag: input.signal.allowEstimatedLag, + allowEstimatedLag, }); const latestKnownByListing = appendEligibleFundamentalsObservations({ table: rawTable, - field: input.signal.field, + field: fundamentalsField, listingIdSet, snapshotAsOfMs: snapshot.asOfMs, fencedAsOfMs: fenced.asOfMs, @@ -1046,17 +1047,27 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT // Backfill vintages superseded earlier within this month (or prior // to the first eligible bar for the initial month) by stepping to // the latest uncovered eligible bar strictly before each returned - // vintage. Listings sharing a target bar timestamp are batched. + // vintage. When `allowEstimatedLag` is false, DuckDB omits listings + // whose latest vintage uses estimated publication lag, so treat + // omitted listings as unresolved intervals and probe earlier + // eligible closes in the month. Listings sharing a target bar + // timestamp are batched. const pendingByBarTs = new Map(); const enqueueBackfill = ( + queriedListingIds: readonly number[], knownByListing: ReadonlyMap, - upperBoundExclusiveMs?: number + upperBoundExclusiveMs: number ): void => { - for (const [lid, knownAt] of knownByListing) { - const upperExclusive = - upperBoundExclusiveMs !== undefined - ? Math.min(knownAt, upperBoundExclusiveMs) - : knownAt; + for (const lid of queriedListingIds) { + const knownAt = knownByListing.get(lid); + let upperExclusive: number; + if (knownAt !== undefined) { + upperExclusive = Math.min(knownAt, upperBoundExclusiveMs); + } else if (!allowEstimatedLag) { + upperExclusive = upperBoundExclusiveMs; + } else { + continue; + } const prevBarTs = findLatestBarBefore( barTimestampsByListing.get(lid), upperExclusive, @@ -1073,7 +1084,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT } }; - enqueueBackfill(latestKnownByListing); + enqueueBackfill(listingIds, latestKnownByListing, snapshot.asOfMs); while (pendingByBarTs.size > 0) { // Pop the highest bar timestamp first so earlier buckets merge @@ -1099,13 +1110,13 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT const backfillTable = await store.fundamentalsAsOf({ listingIds: batchListingIds, - fields: [input.signal.field], + fields: [fundamentalsField], asOf: batchAsOf, - allowEstimatedLag: input.signal.allowEstimatedLag, + allowEstimatedLag, }); const backfillKnownByListing = appendEligibleFundamentalsObservations({ table: backfillTable, - field: input.signal.field, + field: fundamentalsField, listingIdSet: batchListingIdSet, snapshotAsOfMs: batchAsOfMs, fencedAsOfMs: fenced.asOfMs, @@ -1114,7 +1125,7 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT out: signals, }); - enqueueBackfill(backfillKnownByListing, nextBarTs); + enqueueBackfill(batchListingIds, backfillKnownByListing, nextBarTs); } windowFloorMs = snapshot.asOfMs; diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 8176615e..41ee7c95 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -2189,9 +2189,17 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } const cutoffTs = makeUtcMs('2023-04-01', 0); + const preWindowKnownAt = makeUtcMs('2022-12-15', 13); const storeOrder = createFakeStore({ bars, - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + fundamentalsResolver: q => ({ + columns: ['listing_id', 'effective_known_at', 'revenue'], + rows: q.listingIds.map(lid => ({ + listing_id: lid, + effective_known_at: preWindowKnownAt, + revenue: 100, + })), + }), }); const ledgerOrder = createFakeTrialLedger(); @@ -2273,9 +2281,17 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } const capCutoffTs = makeUtcMs('2025-01-01', 0); + const capPreWindowKnownAt = makeUtcMs('2009-12-15', 13); const exactCapStore = createFakeStore({ bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), + fundamentalsResolver: q => ({ + columns: ['listing_id', 'effective_known_at', 'revenue'], + rows: q.listingIds.map(lid => ({ + listing_id: lid, + effective_known_at: capPreWindowKnownAt, + revenue: 100, + })), + }), }); const exactCapLedger = createFakeTrialLedger(); const exactCapRes = await callAnalyzeSignal({ @@ -2796,6 +2812,354 @@ describe('MCP analyze_signal tool — fundamentals source', () => { } }); + test('estimated-lag omission backfill recovers earlier verified intra-month vintages when allowEstimatedLag is false', async () => { + // Regression fixture for DuckDB estimated-lag omission under allowEstimatedLag: false: + // - Dataset ID: `synthetic:mcp-analyze-signal-estimated-lag-omission:seed-20261205:v1` + // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z + // - March 10: verified Q1 release (listings 0..4 only; listing 5 has no March prior) + // - April 5: verified Q2 release (`has_estimated_lag: false`) for all 6 listings + // - April 18: estimated-lag update (`has_estimated_lag: true`) for all 6 listings, so + // DuckDB's `fundamentalsAsOf(..., allowEstimatedLag: false)` omits listings 1..5 + // at April month-end and omits listing 0 at intermediate backfill probes. + // - April 25: verified update (`has_estimated_lag: false`) for listing 0 only (exercises + // sandwiched omission during backfill after a later verified release). + const listingIds = [82_001, 82_002, 82_003, 82_004, 82_005, 82_006]; + const allDates = makeBusinessDates('2023-03-01', 53); + const vaultCutoffDate = '2023-05-15'; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const marKnownAt = makeUtcMs('2023-03-10', 13); + const aprVerifiedKnownAt = makeUtcMs('2023-04-05', 13); + const aprEstimatedLagKnownAt = makeUtcMs('2023-04-18', 13); + const aprLateVerifiedKnownAt = makeUtcMs('2023-04-25', 13); + + const rand = createSeededRng(20261205); + const bars: BarRecord[] = []; + const prices = new Float64Array(listingIds.length).fill(45); + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); + for (let l = 0; l < listingIds.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 30_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + const pitRows: FundamentalsPitFixtureRow[] = []; + const expectedVerifiedObs: SignalObservation[] = []; + const expectedAllowLagObs: SignalObservation[] = []; + const brokenOmittedAprilObs: SignalObservation[] = []; + + for (let l = 0; l < listingIds.length; l += 1) { + const lid = listingIds[l]!; + const marVal = 200 + ((l * 3) % listingIds.length) * 25; + const aprVerifiedVal = 100 + l * 40; + const aprEstimatedVal = 400 - l * 45; + const aprLateVerifiedVal = 150; + + if (l < 5) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: marKnownAt, + periodEnd: '2022-12-31', + fiscalPeriod: 'Q1', + revenue: marVal / 4, + ttmRevenue: marVal, + hasEstimatedLag: false, + }) + ); + expectedVerifiedObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + expectedAllowLagObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + brokenOmittedAprilObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); + } + + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprVerifiedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprVerifiedVal / 4, + ttmRevenue: aprVerifiedVal, + hasEstimatedLag: false, + }), + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprEstimatedLagKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprEstimatedVal / 4, + ttmRevenue: aprEstimatedVal, + hasEstimatedLag: true, + }) + ); + + expectedVerifiedObs.push({ + listingId: lid, + knownAt: aprVerifiedKnownAt, + value: aprVerifiedVal, + }); + expectedAllowLagObs.push( + { listingId: lid, knownAt: aprVerifiedKnownAt, value: aprVerifiedVal }, + { listingId: lid, knownAt: aprEstimatedLagKnownAt, value: aprEstimatedVal } + ); + + if (l === 0) { + pitRows.push( + makeFundamentalsRow({ + listingId: lid, + effectiveKnownAt: aprLateVerifiedKnownAt, + periodEnd: '2023-03-31', + fiscalPeriod: 'Q2', + revenue: aprLateVerifiedVal / 4, + ttmRevenue: aprLateVerifiedVal, + hasEstimatedLag: false, + }) + ); + expectedVerifiedObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + expectedAllowLagObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + brokenOmittedAprilObs.push({ + listingId: lid, + knownAt: aprLateVerifiedKnownAt, + value: aprLateVerifiedVal, + }); + } + } + + // 1. Direct verified-only baseline (includes April 5 verified release; excludes April 18 estimated lag) + const directVerifiedBuilt = buildForwardReturnPanel({ + bars, + signals: expectedVerifiedObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const directVerifiedLedger = createFakeTrialLedger(); + const directVerifiedStudy = await analyzeSignal(directVerifiedLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_omission_verified_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: directVerifiedBuilt.panel, + vaultCutoffDate, + }); + expect(directVerifiedStudy.status).toBe('ok'); + if (directVerifiedStudy.status !== 'ok') { + return; + } + + // 2. Broken counterfactual without omission backfill (loses April 5 for all omitted listings) + const brokenBuilt = buildForwardReturnPanel({ + bars, + signals: brokenOmittedAprilObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const brokenLedger = createFakeTrialLedger(); + const brokenStudy = await analyzeSignal(brokenLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'broken_estimated_lag_omission_counterfactual', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: brokenBuilt.panel, + vaultCutoffDate, + }); + expect(brokenStudy.status).toBe('ok'); + + // 3. MCP handler with allowEstimatedLag: false (default) over March..May + const mcpStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const mcpLedger = createFakeTrialLedger(); + const mcpRes = await callAnalyzeSignal({ + store: mcpStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(mcpRes.isError).toBe(false); + const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; + expect(mcpPayload.status).toBe('ok'); + if (mcpPayload.status !== 'ok') { + return; + } + + // Exact parity with the verified-only direct baseline across all dates (including April 5..17) + expect(mcpPayload.analysis.rankIc).toEqual(directVerifiedStudy.analysis.rankIc); + expect(mcpPayload.analysis.pearsonIc).toEqual(directVerifiedStudy.analysis.pearsonIc); + expect(mcpLedger.rows[0]?.daily_series).toEqual(directVerifiedLedger.rows[0]?.daily_series); + + const aprilPreEstimatedDates = mcpPayload.analysis.ledgerSeries.points + .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') + .map(p => p.date); + expect(aprilPreEstimatedDates[0]).toBe('2023-04-05'); + expect(aprilPreEstimatedDates[aprilPreEstimatedDates.length - 1]).toBe('2023-04-17'); + + const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); + const brokenByDate = new Map( + brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) + ); + let aprilDiffCount = 0; + for (const d of aprilPreEstimatedDates) { + if (mcpByDate.get(d) !== brokenByDate.get(d)) { + aprilDiffCount += 1; + } + } + expect(aprilDiffCount).toBeGreaterThan(0); + + // Every fundamentalsAsOf call stays strictly below Vault cutoff and forwards allowEstimatedLag: false + for (const call of mcpStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 4. Single-month April-only window (2023-04-03..2023-04-28) with allowEstimatedLag: false + const aprilOnlyBars = bars.filter( + b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23) + ); + const aprilDirectBuilt = buildForwardReturnPanel({ + bars: aprilOnlyBars, + signals: expectedVerifiedObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const aprilDirectLedger = createFakeTrialLedger(); + const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_april_only_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, + universe: listingIds, + horizon: '3d', + }, + panel: aprilDirectBuilt.panel, + vaultCutoffDate, + }); + expect(aprilDirectStudy.status).toBe('ok'); + + const aprilMcpStore = createFakeStore({ + bars: aprilOnlyBars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const aprilMcpLedger = createFakeTrialLedger(); + const aprilMcpRes = await callAnalyzeSignal({ + store: aprilMcpStore.store, + ledger: aprilMcpLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: '2023-04-03', + to: '2023-04-28', + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(aprilMcpRes.isError).toBe(false); + const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; + expect(aprilMcpPayload.status).toBe('ok'); + if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { + expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); + expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); + } + + // 5. With allowEstimatedLag: true, April 18 estimated-lag update is included alongside April 5 + const allowLagDirectBuilt = buildForwardReturnPanel({ + bars, + signals: expectedAllowLagObs, + horizonSessions: 3, + vaultCutoffDate, + }); + const allowLagDirectLedger = createFakeTrialLedger(); + const allowLagDirectStudy = await analyzeSignal(allowLagDirectLedger.executor, { + principalId: AGENT_PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_estimated_lag_allowed_baseline', + params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: true }, + universe: listingIds, + horizon: '3d', + }, + panel: allowLagDirectBuilt.panel, + vaultCutoffDate, + }); + expect(allowLagDirectStudy.status).toBe('ok'); + + const allowLagStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), + }); + const allowLagLedger = createFakeTrialLedger(); + const allowLagRes = await callAnalyzeSignal({ + store: allowLagStore.store, + ledger: allowLagLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(allowLagRes.isError).toBe(false); + const allowLagPayload = JSON.parse(allowLagRes.text) as AnalyzeSignalResultPayload; + expect(allowLagPayload.status).toBe('ok'); + if (allowLagPayload.status === 'ok' && allowLagDirectStudy.status === 'ok') { + expect(allowLagPayload.analysis.rankIc).toEqual(allowLagDirectStudy.analysis.rankIc); + expect(allowLagLedger.rows[0]?.daily_series).toEqual( + allowLagDirectLedger.rows[0]?.daily_series + ); + expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); + } + expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + }); + test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { const fixture = buildFundamentalsStudyFixture(); const from = fixture.allDates[0]!; From 5de54be1e3b74a947b122c9cb89b9d1290ce728f Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:48:26 -0500 Subject: [PATCH 06/10] =?UTF-8?q?T-149:=20M2.1h=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`:=20add=20a=20Vault-fenced=20`fundamental?= =?UTF-8?q?s`=20signal=20source=20(point-in-time=20`fundamentalsAsOf`=20mo?= =?UTF-8?q?nth-end=20snapshots=20=E2=86=92=20`SignalObservation`s)=20+=20e?= =?UTF-8?q?xtend=20the=20headless=20stdio=20end-to-end=20test=20to=20run?= =?UTF-8?q?=20a=20fundamental=20AND=20a=20shorts=20study=20(pure,=20inject?= =?UTF-8?q?ed=20ports,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 27 ++--- libs/research/test/mcp-analyze-signal.test.ts | 112 ++++++++++++++++++ 2 files changed, 121 insertions(+), 18 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index eaa43c40..0103f10a 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -705,8 +705,7 @@ function appendEligibleFundamentalsObservations(params: { } const rawValue = row[field]; - const isFiniteValue = typeof rawValue === 'number' && Number.isFinite(rawValue); - if (!isFiniteValue && rawValue !== null) { + if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { continue; } @@ -717,10 +716,6 @@ function appendEligibleFundamentalsObservations(params: { latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); } - if (!isFiniteValue) { - continue; - } - const normalizedValue = rawValue === 0 ? 0 : rawValue; const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; if (seenKeys.has(dedupeKey)) { @@ -1047,10 +1042,10 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT // Backfill vintages superseded earlier within this month (or prior // to the first eligible bar for the initial month) by stepping to // the latest uncovered eligible bar strictly before each returned - // vintage. When `allowEstimatedLag` is false, DuckDB omits listings - // whose latest vintage uses estimated publication lag, so treat - // omitted listings as unresolved intervals and probe earlier - // eligible closes in the month. Listings sharing a target bar + // vintage. Under either lag setting, a requested listing with no + // valid observation (omitted by DuckDB or carrying a null/non-finite + // field) is treated as an unresolved interval so earlier eligible + // closes within the month are probed. Listings sharing a target bar // timestamp are batched. const pendingByBarTs = new Map(); const enqueueBackfill = ( @@ -1060,14 +1055,10 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT ): void => { for (const lid of queriedListingIds) { const knownAt = knownByListing.get(lid); - let upperExclusive: number; - if (knownAt !== undefined) { - upperExclusive = Math.min(knownAt, upperBoundExclusiveMs); - } else if (!allowEstimatedLag) { - upperExclusive = upperBoundExclusiveMs; - } else { - continue; - } + const upperExclusive = + knownAt !== undefined + ? Math.min(knownAt, upperBoundExclusiveMs) + : upperBoundExclusiveMs; const prevBarTs = findLatestBarBefore( barTimestampsByListing.get(lid), upperExclusive, diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 41ee7c95..e871fdeb 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -3158,6 +3158,118 @@ describe('MCP analyze_signal tool — fundamentals source', () => { expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); } expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); + + // 6. Stale March null row for an omitted listing must not suppress April omission backfill; + // exact payload and ledger rows must match the clean run. + const staleNullKnownAt = makeUtcMs('2023-03-20', 13); + const staleNullStore = createFakeStore({ + bars, + fundamentalsResolver: q => { + const cleanTable = queryFundamentalsFixtureRows(pitRows, q); + const returnedIds = new Set(cleanTable.rows.map(r => r.listing_id)); + const injected: TableRow[] = []; + for (const omittedTarget of [listingIds[1]!, listingIds[5]!]) { + if (q.listingIds.includes(omittedTarget) && !returnedIds.has(omittedTarget)) { + injected.push({ + listing_id: omittedTarget, + effective_known_at: staleNullKnownAt, + known_at_source: 'sec_edgar_filing', + has_estimated_lag: false, + period_end: '2022-12-31', + fiscal_period: 'Q1', + currency: 'USD', + period_known_at: staleNullKnownAt, + ttm_revenue: null, + ttm_period_end: null, + ttm_currency: null, + ttm_has_estimated_lag: false, + }); + } + } + return { + columns: cleanTable.columns, + rows: [...cleanTable.rows, ...injected], + }; + }, + }); + const staleNullLedger = createFakeTrialLedger(); + const staleNullRes = await callAnalyzeSignal({ + store: staleNullStore.store, + ledger: staleNullLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue' }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(staleNullRes.isError).toBe(false); + expect(staleNullRes.text).toBe(mcpRes.text); + expect(staleNullLedger.rows).toEqual(mcpLedger.rows); + for (const call of staleNullStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(false); + } + + // 7. Genuinely null latest field with allowEstimatedLag: true must still probe earlier + // eligible closes and recover the valid April 5 release. + const nullLatestPitRows: FundamentalsPitFixtureRow[] = pitRows.map(row => + row.effective_known_at === aprEstimatedLagKnownAt ? { ...row, ttm_revenue: null } : row + ); + const nullLatestAllowLagStore = createFakeStore({ + bars, + fundamentalsResolver: q => queryFundamentalsFixtureRows(nullLatestPitRows, q), + }); + const nullLatestAllowLagLedger = createFakeTrialLedger(); + const nullLatestAllowLagRes = await callAnalyzeSignal({ + store: nullLatestAllowLagStore.store, + ledger: nullLatestAllowLagLedger.executor, + vaultCutoffTs, + args: { + listingIds, + from: allDates[0]!, + to: allDates[allDates.length - 1]!, + signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, + horizonSessions: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(nullLatestAllowLagRes.isError).toBe(false); + const nullLatestAllowLagPayload = JSON.parse( + nullLatestAllowLagRes.text + ) as AnalyzeSignalResultPayload; + expect(nullLatestAllowLagPayload.status).toBe('ok'); + if (nullLatestAllowLagPayload.status === 'ok') { + expect(nullLatestAllowLagPayload.analysis.rankIc).toEqual( + directVerifiedStudy.analysis.rankIc + ); + expect(nullLatestAllowLagPayload.analysis.pearsonIc).toEqual( + directVerifiedStudy.analysis.pearsonIc + ); + expect(nullLatestAllowLagLedger.rows[0]?.daily_series).toEqual( + directVerifiedLedger.rows[0]?.daily_series + ); + const recoveredByDate = new Map( + nullLatestAllowLagPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value]) + ); + let recoveredAprilDiffCount = 0; + for (const d of aprilPreEstimatedDates) { + if (recoveredByDate.get(d) !== brokenByDate.get(d)) { + recoveredAprilDiffCount += 1; + } + } + expect(recoveredAprilDiffCount).toBeGreaterThan(0); + } + expect(nullLatestAllowLagStore.fundamentalsCalls.length).toBeGreaterThan(0); + for (const call of nullLatestAllowLagStore.fundamentalsCalls) { + expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); + expect(call.allowEstimatedLag).toBe(true); + } }); test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { From 83feb6e5eed3a98db2e6555dda594641537e9cb1 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:01:05 -0500 Subject: [PATCH 07/10] T-149: tests --- ...ze-signal-fundamentals-real-duckdb.test.ts | 522 ++++++++++++++++++ 1 file changed, 522 insertions(+) create mode 100644 libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts diff --git a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts new file mode 100644 index 00000000..9cff62f1 --- /dev/null +++ b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts @@ -0,0 +1,522 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdir, mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { MarketDataStore } from '@stock-bot/research/market-data-store'; +import type { FundamentalsAsOfQuery } from '@stock-bot/research/market-data-store-duckdb'; +import { createAnalyzeSignalTool, createMcpServer } from '@stock-bot/research/mcp'; +import { type SignalObservation, buildForwardReturnPanel, collectBars } from '@stock-bot/research/signal-panel'; +import { analyzeSignal } from '@stock-bot/research/signal-study'; +import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger'; +import { createNodeDuckDbExecutor, openDuckDbMarketDataStore } from '../src/index'; + +// QA end-to-end evidence for T-149: MCP `analyze_signal` (source = fundamentals) +// driven against the REAL DuckDB `fundamentalsAsOf` over Hive Parquet files. +// - Dataset ID: `synthetic:qa-analyze-signal-fundamentals-real-duckdb:seed-20261206:v1` +// - Tool version: `mcp:analyze_signal:v1`; adjustment `raw`; horizon 3 sessions; modeled costs 0 +// - Pre-Vault window 2023-03-01..2023-05-12; Vault cutoff 2023-05-15T00:00:00.000Z +// - Bars: 6 listings (101..106), 20:00 UTC closes; 5 post-cutoff bars must be fenced out. +// - Fundamentals (ttm_revenue), all 13:00 UTC: +// 2023-03-10 verified (101..105), 2023-04-05 verified Q2 (all), +// 2023-04-18 same-month restatement (101..103, verified), +// 2023-04-18 estimated-lag update (104) -> omitted by DuckDB under default lag, +// 2023-04-20 verified row with NULL ttm_revenue (105) -> must not displace 2023-04-05. +// - Baseline: direct `buildForwardReturnPanel` + `analyzeSignal` over independently listed +// expected observations. + +const VAULT_CUTOFF_TS = Date.UTC(2023, 4, 15); +const VAULT_CUTOFF_DATE = '2023-05-15'; +const PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const LISTING_IDS = [101, 102, 103, 104, 105, 106] as const; +const HORIZON = 3; +// Listing with bars but no fundamentals rows at all (sparse coverage probe). +const UNCOVERED_LISTING_ID = 107; +const BAR_LISTING_IDS = [...LISTING_IDS, UNCOVERED_LISTING_ID] as const; + +const tempDirs: string[] = []; + +afterEach(async () => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +function createSeededRng(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function businessDates(start: string, count: number): string[] { + const out: string[] = []; + const d = new Date(`${start}T00:00:00Z`); + while (out.length < count) { + const dow = d.getUTCDay(); + if (dow !== 0 && dow !== 6) { + out.push(d.toISOString().slice(0, 10)); + } + d.setUTCDate(d.getUTCDate() + 1); + } + return out; +} + +function ms(date: string, hour: number): number { + return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); +} + +interface PitRow { + readonly listingId: number; + readonly knownAt: string; // YYYY-MM-DD + readonly hour?: number; // UTC hour, default 13 + readonly ttm: number | null; + readonly estimated?: boolean; +} + +const BASE_PIT_ROWS: readonly PitRow[] = [ + ...[101, 102, 103, 104, 105].map((lid, l) => ({ + listingId: lid, + knownAt: '2023-03-10', + ttm: 200 + ((l * 3) % 5) * 25, + })), + ...LISTING_IDS.map((lid, l) => ({ listingId: lid, knownAt: '2023-04-05', ttm: 100 + l * 40 })), + ...[101, 102, 103].map((lid, l) => ({ listingId: lid, knownAt: '2023-04-18', ttm: 400 - l * 90 })), + { listingId: 104, knownAt: '2023-04-18', ttm: 999, estimated: true }, + { listingId: 105, knownAt: '2023-04-20', ttm: null }, +]; + +function pitRowSql(r: PitRow): string { + const est = r.estimated === true ? 'TRUE' : 'FALSE'; + const ttm = r.ttm === null ? 'NULL::DOUBLE' : `${r.ttm}::DOUBLE`; + const ttmMeta = + r.ttm === null ? 'NULL::DATE, NULL::VARCHAR' : `DATE '2023-03-31', 'USD'::VARCHAR`; + const ts = `${r.knownAt} ${String(r.hour ?? 13).padStart(2, '0')}:00:00+00`; + return `(${r.listingId}::INTEGER, TIMESTAMPTZ '${ts}', 'filing_date'::VARCHAR, ${est}::BOOLEAN, + DATE '2023-03-31', 'Q1'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${ts}', + 1.0::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, + ${ttmMeta}, ${ttm}, NULL::DOUBLE, NULL::DOUBLE, ${est}::BOOLEAN)`; +} + +async function writeCurated( + curatedRoot: string, + pitPartitions: Readonly> +): Promise { + const rand = createSeededRng(20261206); + const dates = businessDates('2023-03-01', 58); // 53 pre-cutoff + 5 Vault sessions + const prices = BAR_LISTING_IDS.map(() => 40); + const barValues: string[] = []; + for (const date of dates) { + for (let l = 0; l < BAR_LISTING_IDS.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + const ts = `TIMESTAMPTZ '${date} 20:00:00+00'`; + barValues.push( + `(${BAR_LISTING_IDS[l]}::INTEGER, DATE '${date}', ${ts}, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, 50000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, ${ts})` + ); + } + } + + await mkdir(join(curatedRoot, 'bars_1d', 'year=2023'), { recursive: true }); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${barValues.join(', ')}) + AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) + `); + for (const [year, rows] of Object.entries(pitPartitions)) { + const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); + await mkdir(dir, { recursive: true }); + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${rows.map(pitRowSql).join(', ')}) AS t( + listing_id, effective_known_at, known_at_source, has_estimated_lag, + period_end, fiscal_period, currency, period_known_at, + revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, + ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag + ) + ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) + `); + } + } finally { + await writer.close(); + } +} + +interface LedgerRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: number[]; +} + +// Deterministic in-memory trial_ledger port (fixed created_at, sequential ids). +function createLedger(): { executor: TrialLedgerExecutor; rows: LedgerRow[] } { + const rows: LedgerRow[] = []; + let nextId = 1; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const p = params ?? []; + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const id = nextId++; + const row: LedgerRow = { + trial_id: String(id), + created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), + }; + rows.push(row); + return { + rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], + rowCount: 1, + }; + } + if (trimmed.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const matched = rows.filter(r => r.trial_id === String(p[0])); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const matched = rows.filter( + r => r.universe_market === p[0] && r.horizon_bucket === p[1] + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + return { rows: [], rowCount: 0 }; + }, + }; + return { executor, rows }; +} + +async function openStore( + pitPartitions: Readonly> +): Promise<{ + store: MarketDataStore; + calls: FundamentalsAsOfQuery[]; + close: () => Promise; +}> { + const root = await mkdtemp(join(tmpdir(), 'stockbot-qa-as-fnd-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(duckTempDir, { recursive: true }); + await writeCurated(curatedRoot, pitPartitions); + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs: VAULT_CUTOFF_TS, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '1GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + const calls: FundamentalsAsOfQuery[] = []; + const inner = opened.store; + const store: MarketDataStore = { + ...inner, + bars: q => inner.bars(q), + shortsAsOf: q => inner.shortsAsOf(q), + universe: q => inner.universe(q), + fundamentalsAsOf: q => { + calls.push(q); + return inner.fundamentalsAsOf(q); + }, + }; + return { store, calls, close: () => opened.close() }; +} + +async function runTool( + store: MarketDataStore, + ledger: TrialLedgerExecutor, + allowEstimatedLag?: boolean, + listingIds: readonly number[] = LISTING_IDS +): Promise<{ isError: boolean; text: string }> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: PRINCIPAL, + }), + ], + }); + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'qa-1', + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...listingIds], + from: '2023-03-01', + to: '2023-05-19', // straddles the Vault cutoff; must be clamped + signal: { + source: 'fundamentals', + field: 'ttm_revenue', + ...(allowEstimatedLag === undefined ? {} : { allowEstimatedLag }), + }, + horizonSessions: HORIZON, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }, + }) + ); + const parsed = JSON.parse(raw as string) as { + result: { isError?: boolean; content: { text: string }[] }; + }; + return { isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '' }; +} + +function expectedObservations( + includeEstimated: boolean, + rows: readonly PitRow[] = BASE_PIT_ROWS +): SignalObservation[] { + const out: SignalObservation[] = []; + for (const r of rows) { + if (r.ttm === null || (r.estimated === true && !includeEstimated)) { + continue; + } + out.push({ listingId: r.listingId, knownAt: ms(r.knownAt, r.hour ?? 13), value: r.ttm }); + } + return out; +} + +async function directBaseline( + store: MarketDataStore, + signals: SignalObservation[], + listingIds: readonly number[] = LISTING_IDS +): Promise<{ rankIc: unknown; series: number[]; sampleStart: string; sampleEnd: string }> { + const bars = await collectBars(store.bars({ + listingIds: [...listingIds], + from: '2023-03-01', + to: '2023-05-12', + timeframe: '1d', + adjustment: 'raw', + })); + const built = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: HORIZON, + vaultCutoffDate: VAULT_CUTOFF_DATE, + }); + const ledger = createLedger(); + const study = await analyzeSignal(ledger.executor, { + principalId: PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'qa_direct_baseline', + params: { field: 'ttm_revenue' }, + universe: [...listingIds], + horizon: `${HORIZON}d`, + }, + panel: built.panel, + vaultCutoffDate: VAULT_CUTOFF_DATE, + }); + if (study.status !== 'ok') { + throw new Error(`baseline study not ok: ${study.status}`); + } + return { + rankIc: study.analysis.rankIc, + series: ledger.rows[0]!.daily_series, + sampleStart: study.trial.sampleStart, + sampleEnd: study.trial.sampleEnd, + }; +} + +interface OkPayload { + status: 'ok'; + signal: unknown; + analysis: { rankIc: unknown }; + trial: { sampleStart: string; sampleEnd: string; expressionHash: string }; +} + +describe('analyze_signal fundamentals over real DuckDB fundamentalsAsOf (QA)', () => { + test('default lag: same-month restatement, estimated-lag omission and null-field rows replay exactly like the verified-only baseline', async () => { + const s = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor); + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + expect(payload.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + + const baseline = await directBaseline(s.store, expectedObservations(false)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows).toHaveLength(1); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + expect(payload.trial.sampleStart).toBe(baseline.sampleStart); + expect(payload.trial.sampleEnd).toBe(baseline.sampleEnd); + expect(payload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); + + // Every real-store read is strictly pre-Vault and forwards the lag flag verbatim. + expect(s.calls.length).toBeGreaterThan(0); + for (const call of s.calls) { + expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); + expect(call.allowEstimatedLag).toBe(false); + expect(call.fields).toEqual(['ttm_revenue']); + } + // Fan-out bound: month-end snapshots (3) + at most one probe per eligible session (53). + expect(s.calls.length).toBeLessThanOrEqual(3 + 53); + } finally { + await s.close(); + } + }); + + test('allowEstimatedLag true includes the estimated update and matches its own baseline', async () => { + const s = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor, true); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + const baseline = await directBaseline(s.store, expectedObservations(true)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + expect(s.calls.every(c => c.allowEstimatedLag === true)).toBe(true); + + const defaultLedger = createLedger(); + const defaultRes = await runTool(s.store, defaultLedger.executor); + const defaultPayload = JSON.parse(defaultRes.text) as OkPayload; + expect(defaultPayload.trial.expressionHash).not.toBe(payload.trial.expressionHash); + expect(defaultLedger.rows[0]!.daily_series).not.toEqual(ledger.rows[0]!.daily_series); + } finally { + await s.close(); + } + }); + + test('appending Vault-window and post-cutoff revisions in another Parquet partition leaves payload and ledger rows byte-identical', async () => { + const clean = await openStore({ '2023': BASE_PIT_ROWS }); + const poisoned = await openStore({ + '2023': BASE_PIT_ROWS, + '2099': [ + // Exactly at the Vault cutoff, inside the Vault, and long after. + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-15', ttm: 5_000 + lid })), + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-17', ttm: 7_000 - lid })), + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2024-01-02', ttm: 9_000 + lid })), + ], + }); + try { + const cleanLedger = createLedger(); + const poisonedLedger = createLedger(); + const cleanRes = await runTool(clean.store, cleanLedger.executor); + const poisonedRes = await runTool(poisoned.store, poisonedLedger.executor); + expect(cleanRes.isError).toBe(false); + expect(poisonedRes.text).toBe(cleanRes.text); + expect(poisonedLedger.rows).toEqual(cleanLedger.rows); + expect(poisoned.calls.map(c => c.asOf)).toEqual(clean.calls.map(c => c.asOf)); + } finally { + await clean.close(); + await poisoned.close(); + } + }); + + test('a release stamped exactly at a bar close and superseded next morning is replayed at that close', async () => { + // 106 files at 2023-04-12 20:00:00Z (== bar close ts) and restates at 2023-04-13 13:00Z. + // A month-end-only read would only see the 04-13 vintage; the 04-12 close must use 50. + const rows: readonly PitRow[] = [ + ...BASE_PIT_ROWS, + { listingId: 106, knownAt: '2023-04-12', hour: 20, ttm: 50 }, + { listingId: 106, knownAt: '2023-04-13', ttm: 900 }, + ]; + const s = await openStore({ '2023': rows }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + const baseline = await directBaseline(s.store, expectedObservations(false, rows)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + // Probe at the exact close timestamp is issued (store compares effective_known_at <= asOf). + expect(s.calls.some(c => Date.parse(c.asOf) === ms('2023-04-12', 20))).toBe(true); + } finally { + await s.close(); + } + }); + + test('sparse coverage: a listing with bars but no fundamentals stays bounded and does not change the study', async () => { + // Measurement for the reviewer's non-blocking fan-out note. The uncovered listing is + // probed at each eligible session, so calls grow with sessions, not with listings. + const covered = await openStore({ '2023': BASE_PIT_ROWS }); + const sparse = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const coveredLedger = createLedger(); + const sparseLedger = createLedger(); + const coveredRes = await runTool(covered.store, coveredLedger.executor); + const sparseRes = await runTool(sparse.store, sparseLedger.executor, undefined, [ + ...LISTING_IDS, + UNCOVERED_LISTING_ID, + ]); + const coveredPayload = JSON.parse(coveredRes.text) as OkPayload; + const sparsePayload = JSON.parse(sparseRes.text) as OkPayload; + expect(coveredPayload.status).toBe('ok'); + expect(sparsePayload.status).toBe('ok'); + + // No signal for 107 -> same cross-sectional series as the covered-only study. + const baseline = await directBaseline(sparse.store, expectedObservations(false), [ + ...LISTING_IDS, + UNCOVERED_LISTING_ID, + ]); + expect(sparseLedger.rows[0]!.daily_series).toEqual(baseline.series); + + // 53 eligible sessions over 3 UTC months: <= 3 month-end snapshots + 53 probes. + expect(sparse.calls.length).toBeLessThanOrEqual(3 + 53); + expect(sparse.calls.length).toBeGreaterThan(covered.calls.length); + // Each session timestamp is probed at most once. + const asOfs = sparse.calls.map(c => c.asOf); + expect(new Set(asOfs).size).toBe(asOfs.length); + for (const call of sparse.calls) { + expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); + } + } finally { + await covered.close(); + await sparse.close(); + } + }); +}); From b7bd6bdfe1860e96f31ec09613a94c0e117e0dba Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:14:04 -0500 Subject: [PATCH 08/10] =?UTF-8?q?T-152:=20M2.3j=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`qmIntraday`=20=E2=86=92=20`bars=5F1m`=20curat?= =?UTF-8?q?ion=20stage=20(raw=20bars,=20no=20split=20un-adjustment=20?= =?UTF-8?q?=E2=86=92=20`provider=5Fmapping`=20=E2=86=92=20`Bar1mRow`?= =?UTF-8?q?=20=E2=86=92=20`IlpShardedWriter`)=20with=20tests=20(no=20new?= =?UTF-8?q?=20crates,=20no=20CLI/bench=20changes,=20no=20live=20Mongo/Ques?= =?UTF-8?q?tDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bars_1m.rs | 3 + tools/curate-etl/src/bson_stream.rs | 63 ++ tools/curate-etl/src/bson_stream_tests.rs | 190 +++++- tools/curate-etl/src/curate_bars_1m.rs | 78 ++- tools/curate-etl/src/curate_qm_bars_1m.rs | 206 ++++++ .../curate-etl/src/curate_qm_bars_1m_tests.rs | 605 ++++++++++++++++++ tools/curate-etl/src/lib.rs | 21 +- 7 files changed, 1127 insertions(+), 39 deletions(-) create mode 100644 tools/curate-etl/src/curate_qm_bars_1m.rs create mode 100644 tools/curate-etl/src/curate_qm_bars_1m_tests.rs diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs index d4d603cd..88d2ad9d 100644 --- a/tools/curate-etl/src/bars_1m.rs +++ b/tools/curate-etl/src/bars_1m.rs @@ -32,6 +32,9 @@ use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; /// Canonical provenance label written to [`Bar1mRow::source`] for un-adjusted `eodIntraday1M` bars. pub const BARS_1M_SOURCE_EOD: &str = "eod_unadj"; +/// Canonical provenance label written to [`Bar1mRow::source`] for raw `qmIntraday` bars. +pub const BARS_1M_SOURCE_QM: &str = "qm_raw"; + /// Regular Trading Hours start minute in Eastern Time (`09:30 ET` = `570`). pub const RTH_START_MINUTE_ET: u16 = 9 * 60 + 30; diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index df36a1bf..be7c201a 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -40,6 +40,9 @@ use crate::bson_qm_events::{ BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames, RawQmEarning, RawQmFiling, }; +use crate::bson_qm_intraday::{ + decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar, +}; use crate::bson_qm_prices::{ decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice, }; @@ -613,6 +616,66 @@ where decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error) } +#[inline] +fn rebase_qm_intraday_error(base: u64, err: BsonQmIntradayError) -> BsonQmIntradayError { + match err { + BsonQmIntradayError::CorruptBson { offset, detail } => BsonQmIntradayError::CorruptBson { + offset: rebase_offset(base, offset), + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_intraday_buffer`], +/// accumulating [`BsonQmIntradayDecodeStats`] and rebasing per-document error offsets to +/// absolute stream byte offsets. +pub fn decode_qm_intraday_chunks( + reader: &mut RawBsonChunkReader, + mut on_bar: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmIntradayBar<'a>), + E: FnMut(u64, BsonQmIntradayError), +{ + let mut total = BsonQmIntradayDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_qm_intraday_buffer( + chunk.bytes, + &mut on_bar, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_qm_intraday_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmIntraday` [`std::io::Read`] source through +/// [`decode_qm_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_qm_intraday_stream( + reader: R, + options: BsonStreamOptions, + on_bar: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmIntradayBar<'a>), + E: FnMut(u64, BsonQmIntradayError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_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. diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 5e05e142..1ca61802 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -13,12 +13,15 @@ use crate::bson_eod_prices::{ use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, }; +use crate::bson_qm_intraday::{ + decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, +}; use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError}; use crate::bson_stream::{ 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, + decode_qm_dividend_stream, decode_qm_intraday_chunks, decode_qm_intraday_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)] @@ -2278,3 +2281,184 @@ fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { } if offset == trunc_offset )); } + +#[test] +fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { + let make_doc = |code: &str, ts_ms: i64, open: f64, close: f64, vol: f64| -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(ts_ms)); + 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!("sharevolume"), vol); + // Include adjusted fields that must be validated and ignored. + doc.append(cstr!("adjustedopen"), open / 10.0); + doc.append(cstr!("adjustedclose"), close / 10.0); + doc.append(cstr!("avolume"), vol * 10.0); + doc.into_bytes() + }; + + // Empty input returns zeroed stats with zero callbacks. + { + let mut empty_rows = 0usize; + let mut empty_errs = 0usize; + let stats = decode_qm_intraday_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + |_| empty_rows += 1, + |_, _| empty_errs += 1, + ) + .unwrap(); + assert_eq!(stats, BsonQmIntradayDecodeStats::default()); + assert_eq!(empty_rows, 0); + assert_eq!(empty_errs, 0); + } + + let mut fixture = Vec::new(); + fixture.extend_from_slice(&make_doc("NVDA", 1_717_767_000_000, 1200.0, 1205.0, 1_000.0)); + fixture.extend_from_slice(&make_doc("AAPL", 1_717_767_060_000, 195.0, 195.25, 0.0)); + + // Semantic error: invalid timestamp (negative DateTime millis). + let bad_ts_offset = fixture.len() as u64; + fixture.extend_from_slice(&make_doc("NVDA", -60_000, 1200.0, 1205.0, 100.0)); + + // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset. + let mut corrupt_bytes = make_doc("MSFT", 1_717_767_120_000, 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:CA", 1_717_767_180_000, 88.0, 88.4, 2_500.0)); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_intraday_buffer( + &fixture, + |b| { + expected_rows.push(( + b.qm_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_qm_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_qm_intraday_stream( + FixedStepReader::new(&fixture, step), + opts, + |b| { + got_rows.push(( + b.qm_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, BsonQmIntradayError::CorruptBson { offset, .. }) + if off == corrupt_offset && offset as u64 == corrupt_offset + )); + } + + // Exercise decode_qm_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, 0x152, true), opts) + .unwrap(); + let mut chunk_rows = Vec::new(); + let mut chunk_errs = Vec::new(); + let chunk_stats = decode_qm_intraday_chunks( + &mut chunk_reader, + |b| { + chunk_rows.push(( + b.qm_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_qm_intraday_stream( + FixedStepReader::new(&truncated, 5), + BsonStreamOptions { + chunk_capacity_bytes: 32, + max_doc_bytes: 4096, + }, + |b| { + prefix_rows.push(( + b.qm_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 + )); +} diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs index 7ca5af9e..849ebbc7 100644 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ b/tools/curate-etl/src/curate_bars_1m.rs @@ -25,8 +25,9 @@ use std::io::{self, Write}; use crate::bars::Bar1dRow; use crate::bars_1m::{ - build_bars_1m, check_session_closes_against_bars_1d, Bar1mRow, Bars1mError, Bars1mStats, - EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, + build_bars_1m, check_session_closes_against_bars_1d, Bar1mRow, Bars1mBuild, Bars1mError, + Bars1mStats, EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, + BARS_1M_SOURCE_EOD, }; use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; @@ -184,35 +185,18 @@ fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> bool { && a.session == b.session } -/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via -/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through -/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] -/// rows sorted and unique by `(listing_id, ts)`. -/// -/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`]. -/// Non-blank `mapping_source` values are looked up verbatim. -/// - Rows whose `(mapping_source, source_id, session_date)` is not covered by any range in -/// `provider_mapping` are counted in [`CurateBars1mStats::dropped_unmapped`]. -/// - After re-sorting in place by `(listing_id, ts)`, cross-`source_id` collisions on the same -/// `(listing_id, ts)` collapse to one row when OHLCV (bitwise) and `session` match -/// (`listing_collision_collapsed += g - 1`), and drop the entire group otherwise -/// (`listing_collision_dropped += g`). -pub fn curate_bars_1m( - bars: B, - splits: &SplitTable, +/// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via +/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in +/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions. +pub(crate) fn map_bars_1m( + built: Bars1mBuild, provider_mapping: &ProviderMappingTable, mapping_source: &str, -) -> Result + source: &'static str, +) -> CurateBars1mOutput where - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, + K: Eq + AsRef, { - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource); - } - - let built = build_bars_1m(bars, splits); - let mut stats = CurateBars1mStats { builder: built.stats, rows_in: built.rows.len(), @@ -254,7 +238,7 @@ where close: bar.close, volume: bar.volume, session: bar.session, - source: bar.source, + source, }); } } @@ -319,7 +303,43 @@ where rows.truncate(write_idx); stats.rows_out = rows.len(); - Ok(CurateBars1mOutput { rows, stats }) + CurateBars1mOutput { rows, stats } +} + +/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via +/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through +/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] +/// rows sorted and unique by `(listing_id, ts)`. +/// +/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`]. +/// Non-blank `mapping_source` values are looked up verbatim. +/// - Rows whose `(mapping_source, source_id, session_date)` is not covered by any range in +/// `provider_mapping` are counted in [`CurateBars1mStats::dropped_unmapped`]. +/// - After re-sorting in place by `(listing_id, ts)`, cross-`source_id` collisions on the same +/// `(listing_id, ts)` collapse to one row when OHLCV (bitwise) and `session` match +/// (`listing_collision_collapsed += g - 1`), and drop the entire group otherwise +/// (`listing_collision_dropped += g`). +pub fn curate_bars_1m( + bars: B, + splits: &SplitTable, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, +) -> Result +where + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mError::EmptyMappingSource); + } + + let built = build_bars_1m(bars, splits); + Ok(map_bars_1m( + built, + provider_mapping, + mapping_source, + BARS_1M_SOURCE_EOD, + )) } /// Thin wrapper running [`check_session_closes_against_bars_1d`] over `listing_id`-keyed curated diff --git a/tools/curate-etl/src/curate_qm_bars_1m.rs b/tools/curate-etl/src/curate_qm_bars_1m.rs new file mode 100644 index 00000000..19fb6e0c --- /dev/null +++ b/tools/curate-etl/src/curate_qm_bars_1m.rs @@ -0,0 +1,206 @@ +//! Pure, in-memory `bars_1m` curation stage for raw QuoteMedia `qmIntraday` bars (`M2.3j`), +//! joining [`crate::bars_1m::build_bars_1m`], [`crate::provider_mapping::ProviderMappingTable`], +//! [`crate::ilp::IlpShardedWriter`], and [`crate::bson_stream::decode_qm_intraday_stream`]. +//! +//! # Contract & Point-in-Time Rules +//! - Uses [`EodIntradayBar`] as the existing source-keyed carrier for canonical raw QuoteMedia +//! OHLCV and `qmSearchCode`. +//! - **No split un-adjustment:** `qmIntraday` raw fields (`open`, `high`, `low`, `close`, +//! `sharevolume`) are already un-adjusted (`design/DATA-CONTRACTS.md` §1). This stage takes no +//! [`SplitTable`] and invokes [`build_bars_1m`] with an internal empty [`SplitTable`] so valid +//! OHLCV values pass through bit-identical while reusing Eastern Time session tagging, OHLCV +//! validation, and same-key deduplication. +//! - **Signed-zero volume normalization:** [`crate::bson_qm_intraday::decode_qm_intraday_doc`] +//! normalizes `-0.0` `sharevolume` to `+0.0` during BSON decode, and [`build_bars_1m`] applies +//! the same `-0.0 -> +0.0` normalization for direct in-memory inputs. +//! - Resolves each built row's `(mapping_source, qmSearchCode, session_date)` to a permanent +//! `listing_id: i32` on its Eastern Time `session_date`, stamps [`BARS_1M_SOURCE_QM`] +//! (`"qm_raw"`), re-sorts in place by `(listing_id, ts)`, and compacts cross-`source_id` +//! collisions using the same bitwise-equality / conflict-drop rule as [`crate::curate_bars_1m`]. +//! - Writes sorted `Bar1mRow` rows into a caller-owned [`IlpShardedWriter`] without calling +//! [`IlpShardedWriter::finish`], allowing multiple chunks to stream through one writer. + +use std::error::Error; +use std::fmt; +use std::hash::Hash; +use std::io::{self, Write}; + +use crate::bars_1m::{build_bars_1m, EodIntradayBar, BARS_1M_SOURCE_QM}; +use crate::bson_qm_intraday::BsonQmIntradayDecodeStats; +use crate::bson_stream::{decode_qm_intraday_stream, BsonStreamError, BsonStreamOptions}; +use crate::curate_bars_1m::{ + map_bars_1m, CurateBars1mError, CurateBars1mOutput, CurateBars1mWriteError, + CurateBars1mWriteReport, +}; +use crate::ilp::IlpShardedWriter; +use crate::provider_mapping::ProviderMappingTable; +use crate::split::SplitTable; + +/// Combined decode and write summary returned by [`curate_and_write_qm_bars_1m_from_bson`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateQmBars1mBsonReport { + pub decode_stats: BsonQmIntradayDecodeStats, + pub write_report: CurateBars1mWriteReport, +} + +/// Typed error returned by [`curate_and_write_qm_bars_1m_from_bson`]. +#[derive(Debug)] +pub enum CurateQmBars1mBsonError { + Stream(BsonStreamError), + Write(CurateBars1mWriteError), +} + +impl fmt::Display for CurateQmBars1mBsonError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "qmIntraday bars_1m BSON stream failed: {err}"), + Self::Write(err) => write!(f, "{err}"), + } + } +} + +impl Error for CurateQmBars1mBsonError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Write(err) => Some(err), + } + } +} + +impl From for CurateQmBars1mBsonError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for CurateQmBars1mBsonError { + fn from(err: CurateBars1mWriteError) -> Self { + Self::Write(err) + } +} + +/// Pure `qmIntraday` -> `bars_1m` curation stage: validates, session-tags, and deduplicates +/// already-raw QuoteMedia 1-minute bars via [`build_bars_1m`] with an internal empty +/// [`SplitTable`] (no split un-adjustment), resolves +/// `(mapping_source, qmSearchCode, session_date) -> listing_id` on each bar's Eastern Time +/// `session_date`, stamps [`BARS_1M_SOURCE_QM`], and emits [`crate::bars_1m::Bar1mRow`] rows +/// sorted and unique by `(listing_id, ts)`. +/// +/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`] +/// before consuming `bars`. Non-blank `mapping_source` values are looked up verbatim. +/// - Accepts no [`SplitTable`]: raw `qmIntraday` OHLCV passes through bit-identical (aside from +/// `-0.0 -> +0.0` volume normalization). +/// - Shares [`CurateBars1mOutput`], [`crate::curate_bars_1m::CurateBars1mStats`], and +/// [`CurateBars1mError`] with [`crate::curate_bars_1m::curate_bars_1m`]. +pub fn curate_qm_bars_1m( + bars: B, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, +) -> Result +where + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mError::EmptyMappingSource); + } + + let empty_splits = SplitTable::::default(); + let built = build_bars_1m(bars, &empty_splits); + Ok(map_bars_1m( + built, + provider_mapping, + mapping_source, + BARS_1M_SOURCE_QM, + )) +} + +/// Runs [`curate_qm_bars_1m`] and streams every curated row in `(listing_id, ts)` order into the +/// caller-owned [`IlpShardedWriter`] using `known_at_micros`. +/// +/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple +/// chunks through a single writer before flushing and collecting aggregate +/// [`crate::ilp::IlpWriteStats`]. +pub fn curate_and_write_qm_bars_1m( + bars: B, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + writer: &mut IlpShardedWriter, + known_at_micros: i64, +) -> Result +where + W: Write + Send, + K: Ord + Eq + Hash + Clone + AsRef, + B: IntoIterator>, +{ + let curated = curate_qm_bars_1m(bars, provider_mapping, mapping_source)?; + let mut rows_written = 0usize; + for row in &curated.rows { + writer.write_bar_1m(row, known_at_micros)?; + rows_written += 1; + } + + Ok(CurateBars1mWriteReport { + curate_stats: curated.stats, + rows_written, + }) +} + +/// Decodes a concatenated raw BSON `qmIntraday` stream via [`decode_qm_intraday_stream`], +/// converts each valid document via +/// [`crate::bson_qm_intraday::RawQmIntradayBar::into_eod_intraday_bar`], and runs +/// [`curate_and_write_qm_bars_1m`] against the caller-owned [`IlpShardedWriter`]. +/// +/// - Rejects empty or whitespace-only `mapping_source` before reading `reader` or writing to +/// `writer`. +/// - Per-document semantic decode errors are counted and skipped in [`BsonQmIntradayDecodeStats`]; +/// fatal stream framing or I/O errors abort before any row from this call is written to `writer`. +/// +/// # Memory note +/// This helper buffers all decoded [`EodIntradayBar`] rows for a single call in memory +/// before curating and writing. Bounded chunking by listing or calendar month is handled by +/// higher-level runner stages. +pub fn curate_and_write_qm_bars_1m_from_bson( + reader: R, + options: BsonStreamOptions, + provider_mapping: &ProviderMappingTable, + mapping_source: &str, + writer: &mut IlpShardedWriter, + known_at_micros: i64, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource).into()); + } + + let mut bars: Vec> = Vec::new(); + let decode_stats = decode_qm_intraday_stream( + reader, + options, + |raw| { + bars.push(raw.into_eod_intraday_bar(|code, _| code.to_owned())); + }, + |_offset, _err| {}, + )?; + + let write_report = curate_and_write_qm_bars_1m( + bars, + provider_mapping, + mapping_source, + writer, + known_at_micros, + )?; + + Ok(CurateQmBars1mBsonReport { + decode_stats, + write_report, + }) +} + +#[cfg(test)] +#[path = "curate_qm_bars_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs new file mode 100644 index 00000000..1812141c --- /dev/null +++ b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs @@ -0,0 +1,605 @@ +use std::error::Error; +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime; + +use super::*; +use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM}; +use crate::bson_qm_intraday::decode_qm_intraday_bytes; +use crate::curate_bars_1m::curate_bars_1m; +use crate::ilp::{encode_bar_1m, shard_for_listing_id, IlpWriterOptions, TABLE_BARS_1M}; +use crate::provider_mapping::ProviderMappingRow; +use crate::shorts::et_to_utc_micros; +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).expect("valid date") +} + +fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") +} + +fn bar_1m( + key: &str, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> EodIntradayBar { + EodIntradayBar { + key: key.to_string(), + ts, + open, + high, + low, + close, + volume, + } +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +#[allow(clippy::too_many_arguments)] +fn make_qm_bson_doc( + code: &str, + ts_micros: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, +) -> RawDocumentBuf { + assert_eq!(ts_micros % 1_000, 0, "qm timestamp must be millisecond-aligned"); + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), DateTime::from_millis(ts_micros / 1_000)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), sharevolume); + doc +} + +fn assert_conservation_and_order(out: &CurateBars1mOutput) { + let s = &out.stats; + assert_eq!( + s.rows_in, s.builder.rows_out, + "rows_in != builder.rows_out: {s:?}" + ); + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.listing_collision_collapsed + + s.listing_collision_dropped, + "curate_qm_bars_1m conservation invariant failed: {s:?}" + ); + assert_eq!( + s.rows_out, + s.pre_rows_out + s.rth_rows_out + s.post_rows_out, + "session breakdown != rows_out: {s:?}" + ); + + for pair in out.rows.windows(2) { + assert!( + (pair[0].key, pair[0].ts) < (pair[1].key, pair[1].ts), + "rows not strictly sorted and unique by (listing_id, ts): {:?} vs {:?}", + (pair[0].key, pair[0].ts), + (pair[1].key, pair[1].ts) + ); + } +} + +fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) +} + +#[test] +fn raw_qm_passthrough_preserves_ohlcv_bits_across_future_split_unlike_eod_control() { + let pre_day = day(2024, 6, 7); + let ex_date = day(2024, 6, 10); + let nvda_listing_id = 77_001; + let pre_ts = et_ts(2024, 6, 7, 15, 59); + + // Pre-split NVDA raw values vs 10:1 retroactively split-adjusted values. + let raw_open = 1205.0_f64; + let raw_high = 1210.0_f64; + let raw_low = 1204.0_f64; + let raw_close = 1208.88_f64; + let raw_vol = 41_239.0_f64; + + let mut qm_doc = make_qm_bson_doc( + "NVDA", + pre_ts, + raw_open, + raw_high, + raw_low, + raw_close, + raw_vol, + ); + // Distinct adjusted fields in the same BSON document must be ignored. + qm_doc.append(cstr!("adjustedopen"), 120.50_f64); + qm_doc.append(cstr!("adjustedhigh"), 121.00_f64); + qm_doc.append(cstr!("adjustedlow"), 120.40_f64); + qm_doc.append(cstr!("adjustedclose"), 120.888_f64); + qm_doc.append(cstr!("avolume"), 412_390.0_f64); + + let decoded = decode_qm_intraday_bytes(qm_doc.as_bytes()).unwrap(); + let qm_bar = decoded.into_eod_intraday_bar(|code, _| code.to_owned()); + + let splits = SplitTable::from_events([( + "NVDA".to_string(), + SplitEvent { + ex_date, + ratio: 10.0, + }, + )]) + .unwrap(); + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(2020, 1, 1), + None, + nvda_listing_id, + )]) + .unwrap(); + + // Control: EOD stage with the 10:1 split DOES scale OHLCV (and stamps BARS_1M_SOURCE_EOD). + let eod_control = curate_bars_1m([qm_bar.clone()], &splits, &mapping, "qm").unwrap(); + assert_eq!(eod_control.rows.len(), 1); + let eod_row = &eod_control.rows[0]; + assert_eq!(eod_row.source, BARS_1M_SOURCE_EOD); + assert_ne!(eod_row.open.to_bits(), qm_bar.open.to_bits()); + assert_ne!(eod_row.high.to_bits(), qm_bar.high.to_bits()); + assert_ne!(eod_row.low.to_bits(), qm_bar.low.to_bits()); + assert_ne!(eod_row.close.to_bits(), qm_bar.close.to_bits()); + assert_ne!(eod_row.volume.to_bits(), qm_bar.volume.to_bits()); + + // QuoteMedia stage accepts no SplitTable and preserves all five OHLCV fields bit-identically. + let qm_out = curate_qm_bars_1m([qm_bar.clone()], &mapping, "qm").unwrap(); + assert_conservation_and_order(&qm_out); + assert_eq!(qm_out.rows.len(), 1); + let row = &qm_out.rows[0]; + assert_eq!(row.key, nvda_listing_id); + assert_eq!(row.ts, pre_ts); + assert_eq!(row.session_date, pre_day); + assert_eq!(row.session, IntradaySession::Rth); + assert_eq!(row.source, BARS_1M_SOURCE_QM); + assert_ne!(row.source, BARS_1M_SOURCE_EOD); + assert_eq!(row.open.to_bits(), raw_open.to_bits()); + assert_eq!(row.high.to_bits(), raw_high.to_bits()); + assert_eq!(row.low.to_bits(), raw_low.to_bits()); + assert_eq!(row.close.to_bits(), raw_close.to_bits()); + assert_eq!(row.volume.to_bits(), raw_vol.to_bits()); +} + +#[test] +fn mapping_uses_eastern_time_session_date_boundaries_gaps_and_is_shuffle_invariant() { + // 2024-06-10 20:30 ET (EDT = UTC-4) is 2024-06-11 00:30 UTC (next UTC calendar day). + // Mapping ends inclusively on 2024-06-10, so ET session_date resolves while UTC date would drop. + let d_start = day(2024, 6, 10); + let d_gap = day(2024, 6, 11); + let d_resume = day(2024, 6, 12); + + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "ACME:CA", d_start, Some(d_start), 101), + map_row("qm", "ACME:CA", d_resume, None, 202), + map_row("qm", "BETA", d_start, Some(d_resume), 303), + ]) + .unwrap(); + + // PRE on inclusive valid_from (2024-06-10 08:00 ET) -> listing 101 + let b_pre = bar_1m("ACME:CA", et_ts(2024, 6, 10, 8, 0), 10.0, 10.2, 9.9, 10.1, 100.0); + // POST on inclusive valid_to whose UTC date is 2024-06-11 -> listing 101 + let b_post_utc_next = bar_1m("ACME:CA", et_ts(2024, 6, 10, 20, 30), 10.1, 10.3, 10.0, 10.2, 50.0); + // Date inside gap (2024-06-11) -> dropped_unmapped + let b_gap = bar_1m("ACME:CA", et_ts(2024, 6, 11, 10, 0), 10.5, 10.6, 10.4, 10.5, 200.0); + // RTH on inclusive second range valid_from (2024-06-12) -> listing 202 + let b_resumed = bar_1m("ACME:CA", et_ts(2024, 6, 12, 10, 0), 11.0, 11.2, 10.9, 11.1, 300.0); + // RTH for BETA on 2024-06-11 -> listing 303 + let b_beta = bar_1m("BETA", et_ts(2024, 6, 11, 14, 15), 25.0, 25.5, 24.8, 25.2, 400.0); + // Unknown qmSearchCode -> dropped_unmapped + let b_unknown = bar_1m("UNKNOWN", et_ts(2024, 6, 10, 10, 0), 5.0, 5.1, 4.9, 5.0, 10.0); + + let ordered = vec![ + b_pre.clone(), + b_post_utc_next.clone(), + b_gap.clone(), + b_resumed.clone(), + b_beta.clone(), + b_unknown.clone(), + ]; + let shuffled = vec![ + b_unknown, + b_resumed, + b_post_utc_next, + b_beta, + b_gap, + b_pre, + ]; + + let out_ordered = curate_qm_bars_1m(ordered, &mapping, "qm").unwrap(); + let out_shuffled = curate_qm_bars_1m(shuffled, &mapping, "qm").unwrap(); + + assert_conservation_and_order(&out_ordered); + assert_conservation_and_order(&out_shuffled); + assert_eq!(out_ordered, out_shuffled); + + assert_eq!(out_ordered.stats.rows_in, 6); + assert_eq!(out_ordered.stats.rows_out, 4); + assert_eq!(out_ordered.stats.dropped_unmapped, 2); + assert_eq!(out_ordered.stats.listings_out, 3); + assert_eq!(out_ordered.stats.pre_rows_out, 1); + assert_eq!(out_ordered.stats.rth_rows_out, 2); + assert_eq!(out_ordered.stats.post_rows_out, 1); + + // Verify exact ET session_date and listing assignment on the UTC-next-day POST bar. + let post_row = out_ordered + .rows + .iter() + .find(|r| r.session == IntradaySession::Post) + .expect("POST row present"); + assert_eq!(post_row.key, 101); + assert_eq!(post_row.session_date, d_start); + assert_ne!(post_row.session_date, d_gap); + assert!(out_ordered.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); +} + +#[test] +fn same_code_duplicates_and_cross_code_alias_collisions_enforce_conservation() { + let listing_id = 505; + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "OLD:CA", day(2024, 1, 1), None, listing_id), + map_row("qm", "NEW:CA", day(2024, 1, 1), None, listing_id), + map_row("qm", "ALT:CA", day(2024, 1, 1), None, listing_id), + ]) + .unwrap(); + + let ts_same_dup = et_ts(2024, 6, 10, 9, 30); + let ts_alias_ok = et_ts(2024, 6, 10, 9, 31); + let ts_alias_conflict = et_ts(2024, 6, 10, 9, 32); + let ts_unique_post = et_ts(2024, 6, 10, 16, 5); + + let bars = vec![ + // Same-code exact duplicate -> collapsed in builder (duplicate_collapsed = 1). + bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), + bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), + // Three distinct qmSearchCodes with bit-identical OHLCV -> group of 3 collapses by g-1 = 2. + bar_1m("OLD:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), + bar_1m("NEW:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), + bar_1m("ALT:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), + // Two distinct qmSearchCodes with conflicting close -> entire group of g = 2 dropped. + bar_1m("OLD:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.5, 300.0), + bar_1m("NEW:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.6, 300.0), + // Clean POST row. + bar_1m("NEW:CA", ts_unique_post, 10.6, 10.7, 10.5, 10.65, 0.0), + ]; + + let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.builder.bars_in, 8); + assert_eq!(out.stats.builder.duplicate_collapsed, 1); + assert_eq!(out.stats.builder.rows_out, 7); + assert_eq!(out.stats.rows_in, 7); + assert_eq!(out.stats.listing_collision_collapsed, 2); + assert_eq!(out.stats.listing_collision_dropped, 2); + assert_eq!(out.stats.dropped_unmapped, 0); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.listings_out, 1); + assert_eq!(out.stats.pre_rows_out, 0); + assert_eq!(out.stats.rth_rows_out, 2); + assert_eq!(out.stats.post_rows_out, 1); + + let emitted_ts: Vec = out.rows.iter().map(|r| r.ts).collect(); + assert_eq!(emitted_ts, vec![ts_same_dup, ts_alias_ok, ts_unique_post]); + assert!(out.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); +} + +#[test] +fn bson_to_ilp_streams_multi_chunk_writes_qm_raw_and_supports_writer_reuse() { + let known_at = 1_718_050_123_456_000_i64; + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "NVDA", day(2020, 1, 1), None, 101), + map_row("qm", "SHOP:CA", day(2020, 1, 1), None, 202), + ]) + .unwrap(); + + let ts1 = et_ts(2024, 6, 7, 15, 59); + let ts2 = et_ts(2024, 6, 10, 9, 30); + let ts3 = et_ts(2024, 6, 10, 16, 10); + + let doc1 = make_qm_bson_doc("NVDA", ts1, 1205.0, 1210.0, 1204.0, 1208.88, 41_239.0); + // Semantically invalid doc: missing required field `close`. + let mut bad_doc = RawDocumentBuf::new(); + bad_doc.append(cstr!("qmSearchCode"), "NVDA"); + bad_doc.append(cstr!("timestamp"), DateTime::from_millis(ts2 / 1_000)); + bad_doc.append(cstr!("open"), 120.0_f64); + bad_doc.append(cstr!("high"), 121.0_f64); + bad_doc.append(cstr!("low"), 119.5_f64); + bad_doc.append(cstr!("sharevolume"), 1_000.0_f64); + let doc2 = make_qm_bson_doc("SHOP:CA", ts2, 88.0, 89.0, 87.5, 88.4, 2_500.0); + + let mut chunk1_bytes = Vec::new(); + chunk1_bytes.extend_from_slice(doc1.as_bytes()); + chunk1_bytes.extend_from_slice(bad_doc.as_bytes()); + chunk1_bytes.extend_from_slice(doc2.as_bytes()); + + let doc3 = make_qm_bson_doc("NVDA", ts3, 121.0, 121.5, 120.8, 121.2, 5_000.0); + let chunk2_bytes = doc3.as_bytes().to_vec(); + + // Force multi-chunk streaming with a tiny chunk capacity smaller than two documents. + let stream_opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let mut s2 = Vec::new(); + let mut s3 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1, &mut s2, &mut s3], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&chunk1_bytes), + stream_opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + // Reuse the same open writer for a second call. + let rep2 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&chunk2_bytes), + stream_opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + assert_eq!(rep1.decode_stats.docs_seen, 3); + assert_eq!(rep1.decode_stats.rows_decoded, 2); + assert_eq!(rep1.decode_stats.rejected_missing_field, 1); + assert_eq!( + rep1.decode_stats.docs_seen, + rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() + ); + assert_eq!(rep1.write_report.rows_written, 2); + assert_eq!( + rep1.write_report.rows_written, + rep1.write_report.curate_stats.rows_out + ); + + assert_eq!(rep2.decode_stats.docs_seen, 1); + assert_eq!(rep2.decode_stats.rows_decoded, 1); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!( + ilp_stats.rows, + rep1.write_report.rows_written + rep2.write_report.rows_written + ); + assert_eq!(ilp_stats.rows, 3); + + // Build expected exact ILP lines for each emitted row and verify per-shard routing, + // `source=qm_raw`, exact `known_at`, and per-shard ordering. + let expected_row1 = Bar1mRow { + key: 101, + ts: ts1, + session_date: day(2024, 6, 7), + open: 1205.0, + high: 1210.0, + low: 1204.0, + close: 1208.88, + volume: 41_239.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_QM, + }; + let expected_row2 = Bar1mRow { + key: 202, + ts: ts2, + session_date: day(2024, 6, 10), + open: 88.0, + high: 89.0, + low: 87.5, + close: 88.4, + volume: 2_500.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_QM, + }; + let expected_row3 = Bar1mRow { + key: 101, + ts: ts3, + session_date: day(2024, 6, 10), + open: 121.0, + high: 121.5, + low: 120.8, + close: 121.2, + volume: 5_000.0, + session: IntradaySession::Post, + source: BARS_1M_SOURCE_QM, + }; + + let mut expected_shards = vec![Vec::::new(); 4]; + for row in [&expected_row1, &expected_row2, &expected_row3] { + let shard = shard_for_listing_id(row.key, 4); + encode_bar_1m(&mut expected_shards[shard], row, known_at).unwrap(); + } + + let actual_shards = [&s0, &s1, &s2, &s3]; + for (idx, (actual, expected)) in actual_shards.iter().zip(&expected_shards).enumerate() { + assert_eq!(*actual, expected, "shard {idx} ILP bytes mismatch"); + } + + let all_bytes: Vec = actual_shards.iter().flat_map(|s| s.iter().copied()).collect(); + assert!(contains_subslice(&all_bytes, TABLE_BARS_1M.as_bytes())); + assert!(contains_subslice( + &all_bytes, + format!("source={BARS_1M_SOURCE_QM}").as_bytes() + )); + assert!(!contains_subslice( + &all_bytes, + format!("source={BARS_1M_SOURCE_EOD}").as_bytes() + )); + assert!(contains_subslice( + &all_bytes, + format!("known_at={known_at}t").as_bytes() + )); +} + +struct CountingReader { + inner: R, + reads: usize, +} + +impl Read for CountingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reads += 1; + self.inner.read(buf) + } +} + +#[test] +fn truncated_stream_and_blank_mapping_source_fail_closed_with_zero_writes() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(2020, 1, 1), + None, + 101, + )]) + .unwrap(); + let known_at = 1_718_050_000_000_000_i64; + + let doc1 = make_qm_bson_doc( + "NVDA", + et_ts(2024, 6, 7, 15, 59), + 1205.0, + 1210.0, + 1204.0, + 1208.88, + 41_239.0, + ); + let doc2 = make_qm_bson_doc( + "NVDA", + et_ts(2024, 6, 10, 15, 59), + 121.0, + 121.5, + 120.8, + 121.2, + 5_000.0, + ); + + // Truncated tail after a valid document with max_batch_rows = 1 must write zero bytes. + let mut truncated_bytes = Vec::new(); + truncated_bytes.extend_from_slice(doc1.as_bytes()); + let doc2_bytes = doc2.as_bytes(); + truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (err, trunc_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&truncated_bytes), + BsonStreamOptions::default(), + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + assert!(matches!( + err, + CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert!(err.source().is_some()); + assert_eq!(trunc_stats.rows, 0); + assert!(s0.is_empty()); + assert!(s1.is_empty()); + + // Blank mapping_source on pure stage returns EmptyMappingSource. + let pure_err = curate_qm_bars_1m( + [bar_1m("NVDA", et_ts(2024, 6, 7, 15, 59), 10.0, 11.0, 9.0, 10.5, 100.0)], + &mapping, + " \t", + ) + .unwrap_err(); + assert_eq!(pure_err, CurateBars1mError::EmptyMappingSource); + + // Blank mapping_source on BSON stage rejects before any read or write. + let mut counting_reader = CountingReader { + inner: Cursor::new(doc1.as_bytes()), + reads: 0, + }; + let mut sink = Vec::new(); + let (blank_err, blank_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m_from_bson( + &mut counting_reader, + BsonStreamOptions::default(), + &mapping, + " \n\t ", + &mut writer, + known_at, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + assert!(matches!( + blank_err, + CurateQmBars1mBsonError::Write(CurateBars1mWriteError::Curate( + CurateBars1mError::EmptyMappingSource + )) + )); + assert!(blank_err.source().is_some()); + assert_eq!(counting_reader.reads, 0); + assert_eq!(blank_stats.rows, 0); + assert!(sink.is_empty()); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index e853e210..c174442b 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -47,7 +47,7 @@ pub use bars_1m::{ build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, Bar1mRow, Bars1mBuild, Bars1mError, Bars1mStats, DailySessionClose, EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, - BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, + BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, }; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, @@ -82,12 +82,13 @@ pub use bson_qm_prices::{ }; pub use bson_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, - decode_te_market_data_stream, BsonCeoShortsStreamError, BsonQmEventsStreamError, - BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, + 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_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_chunks, + decode_qm_price_stream, decode_qm_split_chunks, decode_qm_split_stream, + decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError, + BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; pub use bson_te_market_data::{ @@ -249,6 +250,12 @@ pub use curate_bars_1m::{ CurateBars1mOutput, CurateBars1mStats, CurateBars1mWriteError, CurateBars1mWriteReport, }; +pub mod curate_qm_bars_1m; +pub use curate_qm_bars_1m::{ + curate_and_write_qm_bars_1m, curate_and_write_qm_bars_1m_from_bson, curate_qm_bars_1m, + CurateQmBars1mBsonError, CurateQmBars1mBsonReport, +}; + pub mod run_curate_bars; pub use run_curate_bars::{ default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv, From 1e47524343f6244f722b9d2f1c1cdc9543fe20e0 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:20:59 -0500 Subject: [PATCH 09/10] T-152: tests --- .../curate-etl/src/curate_qm_bars_1m_tests.rs | 218 ++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs index 1812141c..22a3eff9 100644 --- a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs +++ b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs @@ -603,3 +603,221 @@ fn truncated_stream_and_blank_mapping_source_fail_closed_with_zero_writes() { assert_eq!(blank_stats.rows, 0); assert!(sink.is_empty()); } + +// --------------------------------------------------------------------------------------------- +// QA (T-152) additional coverage. +// --------------------------------------------------------------------------------------------- + +#[test] +fn qa_bson_to_ilp_reorders_reverse_ts_rows_within_one_shard_and_reuses_writer() { + // Two valid bars for the same listing in REVERSE timestamp order in one BSON call: the shard + // must receive them ascending by ts. A single shard makes every row share one sink. + let known_at = 1_718_100_000_000_000_i64; + let mapping = + ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) + .unwrap(); + let ts_early = et_ts(2024, 6, 10, 9, 30); + let ts_late = et_ts(2024, 6, 10, 9, 45); + let ts_next = et_ts(2024, 6, 11, 9, 30); + + let late = make_qm_bson_doc("NVDA", ts_late, 121.0, 122.0, 120.5, 121.5, 900.0); + let early = make_qm_bson_doc("NVDA", ts_early, 120.0, 120.9, 119.8, 120.6, 700.0); + let mut call1 = Vec::new(); + call1.extend_from_slice(late.as_bytes()); + call1.extend_from_slice(early.as_bytes()); + let call2 = make_qm_bson_doc("NVDA", ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0) + .as_bytes() + .to_vec(); + + let opts = BsonStreamOptions { + chunk_capacity_bytes: 48, + max_doc_bytes: 4096, + }; + let mut sink = Vec::new(); + let (rep1, rep2, stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_bytes: 1 << 16, + max_batch_rows: 1, + }, + ) + .unwrap(); + let rep1 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&call1), + opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + let rep2 = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&call2), + opts, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap(); + (rep1, rep2, writer.finish().unwrap()) + }; + assert_eq!(rep1.write_report.rows_written, 2); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!(stats.rows, 3); + + let row = |ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64, date: i32| Bar1mRow { + key: 101, + ts, + session_date: date, + open: o, + high: h, + low: l, + close: c, + volume: v, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_QM, + }; + let mut expected = Vec::new(); + for r in [ + row(ts_early, 120.0, 120.9, 119.8, 120.6, 700.0, day(2024, 6, 10)), + row(ts_late, 121.0, 122.0, 120.5, 121.5, 900.0, day(2024, 6, 10)), + row(ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0, day(2024, 6, 11)), + ] { + encode_bar_1m(&mut expected, &r, known_at).unwrap(); + } + assert_eq!(sink, expected, "shard must receive rows ascending by ts across calls"); +} + +#[test] +fn qa_invalid_ohlcv_and_out_of_range_dates_are_accounted_and_volume_neg_zero_normalized() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "ACME", + day(2024, 6, 10), + Some(day(2024, 6, 10)), + 9, + )]) + .unwrap(); + let bars = vec![ + // Valid, -0.0 volume -> +0.0. + bar_1m("ACME", et_ts(2024, 6, 10, 10, 0), 10.0, 10.5, 9.5, 10.2, -0.0), + // high < low -> builder drops (inconsistent). + bar_1m("ACME", et_ts(2024, 6, 10, 10, 1), 10.0, 9.0, 9.5, 10.2, 1.0), + // NaN close -> builder drops. + bar_1m("ACME", et_ts(2024, 6, 10, 10, 2), 10.0, 10.5, 9.5, f64::NAN, 1.0), + // Negative volume -> builder drops. + bar_1m("ACME", et_ts(2024, 6, 10, 10, 3), 10.0, 10.5, 9.5, 10.2, -5.0), + // Day before valid_from and day after valid_to -> dropped_unmapped. + bar_1m("ACME", et_ts(2024, 6, 7, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), + bar_1m("ACME", et_ts(2024, 6, 11, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), + ]; + let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); + assert_conservation_and_order(&out); + let b = &out.stats.builder; + assert_eq!(b.bars_in, 6); + assert_eq!( + b.dropped_invalid_ohlc + b.dropped_inconsistent_ohlc + b.dropped_invalid_volume, + 3, + "{b:?}" + ); + assert_eq!(out.stats.rows_in, 3); + assert_eq!(out.stats.dropped_unmapped, 2); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.rows[0].volume.to_bits(), 0.0_f64.to_bits()); + assert_eq!(out.rows[0].source, BARS_1M_SOURCE_QM); +} + +#[test] +fn qa_mapping_source_is_namespace_scoped_and_matched_verbatim() { + // Same code under a different provider namespace (`eod`) must not resolve for `qm`. + let mapping = ProviderMappingTable::from_rows([ + map_row("eod", "NVDA", day(2020, 1, 1), None, 1), + map_row("qm", "NVDA", day(2020, 1, 1), None, 2), + ]) + .unwrap(); + let bars = || [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)]; + let qm = curate_qm_bars_1m(bars(), &mapping, "qm").unwrap(); + assert_eq!(qm.rows.len(), 1); + assert_eq!(qm.rows[0].key, 2); + // Padded namespace is non-blank and looked up verbatim -> nothing matches. + let padded = curate_qm_bars_1m(bars(), &mapping, " qm").unwrap(); + assert_conservation_and_order(&padded); + assert_eq!(padded.rows.len(), 0); + assert_eq!(padded.stats.dropped_unmapped, 1); +} + +#[test] +fn qa_curate_and_write_blank_namespace_and_multichunk_truncation_write_nothing() { + let mapping = + ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) + .unwrap(); + let known_at = 1_718_000_000_000_000_i64; + + // In-memory write path: blank namespace -> Curate error, zero bytes. + let mut sink = Vec::new(); + { + let mut writer = IlpShardedWriter::new( + vec![&mut sink], + IlpWriterOptions { + max_batch_bytes: 1, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m( + [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)], + &mapping, + "", + &mut writer, + known_at, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource) + )); + assert_eq!(writer.finish().unwrap().rows, 0); + } + assert!(sink.is_empty()); + + // Many valid docs streamed across many small chunks, then a truncated tail: zero bytes. + let mut bytes = Vec::new(); + for m in 0..20u8 { + let doc = make_qm_bson_doc("NVDA", et_ts(2024, 6, 10, 10, m), 1.0, 1.0, 1.0, 1.0, 1.0); + bytes.extend_from_slice(doc.as_bytes()); + } + bytes.extend_from_slice(&200_i32.to_le_bytes()); + bytes.extend_from_slice(&[0x02, b'x']); + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_qm_bars_1m_from_bson( + Cursor::new(&bytes), + BsonStreamOptions { + chunk_capacity_bytes: 40, + max_doc_bytes: 4096, + }, + &mapping, + "qm", + &mut writer, + known_at, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert_eq!(writer.finish().unwrap().rows, 0); + } + assert!(s0.is_empty() && s1.is_empty()); +} From 95875dc87da6867709e7d37313cd27818f86cfe9 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:39:51 -0500 Subject: [PATCH 10/10] =?UTF-8?q?T-153:=20M2.3k=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`fx=5F1m`=20curation=20stage=20(`CAD.FOREX`=20?= =?UTF-8?q?`eodIntraday1M`=20=E2=86=92=20validated/deduped=20`Fx1mRow`=20?= =?UTF-8?q?=E2=86=92=20`IlpShardedWriter`)=20with=20tests=20(full=20pipeli?= =?UTF-8?q?ne;=20no=20new=20crates,=20no=20CLI/bench=20changes,=20no=20liv?= =?UTF-8?q?e=20Mongo/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/curate_fx_1m.rs | 327 ++++++++++++ tools/curate-etl/src/curate_fx_1m_tests.rs | 560 +++++++++++++++++++++ tools/curate-etl/src/lib.rs | 7 + 3 files changed, 894 insertions(+) create mode 100644 tools/curate-etl/src/curate_fx_1m.rs create mode 100644 tools/curate-etl/src/curate_fx_1m_tests.rs diff --git a/tools/curate-etl/src/curate_fx_1m.rs b/tools/curate-etl/src/curate_fx_1m.rs new file mode 100644 index 00000000..0bdcc390 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_1m.rs @@ -0,0 +1,327 @@ +//! Pure, in-memory `fx_1m` curation stage for EODHD `CAD.FOREX` 1-minute FX bars (`M2.3k`), +//! joining [`crate::bson_eod_intraday::RawEodIntradayBar`], +//! [`crate::bson_stream::decode_eod_intraday_stream`], and [`crate::ilp::IlpShardedWriter`]. +//! +//! # Contract & Point-in-Time Rules +//! - **Source selection:** accepts only rows whose `eod_search_code` matches +//! [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`) verbatim. Any other code is dropped and counted in +//! [`CurateFx1mStats::dropped_wrong_code`] without erroring. +//! - **No split un-adjustment, listing mapping, or session tagging:** FX trades ~24h and is not +//! subject to equity splits or `provider_mapping` ranges. Every valid `CAD.FOREX` bar is kept +//! with its UTC microsecond bar-start `ts` unchanged (preserving the source clock without +//! implying the bar's close was observable at bar start). +//! - **Rate direction & bitwise preservation:** OHLC values pass through bit-identical in CAD per +//! 1 USD (matching `fx_1d`); `volume` is ignored at the curation layer. +//! - **Canonical labels:** emits `pair = FX_PAIR_USDCAD` (`"USDCAD"`, shared with `fx_1d` so +//! daily and intraday FX tables join on the same label) and `source = FX_1M_SOURCE_EOD` +//! (`"eod"`, fitting QuestDB `SYMBOL CAPACITY 8`). +//! - **Validation precedence:** bad single bars never panic or abort the stage; each bar is +//! classified once in strict priority order: +//! 1. `dropped_wrong_code` (`eod_search_code != "CAD.FOREX"`) +//! 2. `dropped_negative_ts` (`ts < 0`) +//! 3. `dropped_invalid_ohlc` (any of `open`, `high`, `low`, `close` non-finite or `<= 0.0`) +//! 4. `dropped_high_below_bound` (`high < max(open, close, low)`) +//! 5. `dropped_low_above_bound` (`low > min(open, close)`) +//! - **Ordering & deduplication:** surviving rows are sorted ascending by `ts` and compacted in +//! place per timestamp group using `f64::to_bits` equality across all four OHLC fields: +//! bitwise-identical groups of size `n` emit one row (`duplicate_collapsed += n - 1`), while +//! conflicting groups emit zero rows (`duplicate_conflict_dropped += n`). +//! - **Writer lifecycle:** [`curate_and_write_fx_1m`] and [`curate_and_write_fx_1m_from_bson`] +//! stream sorted [`Fx1mRow`]s into a caller-owned [`IlpShardedWriter`] via +//! [`IlpShardedWriter::write_fx_1m`] without calling [`IlpShardedWriter::finish`], allowing +//! multiple chunks to share one writer. +//! +//! # Memory, Chunking & BSON Validation Boundary +//! - **In-memory sort & per-call deduplication:** sorting buffers accepted `CAD.FOREX` rows for a +//! single call in memory, and deduplication applies within that call only. Callers splitting +//! large inputs across calls must keep all copies of a timestamp in the same call and submit +//! chunks in chronological order when global ordering is required. +//! - **BSON validation boundary:** [`curate_and_write_fx_1m_from_bson`] decodes via +//! [`decode_eod_intraday_stream`], which validates non-empty `eodSearchCode`, non-negative +//! integral `timestamp`, finite positive OHLC, and finite non-negative `volume` before invoking +//! the curation accumulator. Document-level decode rejects are accounted in +//! [`BsonEodIntradayDecodeStats`] (so `decode_stats.rows_decoded == write_report.curate_stats.bars_in`), +//! while direct in-memory calls to [`build_fx_1m`] / [`curate_and_write_fx_1m`] exercise the full +//! builder validation rules and ignore `volume`. + +use std::error::Error; +use std::fmt; +use std::io::{self, Write}; + +use crate::bson_eod_intraday::{BsonEodIntradayDecodeStats, RawEodIntradayBar}; +use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; +use crate::fx::FX_PAIR_USDCAD; +use crate::ilp::{Fx1mRow, IlpShardedWriter, IlpWriterError}; +use crate::run_curate_fx::EOD_CAD_FOREX_CODE; + +/// Canonical provenance label written to [`Fx1mRow::source`] for EODHD `eodIntraday1M` FX bars +/// (`SYMBOL CAPACITY 8`). +pub const FX_1M_SOURCE_EOD: &str = "eod"; + +/// Accounting summary produced alongside [`CurateFx1mOutput::rows`]. +/// +/// Conservation invariant: +/// `bars_in == rows_out + dropped_wrong_code + dropped_negative_ts + dropped_invalid_ohlc + dropped_high_below_bound + dropped_low_above_bound + duplicate_collapsed + duplicate_conflict_dropped` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mStats { + pub bars_in: usize, + pub rows_out: usize, + pub dropped_wrong_code: usize, + pub dropped_negative_ts: usize, + pub dropped_invalid_ohlc: usize, + pub dropped_high_below_bound: usize, + pub dropped_low_above_bound: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, +} + +/// Output of [`build_fx_1m`]: curated `fx_1m` rows sorted and unique by `ts`, plus exact +/// accounting statistics. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1mOutput { + pub rows: Vec>, + pub stats: CurateFx1mStats, +} + +/// Summary returned by [`curate_and_write_fx_1m`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mWriteReport { + pub curate_stats: CurateFx1mStats, + /// Number of curated rows accepted by [`IlpShardedWriter::write_fx_1m`] in this call. + pub rows_written: usize, +} + +/// Combined decode and write summary returned by [`curate_and_write_fx_1m_from_bson`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mBsonReport { + pub decode_stats: BsonEodIntradayDecodeStats, + pub write_report: CurateFx1mWriteReport, +} + +/// Typed error returned by [`curate_and_write_fx_1m_from_bson`]. +#[derive(Debug)] +pub enum CurateFx1mBsonError { + Stream(BsonStreamError), + Write(IlpWriterError), +} + +impl fmt::Display for CurateFx1mBsonError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "fx_1m BSON stream failed: {err}"), + Self::Write(err) => write!(f, "fx_1m ILP write failed: {err}"), + } + } +} + +impl Error for CurateFx1mBsonError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Write(err) => Some(err), + } + } +} + +impl From for CurateFx1mBsonError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for CurateFx1mBsonError { + fn from(err: IlpWriterError) -> Self { + Self::Write(err) + } +} + +#[inline] +fn is_valid_rate(rate: f64) -> bool { + rate.is_finite() && rate > 0.0 +} + +#[inline] +fn fx_1m_ohlc_bit_eq(a: &Fx1mRow<'_>, b: &Fx1mRow<'_>) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() +} + +#[derive(Default)] +struct Fx1mAccumulator { + rows: Vec>, + stats: CurateFx1mStats, +} + +impl Fx1mAccumulator { + #[inline] + fn push(&mut self, bar: RawEodIntradayBar<'_>) { + self.stats.bars_in += 1; + + if bar.eod_search_code != EOD_CAD_FOREX_CODE { + self.stats.dropped_wrong_code += 1; + return; + } + if bar.ts < 0 { + self.stats.dropped_negative_ts += 1; + return; + } + if !is_valid_rate(bar.open) + || !is_valid_rate(bar.high) + || !is_valid_rate(bar.low) + || !is_valid_rate(bar.close) + { + self.stats.dropped_invalid_ohlc += 1; + return; + } + if bar.high < bar.open || bar.high < bar.close || bar.high < bar.low { + self.stats.dropped_high_below_bound += 1; + return; + } + if bar.low > bar.open || bar.low > bar.close { + self.stats.dropped_low_above_bound += 1; + return; + } + + self.rows.push(Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: bar.ts, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + source: FX_1M_SOURCE_EOD, + }); + } + + fn finish(mut self) -> CurateFx1mOutput { + self.rows.sort_unstable_by_key(|row| row.ts); + + let len = self.rows.len(); + let mut write_idx = 0usize; + let mut read_idx = 0usize; + + while read_idx < len { + let ts = self.rows[read_idx].ts; + let mut group_end = read_idx + 1; + while group_end < len && self.rows[group_end].ts == ts { + group_end += 1; + } + let group_len = group_end - read_idx; + let first = self.rows[read_idx]; + let all_identical = self.rows[read_idx + 1..group_end] + .iter() + .all(|other| fx_1m_ohlc_bit_eq(&first, other)); + + if all_identical { + self.stats.duplicate_collapsed += group_len - 1; + if write_idx != read_idx { + self.rows[write_idx] = first; + } + write_idx += 1; + } else { + self.stats.duplicate_conflict_dropped += group_len; + } + + read_idx = group_end; + } + + self.rows.truncate(write_idx); + self.stats.rows_out = self.rows.len(); + + CurateFx1mOutput { + rows: self.rows, + stats: self.stats, + } + } +} + +fn write_curated_fx_1m( + curated: CurateFx1mOutput, + writer: &mut IlpShardedWriter, +) -> Result { + let mut rows_written = 0usize; + for row in &curated.rows { + writer.write_fx_1m(row)?; + rows_written += 1; + } + + Ok(CurateFx1mWriteReport { + curate_stats: curated.stats, + rows_written, + }) +} + +/// Pure `eodIntraday1M` (`CAD.FOREX`) -> `fx_1m` curation builder. +/// +/// Filters to exact [`EOD_CAD_FOREX_CODE`] rows, validates timestamps and OHLC in strict priority +/// order (ignoring `volume`), sorts ascending by `ts`, and deduplicates same-`ts` groups using +/// bitwise OHLC equality. Valid OHLC and UTC microsecond `ts` pass through unchanged, stamped +/// with `pair = FX_PAIR_USDCAD` and `source = FX_1M_SOURCE_EOD`. +pub fn build_fx_1m<'a, B>(bars: B) -> CurateFx1mOutput +where + B: IntoIterator>, +{ + let mut acc = Fx1mAccumulator::default(); + for bar in bars { + acc.push(bar); + } + acc.finish() +} + +/// Runs [`build_fx_1m`] and streams every curated row in ascending `ts` order into the +/// caller-owned [`IlpShardedWriter`] via [`IlpShardedWriter::write_fx_1m`]. +/// +/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple +/// chunks through a single writer before flushing and collecting aggregate +/// [`crate::ilp::IlpWriteStats`]. +pub fn curate_and_write_fx_1m<'a, W, B>( + bars: B, + writer: &mut IlpShardedWriter, +) -> Result +where + W: Write + Send, + B: IntoIterator>, +{ + let curated = build_fx_1m(bars); + write_curated_fx_1m(curated, writer) +} + +/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], +/// feeds every decoded [`RawEodIntradayBar`] directly into the `fx_1m` curation accumulator, and +/// streams sorted curated rows into the caller-owned [`IlpShardedWriter`]. +/// +/// - Per-document semantic decode errors are counted and skipped in +/// [`BsonEodIntradayDecodeStats`]; fatal stream framing or I/O errors abort before any row from +/// this call is written to `writer`. +/// - Intentionally does **not** call [`IlpShardedWriter::finish`]. +pub fn curate_and_write_fx_1m_from_bson( + reader: R, + options: BsonStreamOptions, + writer: &mut IlpShardedWriter, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let mut acc = Fx1mAccumulator::default(); + let decode_stats = decode_eod_intraday_stream( + reader, + options, + |raw| acc.push(raw), + |_offset, _err| {}, + )?; + + let curated = acc.finish(); + let write_report = write_curated_fx_1m(curated, writer)?; + + Ok(CurateFx1mBsonReport { + decode_stats, + write_report, + }) +} + +#[cfg(test)] +#[path = "curate_fx_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_fx_1m_tests.rs b/tools/curate-etl/src/curate_fx_1m_tests.rs new file mode 100644 index 00000000..8a5622d3 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_1m_tests.rs @@ -0,0 +1,560 @@ +use std::error::Error; +use std::io::{self, Cursor, Write}; + +use bson::raw::{cstr, RawDocumentBuf}; + +use super::*; +use crate::ilp::{encode_fx_1m, shard_for_fx_pair, IlpWriterOptions}; + +fn raw_bar<'a>( + code: &'a str, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawEodIntradayBar<'a> { + RawEodIntradayBar { + eod_search_code: code, + ts, + open, + high, + low, + close, + volume, + } +} + +fn make_eod_intraday_bson_doc( + code: &str, + ts_seconds: 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"), ts_seconds); + 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 assert_conservation_and_order(out: &CurateFx1mOutput) { + let s = &out.stats; + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.bars_in, + s.rows_out + + s.dropped_wrong_code + + s.dropped_negative_ts + + s.dropped_invalid_ohlc + + s.dropped_high_below_bound + + s.dropped_low_above_bound + + s.duplicate_collapsed + + s.duplicate_conflict_dropped, + "curate_fx_1m conservation invariant failed: {s:?}" + ); + + for pair in out.rows.windows(2) { + assert!( + pair[0].ts < pair[1].ts, + "rows not strictly ascending by ts: {} >= {}", + pair[0].ts, + pair[1].ts + ); + } + + for row in &out.rows { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + } +} + +struct FailingSink; + +impl Write for FailingSink { + fn write(&mut self, _buf: &[u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "sink failure")) + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "flush failure")) + } +} + +#[test] +fn empty_input_returns_empty_rows_and_zeroed_stats() { + let out = build_fx_1m(std::iter::empty()); + assert!(out.rows.is_empty()); + assert_eq!(out.stats, CurateFx1mStats::default()); + assert_conservation_and_order(&out); +} + +#[test] +fn valid_out_of_order_bars_sort_preserve_ohlc_bits_keep_off_session_and_ignore_volume() { + // 2024-06-09 22:15:00 UTC (Sunday evening FX open, off equity RTH). + let ts_sunday_utc = 1_717_971_300_000_000_i64; + // 2024-06-10 03:00:00 UTC (overnight). + let ts_overnight_utc = 1_717_988_400_000_000_i64; + // Exact epoch start ts = 0 must be accepted. + let ts_zero = 0_i64; + + let b_late = raw_bar( + EOD_CAD_FOREX_CODE, + ts_overnight_utc, + 1.37654321, + 1.37712345, + 1.37611111, + 1.37689012, + -99.0, // invalid volume ignored by builder + ); + let b_zero = raw_bar( + EOD_CAD_FOREX_CODE, + ts_zero, + 1.0725, + 1.0731, + 1.0720, + 1.0728, + f64::NAN, // NaN volume ignored by builder + ); + let b_mid = raw_bar( + EOD_CAD_FOREX_CODE, + ts_sunday_utc, + 1.3750, + 1.3755, + 1.3745, + 1.3752, + f64::INFINITY, // inf volume ignored by builder + ); + // Exact-match failures (case mismatch, trailing space, different ticker) -> dropped, not errored. + let b_lowercase = raw_bar("cad.forex", ts_sunday_utc + 60_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); + let b_padded = raw_bar("CAD.FOREX ", ts_sunday_utc + 120_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); + let b_other = raw_bar("AAPL.US", ts_sunday_utc + 180_000_000, 195.0, 196.0, 194.5, 195.5, 1000.0); + + let out = build_fx_1m([b_late, b_lowercase, b_zero, b_other, b_mid, b_padded]); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.bars_in, 6); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.dropped_wrong_code, 3); + assert_eq!(out.stats.dropped_negative_ts, 0); + assert_eq!(out.stats.dropped_invalid_ohlc, 0); + assert_eq!(out.stats.dropped_high_below_bound, 0); + assert_eq!(out.stats.dropped_low_above_bound, 0); + assert_eq!(out.stats.duplicate_collapsed, 0); + assert_eq!(out.stats.duplicate_conflict_dropped, 0); + + let expected_inputs = [b_zero, b_mid, b_late]; + for (row, src) in out.rows.iter().zip(expected_inputs) { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + assert_eq!(row.ts, src.ts); + assert_eq!(row.open.to_bits(), src.open.to_bits()); + assert_eq!(row.high.to_bits(), src.high.to_bits()); + assert_eq!(row.low.to_bits(), src.low.to_bits()); + assert_eq!(row.close.to_bits(), src.close.to_bits()); + } +} + +#[test] +fn every_reject_reason_counted_separately_with_strict_precedence() { + let base_ts = 1_718_000_000_000_000_i64; + let bars = vec![ + // 1. Wrong code (also has negative ts and NaN OHLC to verify wrong_code precedence). + raw_bar("USD.FOREX", -1, f64::NAN, 1.0, 2.0, 0.0, 0.0), + // 2. Negative timestamps (second also has NaN OHLC to verify negative_ts precedence). + raw_bar(EOD_CAD_FOREX_CODE, -1, 1.35, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, i64::MIN, f64::NAN, 1.36, 1.34, 1.35, 0.0), + // 3. Invalid OHLC: NaN, +inf, -inf, +0.0, -0.0, negative price. + raw_bar(EOD_CAD_FOREX_CODE, base_ts, f64::NAN, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 1, 1.35, f64::INFINITY, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 2, 1.35, 1.36, f64::NEG_INFINITY, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 3, 1.35, 1.36, 1.34, 0.0, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 4, -0.0, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 5, 1.35, 1.36, -1.34, 1.35, 0.0), + // 4. high < max(open, close, low): + // - high < open + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 6, 1.37, 1.36, 1.34, 1.35, 0.0), + // - high < close + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 7, 1.35, 1.36, 1.34, 1.37, 0.0), + // - high < low (while high >= open/close is impossible if low > open/close, test open=close=1.35, high=1.35, low=1.36) + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 8, 1.35, 1.35, 1.36, 1.35, 0.0), + // - overlapping high < open AND low > close -> pinned to dropped_high_below_bound + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 9, 1.38, 1.36, 1.37, 1.35, 0.0), + // 5. low > min(open, close) (with high >= max(open, close, low)): + // - low > open + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 10, 1.33, 1.36, 1.34, 1.35, 0.0), + // - low > close + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 11, 1.35, 1.36, 1.34, 1.33, 0.0), + // Valid bar. + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 12, 1.35, 1.36, 1.34, 1.355, 0.0), + ]; + + let out = build_fx_1m(bars); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.bars_in, 16); + assert_eq!(out.stats.dropped_wrong_code, 1); + assert_eq!(out.stats.dropped_negative_ts, 2); + assert_eq!(out.stats.dropped_invalid_ohlc, 6); + assert_eq!(out.stats.dropped_high_below_bound, 4); + assert_eq!(out.stats.dropped_low_above_bound, 2); + assert_eq!(out.stats.duplicate_collapsed, 0); + assert_eq!(out.stats.duplicate_conflict_dropped, 0); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.rows[0].ts, base_ts + 12); +} + +#[test] +fn dedup_collapses_identical_ohlc_drops_conflicting_group_and_is_permutation_invariant() { + let ts_identical = 1_718_000_060_000_000_i64; + let ts_conflict = 1_718_000_120_000_000_i64; + let ts_valid_plus_bad = 1_718_000_180_000_000_i64; + + // Group 1: three bitwise-identical OHLC bars with differing volumes -> collapse to 1. + let id1 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 0.0); + let id2 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 42.0); + let id3 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, f64::NAN); + + // Group 2: two identical rows + one conflicting close -> drop all 3. + let cf1 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); + let cf2 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); + let cf3 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3626, 1.0); + + // Group 3: one valid row + one invalid row at same ts -> invalid rejected early, valid survives. + let ok = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, 1.3630, 1.3640, 1.3625, 1.3635, 0.0); + let bad = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, f64::NAN, 1.3640, 1.3625, 1.3635, 0.0); + + let perm_a = [id1, id2, id3, cf1, cf2, cf3, ok, bad]; + let perm_b = [cf3, bad, id3, cf1, ok, id1, cf2, id2]; + let perm_c = [ok, cf2, id2, cf3, id1, bad, cf1, id3]; + + let out_a = build_fx_1m(perm_a); + let out_b = build_fx_1m(perm_b); + let out_c = build_fx_1m(perm_c); + + assert_conservation_and_order(&out_a); + assert_conservation_and_order(&out_b); + assert_conservation_and_order(&out_c); + assert_eq!(out_a, out_b); + assert_eq!(out_a, out_c); + + assert_eq!(out_a.stats.bars_in, 8); + assert_eq!(out_a.stats.dropped_invalid_ohlc, 1); + assert_eq!(out_a.stats.duplicate_collapsed, 2); + assert_eq!(out_a.stats.duplicate_conflict_dropped, 3); + assert_eq!(out_a.stats.rows_out, 2); + + assert_eq!(out_a.rows[0].ts, ts_identical); + assert_eq!(out_a.rows[0].close.to_bits(), 1.3615_f64.to_bits()); + assert_eq!(out_a.rows[1].ts, ts_valid_plus_bad); + assert_eq!(out_a.rows[1].close.to_bits(), 1.3635_f64.to_bits()); +} + +#[test] +fn writer_streams_two_chunks_through_one_writer_matches_encode_fx_1m_and_routes_one_shard() { + let ts1 = 1_718_000_000_000_000_i64; + let ts2 = 1_718_000_060_000_000_i64; + let ts3 = 1_718_000_120_000_000_i64; + + // Chunk 1 given out of order plus an unrelated ticker. + let chunk1 = [ + raw_bar(EOD_CAD_FOREX_CODE, ts2, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), + raw_bar("EUR.FOREX", ts1, 1.0800, 1.0810, 1.0790, 1.0805, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), + ]; + // Chunk 2 chronologically after chunk 1. + let chunk2 = [raw_bar( + EOD_CAD_FOREX_CODE, + ts3, + 1.3715, + 1.3725, + 1.3710, + 1.3722, + 0.0, + )]; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let mut s2 = Vec::new(); + let mut s3 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1, &mut s2, &mut s3], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = curate_and_write_fx_1m(chunk1, &mut writer).unwrap(); + // Writer remains open (finish was NOT called) so chunk 2 streams into the same writer. + let rep2 = curate_and_write_fx_1m(chunk2, &mut writer).unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + assert_eq!(rep1.curate_stats.bars_in, 3); + assert_eq!(rep1.curate_stats.dropped_wrong_code, 1); + assert_eq!(rep1.curate_stats.rows_out, 2); + assert_eq!(rep1.rows_written, 2); + + assert_eq!(rep2.curate_stats.bars_in, 1); + assert_eq!(rep2.curate_stats.rows_out, 1); + assert_eq!(rep2.rows_written, 1); + + assert_eq!(ilp_stats.rows, rep1.rows_written + rep2.rows_written); + assert_eq!(ilp_stats.rows, 3); + + let expected_rows = [ + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts1, + open: 1.3700, + high: 1.3710, + low: 1.3695, + close: 1.3705, + source: FX_1M_SOURCE_EOD, + }, + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts2, + open: 1.3710, + high: 1.3720, + low: 1.3705, + close: 1.3715, + source: FX_1M_SOURCE_EOD, + }, + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts3, + open: 1.3715, + high: 1.3725, + low: 1.3710, + close: 1.3722, + source: FX_1M_SOURCE_EOD, + }, + ]; + let mut expected_bytes = Vec::new(); + for row in &expected_rows { + encode_fx_1m(&mut expected_bytes, row).unwrap(); + } + + let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 4); + let actual_shards = [&s0, &s1, &s2, &s3]; + for (idx, shard_bytes) in actual_shards.iter().enumerate() { + if idx == target_shard { + assert_eq!(*shard_bytes, &expected_bytes, "target shard ILP mismatch"); + } else { + assert!( + shard_bytes.is_empty(), + "non-target shard {idx} should be empty" + ); + } + } + assert_eq!(ilp_stats.per_shard_rows[target_shard], 3); +} + +#[test] +fn bson_stream_handles_mixed_docs_matches_builder_and_supports_writer_reuse() { + let ts1_sec = 1_718_000_000_i64; + let ts2_sec = 1_718_000_060_i64; + let ts3_sec = 1_718_000_120_i64; + + // Out-of-order CAD.FOREX docs + an identical duplicate + a decodable other code + a malformed doc. + let doc_late = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts2_sec, 1.3720, 1.3730, 1.3715, 1.3725, 0.0); + let doc_other = + make_eod_intraday_bson_doc("AAPL.US", ts1_sec, 195.0, 196.0, 194.5, 195.5, 1200.0); + // Correctly framed BSON document missing required field `close`. + let mut doc_missing_close = RawDocumentBuf::new(); + doc_missing_close.append(cstr!("eodSearchCode"), EOD_CAD_FOREX_CODE); + doc_missing_close.append(cstr!("timestamp"), ts1_sec); + doc_missing_close.append(cstr!("open"), 1.3700_f64); + doc_missing_close.append(cstr!("high"), 1.3710_f64); + doc_missing_close.append(cstr!("low"), 1.3695_f64); + doc_missing_close.append(cstr!("volume"), 0.0_f64); + + let doc_early = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 0.0); + let doc_early_dup = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 5.0); + + let mut chunk1_bytes = Vec::new(); + chunk1_bytes.extend_from_slice(doc_late.as_bytes()); + chunk1_bytes.extend_from_slice(doc_other.as_bytes()); + chunk1_bytes.extend_from_slice(doc_missing_close.as_bytes()); + chunk1_bytes.extend_from_slice(doc_early.as_bytes()); + chunk1_bytes.extend_from_slice(doc_early_dup.as_bytes()); + + let doc_chunk2 = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts3_sec, 1.3725, 1.3735, 1.3720, 1.3731, 0.0); + let chunk2_bytes = doc_chunk2.as_bytes().to_vec(); + + // Small chunk capacity forces multi-chunk framing across documents. + let stream_opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = + curate_and_write_fx_1m_from_bson(Cursor::new(&chunk1_bytes), stream_opts, &mut writer) + .unwrap(); + let rep2 = + curate_and_write_fx_1m_from_bson(Cursor::new(&chunk2_bytes), stream_opts, &mut writer) + .unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + // Decode accounting: 5 docs seen = 4 decoded + 1 missing_field reject. + assert_eq!(rep1.decode_stats.docs_seen, 5); + assert_eq!(rep1.decode_stats.rows_decoded, 4); + assert_eq!(rep1.decode_stats.rejected_missing_field, 1); + assert_eq!( + rep1.decode_stats.docs_seen, + rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() + ); + + // Builder input equals rows_decoded. + assert_eq!( + rep1.write_report.curate_stats.bars_in, + rep1.decode_stats.rows_decoded + ); + assert_eq!(rep1.write_report.curate_stats.dropped_wrong_code, 1); + assert_eq!(rep1.write_report.curate_stats.duplicate_collapsed, 1); + assert_eq!(rep1.write_report.curate_stats.rows_out, 2); + assert_eq!(rep1.write_report.rows_written, 2); + + // Compare chunk 1 curation stats directly against `build_fx_1m` on the same decoded inputs. + let direct_expected = build_fx_1m([ + raw_bar(EOD_CAD_FOREX_CODE, ts2_sec * 1_000_000, 1.3720, 1.3730, 1.3715, 1.3725, 0.0), + raw_bar("AAPL.US", ts1_sec * 1_000_000, 195.0, 196.0, 194.5, 195.5, 1200.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 5.0), + ]); + assert_eq!(rep1.write_report.curate_stats, direct_expected.stats); + + // Chunk 2 stats & aggregate ILP stats. + assert_eq!(rep2.decode_stats.docs_seen, 1); + assert_eq!(rep2.decode_stats.rows_decoded, 1); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!(ilp_stats.rows, 3); + + // Exact ILP bytes match `encode_fx_1m` of chunk 1 + chunk 2 expected rows in order. + let mut expected_bytes = Vec::new(); + for row in &direct_expected.rows { + encode_fx_1m(&mut expected_bytes, row).unwrap(); + } + encode_fx_1m( + &mut expected_bytes, + &Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts3_sec * 1_000_000, + open: 1.3725, + high: 1.3735, + low: 1.3720, + close: 1.3731, + source: FX_1M_SOURCE_EOD, + }, + ) + .unwrap(); + + let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 2); + let other_shard = 1 - target_shard; + let shards = [&s0, &s1]; + assert_eq!(shards[target_shard], &expected_bytes); + assert!(shards[other_shard].is_empty()); +} + +#[test] +fn truncated_bson_stream_fails_closed_with_zero_rows_written_and_typed_errors_format() { + let doc1 = make_eod_intraday_bson_doc( + EOD_CAD_FOREX_CODE, + 1_718_000_000, + 1.3700, + 1.3710, + 1.3695, + 1.3705, + 0.0, + ); + let doc2 = make_eod_intraday_bson_doc( + EOD_CAD_FOREX_CODE, + 1_718_000_060, + 1.3710, + 1.3720, + 1.3705, + 1.3715, + 0.0, + ); + + let mut truncated_bytes = Vec::new(); + truncated_bytes.extend_from_slice(doc1.as_bytes()); + let doc2_bytes = doc2.as_bytes(); + truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (stream_err, stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_fx_1m_from_bson( + Cursor::new(&truncated_bytes), + BsonStreamOptions::default(), + &mut writer, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + + assert!(matches!( + stream_err, + CurateFx1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert!(stream_err.source().is_some()); + assert!(stream_err.to_string().contains("fx_1m BSON stream failed")); + assert_eq!(stats.rows, 0); + assert!(s0.is_empty()); + assert!(s1.is_empty()); + + // Writer I/O failure surfaces as `CurateFx1mBsonError::Write(IlpWriterError::Io { .. })`. + let mut failing_writer = IlpShardedWriter::new( + vec![FailingSink], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let write_err = curate_and_write_fx_1m_from_bson( + Cursor::new(doc1.as_bytes()), + BsonStreamOptions::default(), + &mut failing_writer, + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFx1mBsonError::Write(IlpWriterError::Io { shard: 0, .. }) + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("fx_1m ILP write failed")); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index c174442b..1a8ff478 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -256,6 +256,13 @@ pub use curate_qm_bars_1m::{ CurateQmBars1mBsonError, CurateQmBars1mBsonReport, }; +pub mod curate_fx_1m; +pub use curate_fx_1m::{ + build_fx_1m, curate_and_write_fx_1m, curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, + CurateFx1mBsonReport, CurateFx1mOutput, CurateFx1mStats, CurateFx1mWriteReport, + FX_1M_SOURCE_EOD, +}; + pub mod run_curate_bars; pub use run_curate_bars::{ default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv,