From 288fdec14d4ee188ffc94be5cec6c51663d154c8 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 21:56:47 -0500 Subject: [PATCH 01/26] =?UTF-8?q?T-143:=20M2.2c=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20Zstd=20Parquet=20writer=20for=20`fundamentals=5Fpit/y?= =?UTF-8?q?ear=3DYYYY/part.parquet`=20(flat=20latest-period=20+=20TTM=20sn?= =?UTF-8?q?apshot=20rows=20from=20`FundamentalsSnapshot`)=20with=20re?= =?UTF-8?q?statement=20round-trip=20test=20(no=20new=20crates,=20no=20CLI/?= =?UTF-8?q?bench=20changes)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- design/DATA-CONTRACTS.md | 4 +- tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/parquet_fundamentals.rs | 1327 +++++++++++++++++ .../src/parquet_fundamentals_tests.rs | 1265 ++++++++++++++++ tools/curate-etl/src/parquet_publish.rs | 19 + 5 files changed, 2619 insertions(+), 2 deletions(-) create mode 100644 tools/curate-etl/src/parquet_fundamentals.rs create mode 100644 tools/curate-etl/src/parquet_fundamentals_tests.rs diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 9f973afe..278c1999 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -217,9 +217,9 @@ Schemas: - **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`. - **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`. - **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, )`. -- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes: +- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes: $$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$ - forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2. + forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted). - **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`. - **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`. - **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`. diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6244dcc7..6b795fef 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -24,6 +24,7 @@ pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; pub mod parquet_events; +pub mod parquet_fundamentals; pub mod parquet_fx; mod parquet_publish; pub mod parquet_shorts; @@ -160,6 +161,11 @@ pub use parquet_events::{ events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, }; +pub use parquet_fundamentals::{ + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, + FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, + ParquetFundamentalsError, +}; pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs new file mode 100644 index 00000000..9e804d26 --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -0,0 +1,1327 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. +//! +//! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column +//! contract schema in `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `effective_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 3. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 4. `has_estimated_lag` (`BOOLEAN`, `REQUIRED`) +//! 5. `period_end` (`INT32`, `REQUIRED`, `DATE`) +//! 6. `fiscal_period` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 7. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 8. `period_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 9. `revenue` (`DOUBLE`, `OPTIONAL`) +//! 10. `net_income` (`DOUBLE`, `OPTIONAL`) +//! 11. `operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`) +//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`) +//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`) +//! 15. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) +//! 16. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 17. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) +//! 18. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) +//! 19. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) +//! +//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the +//! builder-provided 4-quarter `ttm` summary from a [`FundamentalsSnapshot`]. Lagged period slots +//! (`periods[1..]`) are intentionally omitted from the flat Parquet representation; TTM values +//! computed by [`crate::fundamentals::build_fundamentals_snapshots`] are preserved as-is. + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{ + Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, +}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::events::partition_year_utc; +use crate::fundamentals::{FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm}; +pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + rollback_published, write_bool_col, write_i32_col, write_i64_col, write_interned_str_col, + write_optional_f64_col, write_optional_i32_col, write_optional_interned_str_col, + DatasetFileLock, PublishIoError, PublishedPartition, StagingFileGuard, StringInterner, + DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; + +/// Latest visible period projection flattened into a [`FundamentalsPitParquetRow`]. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPitLatestPeriod { + pub period_end: i32, + pub fiscal_period: Cow<'static, str>, + pub currency: String, + pub period_known_at_micros: i64, + pub fields: FundamentalsFields, +} + +/// Single `fundamentals_pit` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. +/// +/// Only `periods[0]` (the latest visible period) and `ttm` are stored; lagged slots +/// (`periods[1..]`) are intentionally omitted. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPitParquetRow { + pub listing_id: i32, + pub effective_known_at_micros: i64, + pub known_at_source: Cow<'static, str>, + pub has_estimated_lag: bool, + latest_period: Option, + pub ttm: Option, +} + +impl FundamentalsPitParquetRow { + /// Constructs a valid `fundamentals_pit` Parquet row with an explicit latest visible period. + pub fn new( + listing_id: i32, + effective_known_at_micros: i64, + known_at_source: Cow<'static, str>, + has_estimated_lag: bool, + latest_period: FundamentalsPitLatestPeriod, + ttm: Option, + ) -> Self { + Self { + listing_id, + effective_known_at_micros, + known_at_source, + has_estimated_lag, + latest_period: Some(latest_period), + ttm, + } + } + + /// Returns the flattened latest visible period (`periods[0]`), or `None` if converted from a + /// malformed snapshot with an empty `periods` vector. + #[inline] + pub fn latest_period(&self) -> Option<&FundamentalsPitLatestPeriod> { + self.latest_period.as_ref() + } +} + +impl From<&FundamentalsSnapshot> for FundamentalsPitParquetRow { + fn from(snapshot: &FundamentalsSnapshot) -> Self { + let latest_period = snapshot.periods.first().map(|slot| FundamentalsPitLatestPeriod { + period_end: slot.period_end, + fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), + currency: slot.currency.clone(), + period_known_at_micros: slot.known_at_utc_micros, + fields: slot.fields, + }); + Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + latest_period, + ttm: snapshot.ttm.clone(), + } + } +} + +impl From> for FundamentalsPitParquetRow { + fn from(snapshot: FundamentalsSnapshot) -> Self { + let latest_period = snapshot + .periods + .into_iter() + .next() + .map(|slot| FundamentalsPitLatestPeriod { + period_end: slot.period_end, + fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), + currency: slot.currency, + period_known_at_micros: slot.known_at_utc_micros, + fields: slot.fields, + }); + Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + latest_period, + ttm: snapshot.ttm, + } + } +} + +/// Configuration for [`write_fundamentals_pit_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FundamentalsPitWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for FundamentalsPitWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_fundamentals_pit_dataset`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FundamentalsPitWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub rows_by_year: BTreeMap, +} + +/// Typed error returned by [`write_fundamentals_pit_dataset`]. +#[derive(Debug)] +pub enum ParquetFundamentalsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + EmptyPeriods { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + UnsortedInput { + row_index: usize, + prev_listing_id: i32, + prev_effective_known_at_micros: i64, + listing_id: i32, + effective_known_at_micros: i64, + }, + DuplicateRow { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + PartitionYearOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + year: i32, + min_year: i32, + max_year: i32, + }, + EmptyKnownAtSource { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyFiscalPeriod { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyCurrency { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyTtmCurrency { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + NonFiniteValue { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + field: &'static str, + value: f64, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetFundamentalsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::EmptyPeriods { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "snapshot has empty periods at row {row_index} for (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" + ), + Self::UnsortedInput { + row_index, + prev_listing_id, + prev_effective_known_at_micros, + listing_id, + effective_known_at_micros, + } => write!( + f, + "unsorted input at row {row_index}: ({listing_id}, {effective_known_at_micros}) follows ({prev_listing_id}, {prev_effective_known_at_micros})" + ), + Self::DuplicateRow { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "duplicate fundamentals_pit row at row {row_index}: (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" + ), + Self::PartitionYearOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + year, + min_year, + max_year, + } => write!( + f, + "partition year {year} (effective_known_at {effective_known_at_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" + ), + Self::EmptyKnownAtSource { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyFiscalPeriod { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty fiscal_period at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyCurrency { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyTtmCurrency { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::NonFiniteValue { + row_index, + listing_id, + effective_known_at_micros, + field, + value, + } => write!( + f, + "non-finite {field} value {value} at row {row_index} for ({listing_id}, {effective_known_at_micros})" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetFundamentalsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetFundamentalsError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 20-column Parquet schema for `fundamentals_pit` per `design/DATA-CONTRACTS.md` (§3A). +pub fn fundamentals_pit_parquet_schema() -> Result { + let fields: Vec = vec![ + // 1. listing_id INT32 REQUIRED + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + // 2. effective_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) + Arc::new( + Type::primitive_type_builder("effective_known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + // 3. known_at_source STRING REQUIRED + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 4. has_estimated_lag BOOLEAN REQUIRED + Arc::new( + Type::primitive_type_builder("has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + // 5. period_end INT32 DATE REQUIRED + Arc::new( + Type::primitive_type_builder("period_end", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + // 6. fiscal_period STRING REQUIRED + Arc::new( + Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 7. currency STRING REQUIRED + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 8. period_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) + Arc::new( + Type::primitive_type_builder("period_known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + // 9-14. latest-period financial metrics DOUBLE OPTIONAL + Arc::new( + Type::primitive_type_builder("revenue", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("net_income", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("operating_cash_flow", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("total_assets", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("total_equity", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("shares_outstanding", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + // 15. ttm_period_end INT32 DATE OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + // 16. ttm_currency STRING OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 17-19. TTM flow sums DOUBLE OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_net_income", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_operating_cash_flow", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + // 20. ttm_has_estimated_lag BOOLEAN OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("fundamentals_pit") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) + .set_column_dictionary_enabled(ColumnPath::from("fiscal_period"), true) + .set_column_dictionary_enabled(ColumnPath::from("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("ttm_currency"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn check_opt_finite( + row: &FundamentalsPitParquetRow, + row_index: usize, + field: &'static str, + val: Option, +) -> Result<(), ParquetFundamentalsError> { + if let Some(value) = val { + if !value.is_finite() { + return Err(ParquetFundamentalsError::NonFiniteValue { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + field, + value, + }); + } + } + Ok(()) +} + +#[inline] +fn validate_row( + row: &FundamentalsPitParquetRow, + row_index: usize, +) -> Result<(i32, &FundamentalsPitLatestPeriod), ParquetFundamentalsError> { + let Some(latest) = row.latest_period.as_ref() else { + return Err(ParquetFundamentalsError::EmptyPeriods { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + }; + + let year = partition_year_utc(row.effective_known_at_micros); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetFundamentalsError::PartitionYearOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + if row.known_at_source.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyKnownAtSource { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + if latest.fiscal_period.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyFiscalPeriod { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + if latest.currency.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + + check_opt_finite(row, row_index, "revenue", latest.fields.revenue)?; + check_opt_finite(row, row_index, "net_income", latest.fields.net_income)?; + check_opt_finite( + row, + row_index, + "operating_cash_flow", + latest.fields.operating_cash_flow, + )?; + check_opt_finite(row, row_index, "total_assets", latest.fields.total_assets)?; + check_opt_finite(row, row_index, "total_equity", latest.fields.total_equity)?; + check_opt_finite( + row, + row_index, + "shares_outstanding", + latest.fields.shares_outstanding, + )?; + + if let Some(ttm) = row.ttm.as_ref() { + if ttm.currency.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyTtmCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + check_opt_finite(row, row_index, "ttm_revenue", ttm.flows.revenue)?; + check_opt_finite(row, row_index, "ttm_net_income", ttm.flows.net_income)?; + check_opt_finite( + row, + row_index, + "ttm_operating_cash_flow", + ttm.flows.operating_cash_flow, + )?; + } + + Ok((year, latest)) +} + +#[inline] +fn push_opt_f64(values: &mut Vec, defs: &mut Vec, val: Option) { + match val { + Some(v) => { + values.push(v); + defs.push(1); + } + None => { + defs.push(0); + } + } +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + effective_known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, + has_estimated_lag: Vec, + period_end: Vec, + fiscal_period_ids: Vec, + fiscal_period_interner: StringInterner, + currency_ids: Vec, + currency_interner: StringInterner, + period_known_at_micros: Vec, + revenue_values: Vec, + revenue_def: Vec, + net_income_values: Vec, + net_income_def: Vec, + operating_cash_flow_values: Vec, + operating_cash_flow_def: Vec, + total_assets_values: Vec, + total_assets_def: Vec, + total_equity_values: Vec, + total_equity_def: Vec, + shares_outstanding_values: Vec, + shares_outstanding_def: Vec, + ttm_period_end_values: Vec, + ttm_period_end_def: Vec, + ttm_currency_ids: Vec, + ttm_currency_def: Vec, + ttm_currency_interner: StringInterner, + ttm_revenue_values: Vec, + ttm_revenue_def: Vec, + ttm_net_income_values: Vec, + ttm_net_income_def: Vec, + ttm_operating_cash_flow_values: Vec, + ttm_operating_cash_flow_def: Vec, + ttm_has_estimated_lag_values: Vec, + ttm_has_estimated_lag_def: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &FundamentalsPitParquetRow, latest: &FundamentalsPitLatestPeriod) { + self.listing_id.push(row.listing_id); + self.effective_known_at_micros + .push(row.effective_known_at_micros); + let kas_id = self + .known_at_source_interner + .intern(row.known_at_source.as_ref()); + self.known_at_source_ids.push(kas_id); + self.has_estimated_lag.push(row.has_estimated_lag); + self.period_end.push(latest.period_end); + let fp_id = self + .fiscal_period_interner + .intern(latest.fiscal_period.as_ref()); + self.fiscal_period_ids.push(fp_id); + let cur_id = self.currency_interner.intern(latest.currency.as_str()); + self.currency_ids.push(cur_id); + self.period_known_at_micros + .push(latest.period_known_at_micros); + + push_opt_f64( + &mut self.revenue_values, + &mut self.revenue_def, + latest.fields.revenue, + ); + push_opt_f64( + &mut self.net_income_values, + &mut self.net_income_def, + latest.fields.net_income, + ); + push_opt_f64( + &mut self.operating_cash_flow_values, + &mut self.operating_cash_flow_def, + latest.fields.operating_cash_flow, + ); + push_opt_f64( + &mut self.total_assets_values, + &mut self.total_assets_def, + latest.fields.total_assets, + ); + push_opt_f64( + &mut self.total_equity_values, + &mut self.total_equity_def, + latest.fields.total_equity, + ); + push_opt_f64( + &mut self.shares_outstanding_values, + &mut self.shares_outstanding_def, + latest.fields.shares_outstanding, + ); + + match row.ttm.as_ref() { + Some(ttm) => { + self.ttm_period_end_values.push(ttm.ending_period_end); + self.ttm_period_end_def.push(1); + let ttm_cur_id = self.ttm_currency_interner.intern(ttm.currency.as_str()); + self.ttm_currency_ids.push(ttm_cur_id); + self.ttm_currency_def.push(1); + push_opt_f64( + &mut self.ttm_revenue_values, + &mut self.ttm_revenue_def, + ttm.flows.revenue, + ); + push_opt_f64( + &mut self.ttm_net_income_values, + &mut self.ttm_net_income_def, + ttm.flows.net_income, + ); + push_opt_f64( + &mut self.ttm_operating_cash_flow_values, + &mut self.ttm_operating_cash_flow_def, + ttm.flows.operating_cash_flow, + ); + self.ttm_has_estimated_lag_values + .push(ttm.has_estimated_lag); + self.ttm_has_estimated_lag_def.push(1); + } + None => { + self.ttm_period_end_def.push(0); + self.ttm_currency_def.push(0); + self.ttm_revenue_def.push(0); + self.ttm_net_income_def.push(0); + self.ttm_operating_cash_flow_def.push(0); + self.ttm_has_estimated_lag_def.push(0); + } + } + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.effective_known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + self.has_estimated_lag.clear(); + self.period_end.clear(); + self.fiscal_period_ids.clear(); + self.fiscal_period_interner.clear(); + self.currency_ids.clear(); + self.currency_interner.clear(); + self.period_known_at_micros.clear(); + self.revenue_values.clear(); + self.revenue_def.clear(); + self.net_income_values.clear(); + self.net_income_def.clear(); + self.operating_cash_flow_values.clear(); + self.operating_cash_flow_def.clear(); + self.total_assets_values.clear(); + self.total_assets_def.clear(); + self.total_equity_values.clear(); + self.total_equity_def.clear(); + self.shares_outstanding_values.clear(); + self.shares_outstanding_def.clear(); + self.ttm_period_end_values.clear(); + self.ttm_period_end_def.clear(); + self.ttm_currency_ids.clear(); + self.ttm_currency_def.clear(); + self.ttm_currency_interner.clear(); + self.ttm_revenue_values.clear(); + self.ttm_revenue_def.clear(); + self.ttm_net_income_values.clear(); + self.ttm_net_income_def.clear(); + self.ttm_operating_cash_flow_values.clear(); + self.ttm_operating_cash_flow_def.clear(); + self.ttm_has_estimated_lag_values.clear(); + self.ttm_has_estimated_lag_def.clear(); + } +} + +struct YearWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl YearWriter { + fn open( + dataset_dir: &Path, + year: i32, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + staging_guards: &mut BTreeMap, + ) -> Result { + let year_dir = dataset_dir.join(format!("year={year:04}")); + fs::create_dir_all(&year_dir).map_err(|source| ParquetFundamentalsError::Io { + path: year_dir.clone(), + source, + })?; + + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); + let final_path = year_dir.join("part.parquet"); + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetFundamentalsError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group( + &mut self, + scratch: &mut Vec, + ) -> Result<(), ParquetFundamentalsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetFundamentalsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. effective_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.effective_known_at_micros).map_err(map_pq)?; + // 3. known_at_source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.known_at_source_ids, + &self.buf.known_at_source_interner, + scratch, + ) + .map_err(map_pq)?; + // 4. has_estimated_lag (BOOLEAN, REQUIRED) + write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag, None).map_err(map_pq)?; + // 5. period_end (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.period_end).map_err(map_pq)?; + // 6. fiscal_period (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.fiscal_period_ids, + &self.buf.fiscal_period_interner, + scratch, + ) + .map_err(map_pq)?; + // 7. currency (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 8. period_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.period_known_at_micros).map_err(map_pq)?; + // 9. revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.revenue_values, + &self.buf.revenue_def, + ) + .map_err(map_pq)?; + // 10. net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.net_income_values, + &self.buf.net_income_def, + ) + .map_err(map_pq)?; + // 11. operating_cash_flow (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.operating_cash_flow_values, + &self.buf.operating_cash_flow_def, + ) + .map_err(map_pq)?; + // 12. total_assets (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.total_assets_values, + &self.buf.total_assets_def, + ) + .map_err(map_pq)?; + // 13. total_equity (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.total_equity_values, + &self.buf.total_equity_def, + ) + .map_err(map_pq)?; + // 14. shares_outstanding (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.shares_outstanding_values, + &self.buf.shares_outstanding_def, + ) + .map_err(map_pq)?; + // 15. ttm_period_end (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.ttm_period_end_values, + &self.buf.ttm_period_end_def, + ) + .map_err(map_pq)?; + // 16. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.ttm_currency_ids, + &self.buf.ttm_currency_def, + &self.buf.ttm_currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 17. ttm_revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_revenue_values, + &self.buf.ttm_revenue_def, + ) + .map_err(map_pq)?; + // 18. ttm_net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_net_income_values, + &self.buf.ttm_net_income_def, + ) + .map_err(map_pq)?; + // 19. ttm_operating_cash_flow (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_operating_cash_flow_values, + &self.buf.ttm_operating_cash_flow_def, + ) + .map_err(map_pq)?; + // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) + write_bool_col( + &mut rg_writer, + &self.buf.ttm_has_estimated_lag_values, + Some(&self.buf.ttm_has_estimated_lag_def), + ) + .map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetFundamentalsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer + .flush() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedYearFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedYearFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +fn finish_with_rollback( + cause: ParquetFundamentalsError, + published: &[PublishedPartition], + extra_failure: Option, +) -> ParquetFundamentalsError { + let mut failures = Vec::new(); + if let Some(failure) = extra_failure { + failures.push(failure); + } + failures.extend(rollback_published(published)); + if failures.is_empty() { + cause + } else { + ParquetFundamentalsError::RollbackFailed { + cause: Box::new(cause), + failures, + } + } +} + +/// Streams strictly ascending `(listing_id, effective_known_at)` snapshot rows into +/// year-partitioned Zstd Parquet files at `/fundamentals_pit/year=YYYY/part.parquet`, +/// partitioned by the UTC year of `effective_known_at`. +/// +/// # Sort Order & Validation +/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at)`. +/// Out-of-order rows, duplicate keys, snapshots with empty `periods`, partition years outside +/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, empty string metadata fields, and non-finite numeric +/// values return typed [`ParquetFundamentalsError`] variants with nothing published. Empty input +/// returns `Ok(FundamentalsPitWriteStats::default())` without creating +/// `/fundamentals_pit` or touching pre-existing partitions. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/fundamentals_pit` directory are serialized via +/// an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year +/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), +/// flushed, and `sync_all`'d before publication. Pre-existing `part.parquet` files are backed up +/// in place (hard link with exclusive copy fallback) so the live path remains readable until +/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before +/// owned staging files are unlinked, replaced partitions are restored from backup, and newly +/// published partitions are removed (reporting rollback errors via +/// [`ParquetFundamentalsError::RollbackFailed`]). +pub fn write_fundamentals_pit_dataset( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_fundamentals_pit_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _, _| {}, + ) +} + +fn write_fundamentals_pit_dataset_with_hooks( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(i32, &Path, Option<&Path>), +{ + if options.row_group_rows == 0 { + return Err(ParquetFundamentalsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetFundamentalsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(FundamentalsPitWriteStats::default()); + }; + validate_row(first_item.borrow(), 0)?; + + let out_dir = out_dir.as_ref(); + let dataset_dir = out_dir.join("fundamentals_pit"); + let schema = + fundamentals_pit_parquet_schema().map_err(|source| ParquetFundamentalsError::Parquet { + path: dataset_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&dataset_dir).map_err(|source| ParquetFundamentalsError::Io { + path: dataset_dir.clone(), + source, + })?; + + let dataset_mu = dataset_mutex(&dataset_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; + + let run_id = next_run_id(); + // Declared before `writers` so Rust's reverse drop order closes all Parquet file handles + // before unlinking owned `.tmp` staging files on error or panic unwind. + let mut staging_guards: BTreeMap = BTreeMap::new(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let synced_files: Vec<(i32, SyncedYearFile)> = { + let mut prev_key: Option<(i32, i64)> = None; + + for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { + let row = item.borrow(); + let key = (row.listing_id, row.effective_known_at_micros); + if let Some((prev_listing_id, prev_effective_known_at_micros)) = prev_key { + match key.cmp(&(prev_listing_id, prev_effective_known_at_micros)) { + Ordering::Equal => { + return Err(ParquetFundamentalsError::DuplicateRow { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Less => { + return Err(ParquetFundamentalsError::UnsortedInput { + row_index, + prev_listing_id, + prev_effective_known_at_micros, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Greater => {} + } + } + + let (year, latest) = validate_row(row, row_index)?; + + let yw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = YearWriter::open( + &dataset_dir, + year, + &run_id, + &schema, + &props, + &mut staging_guards, + )?; + entry.insert(opened) + } + }; + + yw.buf.push(row, latest); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; + } + prev_key = Some(key); + } + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); + for (year, yw) in drained { + let file = yw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + synced + }; + + let mut stats = FundamentalsPitWriteStats::default(); + let mut published: Vec = Vec::with_capacity(synced_files.len()); + for (year, file) in synced_files { + let backup_path = match fs::symlink_metadata(&file.final_path) { + Ok(meta) if !meta.is_dir() => { + match create_backup_preserving_live(&file.final_path, &run_id) { + Ok(bak) => Some(bak), + Err(err) => { + return Err(finish_with_rollback(err.into(), &published, None)); + } + } + } + // Directory occupying final_path: leave it in place so the rename below fails + // cleanly and triggers rollback of all earlier partitions. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + let err = ParquetFundamentalsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, None)); + } + }; + + on_after_backup(year, &file.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { + let extra_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: file.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let err = ParquetFundamentalsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, extra_failure)); + } + + if let Some(guard) = staging_guards.get_mut(&year) { + guard.disarm(); + } + + published.push(PublishedPartition { + final_path: file.final_path, + backup_path, + }); + stats.rows_written += file.rows_written; + stats.files_written += 1; + stats.row_groups_written += file.row_groups_written; + stats.bytes_written += file.bytes; + stats.rows_by_year.insert(year, file.rows_written); + } + + for part in &published { + if let Some(bak) = &part.backup_path { + let _ = fs::remove_file(bak); + } + } + + Ok(stats) +} + +#[cfg(test)] +#[path = "parquet_fundamentals_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs new file mode 100644 index 00000000..7b4b5712 --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -0,0 +1,1265 @@ +//! Round-trip, schema, partitioning, validation, and atomic rollback tests for +//! `parquet_fundamentals`. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::{ + Compression, ConvertedType, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, + FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, + ParquetFundamentalsError, DEFAULT_ZSTD_LEVEL, +}; +use crate::events::{ + partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, + FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, +}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-fundamentals-test-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8, micro: i64) -> i64 { + let epoch_day = day(y, m, d); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 + micro +} + +fn filing(key: i32, timefiled: &str, form_type: &str) -> QmFiling { + QmFiling { + key, + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: None, + url: None, + } +} + +fn obs( + key: i32, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: &str, + report_date: Option, + fields: FundamentalsFields, +) -> FinancialObservation { + FinancialObservation { + key, + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + } +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedFundamentalsPitRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_has_estimated_lag: Option, +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_rows = meta.row_group(rg_idx).num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_req_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 at col {col_idx}"), + } + vals + }; + + let read_opt_i32 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req i64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 at col {col_idx}"), + } + vals + }; + + let read_req_bool = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read req bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN at col {col_idx}"), + } + vals + }; + + let read_opt_bool = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_opt_f64 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read opt f64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_str = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read req str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY at col {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let read_opt_str = |col_idx: usize| -> Vec> { + let mut raw = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut raw) + .expect("read opt str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let s = std::str::from_utf8(raw[vi].data()) + .expect("valid utf8") + .to_string(); + vi += 1; + Some(s) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let listing_id = read_req_i32(0); + let effective_known_at = read_req_i64(1); + let known_at_source = read_req_str(2); + let has_estimated_lag = read_req_bool(3); + let period_end = read_req_i32(4); + let fiscal_period = read_req_str(5); + let currency = read_req_str(6); + let period_known_at = read_req_i64(7); + let revenue = read_opt_f64(8); + let net_income = read_opt_f64(9); + let operating_cash_flow = read_opt_f64(10); + let total_assets = read_opt_f64(11); + let total_equity = read_opt_f64(12); + let shares_outstanding = read_opt_f64(13); + let ttm_period_end = read_opt_i32(14); + let ttm_currency = read_opt_str(15); + let ttm_revenue = read_opt_f64(16); + let ttm_net_income = read_opt_f64(17); + let ttm_operating_cash_flow = read_opt_f64(18); + let ttm_has_estimated_lag = read_opt_bool(19); + + for i in 0..rg_rows { + out.push(DecodedFundamentalsPitRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + + out +} + +fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + fn walk(dir: &Path) { + for entry in fs::read_dir(dir).expect("read_dir") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(&path); + } else { + let name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or_default(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file left behind: {}", + path.display() + ); + } + } + } + walk(dir); +} + +fn make_row( + listing_id: i32, + effective_known_at_micros: i64, + period_end: i32, + revenue: Option, + ttm: Option, +) -> FundamentalsPitParquetRow { + FundamentalsPitParquetRow::new( + listing_id, + effective_known_at_micros, + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end, + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: effective_known_at_micros, + fields: FundamentalsFields { + revenue, + net_income: revenue.map(|r| r * 0.1), + operating_cash_flow: revenue.map(|r| r * 0.15), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + }, + ttm, + ) +} + +#[test] +fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { + let tmp = TempDirGuard::new("schema"); + + // 1) Row with no TTM (all 6 ttm_* columns must be null) and some null latest-period fields. + let row_no_ttm = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 5, 1, 20, 15, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: utc_micros(2024, 5, 1, 20, 15, 0, 0), + fields: FundamentalsFields { + revenue: Some(100.0), + net_income: None, + operating_cash_flow: Some(15.0), + total_assets: None, + total_equity: Some(220.0), + shares_outstanding: None, + }, + }, + None, + ); + + // 2) Row with TTM where ttm_has_estimated_lag = Some(false) and all flows present. + let row_ttm_false = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 8, 1, 20, 15, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 6, 30), + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: utc_micros(2024, 8, 1, 20, 15, 0, 0), + fields: FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(18.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), + }, + }, + Some(FundamentalsTtm { + ending_period_end: day(2024, 6, 30), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(370.0), + net_income: Some(37.0), + operating_cash_flow: Some(55.0), + }, + has_estimated_lag: false, + }), + ); + + // 3) Row with TTM where ttm_has_estimated_lag = Some(true), FY latest period, and partial null TTM flow. + let row_ttm_true = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 11, 15, 21, 5, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_STATUTORY_LAG), + true, + FundamentalsPitLatestPeriod { + period_end: day(2024, 9, 30), + fiscal_period: Cow::Borrowed("FY"), + currency: "CAD".to_string(), + period_known_at_micros: utc_micros(2024, 11, 15, 21, 5, 0, 0), + fields: FundamentalsFields { + revenue: Some(450.0), + net_income: Some(45.0), + operating_cash_flow: None, + total_assets: Some(600.0), + total_equity: Some(250.0), + shares_outstanding: Some(105.0), + }, + }, + Some(FundamentalsTtm { + ending_period_end: day(2024, 9, 30), + currency: "CAD".to_string(), + flows: TtmFlowFields { + revenue: Some(450.0), + net_income: None, + operating_cash_flow: Some(60.0), + }, + has_estimated_lag: true, + }), + ); + + let rows = vec![row_no_ttm, row_ttm_false, row_ttm_true]; + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write schema test dataset"); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 3)])); + + let path = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let reader = SerializedFileReader::new(File::open(&path).expect("open parquet")) + .expect("open parquet reader"); + let meta = reader.metadata(); + let expected_schema = fundamentals_pit_parquet_schema().expect("schema"); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + assert_eq!(expected_schema.name(), "fundamentals_pit"); + + let fields = meta.file_metadata().schema().get_fields(); + assert_eq!(fields.len(), 20); + + let expected_cols: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 20] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "effective_known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "known_at_source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "period_end", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "fiscal_period", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "period_known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "revenue", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "net_income", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "operating_cash_flow", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "total_assets", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "total_equity", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "shares_outstanding", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_period_end", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ttm_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "ttm_revenue", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_net_income", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_operating_cash_flow", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected_cols.into_iter().enumerate() { + let field = &fields[idx]; + assert_eq!(field.name(), name, "column {idx} name"); + assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); + assert_eq!( + field.get_basic_info().repetition(), + rep, + "column {idx} repetition" + ); + assert_eq!( + field.get_basic_info().logical_type_ref().cloned(), + logical, + "column {idx} logical type" + ); + assert_eq!( + field.get_basic_info().converted_type(), + converted, + "column {idx} converted type" + ); + } + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} must use ZSTD compression", + col.column_path() + ); + } + } + + let decoded = read_parquet_rows(&path); + assert_eq!(decoded.len(), 3); + + // Row 0: no TTM -> all 6 ttm_* columns are None. + assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!decoded[0].has_estimated_lag); + assert_eq!(decoded[0].revenue, Some(100.0)); + assert_eq!(decoded[0].net_income, None); + assert_eq!(decoded[0].operating_cash_flow, Some(15.0)); + assert_eq!(decoded[0].total_assets, None); + assert_eq!(decoded[0].total_equity, Some(220.0)); + assert_eq!(decoded[0].shares_outstanding, None); + assert_eq!(decoded[0].ttm_period_end, None); + assert_eq!(decoded[0].ttm_currency, None); + assert_eq!(decoded[0].ttm_revenue, None); + assert_eq!(decoded[0].ttm_net_income, None); + assert_eq!(decoded[0].ttm_operating_cash_flow, None); + assert_eq!(decoded[0].ttm_has_estimated_lag, None); + + // Row 1: ttm_has_estimated_lag = Some(false) + assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); + assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); + assert_eq!(decoded[1].ttm_revenue, Some(370.0)); + assert_eq!(decoded[1].ttm_net_income, Some(37.0)); + assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0)); + assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false)); + + // Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source. + assert_eq!(decoded[2].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(decoded[2].has_estimated_lag); + assert_eq!(decoded[2].fiscal_period, "FY"); + assert_eq!(decoded[2].currency, "CAD"); + assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); + assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); + assert_eq!(decoded[2].ttm_revenue, Some(450.0)); + assert_eq!(decoded[2].ttm_net_income, None); + assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0)); + assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true)); + + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() { + let listing_id = 42_i32; + let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::UsTsx)]); + + let p_2023_q3 = day(2023, 9, 30); + let p_2023_q4 = day(2023, 12, 31); + let p_2024_q1 = day(2024, 3, 31); + let p_2024_q2 = day(2024, 6, 30); + + let initial_filings = vec![ + filing(listing_id, "2023-11-01T16:15:00 EDT", "10-Q"), + filing(listing_id, "2024-02-01T16:15:00 EST", "10-Q"), + filing(listing_id, "2024-05-01T16:15:00 EDT", "10-Q"), + filing(listing_id, "2024-08-01T16:15:00 EDT", "10-Q"), + ]; + let amendment_filing = filing(listing_id, "2024-09-15T17:00:00 EDT", "10-Q/A"); + + let initial_obs = vec![ + obs( + listing_id, + p_2023_q3, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 1)), + FundamentalsFields { + revenue: Some(70.0), + net_income: Some(7.0), + operating_cash_flow: Some(10.0), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2023_q4, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 1)), + FundamentalsFields { + revenue: Some(80.0), + net_income: Some(8.0), + operating_cash_flow: Some(12.0), + total_assets: Some(520.0), + total_equity: Some(210.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(15.0), + total_assets: Some(540.0), + total_equity: Some(220.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2024_q2, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 1)), + FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(18.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), + }, + ), + ]; + + // Late Q1 amendment filed on 2024-09-15 (after Q2's 2024-08-01 filing). + // Restates revenue 100 -> 110 and net_income 10 -> 11, while omitting operating_cash_flow. + let q1_amendment = obs( + listing_id, + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 15)), + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: None, + total_assets: None, + total_equity: Some(225.0), + shares_outstanding: None, + }, + ); + + let mut full_obs = initial_obs.clone(); + full_obs.push(q1_amendment); + let mut full_filings = initial_filings.clone(); + full_filings.push(amendment_filing); + + let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); + let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).expect("full snapshots"); + assert_eq!(full_snaps.len(), 5); + + let baseline_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); + let baseline_snaps = + build_fundamentals_snapshots(&baseline_build.rows, 4).expect("baseline snapshots"); + assert_eq!(baseline_snaps.len(), 4); + + let full_rows_from_ref: Vec = + full_snaps.iter().map(FundamentalsPitParquetRow::from).collect(); + let full_rows_from_owned: Vec = full_snaps + .into_iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + assert_eq!(full_rows_from_ref, full_rows_from_owned); + + let baseline_rows: Vec = baseline_snaps + .iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + + let tmp_full = TempDirGuard::new("restatement-full"); + let tmp_base = TempDirGuard::new("restatement-baseline"); + + let full_stats = write_fundamentals_pit_dataset( + tmp_full.path(), + &full_rows_from_ref, + FundamentalsPitWriteOptions::default(), + ) + .expect("write full dataset"); + assert_eq!(full_stats.rows_written, 5); + assert_eq!(full_stats.files_written, 2); + assert_eq!(full_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 4)])); + + let base_stats = write_fundamentals_pit_dataset( + tmp_base.path(), + &baseline_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write baseline dataset"); + assert_eq!(base_stats.rows_written, 4); + assert_eq!(base_stats.files_written, 2); + assert_eq!(base_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 3)])); + + let mut full_decoded = read_parquet_rows( + &tmp_full + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + full_decoded.extend(read_parquet_rows( + &tmp_full + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(full_decoded.len(), 5); + + let mut base_decoded = read_parquet_rows( + &tmp_base + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + base_decoded.extend(read_parquet_rows( + &tmp_base + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(base_decoded.len(), 4); + + let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0, 0); + let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0, 0); + + // Every earlier row (before the amendment) must match the unamended baseline identically. + assert_eq!(&full_decoded[..4], &base_decoded[..]); + + // Every row at or after Q2 filing must keep Q2 as the latest visible period with unchanged fields. + let post_q2_rows: Vec<&DecodedFundamentalsPitRow> = full_decoded + .iter() + .filter(|r| r.effective_known_at >= ts_q2) + .collect(); + assert_eq!(post_q2_rows.len(), 2); + assert_eq!(post_q2_rows[0].effective_known_at, ts_q2); + assert_eq!(post_q2_rows[1].effective_known_at, ts_amend); + + for row in &post_q2_rows { + assert_eq!(row.listing_id, listing_id); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!row.has_estimated_lag); + assert_eq!(row.period_end, p_2024_q2); + assert_eq!(row.period_known_at, ts_q2); + assert_eq!(row.fiscal_period, "Q"); + assert_eq!(row.currency, "USD"); + assert_eq!(row.revenue, Some(120.0)); + assert_eq!(row.net_income, Some(12.0)); + assert_eq!(row.operating_cash_flow, Some(18.0)); + assert_eq!(row.total_assets, Some(560.0)); + assert_eq!(row.total_equity, Some(230.0)); + assert_eq!(row.shares_outstanding, Some(100.0)); + assert_eq!(row.ttm_period_end, Some(p_2024_q2)); + assert_eq!(row.ttm_currency.as_deref(), Some("USD")); + assert_eq!(row.ttm_has_estimated_lag, Some(false)); + } + + // At Q2 filing (before amendment): TTM uses original Q1 (revenue=100, net_income=10, ocf=15). + assert_eq!(post_q2_rows[0].ttm_revenue, Some(370.0)); + assert_eq!(post_q2_rows[0].ttm_net_income, Some(37.0)); + assert_eq!(post_q2_rows[0].ttm_operating_cash_flow, Some(55.0)); + + // At Q1 amendment: TTM revenue & net_income update (+10, +1); TTM OCF preserves prior Q1's 15.0. + assert_eq!(post_q2_rows[1].ttm_revenue, Some(380.0)); + assert_eq!(post_q2_rows[1].ttm_net_income, Some(38.0)); + assert_eq!(post_q2_rows[1].ttm_operating_cash_flow, Some(55.0)); + + assert_no_transient_files(&tmp_full.path().join("fundamentals_pit")); + assert_no_transient_files(&tmp_base.path().join("fundamentals_pit")); +} + +#[test] +fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() { + let tmp = TempDirGuard::new("partitioning"); + + // Globally ordered by (listing_id, effective_known_at), with interleaved UTC years across + // multiple listings and timestamps 1 microsecond apart across midnight UTC. + let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); + let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); + assert_eq!(partition_year_utc(ts_2023_end), 2023); + assert_eq!(partition_year_utc(ts_2024_start), 2024); + + let rows = vec![ + make_row(1, utc_micros(2023, 5, 1, 14, 0, 0, 0), day(2023, 3, 31), Some(10.0), None), + make_row(1, ts_2023_end, day(2023, 9, 30), Some(11.0), None), + make_row(1, ts_2024_start, day(2023, 12, 31), Some(12.0), None), + make_row(2, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(20.0), None), + make_row(2, utc_micros(2024, 2, 1, 14, 0, 0, 0), day(2023, 12, 31), Some(21.0), None), + make_row(3, utc_micros(2023, 11, 1, 14, 0, 0, 0), day(2023, 9, 30), Some(30.0), None), + make_row(3, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(31.0), None), + ]; + + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write partitioned dataset"); + + assert_eq!(stats.rows_written, 7); + assert_eq!(stats.files_written, 2); + // 2023: 4 rows -> 2 row groups; 2024: 3 rows -> 2 row groups + assert_eq!(stats.row_groups_written, 4); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 4), (2024, 3)])); + + let path_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + assert!(path_2023.is_file()); + assert!(path_2024.is_file()); + + let decoded_2023 = read_parquet_rows(&path_2023); + let decoded_2024 = read_parquet_rows(&path_2024); + + assert_eq!(decoded_2023.len(), 4); + assert_eq!(decoded_2024.len(), 3); + + // Verify exact membership and strict sort order by (listing_id, effective_known_at). + for (year, decoded) in [(2023, &decoded_2023), (2024, &decoded_2024)] { + for r in decoded { + assert_eq!(partition_year_utc(r.effective_known_at), year); + } + for pair in decoded.windows(2) { + assert!( + (pair[0].listing_id, pair[0].effective_known_at) + < (pair[1].listing_id, pair[1].effective_known_at), + "year {year} rows must be strictly increasing by (listing_id, effective_known_at)" + ); + } + } + + assert_eq!(decoded_2023[1].effective_known_at, ts_2023_end); + assert_eq!(decoded_2024[0].effective_known_at, ts_2024_start); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_preserve_existing_partitions() { + let tmp = TempDirGuard::new("errors"); + + // Seed an existing 2024 partition and snapshot its exact bytes. + let seed = vec![make_row( + 1, + utc_micros(2024, 3, 1, 15, 0, 0, 0), + day(2023, 12, 31), + Some(50.0), + None, + )]; + write_fundamentals_pit_dataset( + tmp.path(), + &seed, + FundamentalsPitWriteOptions::default(), + ) + .expect("seed existing partition"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let before_bytes = fs::read(&part_2024).expect("read seed bytes"); + + let rg1 = FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + + // 1. Duplicate (listing_id, effective_known_at) with different payload after a valid row. + let ts_a = utc_micros(2024, 5, 1, 20, 0, 0, 0); + let dup_rows = vec![ + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + make_row(1, ts_a, day(2024, 3, 31), Some(999.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &dup_rows, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::DuplicateRow { + row_index: 1, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_a + ), + "expected DuplicateRow, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 2. Unsorted (descending effective_known_at for same listing) after a valid row. + let ts_b = utc_micros(2024, 8, 1, 20, 0, 0, 0); + let unsorted_ts = vec![ + make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_ts, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 1, + prev_effective_known_at_micros, + listing_id: 1, + effective_known_at_micros, + } if prev_effective_known_at_micros == ts_b && effective_known_at_micros == ts_a + ), + "expected UnsortedInput, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 3. Unsorted (descending listing_id) after a valid row. + let unsorted_lid = vec![ + make_row(2, ts_a, day(2024, 3, 31), Some(100.0), None), + make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_lid, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 2, + listing_id: 1, + .. + } + ), + "expected UnsortedInput for descending listing_id, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 4. Empty periods snapshot (at row_index 0 and at row_index 1 after a flushed row group). + let empty_snap = FundamentalsSnapshot { + key: 1_i32, + effective_known_at_utc_micros: ts_b, + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + periods: Vec::new(), + ttm: None, + }; + let empty_row = FundamentalsPitParquetRow::from(&empty_snap); + assert!(empty_row.latest_period().is_none()); + + let tmp_fresh = TempDirGuard::new("empty-periods-first"); + let err_first = write_fundamentals_pit_dataset(tmp_fresh.path(), &[empty_row.clone()], rg1) + .unwrap_err(); + assert!( + matches!( + err_first, + ParquetFundamentalsError::EmptyPeriods { + row_index: 0, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_b + ), + "expected EmptyPeriods at row 0, got {err_first:?}" + ); + assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); + + let mixed = vec![ + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + empty_row, + ]; + let err_second = write_fundamentals_pit_dataset(tmp.path(), &mixed, rg1).unwrap_err(); + assert!( + matches!( + err_second, + ParquetFundamentalsError::EmptyPeriods { + row_index: 1, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_b + ), + "expected EmptyPeriods at row 1, got {err_second:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 5. Empty input does not create directory or touch existing partitions. + let tmp_empty = TempDirGuard::new("empty-input"); + let empty_stats = write_fundamentals_pit_dataset( + tmp_empty.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .expect("empty input succeeds"); + assert_eq!(empty_stats, FundamentalsPitWriteStats::default()); + assert!(!tmp_empty.path().join("fundamentals_pit").exists()); +} + +#[test] +fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { + let tmp = TempDirGuard::new("rollback"); + + // Seed an existing 2023 partition. + let seed = vec![make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(50.0), + None, + )]; + write_fundamentals_pit_dataset( + tmp.path(), + &seed, + FundamentalsPitWriteOptions::default(), + ) + .expect("seed 2023"); + + let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let part_2025 = tmp.path().join("fundamentals_pit/year=2025/part.parquet"); + let before_2023 = fs::read(&part_2023).expect("read seed 2023"); + + // Occupy year=2025/part.parquet with a directory so rename fails after 2023 (replaced) + // and 2024 (newly created) have been renamed into place. + fs::create_dir_all(&part_2025).expect("create blocking directory at year=2025/part.parquet"); + + let rows = vec![ + make_row(1, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(75.0), None), + make_row(1, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(100.0), None), + make_row(1, utc_micros(2025, 5, 1, 14, 0, 0, 0), day(2025, 3, 31), Some(125.0), None), + ]; + + let err = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetFundamentalsError::Io { ref path, .. } if path == &part_2025), + "expected Io error at year=2025/part.parquet, got {err:?}" + ); + + // 2023 must be restored byte for byte; 2024 must be removed; no transient files remain. + assert_eq!(fs::read(&part_2023).expect("read restored 2023"), before_2023); + assert!( + !part_2024.exists(), + "newly published 2024 partition must be removed on rollback" + ); + assert!(part_2025.is_dir()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index fd9b89c2..00d6f1a4 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -363,6 +363,25 @@ fn next_column<'a>( } } +pub(crate) fn write_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], + def_levels: Option<&[i16]>, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, def_levels, None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + pub(crate) fn write_i32_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, values: &[i32], From 065af2eade690c1f0d318c2238b2a6608a200fe1 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:05:43 -0500 Subject: [PATCH 02/26] T-143: tests --- .../src/parquet_fundamentals_tests.rs | 612 ++++++++++++++++++ 1 file changed, 612 insertions(+) diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs index 7b4b5712..8e15ea38 100644 --- a/tools/curate-etl/src/parquet_fundamentals_tests.rs +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -1263,3 +1263,615 @@ fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { assert!(part_2025.is_dir()); assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } + + +// --------------------------------------------------------------------------------------------- +// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance, +// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors. +// --------------------------------------------------------------------------------------------- + +/// Expected decoded form of a row: what the reader must see after a write/read round trip. +fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRow { + let latest = row + .latest_period() + .expect("expected row must have a latest period"); + let ttm = row.ttm.as_ref(); + DecodedFundamentalsPitRow { + listing_id: row.listing_id, + effective_known_at: row.effective_known_at_micros, + known_at_source: row.known_at_source.to_string(), + has_estimated_lag: row.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: latest.fiscal_period.to_string(), + currency: latest.currency.clone(), + period_known_at: latest.period_known_at_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_period_end: ttm.map(|t| t.ending_period_end), + ttm_currency: ttm.map(|t| t.currency.clone()), + ttm_revenue: ttm.and_then(|t| t.flows.revenue), + ttm_net_income: ttm.and_then(|t| t.flows.net_income), + ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow), + ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag), + } +} + +fn read_year(out_dir: &Path, year: i32) -> Vec { + read_parquet_rows(&out_dir.join(format!("fundamentals_pit/year={year}/part.parquet"))) +} + +fn list_year_dirs(out_dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(out_dir.join("fundamentals_pit")) + .expect("read dataset dir") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with("year=")) + .collect(); + names.sort(); + names +} + +/// Deterministic LCG so fixtures are reproducible without an RNG crate. +struct Lcg(u64); + +impl Lcg { + fn next_u32(&mut self) -> u32 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as u32 + } + fn chance(&mut self, pct: u32) -> bool { + self.next_u32() % 100 < pct + } + fn opt(&mut self, pct_null: u32, v: f64) -> Option { + if self.chance(pct_null) { + None + } else { + Some(v) + } + } +} + +#[test] +fn partition_files_contain_exact_expected_row_sequence_per_year() { + let tmp = TempDirGuard::new("qa-partition-exact"); + let ttm = |end: i32, rev: f64| FundamentalsTtm { + ending_period_end: end, + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(rev), + net_income: None, + operating_cash_flow: Some(rev / 2.0), + }, + has_estimated_lag: false, + }; + let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); + let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); + let rows = vec![ + make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(10.0), + None, + ), + make_row( + 1, + ts_2023_end, + day(2023, 9, 30), + Some(11.0), + Some(ttm(day(2023, 9, 30), 40.0)), + ), + make_row( + 1, + ts_2024_start, + day(2023, 12, 31), + Some(12.0), + Some(ttm(day(2023, 12, 31), 44.0)), + ), + make_row( + 2, + utc_micros(2023, 8, 1, 14, 0, 0, 0), + day(2023, 6, 30), + None, + None, + ), + make_row( + 2, + utc_micros(2024, 2, 1, 14, 0, 0, 0), + day(2023, 12, 31), + Some(21.0), + None, + ), + make_row( + 3, + utc_micros(2023, 11, 1, 14, 0, 0, 0), + day(2023, 9, 30), + Some(30.0), + None, + ), + make_row( + 3, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + day(2024, 3, 31), + Some(31.0), + Some(ttm(day(2024, 3, 31), 120.0)), + ), + ]; + + write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write"); + + let expected_2023: Vec<_> = [0, 1, 3, 5] + .iter() + .map(|&i| expected_decoded(&rows[i])) + .collect(); + let expected_2024: Vec<_> = [2, 4, 6] + .iter() + .map(|&i| expected_decoded(&rows[i])) + .collect(); + assert_eq!(list_year_dirs(tmp.path()), vec!["year=2023", "year=2024"]); + assert_eq!(read_year(tmp.path(), 2023), expected_2023); + assert_eq!(read_year(tmp.path(), 2024), expected_2024); +} + +#[test] +fn seeded_mixed_null_patterns_round_trip_across_many_row_groups() { + let tmp = TempDirGuard::new("qa-seeded"); + let mut rng = Lcg(0x5EED_1430); + let mut rows = Vec::new(); + for listing_id in 1..=9_i32 { + for q in 0..12_i32 { + // One quarter apart; spans 2021..=2023 so multiple partitions get interleaved. + let ts = utc_micros( + 2021 + q / 4, + (q % 4) as u32 * 3 + 2, + 10, + 20, + 30, + 0, + i64::from(listing_id), + ); + let period_end = day(2021 + q / 4, (q % 4) as u32 * 3 + 1, 1); + let base = f64::from(listing_id * 1000 + q); + let estimated = rng.chance(30); + let currency = if rng.chance(20) { "CAD" } else { "USD" }; + let ttm = if rng.chance(40) { + None + } else { + Some(FundamentalsTtm { + ending_period_end: period_end, + currency: currency.to_string(), + flows: TtmFlowFields { + revenue: rng.opt(25, base * 4.0), + net_income: rng.opt(25, -base * 0.25), + operating_cash_flow: rng.opt(25, 0.0), + }, + has_estimated_lag: rng.chance(50), + }) + }; + rows.push(FundamentalsPitParquetRow::new( + listing_id, + ts, + Cow::Borrowed(if estimated { + KNOWN_AT_SOURCE_STATUTORY_LAG + } else { + KNOWN_AT_SOURCE_FILING_TIMESTAMP + }), + estimated, + FundamentalsPitLatestPeriod { + period_end, + fiscal_period: Cow::Borrowed(if q % 4 == 3 { "FY" } else { "Q" }), + currency: currency.to_string(), + period_known_at_micros: ts - 1, + fields: FundamentalsFields { + revenue: rng.opt(20, base), + net_income: rng.opt(20, -base / 10.0), + operating_cash_flow: rng.opt(20, base / 7.0), + total_assets: rng.opt(20, base * 5.0), + total_equity: rng.opt(20, base * 2.0), + shares_outstanding: rng.opt(20, 1.0e9), + }, + }, + ttm, + )); + } + } + // Sanity: the fixture really exercises all-null and all-present TTM in the same file. + assert!(rows.iter().any(|r| r.ttm.is_none())); + assert!(rows + .iter() + .any(|r| r.ttm.as_ref().is_some_and(|t| t.flows.revenue.is_none()))); + + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 5, + zstd_level: 1, + }, + ) + .expect("write seeded dataset"); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!( + stats.rows_by_year, + BTreeMap::from([(2021, 36), (2022, 36), (2023, 36)]) + ); + // 36 rows per year at 5 rows per group -> 8 groups per year. + assert_eq!(stats.row_groups_written, 24); + + for year in 2021..=2023 { + let expected: Vec<_> = rows + .iter() + .filter(|r| partition_year_utc(r.effective_known_at_micros) == year) + .map(expected_decoded) + .collect(); + assert_eq!(read_year(tmp.path(), year), expected, "year {year}"); + } + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() { + // Listing 7 (TSXV/CSE venue) files Q1 via a 10-Q; Q2 has no filing and no report date, + // so its known_at falls back to period_end + 60d at 16:05 America/Toronto. + let listing_id = 7_i32; + let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::TsxvCse)]); + let p_q1 = day(2024, 3, 31); + let p_q2 = day(2024, 6, 30); + let fields = |rev: f64| FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev / 10.0), + operating_cash_flow: None, + total_assets: Some(900.0), + total_equity: Some(400.0), + shares_outstanding: Some(50.0), + }; + let observations = vec![ + obs( + listing_id, + p_q1, + FiscalPeriod::Quarterly, + "CAD", + None, + fields(100.0), + ), + obs( + listing_id, + p_q2, + FiscalPeriod::Quarterly, + "CAD", + None, + fields(130.0), + ), + ]; + let filings = vec![filing(listing_id, "2024-05-10T16:30:00 EDT", "10-Q")]; + + let build = build_fundamentals_rows(observations, filings, &venues); + let snaps = build_fundamentals_snapshots(&build.rows, 4).expect("snapshots"); + assert_eq!(snaps.len(), 2); + let rows: Vec = + snaps.iter().map(FundamentalsPitParquetRow::from).collect(); + + let tmp = TempDirGuard::new("qa-estimated"); + write_fundamentals_pit_dataset(tmp.path(), &rows, FundamentalsPitWriteOptions::default()) + .expect("write"); + let decoded = read_year(tmp.path(), 2024); + assert_eq!( + decoded, + rows.iter().map(expected_decoded).collect::>() + ); + + // Q1: filing-backed, at the 10-Q's UTC timestamp. + let ts_q1 = utc_micros(2024, 5, 10, 20, 30, 0, 0); + assert_eq!(decoded[0].effective_known_at, ts_q1); + assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!decoded[0].has_estimated_lag); + assert_eq!(decoded[0].period_end, p_q1); + assert_eq!(decoded[0].period_known_at, ts_q1); + assert_eq!(decoded[0].currency, "CAD"); + + // Q2: estimated, 2024-06-30 + 60d = 2024-08-29 16:05 EDT = 20:05 UTC. + let ts_q2_est = utc_micros(2024, 8, 29, 20, 5, 0, 0); + assert_eq!(decoded[1].effective_known_at, ts_q2_est); + assert_eq!(decoded[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(decoded[1].has_estimated_lag); + assert_eq!(decoded[1].period_end, p_q2); + assert_eq!(decoded[1].period_known_at, ts_q2_est); + assert_eq!(decoded[1].revenue, Some(130.0)); + assert_eq!(decoded[1].operating_cash_flow, None); + // Only two quarters exist, so TTM is unavailable and every ttm_* column is null. + for r in &decoded { + assert_eq!(r.ttm_period_end, None); + assert_eq!(r.ttm_currency, None); + assert_eq!(r.ttm_revenue, None); + assert_eq!(r.ttm_net_income, None); + assert_eq!(r.ttm_operating_cash_flow, None); + assert_eq!(r.ttm_has_estimated_lag, None); + } +} + +#[test] +fn rewrite_replaces_only_years_present_in_new_input() { + let tmp = TempDirGuard::new("qa-rewrite"); + let first = vec![ + make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(10.0), + None, + ), + make_row( + 1, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + day(2024, 3, 31), + Some(20.0), + None, + ), + ]; + write_fundamentals_pit_dataset(tmp.path(), &first, FundamentalsPitWriteOptions::default()) + .expect("first write"); + let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let bytes_2023 = fs::read(&part_2023).expect("read 2023"); + + let second = vec![ + make_row( + 5, + utc_micros(2024, 2, 1, 14, 0, 0, 0), + day(2023, 12, 31), + Some(55.0), + None, + ), + make_row( + 5, + utc_micros(2024, 6, 1, 14, 0, 0, 0), + day(2024, 3, 31), + Some(56.0), + None, + ), + ]; + let stats = + write_fundamentals_pit_dataset(tmp.path(), &second, FundamentalsPitWriteOptions::default()) + .expect("second write"); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 2)])); + + // 2024 is fully replaced (no merge with old rows); 2023 is untouched byte for byte. + assert_eq!( + read_year(tmp.path(), 2024), + second.iter().map(expected_decoded).collect::>() + ); + assert_eq!(fs::read(&part_2023).expect("reread 2023"), bytes_2023); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn identical_input_produces_byte_identical_partitions() { + let rows = vec![ + make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(10.0), + None, + ), + make_row( + 2, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + day(2024, 3, 31), + None, + None, + ), + ]; + let a = TempDirGuard::new("qa-determinism-a"); + let b = TempDirGuard::new("qa-determinism-b"); + let opts = FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + write_fundamentals_pit_dataset(a.path(), &rows, opts).expect("write a"); + write_fundamentals_pit_dataset(b.path(), &rows, opts).expect("write b"); + for year in [2023, 2024] { + let rel = format!("fundamentals_pit/year={year}/part.parquet"); + assert_eq!( + fs::read(a.path().join(&rel)).expect("read a"), + fs::read(b.path().join(&rel)).expect("read b"), + "year {year} bytes differ between identical runs" + ); + } +} + +#[test] +fn remaining_validation_errors_are_typed_and_publish_nothing() { + let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); + let valid = make_row(1, ts - 1, day(2024, 3, 31), Some(1.0), None); + let defaults = FundamentalsPitWriteOptions::default(); + + let run = |label: &str, bad: FundamentalsPitParquetRow, opts: FundamentalsPitWriteOptions| { + let tmp = TempDirGuard::new(label); + let err = write_fundamentals_pit_dataset(tmp.path(), [valid.clone(), bad], opts) + .expect_err("invalid input must fail"); + let year_dir = tmp.path().join("fundamentals_pit/year=2024"); + assert!( + !year_dir.join("part.parquet").exists(), + "{label}: partial file published" + ); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + err + }; + + let mut nan_row = make_row(1, ts, day(2024, 3, 31), Some(f64::NAN), None); + nan_row.has_estimated_lag = true; + let err = run("qa-nan", nan_row, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::NonFiniteValue { + row_index: 1, + field: "revenue", + .. + } + ), + "got {err:?}" + ); + + let inf_ttm = make_row( + 1, + ts, + day(2024, 3, 31), + Some(1.0), + Some(FundamentalsTtm { + ending_period_end: day(2024, 3, 31), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(1.0), + net_income: None, + operating_cash_flow: Some(f64::INFINITY), + }, + has_estimated_lag: false, + }), + ); + let err = run("qa-inf-ttm", inf_ttm, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::NonFiniteValue { + field: "ttm_operating_cash_flow", + .. + } + ), + "got {err:?}" + ); + + let mut blank_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); + blank_source.known_at_source = Cow::Borrowed(" "); + let err = run("qa-blank-source", blank_source, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::EmptyKnownAtSource { row_index: 1, .. } + ), + "got {err:?}" + ); + + let blank_ttm_currency = make_row( + 1, + ts, + day(2024, 3, 31), + Some(1.0), + Some(FundamentalsTtm { + ending_period_end: day(2024, 3, 31), + currency: String::new(), + flows: TtmFlowFields { + revenue: None, + net_income: None, + operating_cash_flow: None, + }, + has_estimated_lag: false, + }), + ); + let err = run("qa-blank-ttm-ccy", blank_ttm_currency, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::EmptyTtmCurrency { row_index: 1, .. } + ), + "got {err:?}" + ); + + let blank_currency = FundamentalsPitParquetRow::new( + 1, + ts, + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: String::new(), + period_known_at_micros: ts, + fields: FundamentalsFields { + revenue: None, + net_income: None, + operating_cash_flow: None, + total_assets: None, + total_equity: None, + shares_outstanding: None, + }, + }, + None, + ); + let err = run("qa-blank-ccy", blank_currency, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::EmptyCurrency { row_index: 1, .. } + ), + "got {err:?}" + ); + + // Year 2201 is above MAX_PARQUET_YEAR (2200). + let far_future = make_row( + 1, + utc_micros(2201, 1, 1, 0, 0, 0, 0), + day(2024, 3, 31), + Some(1.0), + None, + ); + let err = run("qa-year-range", far_future, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::PartitionYearOutOfRange { + row_index: 1, + year: 2201, + .. + } + ), + "got {err:?}" + ); + + // Option validation happens before any filesystem side effects. + let tmp = TempDirGuard::new("qa-bad-options"); + let err = write_fundamentals_pit_dataset( + tmp.path(), + [valid.clone()], + FundamentalsPitWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!( + matches!(err, ParquetFundamentalsError::InvalidRowGroupRows), + "got {err:?}" + ); + let err = write_fundamentals_pit_dataset( + tmp.path(), + [valid], + FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: 99, + }, + ) + .unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::InvalidZstdLevel { level: 99 } + ), + "got {err:?}" + ); + assert!(!tmp.path().join("fundamentals_pit").exists()); +} From bb1eca42b1b13e4545756e4b35e436742624e724 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:11:08 -0500 Subject: [PATCH 03/26] =?UTF-8?q?T-143:=20M2.2c=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20Zstd=20Parquet=20writer=20for=20`fundamentals=5Fpit/y?= =?UTF-8?q?ear=3DYYYY/part.parquet`=20(flat=20latest-period=20+=20TTM=20sn?= =?UTF-8?q?apshot=20rows=20from=20`FundamentalsSnapshot`)=20with=20re?= =?UTF-8?q?statement=20round-trip=20test=20(no=20new=20crates,=20no=20CLI/?= =?UTF-8?q?bench=20changes)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/parquet_fundamentals.rs | 29 +++++++++++++++++- .../src/parquet_fundamentals_tests.rs | 30 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs index 9e804d26..0bc2a9b4 100644 --- a/tools/curate-etl/src/parquet_fundamentals.rs +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -49,7 +49,9 @@ use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; use parquet::file::writer::SerializedFileWriter; use parquet::schema::types::{ColumnPath, Type, TypePtr}; -use crate::events::partition_year_utc; +use crate::events::{ + partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; use crate::fundamentals::{FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm}; pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; use crate::parquet_publish::{ @@ -220,6 +222,12 @@ pub enum ParquetFundamentalsError { listing_id: i32, effective_known_at_micros: i64, }, + InvalidKnownAtSource { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + value: String, + }, EmptyFiscalPeriod { row_index: usize, listing_id: i32, @@ -314,6 +322,15 @@ impl fmt::Display for ParquetFundamentalsError { f, "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" ), + Self::InvalidKnownAtSource { + row_index, + listing_id, + effective_known_at_micros, + value, + } => write!( + f, + "invalid known_at_source {value:?} at row {row_index} for ({listing_id}, {effective_known_at_micros}): expected {KNOWN_AT_SOURCE_FILING_TIMESTAMP:?} or {KNOWN_AT_SOURCE_STATUTORY_LAG:?}" + ), Self::EmptyFiscalPeriod { row_index, listing_id, @@ -594,6 +611,16 @@ fn validate_row( effective_known_at_micros: row.effective_known_at_micros, }); } + if row.known_at_source.as_ref() != KNOWN_AT_SOURCE_FILING_TIMESTAMP + && row.known_at_source.as_ref() != KNOWN_AT_SOURCE_STATUTORY_LAG + { + return Err(ParquetFundamentalsError::InvalidKnownAtSource { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + value: row.known_at_source.to_string(), + }); + } if latest.fiscal_period.trim().is_empty() { return Err(ParquetFundamentalsError::EmptyFiscalPeriod { row_index, diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs index 8e15ea38..de8b46e2 100644 --- a/tools/curate-etl/src/parquet_fundamentals_tests.rs +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -1766,6 +1766,36 @@ fn remaining_validation_errors_are_typed_and_publish_nothing() { "got {err:?}" ); + let mut invalid_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); + invalid_source.known_at_source = Cow::Borrowed("manual_override"); + let err = run("qa-invalid-source", invalid_source, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::InvalidKnownAtSource { + row_index: 1, + ref value, + .. + } if value == "manual_override" + ), + "got {err:?}" + ); + + let mut padded_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); + padded_source.known_at_source = Cow::Borrowed(" filing_timestamp "); + let err = run("qa-padded-source", padded_source, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::InvalidKnownAtSource { + row_index: 1, + ref value, + .. + } if value == " filing_timestamp " + ), + "got {err:?}" + ); + let blank_ttm_currency = make_row( 1, ts, From dd8dc692afd3baded276ca4080b94def57d93105 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:25:46 -0500 Subject: [PATCH 04/26] =?UTF-8?q?T-145:=20M2.2d=20=E2=80=94=20`fundamental?= =?UTF-8?q?sAsOf`=20in=20the=20DuckDB=20`MarketDataStore`:=20Vault-fenced?= =?UTF-8?q?=20point-in-time=20read=20of=20`fundamentals=5Fpit/year=3D*/par?= =?UTF-8?q?t.parquet`=20with=20a=20real-DuckDB=20restatement=20fixture=20t?= =?UTF-8?q?est=20(no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/duckdb-market-data-store.test.ts | 481 ++++++++++++++++++ libs/research/README.md | 3 +- libs/research/src/market-data-store-duckdb.ts | 255 +++++++++- .../test/market-data-store-duckdb.test.ts | 370 +++++++++++++- 4 files changed, 1096 insertions(+), 13 deletions(-) diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts index d43bd44c..abd4c3be 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -247,4 +247,485 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { await opened.close(); } }); + + test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + + await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true }); + await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true }); + await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true }); + await mkdir(duckTempDir, { recursive: true }); + + // Vault cutoff = 2025-02-13T00:00:00.000Z + const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); + const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z + const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z + const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z + + const writer = await createNodeDuckDbExecutor(); + try { + // year=2023 partition: listing 50 (only exists in 2023 partition) + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ( + 50::INTEGER, + TIMESTAMPTZ '2023-11-05 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2023-09-30', + 'Q3'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2023-11-05 20:00:00+00', + 80.0::DOUBLE, + 8.0::DOUBLE, + 12.0::DOUBLE, + 500.0::DOUBLE, + 250.0::DOUBLE, + 10.0::DOUBLE, + DATE '2023-09-30', + 'USD'::VARCHAR, + 310.0::DOUBLE, + 31.0::DOUBLE, + 46.0::DOUBLE, + FALSE::BOOLEAN + ) + ) 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(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) + `); + + // year=2024 partition: + // - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes) + // - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback) + // - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag) + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ( + 101::INTEGER, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-03-31', + 'Q1'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 100.0::DOUBLE, + 10.0::DOUBLE, + 15.0::DOUBLE, + 1000.0::DOUBLE, + 500.0::DOUBLE, + 50.0::DOUBLE, + DATE '2024-03-31', + 'USD'::VARCHAR, + 380.0::DOUBLE, + 38.0::DOUBLE, + 55.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 101::INTEGER, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 120.0::DOUBLE, + 14.0::DOUBLE, + 20.0::DOUBLE, + 1050.0::DOUBLE, + 520.0::DOUBLE, + 50.0::DOUBLE, + DATE '2024-06-30', + 'USD'::VARCHAR, + 420.0::DOUBLE, + 44.0::DOUBLE, + 65.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 101::INTEGER, + TIMESTAMPTZ '2024-09-15 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 120.0::DOUBLE, + 14.0::DOUBLE, + 20.0::DOUBLE, + 1050.0::DOUBLE, + 520.0::DOUBLE, + 50.0::DOUBLE, + DATE '2024-06-30', + 'USD'::VARCHAR, + 415.0::DOUBLE, + 42.0::DOUBLE, + 63.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 201::INTEGER, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-03-31', + 'Q1'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-05-01 20:00:00+00', + 50.0::DOUBLE, + 5.0::DOUBLE, + 7.0::DOUBLE, + 400.0::DOUBLE, + 200.0::DOUBLE, + 20.0::DOUBLE, + DATE '2024-03-31', + 'USD'::VARCHAR, + 190.0::DOUBLE, + 19.0::DOUBLE, + 27.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 201::INTEGER, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 'estimated_lag'::VARCHAR, + TRUE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 60.0::DOUBLE, + 6.0::DOUBLE, + 8.0::DOUBLE, + 420.0::DOUBLE, + 210.0::DOUBLE, + 20.0::DOUBLE, + DATE '2024-06-30', + 'USD'::VARCHAR, + 210.0::DOUBLE, + 21.0::DOUBLE, + 30.0::DOUBLE, + TRUE::BOOLEAN + ), + ( + 202::INTEGER, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-06-30', + 'Q2'::VARCHAR, + 'CAD'::VARCHAR, + TIMESTAMPTZ '2024-08-01 20:00:00+00', + 75.0::DOUBLE, + 9.0::DOUBLE, + 11.0::DOUBLE, + 600.0::DOUBLE, + 300.0::DOUBLE, + 30.0::DOUBLE, + DATE '2024-06-30', + 'CAD'::VARCHAR, + 300.0::DOUBLE, + 30.0::DOUBLE, + 45.0::DOUBLE, + TRUE::BOOLEAN + ) + ) 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(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) + `); + + // year=2025 partition: Vault microsecond boundary rows + // - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded) + // - listing 103: exact cutoff only (must return 0 rows) + await writer.run(` + COPY ( + SELECT * FROM (VALUES + ( + 102::INTEGER, + TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-12-31', + 'Q4'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', + 210.0::DOUBLE, + 21.0::DOUBLE, + 31.0::DOUBLE, + 1500.0::DOUBLE, + 750.0::DOUBLE, + 60.0::DOUBLE, + DATE '2024-12-31', + 'USD'::VARCHAR, + 800.0::DOUBLE, + 80.0::DOUBLE, + 120.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 102::INTEGER, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-12-31', + 'Q4'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 999.0::DOUBLE, + 99.0::DOUBLE, + 99.0::DOUBLE, + 9999.0::DOUBLE, + 4999.0::DOUBLE, + 60.0::DOUBLE, + DATE '2024-12-31', + 'USD'::VARCHAR, + 9999.0::DOUBLE, + 999.0::DOUBLE, + 999.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 102::INTEGER, + TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2025-03-31', + 'Q1'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', + 1111.0::DOUBLE, + 111.0::DOUBLE, + 111.0::DOUBLE, + 11111.0::DOUBLE, + 5555.0::DOUBLE, + 60.0::DOUBLE, + DATE '2025-03-31', + 'USD'::VARCHAR, + 11111.0::DOUBLE, + 1111.0::DOUBLE, + 1111.0::DOUBLE, + FALSE::BOOLEAN + ), + ( + 103::INTEGER, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 'filing_date'::VARCHAR, + FALSE::BOOLEAN, + DATE '2024-12-31', + 'Q4'::VARCHAR, + 'USD'::VARCHAR, + TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', + 777.0::DOUBLE, + 77.0::DOUBLE, + 77.0::DOUBLE, + 7777.0::DOUBLE, + 3333.0::DOUBLE, + 40.0::DOUBLE, + DATE '2024-12-31', + 'USD'::VARCHAR, + 7777.0::DOUBLE, + 777.0::DOUBLE, + 777.0::DOUBLE, + FALSE::BOOLEAN + ) + ) 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(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) + `); + } finally { + await writer.close(); + } + + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + + try { + // 1. Before S1: no row for listing 101 + const beforeS1 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-04-30T23:59:59Z', + }); + expect(beforeS1.rows).toEqual([]); + + // 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380) + const betweenS1S2 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-06-15', + }); + expect(betweenS1S2.rows).toHaveLength(1); + expect(betweenS1S2.rows[0]).toEqual({ + listing_id: 101, + effective_known_at: s1KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-03-31', + fiscal_period: 'Q1', + currency: 'USD', + period_known_at: s1KnownMs, + revenue: 100, + ttm_revenue: 380, + ttm_period_end: '2024-03-31', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + + // 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420) + const betweenS2S3 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-08-15', + }); + expect(betweenS2S3.rows).toHaveLength(1); + expect(betweenS2S3.rows[0]).toEqual({ + listing_id: 101, + effective_known_at: s2KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: s2KnownMs, + revenue: 120, + ttm_revenue: 420, + ttm_period_end: '2024-06-30', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + + // 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415 + for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) { + const afterS3 = await opened.store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf, + }); + expect(afterS3.rows).toHaveLength(1); + expect(afterS3.rows[0]).toEqual({ + listing_id: 101, + effective_known_at: s3KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: s2KnownMs, + revenue: 120, + ttm_revenue: 415, + ttm_period_end: '2024-06-30', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }); + } + + // 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns + const multiYear = await opened.store.fundamentalsAsOf({ + listingIds: [101, 50], + fields: ['revenue'], + asOf: '2024-10-01', + }); + expect(multiYear.columns).toEqual([ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + 'revenue', + ]); + expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]); + expect(multiYear.rows[0]!.period_end).toBe('2023-09-30'); + expect(multiYear.rows[0]!.revenue).toBe(80); + expect(multiYear.rows[1]!.revenue).toBe(120); + + // 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded + for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) { + const fenced = await opened.store.fundamentalsAsOf({ + listingIds: [103, 102], + fields: ['revenue'], + asOf, + }); + expect(fenced.rows).toHaveLength(1); + expect(fenced.rows[0]!.listing_id).toBe(102); + expect(fenced.rows[0]!.revenue).toBe(210); + expect(fenced.rows[0]!.period_end).toBe('2024-12-31'); + } + + // 7. allowEstimatedLag default (true) vs strict (false): + // - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row + // - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved + const lagAllowed = await opened.store.fundamentalsAsOf({ + listingIds: [202, 201], + fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], + asOf: '2024-09-01', + }); + expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]); + expect(lagAllowed.rows[0]!.revenue).toBe(60); + expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true); + expect(lagAllowed.rows[1]!.revenue).toBe(75); + expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300); + expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30); + expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45); + expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30'); + expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD'); + expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true); + + const lagStrict = await opened.store.fundamentalsAsOf({ + listingIds: [202, 201], + fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], + asOf: '2024-09-01', + allowEstimatedLag: false, + }); + expect(lagStrict.rows).toHaveLength(1); + expect(lagStrict.rows[0]).toEqual({ + listing_id: 202, + effective_known_at: s2KnownMs, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'CAD', + period_known_at: s2KnownMs, + revenue: 75, + ttm_revenue: null, + ttm_net_income: null, + ttm_operating_cash_flow: null, + ttm_period_end: null, + ttm_currency: null, + ttm_has_estimated_lag: true, + }); + } finally { + await opened.close(); + } + }); }); diff --git a/libs/research/README.md b/libs/research/README.md index c4c1dae2..dd076551 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -85,9 +85,10 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st - **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`). - **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. - **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`. +- **`planFundamentalsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` point-in-time query over `/fundamentals_pit/year=*/part.parquet` (`hive_partitioning = true`) selecting at most one latest snapshot (`effective_known_at <= asOf`, clamped strictly below `vaultCutoffTs`) per requested `listing_id` across allow-listed `FUNDAMENTALS_PIT_VALUE_FIELDS`, with `allowEstimatedLag` (default `true`) failing closed on snapshot-level `has_estimated_lag` without fallback and masking `ttm_*` values/date/currency when `ttm_has_estimated_lag` is `true`. - **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`. - **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`). -- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. +- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. ### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index 0d3013ba..fd6dd8ae 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -14,6 +14,7 @@ * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) * - `/shorts/part.parquet` * - `/fx_1d/part.parquet` + * - `/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`) * * `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`): * - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share @@ -74,6 +75,7 @@ import { type Table, type TableCell, type TableRow, + VaultHoldoutFenceError, applyVaultFence, resolveDuckDbConnectionBudget, } from './market-data-store'; @@ -155,7 +157,29 @@ export const FX_1D_COLUMNS = [ 'known_at', ] as const; -type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string'; +export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ + 'revenue', + 'net_income', + 'operating_cash_flow', + 'total_assets', + 'total_equity', + 'shares_outstanding', + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +] as const; +export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number]; + +const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap = new Map( + FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field]) +); +const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet = new Set([ + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', +]); + +type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean'; interface TableColumnSpec { readonly name: string; @@ -195,6 +219,23 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ { name: 'known_at', kind: 'safe_int', nullable: false }, ]; +const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'listing_id', kind: 'int32', nullable: false }, + { name: 'effective_known_at', kind: 'safe_int', nullable: false }, + { name: 'known_at_source', kind: 'string', nullable: false }, + { name: 'has_estimated_lag', kind: 'boolean', nullable: false }, + { name: 'period_end', kind: 'string', nullable: false }, + { name: 'fiscal_period', kind: 'string', nullable: false }, + { name: 'currency', kind: 'string', nullable: false }, + { name: 'period_known_at', kind: 'safe_int', nullable: false }, +]; + +const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [ + { name: 'ttm_period_end', kind: 'string', nullable: true }, + { name: 'ttm_currency', kind: 'string', nullable: true }, + { name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true }, +]; + /** Scalar parameter value bound separately from SQL text. */ export type DuckDbParam = string | number | boolean | null; @@ -357,6 +398,7 @@ export type EventsQuery = Parameters[0]; export type ShortsAsOfQuery = Parameters[0]; export type FxQuery = Parameters[0]; export type UniverseQuery = Parameters[0]; +export type FundamentalsAsOfQuery = Parameters[0]; /** * Thrown when a `MarketDataStore` method or timeframe is outside the curated @@ -577,6 +619,50 @@ function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKi return normalized; } +function validateFundamentalsFields( + raw: readonly string[], + field = 'fields' +): FundamentalsPitValueField[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty array of fundamentals value fields for "${field}".`, + field + ); + } + + const seen = new Set(); + const normalized: FundamentalsPitValueField[] = []; + for (let i = 0; i < raw.length; i += 1) { + const name: unknown = raw[i]; + const canonical = + typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined; + if (canonical === undefined) { + throw new MarketDataStoreValidationError( + `Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`, + field + ); + } + if (!seen.has(canonical)) { + seen.add(canonical); + normalized.push(canonical); + } + } + return normalized; +} + +function validateAllowEstimatedLag(raw: unknown): boolean { + if (raw === undefined) { + return true; + } + if (typeof raw !== 'boolean') { + throw new MarketDataStoreValidationError( + `Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`, + 'allowEstimatedLag' + ); + } + return raw; +} + function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] { if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) { throw new MarketDataStoreValidationError( @@ -1575,6 +1661,158 @@ export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): Pla }; } +interface PlannedFundamentalsAsOfInternal { + readonly planned: PlannedDuckDbQuery; + readonly columns: readonly string[]; + readonly schema: readonly TableColumnSpec[]; +} + +function planFundamentalsAsOfInternal( + q: FundamentalsAsOfQuery, + ctx: DuckDbPlanContext +): PlannedFundamentalsAsOfInternal { + const curatedRoot = validateContext(ctx); + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError( + 'Expected a fundamentalsAsOf query object.', + 'query' + ); + } + + const listingIds = validateListingIds(q.listingIds); + const fields = validateFundamentalsFields(q.fields); + const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag); + + let fenced: FencedTimeRange; + try { + fenced = applyVaultFence( + { + from: q.asOf, + to: q.asOf, + asOf: q.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + } + ); + } catch (err: unknown) { + if (err instanceof VaultHoldoutFenceError) { + const maxAllowedMs = ctx.vaultCutoffTs - 1; + fenced = { + fromMs: maxAllowedMs, + toMs: maxAllowedMs, + asOfMs: maxAllowedMs, + scope: 'vault_fenced', + clampedTo: true, + clampedAsOf: true, + }; + } else if ( + err instanceof MarketDataStoreValidationError && + (err.field === 'from' || err.field === 'to') + ) { + throw new MarketDataStoreValidationError(err.message, 'asOf'); + } else { + throw err; + } + } + + const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced); + const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); + const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet'); + const listingPlaceholders = buildPlaceholders(listingIds.length); + + let hasTtmField = false; + for (const field of fields) { + if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { + hasTtmField = true; + break; + } + } + + const innerCols: string[] = [ + 'f.listing_id', + 'f.effective_known_at', + 'f.known_at_source', + 'f.has_estimated_lag', + 'f.period_end', + 'f.fiscal_period', + 'f.currency', + 'f.period_known_at', + ]; + const outerCols: string[] = [ + 's.listing_id', + 'epoch_ms(s.effective_known_at) AS effective_known_at', + 's.known_at_source', + 's.has_estimated_lag', + 'CAST(s.period_end AS VARCHAR) AS period_end', + 's.fiscal_period', + 's.currency', + 'epoch_ms(s.period_known_at) AS period_known_at', + ]; + const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA]; + + for (const field of fields) { + innerCols.push(`f.${field}`); + if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { + outerCols.push( + `CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}` + ); + } else { + outerCols.push(`s.${field}`); + } + schema.push({ name: field, kind: 'number', nullable: true }); + } + + if (hasTtmField) { + innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag'); + outerCols.push( + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end', + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency', + 's.ttm_has_estimated_lag' + ); + schema.push(...FUNDAMENTALS_TTM_META_SCHEMA); + } + + const columns = schema.map(spec => spec.name); + const sql = + `WITH latest AS (SELECT ${innerCols.join(', ')} ` + + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + + `WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + + `SELECT ${outerCols.join(', ')} ` + + 'FROM latest AS s ' + + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + + 'ORDER BY s.listing_id ASC'; + const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag]; + + return { + planned: { sql, params, fenced }, + columns, + schema, + }; +} + +/** + * Plans a Vault-fenced point-in-time DuckDB SQL query over curated + * `fundamentals_pit/year=*\/part.parquet` snapshots. + * + * Selects at most one snapshot per requested `listing_id` — the latest with + * `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When + * `allowEstimatedLag` is `false`, listings whose selected snapshot has + * `has_estimated_lag = true` are omitted without falling back to an older + * snapshot, and requested `ttm_*` value fields plus `ttm_period_end` / + * `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true` + * while preserving `ttm_has_estimated_lag`. + */ +export function planFundamentalsAsOfQuery( + q: FundamentalsAsOfQuery, + ctx: DuckDbPlanContext +): PlannedDuckDbQuery { + return planFundamentalsAsOfInternal(q, ctx).planned; +} + function readRequiredInt32(row: Record, key: string, rowIndex: number): number { const val = row[key]; if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { @@ -1712,6 +1950,14 @@ function readValidatedTableCell( ); } return val; + case 'boolean': + if (typeof val !== 'boolean') { + throw new MarketDataStoreValidationError( + `Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, + spec.name + ); + } + return val; } } @@ -2038,8 +2284,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); }, - fundamentalsAsOf(): Promise { - return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf')); + async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ + const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx); + await ensureBudgetInitialized(); + const rawRows = await typedExecutor.query(planned.sql, planned.params); + return mapTableRows(columns, schema, rawRows); }, macroAsOf(): Promise
{ diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index fe7922b0..6bd7c290 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -13,6 +13,7 @@ import { type DuckDbPlanContext, EVENT_KINDS, EVENTS_COLUMNS, + FUNDAMENTALS_PIT_VALUE_FIELDS, FX_1D_COLUMNS, FX_PAIR_MAP, MarketDataStoreNotImplementedError, @@ -28,6 +29,7 @@ import { planAdjFactorsMetadataQuery, planBars1dQuery, planEventsQuery, + planFundamentalsAsOfQuery, planFx1dQuery, planShortsAsOfQuery, planUniverseQuery, @@ -44,6 +46,7 @@ import { DEFAULT_UNIVERSE_LOOKBACK_DAYS as subpathDefaultUniverseLookbackDays, EVENT_KINDS as subpathEventKinds, EVENTS_COLUMNS as subpathEventsColumns, + FUNDAMENTALS_PIT_VALUE_FIELDS as subpathFundamentalsPitValueFields, FX_1D_COLUMNS as subpathFx1dColumns, FX_PAIR_MAP as subpathFxPairMap, MarketDataStoreNotImplementedError as SubpathNotImplementedError, @@ -54,6 +57,7 @@ import { planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery, planBars1dQuery as subpathPlanBars1dQuery, planEventsQuery as subpathPlanEventsQuery, + planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery, planFx1dQuery as subpathPlanFx1dQuery, planShortsAsOfQuery as subpathPlanShortsAsOfQuery, planUniverseQuery as subpathPlanUniverseQuery, @@ -215,6 +219,8 @@ describe('market-data-store-duckdb exports', () => { expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery); expect(planFx1dQuery).toBe(subpathPlanFx1dQuery); expect(planUniverseQuery).toBe(subpathPlanUniverseQuery); + expect(planFundamentalsAsOfQuery).toBe(subpathPlanFundamentalsAsOfQuery); + expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toBe(subpathFundamentalsPitValueFields); expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery); expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata); expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); @@ -2421,15 +2427,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { universe: 'US_EQ', }), }, - { - method: 'fundamentalsAsOf', - run: () => - store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: '2025-01-15', - }), - }, { method: 'macroAsOf', run: () => @@ -2868,3 +2865,358 @@ describe('planUniverseQuery & createDuckDbMarketDataStore().universe()', () => { } }); }); + +describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentalsAsOf()', () => { + const EXPECTED_GLOB = `${CURATED_ROOT}/fundamentals_pit/year=*/part.parquet`; + + it('exports the exact 9 allow-listed FUNDAMENTALS_PIT_VALUE_FIELDS and plans parameterized Hive Parquet SQL', () => { + expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toEqual([ + 'revenue', + 'net_income', + 'operating_cash_flow', + 'total_assets', + 'total_equity', + 'shares_outstanding', + 'ttm_revenue', + 'ttm_net_income', + 'ttm_operating_cash_flow', + ]); + + const nonTtm = planFundamentalsAsOfQuery( + { + listingIds: [202, 101, 202], + fields: ['net_income', 'revenue', 'net_income'], + asOf: '2025-06-15', + }, + DEFAULT_CTX + ); + + expect(nonTtm.sql).toBe( + 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.net_income, f.revenue ' + + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + + 'WHERE f.listing_id IN (?, ?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + + 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.net_income, s.revenue ' + + 'FROM latest AS s ' + + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + + 'ORDER BY s.listing_id ASC' + ); + expect(nonTtm.params).toEqual([ + EXPECTED_GLOB, + 202, + 101, + '2025-06-15T23:59:59.999999Z', + true, + ]); + expect(nonTtm.fenced).toEqual({ + fromMs: Date.UTC(2025, 5, 15, 0, 0, 0, 0), + toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), + asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, + }); + expect(nonTtm.sql).not.toContain(CURATED_ROOT); + expect(nonTtm.sql).not.toContain('2025-06-15'); + expect(nonTtm.sql).not.toContain('ttm_period_end'); + expect(nonTtm.sql).not.toContain('ttm_currency'); + expect(nonTtm.sql).not.toContain('ttm_has_estimated_lag'); + + const withTtm = planFundamentalsAsOfQuery( + { + listingIds: [101], + fields: ['revenue', 'ttm_revenue', 'ttm_operating_cash_flow', 'revenue', 'ttm_revenue'], + asOf: '2025-06-15T14:30:00.123456+02:00', + allowEstimatedLag: false, + }, + DEFAULT_CTX + ); + + expect(withTtm.sql).toBe( + 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.revenue, f.ttm_revenue, f.ttm_operating_cash_flow, f.ttm_period_end, f.ttm_currency, f.ttm_has_estimated_lag ' + + 'FROM read_parquet(?, hive_partitioning = true) AS f ' + + 'WHERE f.listing_id IN (?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + + 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + + 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.revenue, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_revenue ELSE NULL END AS ttm_revenue, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_operating_cash_flow ELSE NULL END AS ttm_operating_cash_flow, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end, ' + + 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency, ' + + 's.ttm_has_estimated_lag ' + + 'FROM latest AS s ' + + 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + + 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + + 'ORDER BY s.listing_id ASC' + ); + expect(withTtm.params).toEqual([ + EXPECTED_GLOB, + 101, + '2025-06-15T12:30:00.123456Z', + false, + ]); + expect(withTtm.fenced.asOfMs).toBe(Date.UTC(2025, 5, 15, 12, 30, 0, 123)); + expect(withTtm.fenced.clampedAsOf).toBe(false); + }); + + it('clamps asOf at or after vaultCutoffTs to vaultCutoffTs * 1000 - 1 micros even when vaultOperatorAuthorized is true', () => { + const authorizedCtx: DuckDbPlanContext = { + ...DEFAULT_CTX, + vaultOperatorAuthorized: true, + }; + + for (const clampedAsOf of [ + '2026-05-28', + '2026-05-28T00:00:00.000Z', + '2026-05-28T00:00:00.000001Z', + '2026-09-01T15:00:00Z', + ]) { + const planned = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: clampedAsOf }, + authorizedCtx + ); + expect(planned.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); + expect(planned.fenced).toEqual({ + fromMs: CUTOFF_MS - 1, + toMs: CUTOFF_MS - 1, + asOfMs: CUTOFF_MS - 1, + scope: 'vault_fenced', + clampedTo: true, + clampedAsOf: true, + }); + } + + // Mid-day cutoff with a date-only asOf on the cutoff date clamps cleanly to 1 microsecond before cutoff. + const midDayCutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0); + const midDayClamped = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28' }, + { curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs } + ); + expect(midDayClamped.params).toEqual([EXPECTED_GLOB, 1, '2026-05-28T11:59:59.999999Z', true]); + expect(midDayClamped.fenced.clampedAsOf).toBe(true); + expect(midDayClamped.fenced.clampedTo).toBe(true); + expect(midDayClamped.fenced.asOfMs).toBe(midDayCutoffMs - 1); + + // One microsecond before cutoff stays unclamped and preserves exact micros. + const preCutoffMicros = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: MAX_ALLOWED_ISO_MICROS }, + DEFAULT_CTX + ); + expect(preCutoffMicros.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); + expect(preCutoffMicros.fenced.clampedAsOf).toBe(false); + }); + + it('validates fields allow-list, allowEstimatedLag, listingIds, and asOf with zero executor calls on invalid input', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + const invalidFieldsCases: unknown[] = [ + [], + 'revenue', + null, + undefined, + ['unknown_field'], + ['revenue', 'period_end'], + ['toString'], + ['revenue; DROP TABLE x'], + [123], + ]; + for (const badFields of invalidFieldsCases) { + let caught: unknown; + try { + await store.fundamentalsAsOf({ + listingIds: [1], + fields: badFields as string[], + asOf: '2025-06-15', + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('fields'); + } + + const invalidLagCases: unknown[] = [null, 1, 0, 'true', 'false', {}]; + for (const badLag of invalidLagCases) { + let caught: unknown; + try { + await store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-06-15', + allowEstimatedLag: badLag as boolean, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('allowEstimatedLag'); + } + + const invalidAsOfCases: unknown[] = ['', 'not-a-date', '2024-02-30', '2025-06-15T12:00:00', null, undefined]; + for (const badAsOf of invalidAsOfCases) { + let caught: unknown; + try { + await store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: badAsOf as string, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('asOf'); + } + + await expect( + store.fundamentalsAsOf({ listingIds: [], fields: ['revenue'], asOf: '2025-06-15' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + await expect( + store.fundamentalsAsOf(null as unknown as Parameters[0]) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + + expect(fake.calls).toHaveLength(0); + }); + + it('initializes DuckDB budget once and maps fundamentalsAsOf columns in exact projection order with strict scalar validation', async () => { + const t1 = Date.UTC(2024, 7, 1, 20, 0, 0, 0); + const t2 = Date.UTC(2024, 7, 15, 20, 0, 0, 0); + let callIndex = 0; + const fake = createRecordingExecutor({ + onQuery: () => { + callIndex += 1; + if (callIndex === 1) { + return [ + { + listing_id: 101, + effective_known_at: t1, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + total_assets: null, + revenue: 120.5, + }, + ]; + } + return [ + { + listing_id: 101, + effective_known_at: t2, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + revenue: 120.5, + ttm_revenue: 450.25, + ttm_period_end: '2024-06-30', + ttm_currency: 'USD', + ttm_has_estimated_lag: false, + }, + ]; + }, + }); + + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + const expectedBudget = resolveDuckDbConnectionBudget().statements; + + const first = await store.fundamentalsAsOf({ + listingIds: [101], + fields: ['total_assets', 'revenue', 'total_assets'], + asOf: '2024-08-05', + }); + expect(first.columns).toEqual([ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + 'total_assets', + 'revenue', + ]); + expect(first.rows).toEqual([ + { + listing_id: 101, + effective_known_at: t1, + known_at_source: 'filing_date', + has_estimated_lag: false, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + total_assets: null, + revenue: 120.5, + }, + ]); + expect(fake.runCalls).toEqual(expectedBudget); + + const second = await store.fundamentalsAsOf({ + listingIds: [101], + fields: ['revenue', 'ttm_revenue'], + asOf: '2024-08-20', + allowEstimatedLag: false, + }); + expect(second.columns).toEqual([ + 'listing_id', + 'effective_known_at', + 'known_at_source', + 'has_estimated_lag', + 'period_end', + 'fiscal_period', + 'currency', + 'period_known_at', + 'revenue', + 'ttm_revenue', + 'ttm_period_end', + 'ttm_currency', + 'ttm_has_estimated_lag', + ]); + expect(second.rows).toHaveLength(1); + expect(second.rows[0]?.ttm_revenue).toBe(450.25); + expect(second.rows[0]?.ttm_has_estimated_lag).toBe(false); + // Budget SET statements must not re-run on second query. + expect(fake.runCalls).toHaveLength(3); + expect(fake.queryCalls).toHaveLength(2); + + // Rejects non-boolean has_estimated_lag from a misbehaving executor. + const badBoolFake = createRecordingExecutor({ + onQuery: () => [ + { + listing_id: 101, + effective_known_at: t1, + known_at_source: 'filing_date', + has_estimated_lag: 'false' as unknown as boolean, + period_end: '2024-06-30', + fiscal_period: 'Q2', + currency: 'USD', + period_known_at: t1, + revenue: 120.5, + }, + ], + }); + const badStore = createDuckDbMarketDataStore({ + executor: badBoolFake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + await expect( + badStore.fundamentalsAsOf({ listingIds: [101], fields: ['revenue'], asOf: '2024-08-05' }) + ).rejects.toBeInstanceOf(MarketDataStoreValidationError); + }); +}); From 8f1bfbe9f18b906c042b3b2ef8389e21ff51a901 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:32:25 -0500 Subject: [PATCH 05/26] T-145: tests --- .../test/duckdb-market-data-store.test.ts | 200 ++++++++++++++++++ .../test/market-data-store-duckdb.test.ts | 57 +++++ 2 files changed, 257 insertions(+) diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts index abd4c3be..dfe3259c 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -729,3 +729,203 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { } }); }); + +interface FundamentalsFixtureRow { + readonly listingId: number; + readonly effectiveKnownAt: string; + readonly hasEstimatedLag?: boolean; + readonly periodEnd: string; + readonly fiscalPeriod: string; + readonly periodKnownAt?: string; + readonly revenue: number | null; + readonly ttmRevenue: number | null; + readonly ttmHasEstimatedLag: boolean | null; +} + +function fundamentalsRowSql(r: FundamentalsFixtureRow): string { + const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`); + const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`); + const ttmMissing = r.ttmRevenue === null; + return `( + ${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)}, + DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}', + ${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, + ${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`}, + ${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)} + )`; +} + +async function writeFundamentalsPartition( + curatedRoot: string, + year: number, + rows: readonly FundamentalsFixtureRow[] +): Promise { + const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); + await mkdir(dir, { recursive: true }); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).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(); + } +} + +describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => { + async function openFundamentalsStore(): Promise>> { + const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(duckTempDir, { recursive: true }); + + // Partition directory does not drive ranking: listing 7's newest snapshot sits in + // year=2023 while its older one sits in year=2024; listing 8 is the reverse. + await writeFundamentalsPartition(curatedRoot, 2023, [ + { listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false }, + { listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false }, + ]); + await writeFundamentalsPartition(curatedRoot, 2024, [ + { listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false }, + { listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false }, + // Sub-millisecond neighbours: only the microsecond distinguishes them. + { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false }, + { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false }, + // Verified Q1, then estimated Q2. + { listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false }, + { listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true }, + // TTM-only estimated lag. + { listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true }, + // No TTM yet (fewer than four quarters): TTM values and flag are NULL. + { listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null }, + ]); + + return openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs: computeVaultCutoffTs('2025-08-13'), + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + } + + test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => { + const opened = await openFundamentalsStore(); + try { + const result = await opened.store.fundamentalsAsOf({ + listingIds: [8, 7], + fields: ['revenue'], + asOf: '2024-06-01', + }); + expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([ + [7, 'Q1', 70], + [8, 'Q4', 85], + ]); + + const earlier = await opened.store.fundamentalsAsOf({ + listingIds: [7, 8], + fields: ['revenue'], + asOf: '2024-01-01', + }); + expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]); + } finally { + await opened.close(); + } + }); + + test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => { + const opened = await openFundamentalsStore(); + try { + const at = async (asOf: string): Promise => + (await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map( + r => r.revenue + ); + expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]); + expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]); + expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]); + expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]); + } finally { + await opened.close(); + } + }); + + test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => { + const opened = await openFundamentalsStore(); + try { + const beforeEstimate = await opened.store.fundamentalsAsOf({ + listingIds: [10], + fields: ['revenue'], + asOf: '2024-07-31', + allowEstimatedLag: false, + }); + expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]); + + const afterEstimate = await opened.store.fundamentalsAsOf({ + listingIds: [10], + fields: ['revenue'], + asOf: '2024-08-02', + allowEstimatedLag: false, + }); + expect(afterEstimate.rows).toEqual([]); + } finally { + await opened.close(); + } + }); + + test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => { + const opened = await openFundamentalsStore(); + try { + const noTtm = await opened.store.fundamentalsAsOf({ + listingIds: [11], + fields: ['revenue'], + asOf: '2024-06-01', + allowEstimatedLag: false, + }); + expect(noTtm.columns).not.toContain('ttm_has_estimated_lag'); + expect(noTtm.rows).toEqual([ + expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }), + ]); + expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]); + + const nullTtm = await opened.store.fundamentalsAsOf({ + listingIds: [12, 11], + fields: ['ttm_revenue'], + asOf: '2024-06-01', + allowEstimatedLag: false, + }); + expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([ + [11, null, null, null, true], + [12, null, null, null, null], + ]); + } finally { + await opened.close(); + } + }); + + test('returns only requested listings and is reproducible across repeated identical queries', async () => { + const opened = await openFundamentalsStore(); + try { + const q = { + listingIds: [12, 999, 7], + fields: ['ttm_revenue', 'revenue'], + asOf: '2024-09-01T00:00:00.000001Z', + }; + const first = await opened.store.fundamentalsAsOf(q); + const second = await opened.store.fundamentalsAsOf(q); + expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]); + expect(second).toEqual(first); + } finally { + await opened.close(); + } + }); +}); diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index 6bd7c290..599edece 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -3220,3 +3220,60 @@ describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentals ).rejects.toBeInstanceOf(MarketDataStoreValidationError); }); }); + +describe('fundamentalsAsOf hostile request inputs', () => { + it('fails closed with zero executor calls for JSON-decoded object, symbol, and sparse field entries', async () => { + const fake = createRecordingExecutor(); + const store = createDuckDbMarketDataStore({ + executor: fake.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: CUTOFF_MS, + }); + + const hostileFields: unknown[] = [ + JSON.parse('[{"toString": 1}]'), + [Object.create(null)], + [Symbol('revenue')], + // eslint-disable-next-line no-sparse-arrays + [, 'revenue'], + ['REVENUE'], + [' revenue'], + ]; + for (const fields of hostileFields) { + await expect( + store.fundamentalsAsOf({ listingIds: [1], fields: fields as string[], asOf: '2025-06-15' }) + ).rejects.toThrow(); + } + + const hostileLag = JSON.parse('{"toString": 1}'); + await expect( + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-06-15', + allowEstimatedLag: hostileLag as boolean, + }) + ).rejects.toThrow(); + + expect(fake.calls).toHaveLength(0); + expect(fake.runCalls).toHaveLength(0); + }); + + it('plans a request asOf with an offset that crosses the cutoff as a clamped bound', () => { + // 2026-05-28T01:00:00+02:00 === 2026-05-27T23:00:00Z, i.e. before the cutoff: not clamped. + const beforeCutoff = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28T01:00:00+02:00' }, + DEFAULT_CTX + ); + expect(Date.parse(beforeCutoff.params[2] as string)).toBe(Date.UTC(2026, 4, 27, 23, 0, 0, 0)); + expect(beforeCutoff.fenced.clampedAsOf).toBe(false); + + // 2026-05-27T23:00:00-02:00 === 2026-05-28T01:00:00Z, i.e. after the cutoff: clamped. + const afterCutoff = planFundamentalsAsOfQuery( + { listingIds: [1], fields: ['revenue'], asOf: '2026-05-27T23:00:00-02:00' }, + DEFAULT_CTX + ); + expect(afterCutoff.params[2]).toBe(MAX_ALLOWED_ISO_MICROS); + expect(afterCutoff.fenced.clampedAsOf).toBe(true); + }); +}); From cfbcb51bd3a226233548d7b27889867a33e2ab78 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:40:36 -0500 Subject: [PATCH 06/26] =?UTF-8?q?T-146:=20M2.3f=20=E2=80=94=20QuestDB=20`b?= =?UTF-8?q?ars=5F1m`=20intraday=20reader=20for=20`MarketDataStore.bars`=20?= =?UTF-8?q?(`timeframe:=20'1m'`):=20Vault-fenced,=20parameterized=20`planB?= =?UTF-8?q?ars1mQuery`=20+=20batch=20iterator=20over=20an=20injected=20PGW?= =?UTF-8?q?ire=20query=20port=20in=20`libs/research/src/market-data-store-?= =?UTF-8?q?questdb.ts`=20(pure,=20no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/index.ts | 1 + .../research/src/market-data-store-questdb.ts | 448 +++++++++++ .../test/market-data-store-questdb.test.ts | 703 ++++++++++++++++++ 3 files changed, 1152 insertions(+) create mode 100644 libs/research/src/market-data-store-questdb.ts create mode 100644 libs/research/test/market-data-store-questdb.test.ts diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 0a9f6987..dcc88deb 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -4,6 +4,7 @@ export * from './event-panel'; export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; +export * from './market-data-store-questdb'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts new file mode 100644 index 00000000..08006f3b --- /dev/null +++ b/libs/research/src/market-data-store-questdb.ts @@ -0,0 +1,448 @@ +/** + * Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor + * intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`, + * `design/DATA-CONTRACTS.md` §3.B & §4). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or + * `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution + * is injected via {@link QuestDbQueryExecutor}, which is structurally + * compatible with `QuestDBClient.query(sql, params)`. + * + * Storage and point-in-time semantics: + * - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`, + * `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at` + * (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`, + * `PARTITION BY MONTH`). + * - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw + * {@link MarketDataStoreNotImplementedError}. + * - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL + * planning. Every user-supplied value is bound via `$1..$n` placeholders; + * only ordinal placeholder tokens are generated in SQL text. + * - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch + * microseconds) and verified in exact microseconds against the fenced bounds + * before converting to epoch milliseconds or yielding any batch. + */ + +import { + type BarBatch, + type BarRecord, + type FencedTimeRange, + type MarketDataStore, + MarketDataStoreValidationError, + type VaultFenceContext, + applyVaultFence, +} from './market-data-store'; +import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb'; + +const INT32_MAX = 2_147_483_647; +const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/; +const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; + +/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ +export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; + +/** Input query type derived from `MarketDataStore['bars']`. */ +export type QuestDbBars1mQuery = Parameters[0]; + +/** + * Injected PGWire SQL executor port, structurally compatible with + * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. + */ +export interface QuestDbQueryExecutor { + query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }>; +} + +/** Pure output of {@link planBars1mQuery}. */ +export interface PlannedQuestDbBars1mQuery { + readonly sql: string; + readonly params: readonly string[]; + readonly fence: FencedTimeRange; +} + +/** Configuration for {@link createQuestDbIntradayBarsReader}. */ +export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { + readonly executor: QuestDbQueryExecutor; + /** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */ + readonly batchSize?: number; +} + +interface InternalPlannedBars1mQuery { + readonly planned: PlannedQuestDbBars1mQuery; + readonly requestedListingIds: ReadonlySet; +} + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function validateVaultCutoffTs(vaultCutoffTs: unknown): number { + if ( + typeof vaultCutoffTs !== 'number' || + !Number.isSafeInteger(vaultCutoffTs) || + Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || + vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, + 'vaultCutoffTs' + ); + } + return vaultCutoffTs === 0 ? 0 : vaultCutoffTs; +} + +function validatePositiveInt32ListingIds(raw: unknown): number[] { + if (!Array.isArray(raw) || raw.length === 0) { + throw new MarketDataStoreValidationError( + 'Expected a non-empty array of positive INT32 listing IDs for "listingIds".', + 'listingIds' + ); + } + + const seen = new Set(); + const normalized: number[] = []; + for (let i = 0; i < raw.length; i += 1) { + const id: unknown = raw[i]; + if ( + typeof id !== 'number' || + !Number.isSafeInteger(id) || + id < 1 || + id > INT32_MAX + ) { + throw new MarketDataStoreValidationError( + `Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`, + 'listingIds' + ); + } + if (!seen.has(id)) { + seen.add(id); + normalized.push(id); + } + } + + normalized.sort((a, b) => a - b); + return normalized; +} + +function formatUtcIsoMs(epochMs: number): string { + return new Date(epochMs).toISOString(); +} + +function planBars1mQueryInternal( + q: QuestDbBars1mQuery, + ctx: VaultFenceContext +): InternalPlannedBars1mQuery { + if (!isPlainRecord(ctx)) { + throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); + } + if (!isPlainRecord(q)) { + throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); + } + + const timeframe: unknown = q.timeframe; + if (timeframe !== '1m') { + throw new MarketDataStoreValidationError( + `Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`, + 'timeframe' + ); + } + + const adjustment: unknown = q.adjustment; + if (adjustment === 'split' || adjustment === 'total') { + throw new MarketDataStoreNotImplementedError( + 'bars', + `Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.` + ); + } + if (adjustment !== 'raw') { + throw new MarketDataStoreValidationError( + `Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`, + 'adjustment' + ); + } + + const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds); + + const fence = applyVaultFence( + { + from: q.from, + to: q.to, + asOf: q.asOf, + scope: q.scope, + }, + { + vaultCutoffTs: ctx.vaultCutoffTs, + vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true, + } + ); + + const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', '); + const asOfPlaceholder = `$${sortedListingIds.length + 3}`; + + const sql = + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m ' + + `WHERE ts >= $1 AND ts <= $2 AND listing_id IN (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` + + 'ORDER BY ts, listing_id'; + + const params: string[] = [ + formatUtcIsoMs(fence.fromMs), + formatUtcIsoMs(fence.toMs), + ...sortedListingIds.map(id => String(id)), + formatUtcIsoMs(fence.asOfMs), + ]; + + return { + planned: { sql, params, fence }, + requestedListingIds: new Set(sortedListingIds), + }; +} + +/** + * Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`. + * + * Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and + * deduplicated, numerically sorted positive INT32 `listingIds` as canonical + * decimal `SYMBOL` strings. + */ +export function planBars1mQuery( + q: QuestDbBars1mQuery, + ctx: VaultFenceContext +): PlannedQuestDbBars1mQuery { + return planBars1mQueryInternal(q, ctx).planned; +} + +function parseListingIdSymbol( + row: Record, + rowIndex: number, + requestedListingIds: ReadonlySet +): number { + const raw = row.listing_id; + if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) { + throw new MarketDataStoreValidationError( + `Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`, + 'listing_id' + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) { + throw new MarketDataStoreValidationError( + `Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`, + 'listing_id' + ); + } + if (!requestedListingIds.has(parsed)) { + throw new MarketDataStoreValidationError( + `Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`, + 'listing_id' + ); + } + return parsed; +} + +function parseTimestampMicros( + row: Record, + column: 'ts_us' | 'known_at_us', + field: 'ts' | 'known_at', + rowIndex: number +): bigint { + const raw = row[column]; + if (typeof raw === 'bigint') { + return raw; + } + if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) { + return BigInt(raw); + } + if (typeof raw === 'number' && Number.isSafeInteger(raw)) { + return BigInt(raw); + } + throw new MarketDataStoreValidationError( + `Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`, + field + ); +} + +function microsToEpochMs(us: bigint, field: 'ts' | 'known_at', rowIndex: number): number { + const quotient = us / 1000n; + const remainder = us % 1000n; + const msBigInt = remainder < 0n ? quotient - 1n : quotient; + const ms = Number(msBigInt); + if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`, + field + ); + } + return ms === 0 ? 0 : ms; +} + +function readRequiredFiniteNumber( + row: Record, + key: 'open' | 'high' | 'low' | 'close' | 'volume', + rowIndex: number +): number { + const val = row[key]; + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function readNullableFiniteNumber( + row: Record, + key: 'vwap', + rowIndex: number +): number | null { + const val = row[key]; + if (val === null || val === undefined) { + return null; + } + if (typeof val !== 'number' || !Number.isFinite(val)) { + throw new MarketDataStoreValidationError( + `Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, + key + ); + } + return val === 0 ? 0 : val; +} + +function mapBars1mRows( + rows: readonly Record[], + fence: FencedTimeRange, + requestedListingIds: ReadonlySet +): BarRecord[] { + const fromUs = BigInt(fence.fromMs) * 1000n; + const toUs = BigInt(fence.toMs) * 1000n; + const asOfUs = BigInt(fence.asOfMs) * 1000n; + + const out: BarRecord[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + const raw = rows[i]; + if (!isPlainRecord(raw)) { + throw new MarketDataStoreValidationError( + `Executor returned a non-object bar row at index ${i}.`, + 'rows' + ); + } + + const listingId = parseListingIdSymbol(raw, i, requestedListingIds); + const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); + if (tsUs < fromUs || tsUs > toUs) { + throw new MarketDataStoreValidationError( + `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`, + 'ts' + ); + } + + const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i); + if (knownAtUs > asOfUs) { + throw new MarketDataStoreValidationError( + `Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`, + 'known_at' + ); + } + + out[i] = { + listingId, + ts: microsToEpochMs(tsUs, 'ts', i), + open: readRequiredFiniteNumber(raw, 'open', i), + high: readRequiredFiniteNumber(raw, 'high', i), + low: readRequiredFiniteNumber(raw, 'low', i), + close: readRequiredFiniteNumber(raw, 'close', i), + volume: readRequiredFiniteNumber(raw, 'volume', i), + vwap: readNullableFiniteNumber(raw, 'vwap', i), + knownAt: microsToEpochMs(knownAtUs, 'known_at', i), + }; + } + + return out; +} + +/** + * Creates a read-only intraday `bars` reader backed by an injected + * {@link QuestDbQueryExecutor} over QuestDB `bars_1m`. + * + * Validates all inputs and applies the Vault fence before invoking + * `executor.query(...)`. Validates and maps all returned rows (including + * exact-microsecond defence-in-depth checks against `fence`) before yielding + * batches of at most `batchSize` rows (default `50_000`). + */ +export function createQuestDbIntradayBarsReader( + options: QuestDbIntradayBarsReaderOptions +): Pick { + if (!isPlainRecord(options)) { + throw new MarketDataStoreValidationError( + 'Expected a QuestDbIntradayBarsReaderOptions object.', + 'options' + ); + } + + const executor: unknown = options.executor; + if (!isPlainRecord(executor) || typeof executor.query !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `executor` with a `query(sql, params)` method.', + 'executor' + ); + } + const typedExecutor = executor as unknown as QuestDbQueryExecutor; + + const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); + + if ( + options.vaultOperatorAuthorized !== undefined && + typeof options.vaultOperatorAuthorized !== 'boolean' + ) { + throw new MarketDataStoreValidationError( + `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, + 'vaultOperatorAuthorized' + ); + } + + const batchSize = options.batchSize ?? DEFAULT_QUESTDB_BARS_BATCH_SIZE; + if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) { + throw new MarketDataStoreValidationError( + `Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`, + 'batchSize' + ); + } + + const planCtx: VaultFenceContext = { + vaultCutoffTs, + vaultOperatorAuthorized: options.vaultOperatorAuthorized === true, + }; + + return { + async *bars(q: QuestDbBars1mQuery): AsyncIterable { + const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx); + const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); + if (!isPlainRecord(result) || !Array.isArray(result.rows)) { + throw new MarketDataStoreValidationError( + 'Executor returned a malformed result; expected `{ rows: Record[] }`.', + 'rows' + ); + } + + const mapped = mapBars1mRows( + result.rows as readonly Record[], + planned.fence, + requestedListingIds + ); + if (mapped.length === 0) { + return; + } + if (mapped.length <= batchSize) { + yield { rows: mapped }; + return; + } + for (let offset = 0; offset < mapped.length; offset += batchSize) { + yield { rows: mapped.slice(offset, offset + batchSize) }; + } + }, + }; +} diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts new file mode 100644 index 00000000..22c030ec --- /dev/null +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -0,0 +1,703 @@ +import { describe, expect, it } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + DEFAULT_QUESTDB_BARS_BATCH_SIZE, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + type QuestDbBars1mQuery, + type QuestDbQueryExecutor, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + createQuestDbIntradayBarsReader, + planBars1mQuery, +} from '@stock-bot/research'; + +interface RecordedCall { + readonly sql: string; + readonly params: readonly unknown[]; +} + +class RecordingQuestDbExecutor implements QuestDbQueryExecutor { + readonly calls: RecordedCall[] = []; + private nextResult: { readonly rows: readonly Record[] } = { rows: [] }; + + setRows(rows: readonly Record[]): void { + this.nextResult = { rows }; + } + + setRawResult(result: unknown): void { + this.nextResult = result as { readonly rows: readonly Record[] }; + } + + async query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }> { + this.calls.push({ sql, params: [...params] }); + return this.nextResult; + } +} + +async function collectBatches(iterable: AsyncIterable): Promise { + const batches: BarBatch[] = []; + for await (const batch of iterable) { + batches.push(batch); + } + return batches; +} + +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z + +describe('planBars1mQuery', () => { + it('snapshots exact parameterized SQL and bound params for a 1-listing, 1-year query', () => { + const query: QuestDbBars1mQuery = { + listingIds: [42], + timeframe: '1m', + from: '2024-01-02', + to: '2024-12-31', + adjustment: 'raw', + asOf: '2025-01-01T00:00:00Z', + }; + + const planned = planBars1mQuery(query, { vaultCutoffTs: VAULT_CUTOFF_TS }); + + expect(planned.sql).toBe( + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m ' + + 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3) AND known_at <= $4 ' + + 'ORDER BY ts, listing_id' + ); + expect(planned.params).toEqual([ + '2024-01-02T00:00:00.000Z', + '2024-12-31T23:59:59.999Z', + '42', + '2025-01-01T00:00:00.000Z', + ]); + expect(planned.fence).toEqual({ + fromMs: Date.UTC(2024, 0, 2, 0, 0, 0, 0), + toMs: Date.UTC(2024, 11, 31, 23, 59, 59, 999), + asOfMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, + }); + + // No caller-supplied values appear in SQL text. + for (const boundValue of planned.params) { + expect(planned.sql).not.toContain(boundValue); + } + expect(planned.sql).not.toContain('42'); + expect(planned.sql).not.toContain('2024'); + expect(planned.sql).not.toContain('2025'); + }); + + it('deduplicates and sorts multi-listing IDs numerically without mutating caller input', () => { + const callerListingIds = [100, 2, 10, 2, 1]; + const snapshotBefore = [...callerListingIds]; + + const planned = planBars1mQuery( + { + listingIds: callerListingIds, + timeframe: '1m', + from: '2024-06-03T13:30:00Z', + to: '2024-06-03T20:00:00Z', + adjustment: 'raw', + asOf: '2024-06-04T00:00:00Z', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + + expect(callerListingIds).toEqual(snapshotBefore); + expect(planned.sql).toBe( + 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + + 'FROM bars_1m ' + + 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3, $4, $5, $6) AND known_at <= $7 ' + + 'ORDER BY ts, listing_id' + ); + expect(planned.params).toEqual([ + '2024-06-03T13:30:00.000Z', + '2024-06-03T20:00:00.000Z', + '1', + '2', + '10', + '100', + '2024-06-04T00:00:00.000Z', + ]); + }); + + it('port is structurally compatible with QuestDBClient.query generic signature', async () => { + class QuestDbClientLike { + readonly calls: RecordedCall[] = []; + async query>( + sql: string, + params?: unknown[] + ): Promise<{ + rows: T[]; + rowCount: number; + executionTime: number; + }> { + this.calls.push({ sql, params: params ? [...params] : [] }); + return { rows: [], rowCount: 0, executionTime: 1 }; + } + } + + const clientLike = new QuestDbClientLike(); + const executorPort: QuestDbQueryExecutor = clientLike; + const reader = createQuestDbIntradayBarsReader({ + executor: executorPort, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const batches = await collectBatches( + reader.bars({ + listingIds: [7], + timeframe: '1m', + from: '2024-05-01T13:30:00Z', + to: '2024-05-01T13:35:00Z', + adjustment: 'raw', + }) + ); + + expect(batches).toEqual([]); + expect(clientLike.calls).toHaveLength(1); + }); +}); + +describe('Vault fence enforcement', () => { + it('rejects from at or past cutoff with VaultHoldoutFenceError and zero executor calls', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + await expect( + collectBatches( + reader.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-07-01T00:00:00.000Z', + to: '2025-07-02T00:00:00.000Z', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(VaultHoldoutFenceError); + + await expect( + collectBatches( + reader.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-07-15', + to: '2025-08-01', + adjustment: 'raw', + }) + ) + ).rejects.toThrow(VaultHoldoutFenceError); + + expect(executor.calls).toHaveLength(0); + }); + + it('clamps to and asOf past cutoff and defaults omitted asOf to cutoff - 1ms', () => { + const clampedPlan = planBars1mQuery( + { + listingIds: [9], + timeframe: '1m', + from: '2025-06-01', + to: '2025-09-01', + asOf: '2025-09-02', + adjustment: 'raw', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + + expect(clampedPlan.fence.clampedTo).toBe(true); + expect(clampedPlan.fence.clampedAsOf).toBe(true); + expect(clampedPlan.fence.toMs).toBe(VAULT_CUTOFF_TS - 1); + expect(clampedPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); + expect(clampedPlan.params).toEqual([ + '2025-06-01T00:00:00.000Z', + '2025-06-30T23:59:59.999Z', + '9', + '2025-06-30T23:59:59.999Z', + ]); + + const omittedAsOfPlan = planBars1mQuery( + { + listingIds: [9], + timeframe: '1m', + from: '2025-06-01', + to: '2025-06-15', + adjustment: 'raw', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + + expect(omittedAsOfPlan.fence.clampedTo).toBe(false); + expect(omittedAsOfPlan.fence.clampedAsOf).toBe(false); + expect(omittedAsOfPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); + expect(omittedAsOfPlan.params[3]).toBe('2025-06-30T23:59:59.999Z'); + }); + + it('rejects unauthorized vault_evaluation_only even if caller attaches authorization flag on query', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const spoofedQuery = { + listingIds: [1], + timeframe: '1m', + from: '2025-07-01', + to: '2025-07-10', + adjustment: 'raw', + scope: 'vault_evaluation_only', + vaultOperatorAuthorized: true, + } as unknown as QuestDbBars1mQuery; + + await expect(collectBatches(reader.bars(spoofedQuery))).rejects.toThrow( + VaultScopeNotAuthorizedError + ); + expect(executor.calls).toHaveLength(0); + }); + + it('permits vault_evaluation_only when trusted factory context is operator-authorized', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: true, + }); + + const batches = await collectBatches( + reader.bars({ + listingIds: [5], + timeframe: '1m', + from: '2025-07-02T13:30:00Z', + to: '2025-07-02T13:31:00Z', + adjustment: 'raw', + scope: 'vault_evaluation_only', + }) + ); + + expect(batches).toEqual([]); + expect(executor.calls).toHaveLength(1); + expect(executor.calls[0]?.params).toEqual([ + '2025-07-02T13:30:00.000Z', + '2025-07-02T13:31:00.000Z', + '5', + '2025-07-02T13:31:00.000Z', + ]); + }); +}); + +describe('Input validation and injection rejection', () => { + it('rejects split and total adjustments with MarketDataStoreNotImplementedError and zero executor calls', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + for (const adjustment of ['split', 'total'] as const) { + await expect( + collectBatches( + reader.bars({ + listingIds: [1], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment, + }) + ) + ).rejects.toThrow(MarketDataStoreNotImplementedError); + } + + expect(executor.calls).toHaveLength(0); + }); + + it('rejects invalid timeframe, adjustment, dates, listingIds, and SQL injection before any executor call', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const invalidQueries: unknown[] = [ + // Wrong timeframes + { listingIds: [1], timeframe: '1d', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { listingIds: [1], timeframe: '5m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { listingIds: [1], timeframe: '1h', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + // Invalid adjustment + { + listingIds: [1], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'dividend', + }, + // Reversed or invalid dates + { listingIds: [1], timeframe: '1m', from: '2024-02-01', to: '2024-01-01', adjustment: 'raw' }, + { + listingIds: [1], + timeframe: '1m', + from: '2024-01-02T13:30:00', + to: '2024-01-03T13:30:00Z', + adjustment: 'raw', + }, + { listingIds: [1], timeframe: '1m', from: 'not-a-date', to: '2024-01-03', adjustment: 'raw' }, + // Invalid listingIds + { listingIds: [], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { listingIds: [0], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, + { + listingIds: [-5], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + { + listingIds: [2_147_483_648], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + { + listingIds: [1.5], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + { + listingIds: [Number.NaN], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + // SQL injection attempt cast through unknown + { + listingIds: ['1; DROP TABLE bars_1m'], + timeframe: '1m', + from: '2024-01-02', + to: '2024-01-03', + adjustment: 'raw', + }, + ]; + + for (const badQuery of invalidQueries) { + await expect(collectBatches(reader.bars(badQuery as QuestDbBars1mQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + + expect(executor.calls).toHaveLength(0); + }); + + it('rejects invalid factory options (executor, vaultCutoffTs, batchSize)', () => { + const executor = new RecordingQuestDbExecutor(); + + expect(() => + createQuestDbIntradayBarsReader({ + executor: {} as unknown as QuestDbQueryExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: Number.NaN, + }) + ).toThrow(MarketDataStoreValidationError); + + for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => + createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: badBatchSize, + }) + ).toThrow(MarketDataStoreValidationError); + } + }); +}); + +describe('1-year single-listing replay, row mapping, and batching', () => { + it('streams 98,280 synthetic 1m rows (252 sessions x 390 min) in exact order across default 50k batches', async () => { + expect(DEFAULT_QUESTDB_BARS_BATCH_SIZE).toBe(50_000); + + const sessions = 252; + const minutesPerSession = 390; + const totalRows = sessions * minutesPerSession; // 98,280 + const listingId = 101; + const listingIdSymbol = String(listingId); + const baseSessionStartMs = Date.UTC(2024, 0, 2, 14, 30, 0, 0); + const msPerDay = 86_400_000; + const msPerMinute = 60_000; + + const rawRows: Record[] = new Array(totalRows); + const expected: BarRecord[] = new Array(totalRows); + + let idx = 0; + for (let s = 0; s < sessions; s += 1) { + const sessionStartMs = baseSessionStartMs + s * msPerDay; + for (let m = 0; m < minutesPerSession; m += 1) { + const tsMs = sessionStartMs + m * msPerMinute; + const knownAtMs = tsMs + msPerMinute; + const tsUs = BigInt(tsMs) * 1000n; + const knownAtUs = BigInt(knownAtMs) * 1000n; + + const open = 100 + s * 0.25 + m * 0.01; + const high = open + 0.15; + const low = open - 0.1; + const close = open + 0.05; + const volume = 1_000 + ((s * 390 + m) % 500); + const vwap = m % 10 === 0 ? null : open + 0.02; + + // Exercise all three supported LONG wire representations: decimal string, bigint, safe int. + const tsWire: unknown = + idx % 3 === 0 ? tsUs.toString() : idx % 3 === 1 ? tsUs : Number(tsUs); + const knownAtWire: unknown = + idx % 3 === 0 ? knownAtUs.toString() : idx % 3 === 1 ? knownAtUs : Number(knownAtUs); + + rawRows[idx] = { + listing_id: listingIdSymbol, + ts_us: tsWire, + open, + high, + low, + close, + volume, + vwap, + known_at_us: knownAtWire, + }; + expected[idx] = { + listingId, + ts: tsMs, + open, + high, + low, + close, + volume, + vwap, + knownAt: knownAtMs, + }; + idx += 1; + } + } + + const executor = new RecordingQuestDbExecutor(); + executor.setRows(rawRows); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const query: QuestDbBars1mQuery = { + listingIds: [listingId], + timeframe: '1m', + from: '2024-01-02', + to: '2024-12-31', + asOf: '2025-01-01T00:00:00Z', + adjustment: 'raw', + }; + + const run1Batches = await collectBatches(reader.bars(query)); + const run2Batches = await collectBatches(reader.bars(query)); + + expect(executor.calls).toHaveLength(2); + expect(run1Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); + expect(run2Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); + + const flat1 = run1Batches.flatMap(b => b.rows); + const flat2 = run2Batches.flatMap(b => b.rows); + expect(flat1).toHaveLength(totalRows); + expect(flat1).toEqual(expected); + expect(flat2).toEqual(flat1); + }); + + it('supports custom small batch sizes and yields zero batches for empty results', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 3, + }); + + const query: QuestDbBars1mQuery = { + listingIds: [12], + timeframe: '1m', + from: '2024-03-01T14:30:00Z', + to: '2024-03-01T14:40:00Z', + asOf: '2024-03-01T15:00:00Z', + adjustment: 'raw', + }; + + executor.setRows([]); + expect(await collectBatches(reader.bars(query))).toEqual([]); + expect(executor.calls).toHaveLength(1); + + const startMs = Date.UTC(2024, 2, 1, 14, 30, 0, 0); + const rows = Array.from({ length: 7 }, (_, i) => { + const tsMs = startMs + i * 60_000; + return { + listing_id: '12', + ts_us: (BigInt(tsMs) * 1000n).toString(), + open: 10 + i, + high: 11 + i, + low: 9 + i, + close: 10.5 + i, + volume: 100 + i, + vwap: i % 2 === 0 ? null : 10.25 + i, + known_at_us: (BigInt(tsMs + 60_000) * 1000n).toString(), + }; + }); + + executor.setRows(rows); + const batches = await collectBatches(reader.bars(query)); + expect(batches.map(b => b.rows.length)).toEqual([3, 3, 1]); + expect(executor.calls).toHaveLength(2); + expect(batches[0]?.rows[0]?.vwap).toBeNull(); + expect(batches[0]?.rows[1]?.vwap).toBe(11.25); + }); +}); + +describe('Malformed and out-of-fence row defence-in-depth', () => { + const baseQuery: QuestDbBars1mQuery = { + listingIds: [101], + timeframe: '1m', + from: '2025-06-30T23:58:00.000Z', + to: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 (2025-06-30T23:59:59.999Z) + asOf: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 + adjustment: 'raw', + }; + + const fromUs = BigInt(Date.UTC(2025, 5, 30, 23, 58, 0, 0)) * 1000n; + const clampedToUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; + const clampedAsOfUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; + + function makeValidRow(overrides: Record = {}): Record { + return { + listing_id: '101', + ts_us: fromUs.toString(), + open: 150, + high: 151, + low: 149.5, + close: 150.25, + volume: 2500, + vwap: 150.1, + known_at_us: clampedAsOfUs.toString(), + ...overrides, + }; + } + + it('accepts rows at exact fenced microsecond endpoints', async () => { + const executor = new RecordingQuestDbExecutor(); + executor.setRows([ + makeValidRow({ ts_us: fromUs.toString(), known_at_us: clampedAsOfUs.toString() }), + makeValidRow({ ts_us: clampedToUs.toString(), known_at_us: clampedAsOfUs.toString() }), + ]); + + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const batches = await collectBatches(reader.bars(baseQuery)); + expect(batches).toHaveLength(1); + expect(batches[0]?.rows).toHaveLength(2); + expect(batches[0]?.rows[0]?.ts).toBe(Date.UTC(2025, 5, 30, 23, 58, 0, 0)); + expect(batches[0]?.rows[1]?.ts).toBe(VAULT_CUTOFF_TS - 1); + }); + + it('rejects rows 1 microsecond before from, 1 microsecond after clamped to, or 1 microsecond after fenced asOf', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const outOfFenceRows: Array<{ label: string; row: Record }> = [ + { label: 'ts 1us before from', row: makeValidRow({ ts_us: (fromUs - 1n).toString() }) }, + { label: 'ts 1us after clamped to', row: makeValidRow({ ts_us: (clampedToUs + 1n).toString() }) }, + { + label: 'known_at 1us after clamped asOf', + row: makeValidRow({ known_at_us: (clampedAsOfUs + 1n).toString() }), + }, + ]; + + for (const testCase of outOfFenceRows) { + executor.setRows([testCase.row]); + await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('rejects invalid SYMBOLs, unrequested listings, non-finite OHLCV/vwap, and invalid timestamps', async () => { + const executor = new RecordingQuestDbExecutor(); + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const malformedRows: Record[] = [ + makeValidRow({ listing_id: '0101' }), + makeValidRow({ listing_id: '-101' }), + makeValidRow({ listing_id: '0' }), + makeValidRow({ listing_id: '2147483648' }), + makeValidRow({ listing_id: 101 }), + makeValidRow({ listing_id: '102' }), // valid INT32 SYMBOL, but unrequested + makeValidRow({ open: Number.NaN }), + makeValidRow({ high: Number.POSITIVE_INFINITY }), + makeValidRow({ low: Number.NEGATIVE_INFINITY }), + makeValidRow({ close: '150.25' }), + makeValidRow({ volume: Number.NaN }), + makeValidRow({ vwap: Number.NaN }), + makeValidRow({ vwap: Number.POSITIVE_INFINITY }), + makeValidRow({ ts_us: 'not-a-timestamp' }), + makeValidRow({ ts_us: 1.5 }), + makeValidRow({ known_at_us: null }), + ]; + + for (const badRow of malformedRows) { + executor.setRows([badRow]); + await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('fails before yielding any batch when a malformed row appears beyond the first batch boundary', async () => { + const executor = new RecordingQuestDbExecutor(); + executor.setRows([ + makeValidRow(), + makeValidRow(), + makeValidRow({ close: Number.NaN }), // row index 2 is past batchSize: 2 + ]); + + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 2, + }); + + const yielded: BarBatch[] = []; + let caught: unknown; + try { + for await (const batch of reader.bars(baseQuery)) { + yielded.push(batch); + } + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect(yielded).toHaveLength(0); + }); +}); From 9f2b184cd253d30810255b8529cbaa79cdcee556 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:46:56 -0500 Subject: [PATCH 07/26] =?UTF-8?q?T-146:=20M2.3f=20=E2=80=94=20QuestDB=20`b?= =?UTF-8?q?ars=5F1m`=20intraday=20reader=20for=20`MarketDataStore.bars`=20?= =?UTF-8?q?(`timeframe:=20'1m'`):=20Vault-fenced,=20parameterized=20`planB?= =?UTF-8?q?ars1mQuery`=20+=20batch=20iterator=20over=20an=20injected=20PGW?= =?UTF-8?q?ire=20query=20port=20in=20`libs/research/src/market-data-store-?= =?UTF-8?q?questdb.ts`=20(pure,=20no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../research/src/market-data-store-questdb.ts | 24 +++++-- .../test/market-data-store-questdb.test.ts | 69 ++++++++++++++++++- 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts index 08006f3b..c6da320c 100644 --- a/libs/research/src/market-data-store-questdb.ts +++ b/libs/research/src/market-data-store-questdb.ts @@ -265,10 +265,22 @@ function parseTimestampMicros( ); } -function microsToEpochMs(us: bigint, field: 'ts' | 'known_at', rowIndex: number): number { +function microsToEpochMs( + us: bigint, + field: 'ts' | 'known_at', + rowIndex: number, + rounding: 'floor' | 'ceil' +): number { const quotient = us / 1000n; const remainder = us % 1000n; - const msBigInt = remainder < 0n ? quotient - 1n : quotient; + const msBigInt = + rounding === 'ceil' + ? remainder > 0n + ? quotient + 1n + : quotient + : remainder < 0n + ? quotient - 1n + : quotient; const ms = Number(msBigInt); if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) { throw new MarketDataStoreValidationError( @@ -350,14 +362,15 @@ function mapBars1mRows( out[i] = { listingId, - ts: microsToEpochMs(tsUs, 'ts', i), + ts: microsToEpochMs(tsUs, 'ts', i, 'floor'), open: readRequiredFiniteNumber(raw, 'open', i), high: readRequiredFiniteNumber(raw, 'high', i), low: readRequiredFiniteNumber(raw, 'low', i), close: readRequiredFiniteNumber(raw, 'close', i), volume: readRequiredFiniteNumber(raw, 'volume', i), vwap: readNullableFiniteNumber(raw, 'vwap', i), - knownAt: microsToEpochMs(knownAtUs, 'known_at', i), + // Round sub-millisecond availability up so replay never treats a bar as known before arrival. + knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'), }; } @@ -404,7 +417,8 @@ export function createQuestDbIntradayBarsReader( ); } - const batchSize = options.batchSize ?? DEFAULT_QUESTDB_BARS_BATCH_SIZE; + const batchSize = + options.batchSize === undefined ? DEFAULT_QUESTDB_BARS_BATCH_SIZE : options.batchSize; if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) { throw new MarketDataStoreValidationError( `Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`, diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts index 22c030ec..b17e06a2 100644 --- a/libs/research/test/market-data-store-questdb.test.ts +++ b/libs/research/test/market-data-store-questdb.test.ts @@ -415,12 +415,12 @@ describe('Input validation and injection rejection', () => { }) ).toThrow(MarketDataStoreValidationError); - for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, null]) { expect(() => createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: badBatchSize, + batchSize: badBatchSize as unknown as number, }) ).toThrow(MarketDataStoreValidationError); } @@ -700,4 +700,69 @@ describe('Malformed and out-of-fence row defence-in-depth', () => { expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect(yielded).toHaveLength(0); }); + + it('rounds sub-millisecond known_at up so wider-window replay never exposes a bar before arrival', async () => { + // Matches the QuestDB storage fixture: + // ts = 2024-01-02T14:30:00.000000Z (1704205800000000 us) + // known_at = 2024-01-02T14:31:00.000700Z (1704205860000700 us) + const executor = new RecordingQuestDbExecutor(); + executor.setRows([ + { + listing_id: '1042', + ts_us: '1704205800000000', + open: 185.1, + high: 185.5, + low: 184.9, + close: 185.4, + volume: 12500, + vwap: 185.28, + known_at_us: '1704205860000700', + }, + { + listing_id: '1042', + ts_us: '1704205860000000', + open: 185.4, + high: 185.6, + low: 185.3, + close: 185.55, + volume: 8200, + vwap: null, + known_at_us: '1704205920000000', // exact millisecond: 2024-01-02T14:32:00.000000Z + }, + ]); + + const reader = createQuestDbIntradayBarsReader({ + executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + const query: QuestDbBars1mQuery = { + listingIds: [1042], + timeframe: '1m', + from: '2024-01-02T14:30:00.000Z', + to: '2024-01-02T21:00:00.000Z', + asOf: '2024-01-02T21:00:00.000Z', + adjustment: 'raw', + }; + + const run1 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); + const run2 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); + expect(run1).toEqual(run2); + expect(run1).toHaveLength(2); + + const decisionAt143100000 = Date.UTC(2024, 0, 2, 14, 31, 0, 0); + const decisionAt143100001 = Date.UTC(2024, 0, 2, 14, 31, 0, 1); + const exactKnownAt143200000 = Date.UTC(2024, 0, 2, 14, 32, 0, 0); + + const subMsBar = run1[0]!; + expect(subMsBar.knownAt).toBe(decisionAt143100001); + // Ineligible at 14:31:00.000 UTC, eligible at 14:31:00.001 UTC. + expect(subMsBar.knownAt <= decisionAt143100000).toBe(false); + expect(subMsBar.knownAt <= decisionAt143100001).toBe(true); + + // Exact whole-millisecond known_at is not pushed forward. + const exactMsBar = run1[1]!; + expect(exactMsBar.knownAt).toBe(exactKnownAt143200000); + expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true); + }); }); From c6ee4d033601a2ebaf834c1a95a8dd9480ffaeb3 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 22:52:38 -0500 Subject: [PATCH 08/26] T-146: tests --- .../test/market-data-store-questdb.qa.test.ts | 346 ++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 libs/research/test/market-data-store-questdb.qa.test.ts diff --git a/libs/research/test/market-data-store-questdb.qa.test.ts b/libs/research/test/market-data-store-questdb.qa.test.ts new file mode 100644 index 00000000..bbe68fb6 --- /dev/null +++ b/libs/research/test/market-data-store-questdb.qa.test.ts @@ -0,0 +1,346 @@ +import { describe, expect, it } from 'bun:test'; +import { + createQuestDbIntradayBarsReader, + MarketDataStoreValidationError, + planBars1mQuery, + VaultScopeNotAuthorizedError, + type BarBatch, + type QuestDbBars1mQuery, + type QuestDbQueryExecutor, +} from '@stock-bot/research'; + +// QA edge cases for T-146 (QuestDB `bars_1m` reader) beyond the programmer suite. + +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + +type QueryResult = { readonly rows: readonly Record[] }; + +class ScriptedExecutor implements QuestDbQueryExecutor { + readonly calls: Array<{ sql: string; params: unknown[] }> = []; + constructor(private readonly respond: () => Promise) {} + async query(sql: string, params: readonly unknown[]): Promise { + this.calls.push({ sql, params: [...params] }); + return this.respond(); + } +} + +function executorReturning(result: unknown): ScriptedExecutor { + return new ScriptedExecutor(async () => result as QueryResult); +} + +async function collect(iterable: AsyncIterable): Promise { + const out: BarBatch[] = []; + for await (const batch of iterable) { + out.push(batch); + } + return out; +} + +function us(ms: number, extraMicros = 0n): string { + return (BigInt(ms) * 1000n + extraMicros).toString(); +} + +function row(overrides: Record): Record { + return { + listing_id: '7', + open: 10, + high: 11, + low: 9, + close: 10.5, + volume: 100, + vwap: 10.2, + ...overrides, + }; +} + +const sessionQuery: QuestDbBars1mQuery = { + listingIds: [7], + timeframe: '1m', + from: '2024-03-01T14:30:00Z', + to: '2024-03-01T21:00:00Z', + asOf: '2024-03-01T21:00:00Z', + adjustment: 'raw', +}; + +describe('QuestDB bars_1m reader QA: planner purity and param binding', () => { + it('is deterministic and binds INT32_MAX as a decimal SYMBOL string only in params', () => { + const q: QuestDbBars1mQuery = { ...sessionQuery, listingIds: [2_147_483_647, 1] }; + const a = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); + const b = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); + + expect(a).toEqual(b); + expect(a.params).toEqual([ + '2024-03-01T14:30:00.000Z', + '2024-03-01T21:00:00.000Z', + '1', + '2147483647', + '2024-03-01T21:00:00.000Z', + ]); + expect(a.sql).not.toContain('2147483647'); + expect(a.sql).toContain('listing_id IN ($3, $4) AND known_at <= $5'); + // Only ordinal placeholders and fixed identifiers: no quotes or digits outside `$n` tokens. + expect(a.sql.replace(/\$\d+/g, '').replace('bars_1m', '')).not.toMatch(/[0-9'";]/); + }); + + it('normalizes offset timestamps to UTC ISO-8601 params', () => { + const planned = planBars1mQuery( + { + ...sessionQuery, + from: '2024-03-01T09:30:00-05:00', + to: '2024-03-01T16:00:00.250-05:00', + asOf: '2024-03-01T17:00:00-05:00', + }, + { vaultCutoffTs: VAULT_CUTOFF_TS } + ); + expect(planned.params).toEqual([ + '2024-03-01T14:30:00.000Z', + '2024-03-01T21:00:00.250Z', + '7', + '2024-03-01T22:00:00.000Z', + ]); + }); + + it('passes the executor a copy of params so executor mutation cannot alter later plans', async () => { + const executor = new ScriptedExecutor(async () => ({ rows: [] })); + const mutating: QuestDbQueryExecutor = { + async query(sql, params) { + (params as unknown[]).splice(0, params.length, 'tampered'); + return executor.query(sql, params); + }, + }; + const reader = createQuestDbIntradayBarsReader({ + executor: mutating, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await collect(reader.bars(sessionQuery)); + await collect(reader.bars(sessionQuery)); + + expect(executor.calls).toHaveLength(2); + expect(executor.calls[1]?.params).toEqual(['tampered']); + expect(planBars1mQuery(sessionQuery, { vaultCutoffTs: VAULT_CUTOFF_TS }).params).toHaveLength( + 4 + ); + }); + + it('rejects numeric-looking string listing IDs and non-array listingIds before querying', async () => { + const executor = executorReturning({ rows: [] }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const bad: unknown[] = [ + { ...sessionQuery, listingIds: ['7'] }, + { ...sessionQuery, listingIds: [7n] }, + { ...sessionQuery, listingIds: 7 }, + { ...sessionQuery, listingIds: undefined }, + { ...sessionQuery, listingIds: [7, Number.POSITIVE_INFINITY] }, + null, + ]; + for (const q of bad) { + await expect(collect(reader.bars(q as QuestDbBars1mQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + expect(executor.calls).toHaveLength(0); + }); +}); + +describe('QuestDB bars_1m reader QA: Vault and trusted context', () => { + it('planner ignores a vaultOperatorAuthorized flag smuggled on the query object', () => { + const spoofed = { + ...sessionQuery, + from: '2025-07-02', + to: '2025-07-03', + asOf: undefined, + scope: 'vault_evaluation_only', + vaultOperatorAuthorized: true, + } as unknown as QuestDbBars1mQuery; + expect(() => planBars1mQuery(spoofed, { vaultCutoffTs: VAULT_CUTOFF_TS })).toThrow( + VaultScopeNotAuthorizedError + ); + }); + + it('rejects non-boolean truthy vaultOperatorAuthorized in factory options', () => { + for (const flag of ['true', 1, {}]) { + expect(() => + createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows: [] }), + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: flag as unknown as boolean, + }) + ).toThrow(MarketDataStoreValidationError); + } + }); + + it('rejects a non-object planner context', () => { + expect(() => + planBars1mQuery(sessionQuery, null as unknown as { vaultCutoffTs: number }) + ).toThrow(MarketDataStoreValidationError); + }); + + it('rejects unknown scope values before querying', async () => { + const executor = executorReturning({ rows: [] }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + await expect( + collect(reader.bars({ ...sessionQuery, scope: 'all' } as unknown as QuestDbBars1mQuery)) + ).rejects.toThrow(MarketDataStoreValidationError); + expect(executor.calls).toHaveLength(0); + }); + + it('a row known one microsecond before a clamped asOf maps to knownAt exactly at the fence, never past it', async () => { + const executor = executorReturning({ + rows: [ + row({ + ts_us: us(VAULT_CUTOFF_TS - 60_000), + known_at_us: us(VAULT_CUTOFF_TS - 1, -1n), + }), + ], + }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const rows = ( + await collect( + reader.bars({ + ...sessionQuery, + from: '2025-06-30T23:00:00Z', + to: '2025-12-31', + asOf: '2025-12-31', + }) + ) + ).flatMap(b => b.rows); + expect(rows).toHaveLength(1); + expect(rows[0]?.knownAt).toBe(VAULT_CUTOFF_TS - 1); + expect(rows[0]!.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + }); +}); + +describe('QuestDB bars_1m reader QA: executor result and row defence-in-depth', () => { + it('rejects malformed executor results with a validation error', async () => { + for (const result of [ + null, + undefined, + {}, + { rows: null }, + { rows: 'x' }, + [], + { rows: [null] }, + { rows: [[1]] }, + ]) { + const reader = createQuestDbIntradayBarsReader({ + executor: executorReturning(result), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('propagates executor failures unchanged and yields nothing', async () => { + const boom = new Error('pgwire connection reset'); + const reader = createQuestDbIntradayBarsReader({ + executor: new ScriptedExecutor(async () => { + throw boom; + }), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await expect(collect(reader.bars(sessionQuery))).rejects.toBe(boom); + }); + + it('does not call the executor until iteration starts (lazy plan + query)', async () => { + const executor = executorReturning({ rows: [] }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const iterable = reader.bars(sessionQuery); + expect(executor.calls).toHaveLength(0); + await collect(iterable); + expect(executor.calls).toHaveLength(1); + }); + + it('maps multi-listing rows, undefined vwap to null, and -0 to 0', async () => { + const t0 = Date.UTC(2024, 2, 1, 14, 30); + const executor = executorReturning({ + rows: [ + row({ listing_id: '3', ts_us: us(t0), known_at_us: us(t0 + 60_000), vwap: undefined }), + row({ listing_id: '7', ts_us: us(t0), known_at_us: us(t0 + 60_000), volume: -0, vwap: 0 }), + ], + }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const rows = (await collect(reader.bars({ ...sessionQuery, listingIds: [7, 3] }))).flatMap( + b => b.rows + ); + expect(rows.map(r => r.listingId)).toEqual([3, 7]); + expect(rows[0]?.vwap).toBeNull(); + expect(Object.is(rows[1]?.volume, 0)).toBe(true); + expect(rows[1]?.vwap).toBe(0); + expect(executor.calls[0]?.params.slice(2, 4)).toEqual(['3', '7']); + }); + + it('rejects timestamp wire values that are unsafe numbers, padded strings, or missing', async () => { + const t0 = Date.UTC(2024, 2, 1, 14, 30); + const bad: Record[] = [ + row({ ts_us: Number.MAX_SAFE_INTEGER + 2, known_at_us: us(t0) }), + row({ ts_us: ` ${us(t0)}`, known_at_us: us(t0) }), + row({ ts_us: `+${us(t0)}`, known_at_us: us(t0) }), + row({ ts_us: us(t0) }), + row({ ts_us: new Date(t0), known_at_us: us(t0) }), + ]; + for (const r of bad) { + const reader = createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows: [r] }), + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( + MarketDataStoreValidationError + ); + } + }); + + it('floors sub-millisecond ts and ceils sub-millisecond known_at for pre-1970 instants', async () => { + // ts = -1.5 ms -> floor -2 ms; known_at = -1.5 ms -> ceil -1 ms. + const executor = executorReturning({ + rows: [row({ ts_us: '-1500', known_at_us: -1500n })], + }); + const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); + const rows = ( + await collect( + reader.bars({ + ...sessionQuery, + from: '1969-12-31T23:59:59.000Z', + to: '1970-01-01T00:00:00.000Z', + asOf: '1970-01-01T00:00:00.000Z', + }) + ) + ).flatMap(b => b.rows); + expect(rows).toEqual([ + { + listingId: 7, + ts: -2, + open: 10, + high: 11, + low: 9, + close: 10.5, + volume: 100, + vwap: 10.2, + knownAt: -1, + }, + ]); + }); + + it('batch size equal to row count yields one batch; batch size 1 yields one row per batch in order', async () => { + const t0 = Date.UTC(2024, 2, 1, 14, 30); + const rows = Array.from({ length: 4 }, (_, i) => + row({ ts_us: us(t0 + i * 60_000), known_at_us: us(t0 + (i + 1) * 60_000), open: 10 + i }) + ); + const exact = createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows }), + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 4, + }); + expect((await collect(exact.bars(sessionQuery))).map(b => b.rows.length)).toEqual([4]); + + const single = createQuestDbIntradayBarsReader({ + executor: executorReturning({ rows }), + vaultCutoffTs: VAULT_CUTOFF_TS, + batchSize: 1, + }); + const batches = await collect(single.bars(sessionQuery)); + expect(batches.map(b => b.rows.length)).toEqual([1, 1, 1, 1]); + expect(batches.map(b => b.rows[0]?.open)).toEqual([10, 11, 12, 13]); + }); +}); From 8f9e9ac1966cb8b29598fd4daa3d2b7660170d2e Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:02:17 -0500 Subject: [PATCH 09/26] =?UTF-8?q?T-148:=20M2.3h=20=E2=80=94=20Route=20`Mar?= =?UTF-8?q?ketDataStore.bars`=20(`timeframe:=20'1m'`)=20to=20the=20QuestDB?= =?UTF-8?q?=20`bars=5F1m`=20reader:=20pure=20`createRoutedMarketDataStore`?= =?UTF-8?q?=20composing=20the=20DuckDB=20daily=20store=20+=20injected=20in?= =?UTF-8?q?traday=20reader=20in=20`libs/research/src/market-data-store-rou?= =?UTF-8?q?ted.ts`=20(no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 31 + libs/research/package.json | 2 + libs/research/src/index.ts | 1 + libs/research/src/market-data-store-routed.ts | 190 +++ .../test/market-data-store-routed.test.ts | 1099 +++++++++++++++++ 5 files changed, 1323 insertions(+) create mode 100644 libs/research/src/market-data-store-routed.ts create mode 100644 libs/research/test/market-data-store-routed.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index dd076551..a65593d7 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -124,6 +124,37 @@ Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across - **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`) - **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`) +## Routed `MarketDataStore` (DuckDB Daily + QuestDB `1m` Intraday) + +Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-routed` (`libs/research/src/market-data-store-routed.ts`). The QuestDB intraday reader is also exported from `@stock-bot/research/market-data-store-questdb`. Both modules are pure, dependency-free, and browser-safe. + +- **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick`, e.g. `createQuestDbIntradayBarsReader`). + - `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars. + - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`. + - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily`, `intraday`, and any MCP tool (`createQueryDataTool` / `createResearchCopilotMcpServer`) with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`: + +```ts +const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); +const vaultOperatorAuthorized = false; + +const daily = createDuckDbMarketDataStore({ + executor: duckDbExecutor, + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs, + vaultOperatorAuthorized, +}); +const intraday = createQuestDbIntradayBarsReader({ + executor: questDbExecutor, + vaultCutoffTs, + vaultOperatorAuthorized, +}); +const store = createRoutedMarketDataStore({ daily, intraday }); +const queryDataTool = createQueryDataTool({ + store, + vaultContext: { vaultCutoffTs, vaultOperatorAuthorized }, +}); +``` + ## Signal Panel Builder Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). diff --git a/libs/research/package.json b/libs/research/package.json index e5cf853d..eb1522e3 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -14,6 +14,8 @@ "./feature-library": "./src/feature-library.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", + "./market-data-store-questdb": "./src/market-data-store-questdb.ts", + "./market-data-store-routed": "./src/market-data-store-routed.ts", "./mcp": "./src/mcp/index.ts", "./results": "./src/results.ts", "./signal-panel": "./src/signal-panel.ts", diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index dcc88deb..bb5e7062 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -5,6 +5,7 @@ export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; export * from './market-data-store-questdb'; +export * from './market-data-store-routed'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts new file mode 100644 index 00000000..c9594321 --- /dev/null +++ b/libs/research/src/market-data-store-routed.ts @@ -0,0 +1,190 @@ +/** + * Pure, dependency-free `MarketDataStore` router that dispatches intraday + * `bars` queries (`timeframe: '1m'`) to an injected intraday reader (such as + * {@link createQuestDbIntradayBarsReader}) and routes every other `bars` + * timeframe and all other `MarketDataStore` methods to the injected daily + * store (such as {@link createDuckDbMarketDataStore}). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` + * access, and no database or filesystem I/O. + * + * Vault & point-in-time semantics: + * - This router adds no Vault logic of its own; each delegate continues to + * enforce its own Vault holdout fence and point-in-time predicates. + * - Callers MUST construct both `daily` and `intraday` with the exact same + * `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same + * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`) so the holdout + * boundary is identical across timeframes. + * - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports + * split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests + * and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective + * delegate without modification. + */ + +import { type MarketDataStore, MarketDataStoreValidationError } from './market-data-store'; + +/** Configuration for {@link createRoutedMarketDataStore}. */ +export interface RoutedMarketDataStoreOptions { + /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ + readonly daily: MarketDataStore; + /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ + readonly intraday: Pick; +} + +const REQUIRED_DAILY_METHODS = [ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', +] as const satisfies readonly (keyof MarketDataStore)[]; + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function isDelegateObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isIntraday1mBarsQuery(q: unknown): boolean { + return ( + typeof q === 'object' && + q !== null && + !Array.isArray(q) && + (q as { readonly timeframe?: unknown }).timeframe === '1m' + ); +} + +/** + * Composes a daily `MarketDataStore` and an intraday `bars` reader into a + * single read-only `MarketDataStore`. + * + * Routing rules: + * - `bars(q)` with `q.timeframe === '1m'` delegates directly to + * `options.intraday.bars(q)` and returns its `AsyncIterable` + * unchanged (preserving receiver, query identity, lazy iteration, and error + * timing). + * - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed + * runtime inputs) delegates directly to `options.daily.bars(q)`. + * - All other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, + * `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly + * to `options.daily` and return its original promise. + * + * Vault fence note: + * Both `daily` and `intraday` MUST be constructed with the exact same + * `vaultCutoffTs` and `vaultOperatorAuthorized` settings. The QuestDB intraday + * reader serves raw (`adjustment: 'raw'`) `1m` bars. + * + * @example + * ```ts + * const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + * const vaultOperatorAuthorized = false; + * + * const daily = createDuckDbMarketDataStore({ + * executor: duckDbExecutor, + * curatedRoot: '/mnt/data/stockbot/curated', + * vaultCutoffTs, + * vaultOperatorAuthorized, + * }); + * const intraday = createQuestDbIntradayBarsReader({ + * executor: questDbExecutor, + * vaultCutoffTs, + * vaultOperatorAuthorized, + * }); + * const store = createRoutedMarketDataStore({ daily, intraday }); + * const queryDataTool = createQueryDataTool({ + * store, + * vaultContext: { vaultCutoffTs, vaultOperatorAuthorized }, + * }); + * ``` + */ +export function createRoutedMarketDataStore( + options: RoutedMarketDataStoreOptions +): MarketDataStore { + if (!isPlainObject(options)) { + throw new MarketDataStoreValidationError( + 'Expected a plain RoutedMarketDataStoreOptions object.', + 'options' + ); + } + + const rawDaily: unknown = options.daily; + if (!isDelegateObject(rawDaily)) { + throw new MarketDataStoreValidationError( + 'Expected `daily` to be a MarketDataStore object.', + 'daily' + ); + } + + for (const method of REQUIRED_DAILY_METHODS) { + if (typeof rawDaily[method] !== 'function') { + throw new MarketDataStoreValidationError( + `Expected \`daily.${method}\` to be a function.`, + `daily.${method}` + ); + } + } + + const rawIntraday: unknown = options.intraday; + if (!isDelegateObject(rawIntraday)) { + throw new MarketDataStoreValidationError( + 'Expected `intraday` to be an object with a `bars` method.', + 'intraday' + ); + } + + if (typeof rawIntraday.bars !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `intraday.bars` to be a function.', + 'intraday.bars' + ); + } + + const daily = options.daily; + const intraday = options.intraday; + + return { + bars(q) { + if (isIntraday1mBarsQuery(q)) { + return intraday.bars(q); + } + return daily.bars(q); + }, + + crossSection(q) { + return daily.crossSection(q); + }, + + fundamentalsAsOf(q) { + return daily.fundamentalsAsOf(q); + }, + + events(q) { + return daily.events(q); + }, + + shortsAsOf(q) { + return daily.shortsAsOf(q); + }, + + macroAsOf(q) { + return daily.macroAsOf(q); + }, + + fx(q) { + return daily.fx(q); + }, + + universe(q) { + return daily.universe(q); + }, + }; +} diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts new file mode 100644 index 00000000..1a7c4e90 --- /dev/null +++ b/libs/research/test/market-data-store-routed.test.ts @@ -0,0 +1,1099 @@ +import { describe, expect, it } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type DuckDbExecutor, + type DuckDbParam, + type MarketDataStore, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + type QuestDbQueryExecutor, + type RoutedMarketDataStoreOptions, + type Table, + type TableRow, + createDuckDbMarketDataStore, + createQuestDbIntradayBarsReader, + createRoutedMarketDataStore, +} from '@stock-bot/research'; +import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; +import { createRoutedMarketDataStore as subpathCreateRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; +import { + type QueryDataResultPayload, + createMcpServer, + createQueryDataTool, +} from '../src/mcp/index'; + +type BarsQuery = Parameters[0]; +type CrossSectionQuery = Parameters[0]; +type FundamentalsQuery = Parameters[0]; +type EventsQuery = Parameters[0]; +type ShortsQuery = Parameters[0]; +type MacroQuery = Parameters[0]; +type FxQuery = Parameters[0]; +type UniverseQuery = Parameters[0]; + +const LISTING_ID = 42; +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z +const VAULT_CUTOFF_US = VAULT_CUTOFF_TS * 1000; +const CLAMPED_END_ISO = '2025-06-30T23:59:59.999Z'; +const CURATED_ROOT = '/mnt/data/stockbot/curated'; + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close - 0.5, + high: close + 0.5, + low: close - 1, + close, + volume: 1_000, + vwap: close, + knownAt, + }; +} + +async function collectBatches(iterable: AsyncIterable): Promise { + const batches: BarBatch[] = []; + for await (const batch of iterable) { + batches.push(batch); + } + return batches; +} + +class PrototypeDailyStore implements MarketDataStore { + readonly calls: { method: keyof MarketDataStore; arg: unknown }[] = []; + readonly returnedPromises = new Map>(); + readonly barsBatches: BarBatch[]; + + constructor(barsBatches: BarBatch[] = []) { + this.barsBatches = barsBatches; + } + + private assertReceiver(): void { + if (!(this instanceof PrototypeDailyStore)) { + throw new Error('Lost daily receiver (`this`).'); + } + } + + bars(q: BarsQuery): AsyncIterable { + this.assertReceiver(); + this.calls.push({ method: 'bars', arg: q }); + const batches = this.barsBatches; + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + } + + crossSection(q: CrossSectionQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'crossSection', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id'], rows: [{ listing_id: 42 }] }); + this.returnedPromises.set('crossSection', p); + return p; + } + + fundamentalsAsOf(q: FundamentalsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'fundamentalsAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'revenue'], rows: [] }); + this.returnedPromises.set('fundamentalsAsOf', p); + return p; + } + + events(q: EventsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'events', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'kind'], rows: [] }); + this.returnedPromises.set('events', p); + return p; + } + + shortsAsOf(q: ShortsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'shortsAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'shares_short'], rows: [] }); + this.returnedPromises.set('shortsAsOf', p); + return p; + } + + macroAsOf(q: MacroQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'macroAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['country', 'value'], rows: [] }); + this.returnedPromises.set('macroAsOf', p); + return p; + } + + fx(q: FxQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'fx', arg: q }); + const p = Promise.resolve
({ columns: ['pair', 'close'], rows: [] }); + this.returnedPromises.set('fx', p); + return p; + } + + universe(q: UniverseQuery): Promise { + this.assertReceiver(); + this.calls.push({ method: 'universe', arg: q }); + const p = Promise.resolve([42, 101]); + this.returnedPromises.set('universe', p); + return p; + } +} + +class PrototypeIntradayReader implements Pick { + readonly calls: BarsQuery[] = []; + readonly barsBatches: BarBatch[]; + + constructor(barsBatches: BarBatch[] = []) { + this.barsBatches = barsBatches; + } + + bars(q: BarsQuery): AsyncIterable { + if (!(this instanceof PrototypeIntradayReader)) { + throw new Error('Lost intraday receiver (`this`).'); + } + this.calls.push(q); + const batches = this.barsBatches; + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + } +} + +interface QuestDbFixtureRow { + readonly listing_id: string; + readonly ts_us: number; + readonly open: number; + readonly high: number; + readonly low: number; + readonly close: number; + readonly volume: number; + readonly vwap: number | null; + readonly known_at_us: number; +} + +class PredicateAwareQuestDbExecutor implements QuestDbQueryExecutor { + readonly calls: { readonly sql: string; readonly params: readonly unknown[] }[] = []; + private readonly rows: readonly QuestDbFixtureRow[]; + private readonly leaky: boolean; + + constructor(rows: readonly QuestDbFixtureRow[], options?: { leaky?: boolean }) { + this.rows = rows; + this.leaky = options?.leaky === true; + } + + async query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }> { + this.calls.push({ sql, params: [...params] }); + if (this.leaky) { + return { rows: this.rows as unknown as readonly Record[] }; + } + const fromUs = Date.parse(String(params[0])) * 1000; + const toUs = Date.parse(String(params[1])) * 1000; + const asOfUs = Date.parse(String(params[params.length - 1])) * 1000; + const listingIds = new Set(params.slice(2, params.length - 1).map(String)); + + const filtered = this.rows.filter( + row => + row.ts_us >= fromUs && + row.ts_us <= toUs && + row.known_at_us <= asOfUs && + listingIds.has(row.listing_id) + ); + return { rows: filtered as unknown as readonly Record[] }; + } +} + +class RecordingDuckDbExecutor implements DuckDbExecutor { + readonly runCalls: string[] = []; + readonly queryCalls: { readonly sql: string; readonly params: readonly DuckDbParam[] }[] = []; + private readonly rows: readonly TableRow[]; + + constructor(rows: readonly TableRow[] = []) { + this.rows = rows; + } + + async run(sql: string): Promise { + this.runCalls.push(sql); + } + + async query(sql: string, params: readonly DuckDbParam[]): Promise { + this.queryCalls.push({ sql, params: [...params] }); + return this.rows; + } +} + +describe('package exports', () => { + it('re-exports createRoutedMarketDataStore and createQuestDbIntradayBarsReader from root and subpaths', () => { + expect(createRoutedMarketDataStore).toBe(subpathCreateRoutedMarketDataStore); + expect(createQuestDbIntradayBarsReader).toBe(subpathCreateQuestDbIntradayBarsReader); + }); +}); + +describe('createRoutedMarketDataStore', () => { + describe('constructor validation', () => { + it('rejects null, primitives, arrays, and class instances for options', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + 42, + 'options', + true, + [], + new Date(), + new (class OptionsClass { + daily = new PrototypeDailyStore(); + intraday = new PrototypeIntradayReader(); + })(), + ]; + + for (const bad of invalidOptions) { + let caught: unknown; + try { + createRoutedMarketDataStore(bad as RoutedMarketDataStoreOptions); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('options'); + } + }); + + it('accepts a null-prototype options object and prototype-backed delegates', () => { + const options = Object.create(null) as { + daily: MarketDataStore; + intraday: Pick; + }; + options.daily = new PrototypeDailyStore(); + options.intraday = new PrototypeIntradayReader(); + + const store = createRoutedMarketDataStore(options); + expect(typeof store.bars).toBe('function'); + }); + + it('rejects missing or malformed daily delegate and each missing daily method', () => { + const intraday = new PrototypeIntradayReader(); + + for (const badDaily of [null, undefined, 'daily', 123, []]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily: badDaily as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('daily'); + } + + const requiredMethods: (keyof MarketDataStore)[] = [ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', + ]; + + for (const missingMethod of requiredMethods) { + const base = new PrototypeDailyStore(); + const incomplete: Record = { + bars: base.bars.bind(base), + crossSection: base.crossSection.bind(base), + fundamentalsAsOf: base.fundamentalsAsOf.bind(base), + events: base.events.bind(base), + shortsAsOf: base.shortsAsOf.bind(base), + macroAsOf: base.macroAsOf.bind(base), + fx: base.fx.bind(base), + universe: base.universe.bind(base), + }; + delete incomplete[missingMethod]; + + let caughtMissing: unknown; + try { + createRoutedMarketDataStore({ + daily: incomplete as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caughtMissing = err; + } + expect(caughtMissing).toBeInstanceOf(MarketDataStoreValidationError); + expect((caughtMissing as MarketDataStoreValidationError).field).toBe( + `daily.${missingMethod}` + ); + + incomplete[missingMethod] = 'not-a-function'; + let caughtNonFn: unknown; + try { + createRoutedMarketDataStore({ + daily: incomplete as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caughtNonFn = err; + } + expect(caughtNonFn).toBeInstanceOf(MarketDataStoreValidationError); + expect((caughtNonFn as MarketDataStoreValidationError).field).toBe( + `daily.${missingMethod}` + ); + } + }); + + it('rejects missing or non-callable intraday delegate and intraday.bars', () => { + const daily = new PrototypeDailyStore(); + + for (const badIntraday of [null, undefined, 'intraday', 99, []]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily, + intraday: badIntraday as unknown as Pick, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('intraday'); + } + + for (const badBars of [undefined, null, 'bars', 42, {}]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily, + intraday: { bars: badBars } as unknown as Pick, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('intraday.bars'); + } + }); + }); + + describe('routing and delegation', () => { + it('routes 1m bars exclusively to intraday and 1d bars exclusively to daily with exact query identity', async () => { + const intradayBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 101.25)], + }; + const dailyBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 20, 0, 0), 102.5)], + }; + const daily = new PrototypeDailyStore([dailyBatch]); + const intraday = new PrototypeIntradayReader([intradayBatch]); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const q1m: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }; + const q1d: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-01', + to: '2025-06-30', + adjustment: 'raw', + }; + + const intradayOut = await collectBatches(store.bars(q1m)); + expect(intraday.calls).toHaveLength(1); + expect(intraday.calls[0]).toBe(q1m); + expect(daily.calls).toHaveLength(0); + expect(intradayOut).toHaveLength(1); + expect(intradayOut[0]).toBe(intradayBatch); + + const dailyOut = await collectBatches(store.bars(q1d)); + expect(daily.calls).toHaveLength(1); + expect(daily.calls[0]?.method).toBe('bars'); + expect(daily.calls[0]?.arg).toBe(q1d); + expect(intraday.calls).toHaveLength(1); + expect(dailyOut).toHaveLength(1); + expect(dailyOut[0]).toBe(dailyBatch); + }); + + it('forwards invalid timeframe values and non-object inputs to daily unchanged', async () => { + const daily = new PrototypeDailyStore(); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const arrayWithTimeframe = Object.assign(['1m'], { timeframe: '1m' }); + const malformedInputs: unknown[] = [ + null, + undefined, + '1m', + 42, + ['1m'], + arrayWithTimeframe, + { listingIds: [42], timeframe: '2m', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, + { listingIds: [42], timeframe: '', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, + ]; + + for (const badInput of malformedInputs) { + await collectBatches(store.bars(badInput as BarsQuery)); + } + + expect(intraday.calls).toHaveLength(0); + expect(daily.calls).toHaveLength(malformedInputs.length); + for (let i = 0; i < malformedInputs.length; i += 1) { + expect(daily.calls[i]?.method).toBe('bars'); + expect(daily.calls[i]?.arg).toBe(malformedInputs[i]); + } + }); + + it('preserves DuckDB MarketDataStoreNotImplementedError for 5m and 1h with zero executor or intraday calls', async () => { + const duckExecutor = new RecordingDuckDbExecutor(); + const daily = createDuckDbMarketDataStore({ + executor: duckExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + for (const timeframe of ['5m', '1h'] as const) { + let caught: unknown; + try { + for await (const _batch of store.bars({ + listingIds: [LISTING_ID], + timeframe, + from: '2025-06-01', + to: '2025-06-30', + adjustment: 'raw', + })) { + // unreachable + } + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); + } + + expect(duckExecutor.runCalls).toHaveLength(0); + expect(duckExecutor.queryCalls).toHaveLength(0); + expect(intraday.calls).toHaveLength(0); + }); + + it('delegates all seven non-bars methods (including fx 1m) to daily with argument, receiver, and promise identity', async () => { + const daily = new PrototypeDailyStore(); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const crossSectionArg: CrossSectionQuery = { + features: ['ret_1d@v1'], + date: '2025-06-30', + universe: 'US_EQ', + }; + const fundamentalsArg: FundamentalsQuery = { + listingIds: [LISTING_ID], + fields: ['revenue'], + asOf: '2025-06-30', + }; + const eventsArg: EventsQuery = { + kinds: ['filing'], + listingIds: [LISTING_ID], + from: '2025-06-01', + to: '2025-06-30', + }; + const shortsArg: ShortsQuery = { + listingIds: [LISTING_ID], + from: '2025-06-01', + to: '2025-06-30', + }; + const macroArg: MacroQuery = { + countries: ['US'], + indicators: ['CPI'], + from: '2025-06-01', + to: '2025-06-30', + }; + const fxArg: FxQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-01', + to: '2025-06-30', + }; + const universeArg: UniverseQuery = { + ref: 'US_EQ', + date: '2025-06-30', + }; + + const pCrossSection = store.crossSection(crossSectionArg); + const pFundamentals = store.fundamentalsAsOf(fundamentalsArg); + const pEvents = store.events(eventsArg); + const pShorts = store.shortsAsOf(shortsArg); + const pMacro = store.macroAsOf(macroArg); + const pFx = store.fx(fxArg); + const pUniverse = store.universe(universeArg); + + expect(pCrossSection).toBe(daily.returnedPromises.get('crossSection') as Promise
); + expect(pFundamentals).toBe(daily.returnedPromises.get('fundamentalsAsOf') as Promise
); + expect(pEvents).toBe(daily.returnedPromises.get('events') as Promise
); + expect(pShorts).toBe(daily.returnedPromises.get('shortsAsOf') as Promise
); + expect(pMacro).toBe(daily.returnedPromises.get('macroAsOf') as Promise
); + expect(pFx).toBe(daily.returnedPromises.get('fx') as Promise
); + expect(pUniverse).toBe(daily.returnedPromises.get('universe') as Promise); + + await Promise.all([ + pCrossSection, + pFundamentals, + pEvents, + pShorts, + pMacro, + pFx, + pUniverse, + ]); + + expect(intraday.calls).toHaveLength(0); + expect(daily.calls).toHaveLength(7); + expect(daily.calls[0]).toEqual({ method: 'crossSection', arg: crossSectionArg }); + expect(daily.calls[0]?.arg).toBe(crossSectionArg); + expect(daily.calls[1]).toEqual({ method: 'fundamentalsAsOf', arg: fundamentalsArg }); + expect(daily.calls[1]?.arg).toBe(fundamentalsArg); + expect(daily.calls[2]).toEqual({ method: 'events', arg: eventsArg }); + expect(daily.calls[2]?.arg).toBe(eventsArg); + expect(daily.calls[3]).toEqual({ method: 'shortsAsOf', arg: shortsArg }); + expect(daily.calls[3]?.arg).toBe(shortsArg); + expect(daily.calls[4]).toEqual({ method: 'macroAsOf', arg: macroArg }); + expect(daily.calls[4]?.arg).toBe(macroArg); + expect(daily.calls[5]).toEqual({ method: 'fx', arg: fxArg }); + expect(daily.calls[5]?.arg).toBe(fxArg); + expect(daily.calls[6]).toEqual({ method: 'universe', arg: universeArg }); + expect(daily.calls[6]?.arg).toBe(universeArg); + }); + }); + + describe('error propagation and lazy iteration', () => { + it('propagates exact error instances for sync throws, promise rejections, and mid-iteration failures', async () => { + const syncIntradayErr = new Error('sync intraday boom'); + const syncDailyErr = new Error('sync daily boom'); + const rejectedUniverseErr = new Error('async universe boom'); + const iterErr = new Error('mid-iteration boom'); + + const baseDaily = new PrototypeDailyStore(); + const firstBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], + }; + + const dailySyncStore = createRoutedMarketDataStore({ + daily: { + bars: () => { + throw syncDailyErr; + }, + crossSection: baseDaily.crossSection.bind(baseDaily), + fundamentalsAsOf: baseDaily.fundamentalsAsOf.bind(baseDaily), + events: baseDaily.events.bind(baseDaily), + shortsAsOf: baseDaily.shortsAsOf.bind(baseDaily), + macroAsOf: baseDaily.macroAsOf.bind(baseDaily), + fx: baseDaily.fx.bind(baseDaily), + universe: () => Promise.reject(rejectedUniverseErr), + }, + intraday: { + bars: () => { + throw syncIntradayErr; + }, + }, + }); + + let caughtSyncIntraday: unknown; + try { + dailySyncStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }); + } catch (err) { + caughtSyncIntraday = err; + } + expect(caughtSyncIntraday).toBe(syncIntradayErr); + + let caughtSyncDaily: unknown; + try { + dailySyncStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }); + } catch (err) { + caughtSyncDaily = err; + } + expect(caughtSyncDaily).toBe(syncDailyErr); + + let caughtRejected: unknown; + try { + await dailySyncStore.universe({ ref: 'US_EQ', date: '2025-06-30' }); + } catch (err) { + caughtRejected = err; + } + expect(caughtRejected).toBe(rejectedUniverseErr); + + const iterFailStore = createRoutedMarketDataStore({ + daily: baseDaily, + intraday: { + bars() { + return { + async *[Symbol.asyncIterator]() { + yield firstBatch; + throw iterErr; + }, + }; + }, + }, + }); + + const received: BarBatch[] = []; + let caughtIter: unknown; + try { + for await (const batch of iterFailStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + })) { + received.push(batch); + } + } catch (err) { + caughtIter = err; + } + expect(received).toHaveLength(1); + expect(received[0]).toBe(firstBatch); + expect(caughtIter).toBe(iterErr); + }); + + it('preserves lazy iteration and closes the delegate iterator on early exit', async () => { + const batch1: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], + }; + const batch2: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 31, 0), 101)], + }; + let nextCalls = 0; + let returnCalls = 0; + + const store = createRoutedMarketDataStore({ + daily: new PrototypeDailyStore(), + intraday: { + bars() { + return { + [Symbol.asyncIterator]() { + const batches = [batch1, batch2]; + return { + async next() { + const idx = nextCalls; + nextCalls += 1; + const value = batches[idx]; + if (value === undefined) { + return { done: true as const, value: undefined }; + } + return { done: false as const, value }; + }, + async return() { + returnCalls += 1; + return { done: true as const, value: undefined }; + }, + }; + }, + }; + }, + }, + }); + + const consumed: BarBatch[] = []; + for await (const batch of store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + })) { + consumed.push(batch); + break; + } + + expect(consumed).toHaveLength(1); + expect(consumed[0]).toBe(batch1); + expect(nextCalls).toBe(1); + expect(returnCalls).toBe(1); + }); + }); + + describe('QuestDB intraday reader integration and Vault fence', () => { + const preCutoffTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; + const preCutoffTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; + const fixtureRows: readonly QuestDbFixtureRow[] = [ + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs1Us, + open: 100.0, + high: 101.0, + low: 99.5, + close: 100.5, + volume: 500, + vwap: 100.25, + known_at_us: preCutoffTs1Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs2Us, + open: 100.5, + high: 101.5, + low: 100.25, + close: 101.25, + volume: 750, + vwap: 101.0, + known_at_us: preCutoffTs2Us + 60_000_000, + }, + // Row with ts exactly at Vault cutoff (must be excluded by fence) + { + listing_id: String(LISTING_ID), + ts_us: VAULT_CUTOFF_US, + open: 102.0, + high: 103.0, + low: 101.5, + close: 102.5, + volume: 900, + vwap: 102.25, + known_at_us: preCutoffTs2Us + 60_000_000, + }, + // Row with known_at exactly at Vault cutoff (must be excluded by fence) + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs2Us + 60_000_000, + open: 101.25, + high: 102.0, + low: 101.0, + close: 101.75, + volume: 600, + vwap: 101.5, + known_at_us: VAULT_CUTOFF_US, + }, + ]; + + const straddlingQuery: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30T13:30:00Z', + to: '2025-07-05T20:00:00Z', + adjustment: 'raw', + asOf: '2025-07-10T00:00:00Z', + }; + + it('streams batches unchanged from createQuestDbIntradayBarsReader and clamps to/asOf strictly below vaultCutoffTs', async () => { + const directExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); + const directReader = createQuestDbIntradayBarsReader({ + executor: directExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + + const routedExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); + const underlyingIntraday = createQuestDbIntradayBarsReader({ + executor: routedExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + + const yieldedByIntraday: BarBatch[] = []; + const recordingIntraday: Pick = { + bars(q) { + const inner = underlyingIntraday.bars(q); + return { + async *[Symbol.asyncIterator]() { + for await (const batch of inner) { + yieldedByIntraday.push(batch); + yield batch; + } + }, + }; + }, + }; + + const daily = new PrototypeDailyStore(); + const store = createRoutedMarketDataStore({ daily, intraday: recordingIntraday }); + + const directBatches = await collectBatches(directReader.bars(straddlingQuery)); + const routedBatches = await collectBatches(store.bars(straddlingQuery)); + + expect(daily.calls).toHaveLength(0); + expect(routedExecutor.calls).toHaveLength(1); + expect(routedExecutor.calls[0]?.params[1]).toBe(CLAMPED_END_ISO); + expect(routedExecutor.calls[0]?.params[3]).toBe(CLAMPED_END_ISO); + + expect(routedBatches).toEqual(directBatches); + expect(routedBatches).toHaveLength(2); + expect(routedBatches[0]).toBe(yieldedByIntraday[0]); + expect(routedBatches[1]).toBe(yieldedByIntraday[1]); + + for (const batch of routedBatches) { + for (const row of batch.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + } + }); + + it('rejects a leaky QuestDB executor returning a row with ts or known_at at vaultCutoffTs before yielding any batch', async () => { + const tsCutoffRow = fixtureRows[2] as QuestDbFixtureRow; + const knownAtCutoffRow = fixtureRows[3] as QuestDbFixtureRow; + const preCutoffRow = fixtureRows[0] as QuestDbFixtureRow; + + for (const leakyRows of [ + [preCutoffRow, tsCutoffRow], + [preCutoffRow, knownAtCutoffRow], + ]) { + const leakyExecutor = new PredicateAwareQuestDbExecutor(leakyRows, { leaky: true }); + const intraday = createQuestDbIntradayBarsReader({ + executor: leakyExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + const store = createRoutedMarketDataStore({ + daily: new PrototypeDailyStore(), + intraday, + }); + + const yielded: BarBatch[] = []; + let caught: unknown; + try { + for await (const batch of store.bars(straddlingQuery)) { + yielded.push(batch); + } + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect(yielded).toHaveLength(0); + } + }); + }); + + describe('MCP query_data end-to-end over routed store', () => { + it('routes 1m calls to fake QuestDB and 1d calls to fake DuckDB, enforcing the Vault cutoff deterministically', async () => { + const intradayTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; + const intradayTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; + const questDbRows: readonly QuestDbFixtureRow[] = [ + { + listing_id: String(LISTING_ID), + ts_us: intradayTs1Us, + open: 100.0, + high: 100.75, + low: 99.5, + close: 100.5, + volume: 1_200, + vwap: 100.2, + known_at_us: intradayTs1Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: intradayTs2Us, + open: 100.5, + high: 101.25, + low: 100.25, + close: 101.0, + volume: 1_500, + vwap: 100.8, + known_at_us: intradayTs2Us + 60_000_000, + }, + // Out-of-fence rows at exact cutoff (filtered by predicate-aware executor) + { + listing_id: String(LISTING_ID), + ts_us: VAULT_CUTOFF_US, + open: 105.0, + high: 106.0, + low: 104.0, + close: 105.5, + volume: 2_000, + vwap: 105.2, + known_at_us: intradayTs2Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: intradayTs2Us + 60_000_000, + open: 101.0, + high: 101.5, + low: 100.75, + close: 101.25, + volume: 1_100, + vwap: 101.1, + known_at_us: VAULT_CUTOFF_US, + }, + ]; + + const dailyBarTs = Date.UTC(2025, 5, 30, 20, 0, 0, 0); + const duckDbRows: readonly TableRow[] = [ + { + listing_id: LISTING_ID, + ts: dailyBarTs, + open: 99.0, + high: 102.0, + low: 98.5, + close: 101.5, + volume: 250_000, + vwap: 100.75, + known_at: dailyBarTs, + }, + ]; + + const questExecutor = new PredicateAwareQuestDbExecutor(questDbRows); + const duckExecutor = new RecordingDuckDbExecutor(duckDbRows); + + const daily = createDuckDbMarketDataStore({ + executor: duckExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }); + const intraday = createQuestDbIntradayBarsReader({ + executor: questExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }); + const routedStore = createRoutedMarketDataStore({ daily, intraday }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: routedStore, + vaultContext: { + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }, + }), + ], + }); + + const direct1mBatches = await collectBatches( + createQuestDbIntradayBarsReader({ + executor: new PredicateAwareQuestDbExecutor(questDbRows), + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }).bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-07-05', + adjustment: 'raw', + }) + ); + const expected1mRows = direct1mBatches.flatMap(b => b.rows); + + const req1m = JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-1m', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-06-30', + to: '2025-07-05', + timeframe: '1m', + adjustment: 'raw', + }, + }, + }); + + const raw1mFirst = await server.handleMessage(req1m); + const raw1mSecond = await server.handleMessage(req1m); + expect(raw1mFirst).not.toBeNull(); + expect(raw1mSecond).toBe(raw1mFirst); + + expect(questExecutor.calls).toHaveLength(2); + expect(duckExecutor.queryCalls).toHaveLength(0); + expect(duckExecutor.runCalls).toHaveLength(0); + + const resp1m = JSON.parse(raw1mFirst as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(resp1m.result.isError).toBeUndefined(); + const payload1m = JSON.parse(resp1m.result.content[0]?.text ?? '') as QueryDataResultPayload; + expect(payload1m.rows).toEqual(expected1mRows); + expect(payload1m.rows).toHaveLength(2); + for (const row of payload1m.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + + const direct1dBatches = await collectBatches( + createDuckDbMarketDataStore({ + executor: new RecordingDuckDbExecutor(duckDbRows), + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }).bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-25', + to: '2025-07-05', + adjustment: 'raw', + }) + ); + const expected1dRows = direct1dBatches.flatMap(b => b.rows); + + const req1d = JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-1d', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-06-25', + to: '2025-07-05', + timeframe: '1d', + adjustment: 'raw', + }, + }, + }); + + const raw1dFirst = await server.handleMessage(req1d); + const raw1dSecond = await server.handleMessage(req1d); + expect(raw1dFirst).not.toBeNull(); + expect(raw1dSecond).toBe(raw1dFirst); + + expect(questExecutor.calls).toHaveLength(2); + expect(duckExecutor.queryCalls).toHaveLength(2); + + const resp1d = JSON.parse(raw1dFirst as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(resp1d.result.isError).toBeUndefined(); + const payload1d = JSON.parse(resp1d.result.content[0]?.text ?? '') as QueryDataResultPayload; + expect(payload1d.rows).toEqual(expected1dRows); + expect(payload1d.rows).toHaveLength(1); + for (const row of payload1d.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + }); + }); +}); From 4f0d16de5a8237baaee87dce2496782286aaae9f Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:24:23 -0500 Subject: [PATCH 10/26] T-148: edits made in the worktree --- libs/research/README.md | 4 ++-- libs/research/src/market-data-store-routed.ts | 8 +++++--- libs/research/test/market-data-store-routed.test.ts | 1 - 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index a65593d7..93e29a1d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -131,7 +131,7 @@ Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-r - **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick`, e.g. `createQuestDbIntradayBarsReader`). - `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars. - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`. - - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily`, `intraday`, and any MCP tool (`createQueryDataTool` / `createResearchCopilotMcpServer`) with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`: + - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily` and `intraday` with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`, and pass that same `vaultCutoffTs` to `createQueryDataTool` (which is always Vault-fenced and accepts only `{ vaultCutoffTs }`): ```ts const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); @@ -151,7 +151,7 @@ const intraday = createQuestDbIntradayBarsReader({ const store = createRoutedMarketDataStore({ daily, intraday }); const queryDataTool = createQueryDataTool({ store, - vaultContext: { vaultCutoffTs, vaultOperatorAuthorized }, + vaultContext: { vaultCutoffTs }, }); ``` diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts index c9594321..a7b52608 100644 --- a/libs/research/src/market-data-store-routed.ts +++ b/libs/research/src/market-data-store-routed.ts @@ -13,8 +13,9 @@ * enforce its own Vault holdout fence and point-in-time predicates. * - Callers MUST construct both `daily` and `intraday` with the exact same * `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same - * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`) so the holdout - * boundary is identical across timeframes. + * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`, which is + * always Vault-fenced) so the holdout boundary is identical across + * timeframes. * - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports * split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests * and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective @@ -100,9 +101,10 @@ function isIntraday1mBarsQuery(q: unknown): boolean { * vaultOperatorAuthorized, * }); * const store = createRoutedMarketDataStore({ daily, intraday }); + * // `createQueryDataTool` is always Vault-fenced and accepts only `vaultCutoffTs`. * const queryDataTool = createQueryDataTool({ * store, - * vaultContext: { vaultCutoffTs, vaultOperatorAuthorized }, + * vaultContext: { vaultCutoffTs }, * }); * ``` */ diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts index 1a7c4e90..81b38fb6 100644 --- a/libs/research/test/market-data-store-routed.test.ts +++ b/libs/research/test/market-data-store-routed.test.ts @@ -985,7 +985,6 @@ describe('createRoutedMarketDataStore', () => { store: routedStore, vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, }, }), ], From 0204f2eff695f3cfe4e5d740c24f29c652e09916 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 23:38:56 -0500 Subject: [PATCH 11/26] =?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 12/26] 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 13/26] =?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 14/26] =?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 15/26] =?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 16/26] =?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 17/26] 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 18/26] =?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 19/26] 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 20/26] =?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, From c16d6b3f603870b9bd5afc0fa7648a278cd567d2 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:12:13 -0500 Subject: [PATCH 21/26] =?UTF-8?q?T-151:=20M2.1i=20=E2=80=94=20`findings`?= =?UTF-8?q?=20+=20`provider=5Fcaveats`=20append-only=20PostgreSQL=20migrat?= =?UTF-8?q?ion=20(research=20track,=20`37-research-findings.sql`)=20with?= =?UTF-8?q?=20fresh-database=20schema=20tests=20(no=20adapters,=20no=20new?= =?UTF-8?q?=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../postgres/init/37-research-findings.sql | 85 +++ design/DATA-CONTRACTS.md | 59 +++ libs/data/postgres/src/migrations.ts | 1 + test/postgres/fresh-database-schema.test.ts | 15 +- test/postgres/migration-runner.test.ts | 17 +- .../postgres/research-findings-schema.test.ts | 495 ++++++++++++++++++ .../postgres/security-master-contract.test.ts | 11 +- 7 files changed, 672 insertions(+), 11 deletions(-) create mode 100644 database/postgres/init/37-research-findings.sql create mode 100644 test/postgres/research-findings-schema.test.ts diff --git a/database/postgres/init/37-research-findings.sql b/database/postgres/init/37-research-findings.sql new file mode 100644 index 00000000..ac9d156f --- /dev/null +++ b/database/postgres/init/37-research-findings.sql @@ -0,0 +1,85 @@ +-- Research findings & provider caveats schema (M2.1i) +-- Research track migration: creates append-only findings and provider_caveats tables, +-- lookup/idempotency indexes, and immutability triggers reusing +-- reject_research_evidence_mutation() from 17-research-retention.sql. + +CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER) +RETURNS BOOLEAN +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + SELECT COALESCE(array_ndims(refs), 1) = 1 + AND NOT EXISTS ( + SELECT 1 + FROM unnest(refs) AS r + WHERE r IS NULL + OR char_length(r) > max_len + ); +$$; + +CREATE TABLE IF NOT EXISTS findings ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + kind TEXT NOT NULL + CHECK (kind IN ('finding', 'dead_end')), + title TEXT NOT NULL + CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256), + summary TEXT NOT NULL + CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096), + status TEXT NOT NULL DEFAULT 'pending_review' + CHECK (status ~ '\S'), + created_at TIMESTAMPTZ NOT NULL, + trial_refs TEXT[] NOT NULL + CHECK (cardinality(trial_refs) <= 32) + CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) + CHECK (research_finding_refs_valid(trial_refs, 256)), + evidence_refs TEXT[] NOT NULL + CHECK (cardinality(evidence_refs) <= 32) + CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) + CHECK (research_finding_refs_valid(evidence_refs, 256)), + idempotency_key TEXT + CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128)) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key + ON findings (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_findings_created_at + ON findings (created_at); + +CREATE TABLE IF NOT EXISTS provider_caveats ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + provider TEXT NOT NULL + CHECK (provider ~ '\S'), + dataset TEXT NOT NULL + CHECK (dataset ~ '\S'), + caveat TEXT NOT NULL + CHECK (caveat ~ '\S'), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider + ON provider_caveats (lower(provider)); + +DROP TRIGGER IF EXISTS findings_retained ON findings; +CREATE TRIGGER findings_retained + BEFORE UPDATE OR DELETE ON findings + FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS findings_no_truncate ON findings; +CREATE TRIGGER findings_no_truncate + BEFORE TRUNCATE ON findings + FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS provider_caveats_retained ON provider_caveats; +CREATE TRIGGER provider_caveats_retained + BEFORE UPDATE OR DELETE ON provider_caveats + FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS provider_caveats_no_truncate ON provider_caveats; +CREATE TRIGGER provider_caveats_no_truncate + BEFORE TRUNCATE ON provider_caveats + FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 278c1999..e119ac72 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -194,6 +194,65 @@ The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD 2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings). 3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols). +### Research Knowledge & Findings Schema (PostgreSQL, Append-Only) + +Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables). + +- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`. +- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt. +- **Character-length convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. + +```sql +CREATE TABLE IF NOT EXISTS findings ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + kind TEXT NOT NULL + CHECK (kind IN ('finding', 'dead_end')), + title TEXT NOT NULL + CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256), + summary TEXT NOT NULL + CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096), + status TEXT NOT NULL DEFAULT 'pending_review' + CHECK (status ~ '\S'), + created_at TIMESTAMPTZ NOT NULL, + trial_refs TEXT[] NOT NULL + CHECK (cardinality(trial_refs) <= 32) + CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) + CHECK (research_finding_refs_valid(trial_refs, 256)), + evidence_refs TEXT[] NOT NULL + CHECK (cardinality(evidence_refs) <= 32) + CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) + CHECK (research_finding_refs_valid(evidence_refs, 256)), + idempotency_key TEXT + CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128)) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key + ON findings (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_findings_created_at + ON findings (created_at); + +CREATE TABLE IF NOT EXISTS provider_caveats ( + id TEXT PRIMARY KEY + CHECK (id ~ '\S'), + provider TEXT NOT NULL + CHECK (provider ~ '\S'), + dataset TEXT NOT NULL + CHECK (dataset ~ '\S'), + caveat TEXT NOT NULL + CHECK (caveat ~ '\S'), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider + ON provider_caveats (lower(provider)); +``` + +- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer. +- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`. + --- ## 3. Curated Storage Schemas diff --git a/libs/data/postgres/src/migrations.ts b/libs/data/postgres/src/migrations.ts index 1f05331a..1fa68e3c 100644 --- a/libs/data/postgres/src/migrations.ts +++ b/libs/data/postgres/src/migrations.ts @@ -45,6 +45,7 @@ const RESEARCH_FILES = new Set([ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]); function locateMigrationsDir(): string { diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts index df95c7b7..8bfb3325 100644 --- a/test/postgres/fresh-database-schema.test.ts +++ b/test/postgres/fresh-database-schema.test.ts @@ -78,6 +78,7 @@ const RESEARCH_FILES = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]; const cleanup: (() => Promise | void)[] = []; @@ -138,13 +139,13 @@ async function createIsolatedFixture() { } describe.skipIf(!url)('fresh PostgreSQL database schema', () => { - test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { + test('Case A: init SQL 01-37 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { const f = await createIsolatedFixture(); const sqlFiles = readdirSync(initDir) .filter(file => file.endsWith('.sql')) .sort(); - expect(sqlFiles.length).toBeGreaterThanOrEqual(36); + expect(sqlFiles.length).toBeGreaterThanOrEqual(37); for (const file of sqlFiles) { const sql = readFileSync(join(initDir, file), 'utf8'); @@ -159,7 +160,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { ...LEGACY_MASTER_TABLES, // Security master tables (34) ...SECURITY_MASTER_TABLES, - // Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36) + // Research tables (06-33, 36-37, including representatives from 12, 16, 20, 22, 28, 30, 36, 37) 'backtests', 'backtest_results', 'runs', @@ -171,6 +172,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { 'paper_deployments', 'trial_ledger', 'vault_evaluations', + 'findings', + 'provider_caveats', ]) { expect(createdTables.has(expectedTable)).toBe(true); } @@ -193,6 +196,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(false); expect(createdTables.has('vault_evaluations')).toBe(false); + expect(createdTables.has('findings')).toBe(false); + expect(createdTables.has('provider_caveats')).toBe(false); expect(await f.hasColumn('exchanges', 'visible')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'master' }); @@ -200,7 +205,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { expect(await f.recorded()).toEqual(MASTER_FILES); }); - test('Case C: all track with 06-08 pre-applied records master + research (including 36) and never records 06-08', async () => { + test('Case C: all track with 06-08 pre-applied records master + research (including 36-37) and never records 06-08', async () => { const f = await createIsolatedFixture(); for (const file of BOOTSTRAP_FILES) { @@ -223,6 +228,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(true); expect(createdTables.has('vault_evaluations')).toBe(true); + expect(createdTables.has('findings')).toBe(true); + expect(createdTables.has('provider_caveats')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'all' }); expect(second).toEqual([]); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 6b43c3d3..0e87eebb 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -37,6 +37,7 @@ const migrations = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { @@ -384,17 +385,22 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { ]; // 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql, - // and MUST apply 36-trial-ledger.sql; master track applies 34-35 (not 36) and is idempotent on re-run. + // and MUST apply 36-trial-ledger.sql and 37-research-findings.sql; master track applies 34-35 (not 36-37) and is idempotent on re-run. const f1 = await fixture(); const runner1 = f1.startup(); const researchApplied = await runner1.runTrack('research'); expect(researchApplied).not.toContain('34-security-master.sql'); expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql'); expect(researchApplied).toContain('36-trial-ledger.sql'); + expect(researchApplied).toContain('37-research-findings.sql'); + expect(researchApplied.indexOf('37-research-findings.sql')).toBe( + researchApplied.indexOf('36-trial-ledger.sql') + 1 + ); const recordedAfterResearch = await f1.recorded(); expect(recordedAfterResearch).not.toContain('34-security-master.sql'); expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterResearch).toContain('36-trial-ledger.sql'); + expect(recordedAfterResearch).toContain('37-research-findings.sql'); const tablesAfterResearch = new Set(await f1.relations()); for (const table of securityMasterTables) { @@ -402,11 +408,14 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterResearch.has('trial_ledger')).toBe(true); expect(tablesAfterResearch.has('vault_evaluations')).toBe(true); + expect(tablesAfterResearch.has('findings')).toBe(true); + expect(tablesAfterResearch.has('provider_caveats')).toBe(true); const masterApplied = await runner1.runTrack('master'); expect(masterApplied).toContain('34-security-master.sql'); expect(masterApplied).toContain('35-security-master-exchange-seed.sql'); expect(masterApplied).not.toContain('36-trial-ledger.sql'); + expect(masterApplied).not.toContain('37-research-findings.sql'); expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe( masterApplied.indexOf('34-security-master.sql') + 1 ); @@ -421,7 +430,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(await runner1.runTrack('master')).toEqual([]); - // 2. all track applies 34, 35, and 36 alongside 01-05 and 09-33 and is idempotent. + // 2. all track applies 34, 35, 36, and 37 alongside 01-05 and 09-33 and is idempotent. const f2 = await fixture(); const runner2 = f2.startup(); const allApplied = await runner2.runTrack('all'); @@ -432,10 +441,12 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(allApplied).toContain('34-security-master.sql'); expect(allApplied).toContain('35-security-master-exchange-seed.sql'); expect(allApplied).toContain('36-trial-ledger.sql'); + expect(allApplied).toContain('37-research-findings.sql'); const recordedAfterAll = await f2.recorded(); expect(recordedAfterAll).toContain('34-security-master.sql'); expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterAll).toContain('36-trial-ledger.sql'); + expect(recordedAfterAll).toContain('37-research-findings.sql'); const tablesAfterAll = new Set(await f2.relations()); for (const table of securityMasterTables) { @@ -443,6 +454,8 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterAll.has('trial_ledger')).toBe(true); expect(tablesAfterAll.has('vault_evaluations')).toBe(true); + expect(tablesAfterAll.has('findings')).toBe(true); + expect(tablesAfterAll.has('provider_caveats')).toBe(true); expect(await runner2.runTrack('all')).toEqual([]); }); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts new file mode 100644 index 00000000..651f2882 --- /dev/null +++ b/test/postgres/research-findings-schema.test.ts @@ -0,0 +1,495 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('research-findings-schema-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const researchFindingsSqlPath = `${initDir}37-research-findings.sql`; + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; +const EXPECTED_IMMUTABLE_MSG = /Retained research evidence cannot be rewritten or deleted/; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { pool, schema, postgres }; +} + +async function expectPgErrorCode( + operation: Promise, + expectedCode: string, + messagePattern?: RegExp +): Promise { + try { + await operation; + } catch (error) { + const pgError = error as { code?: string; message?: string } | null; + expect(pgError?.code).toBe(expectedCode); + if (messagePattern) { + expect(pgError?.message ?? '').toMatch(messagePattern); + } + return; + } + throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); +} + +interface FindingInsertOverrides { + id?: string; + kind?: string; + title?: string; + summary?: string; + status?: string; + createdAt?: string; + trialRefs?: (string | null)[]; + evidenceRefs?: (string | null)[]; + idempotencyKey?: string | null; +} + +function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) { + const id = overrides.id ?? `finding-${randomUUID()}`; + const kind = overrides.kind ?? 'finding'; + const title = overrides.title ?? 'Momentum factor decays after 5 sessions'; + const summary = overrides.summary ?? 'Cross-sectional rank IC turns negative past day 5.'; + const createdAt = overrides.createdAt ?? FIXED_TS; + const trialRefs = overrides.trialRefs ?? ['101', '102']; + const evidenceRefs = overrides.evidenceRefs ?? ['snap:2026-01-15:ic']; + const idempotencyKey = overrides.idempotencyKey === undefined ? null : overrides.idempotencyKey; + + if (overrides.status !== undefined) { + return pool.query( + `INSERT INTO findings ( + id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key + ) VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9) + RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, + [id, kind, title, summary, overrides.status, createdAt, trialRefs, evidenceRefs, idempotencyKey] + ); + } + + return pool.query( + `INSERT INTO findings ( + id, kind, title, summary, created_at, trial_refs, evidence_refs, idempotency_key + ) VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[], $8) + RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, + [id, kind, title, summary, createdAt, trialRefs, evidenceRefs, idempotencyKey] + ); +} + +interface ProviderCaveatInsertOverrides { + id?: string; + provider?: string; + dataset?: string; + caveat?: string; + createdAt?: string; +} + +function insertProviderCaveat(pool: Pool, overrides: ProviderCaveatInsertOverrides = {}) { + const id = overrides.id ?? `caveat-${randomUUID()}`; + const provider = overrides.provider ?? 'EODHD'; + const dataset = overrides.dataset ?? 'eodIntraday1M'; + const caveat = + overrides.caveat ?? 'Intraday 1m OHLCV is retroactively split-adjusted; un-adjust before use.'; + + if (overrides.createdAt !== undefined) { + return pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ($1, $2, $3, $4, $5::timestamptz) + RETURNING id, provider, dataset, caveat, created_at`, + [id, provider, dataset, caveat, overrides.createdAt] + ); + } + + return pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat) + VALUES ($1, $2, $3, $4) + RETURNING id, provider, dataset, caveat, created_at`, + [id, provider, dataset, caveat] + ); +} + +interface ProtectionTriggerRow { + relname: string; + tgname: string; + proname: string; + tgenabled: string; +} + +const EXPECTED_PROTECTION_TRIGGERS: ProtectionTriggerRow[] = [ + { + relname: 'findings', + tgname: 'findings_no_truncate', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, + { + relname: 'findings', + tgname: 'findings_retained', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, + { + relname: 'provider_caveats', + tgname: 'provider_caveats_no_truncate', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, + { + relname: 'provider_caveats', + tgname: 'provider_caveats_retained', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, +]; + +async function listProtectionTriggers(pool: Pool, schema: string): Promise { + const result = await pool.query( + `SELECT c.relname, t.tgname, p.proname, t.tgenabled::text AS tgenabled + FROM pg_trigger t + JOIN pg_class c ON c.oid = t.tgrelid + JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_proc p ON p.oid = t.tgfoid + WHERE NOT t.tgisinternal + AND n.nspname = $1 + AND c.relname IN ('findings', 'provider_caveats') + ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`, + [schema] + ); + return result.rows; +} + +describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { + test('creates tables, indexes, and triggers and is idempotent on runner re-run and raw SQL re-execution', async () => { + const f = await createIsolatedFixture(); + + const tables = new Set( + ( + await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema]) + ).rows.map(row => row.tablename as string) + ); + expect(tables.has('findings')).toBe(true); + expect(tables.has('provider_caveats')).toBe(true); + + const indexDefs = new Map( + ( + await f.pool.query('SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = $1', [ + f.schema, + ]) + ).rows.map(row => [row.indexname as string, row.indexdef as string]) + ); + expect(indexDefs.get('idx_findings_idempotency_key')).toMatch( + /CREATE UNIQUE INDEX idx_findings_idempotency_key ON .*findings .* \(idempotency_key\) WHERE \(idempotency_key IS NOT NULL\)/ + ); + expect(indexDefs.get('idx_findings_created_at')).toMatch( + /CREATE INDEX idx_findings_created_at ON .*findings .* \(created_at\)/ + ); + expect(indexDefs.get('idx_provider_caveats_lower_provider')).toMatch( + /CREATE INDEX idx_provider_caveats_lower_provider ON .*provider_caveats .* \(lower\(provider\)\)/ + ); + + expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); + + const insertedFinding = ( + await insertFinding(f.pool, { id: 'f-idempotent', idempotencyKey: 'idem-keep' }) + ).rows[0]; + const insertedCaveat = ( + await insertProviderCaveat(f.pool, { id: 'c-idempotent', createdAt: FIXED_TS }) + ).rows[0]; + + expect(await runPostgresMigrations(f.postgres, { track: 'research' })).toEqual([]); + + const rawSql = readFileSync(researchFindingsSqlPath, 'utf8'); + await f.pool.query(rawSql); + + expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); + + const findingsAfter = (await f.pool.query('SELECT * FROM findings')).rows; + const caveatsAfter = (await f.pool.query('SELECT * FROM provider_caveats')).rows; + expect(findingsAfter).toEqual([insertedFinding]); + expect(caveatsAfter).toEqual([insertedCaveat]); + + await expectPgErrorCode( + f.pool.query("UPDATE findings SET title = 'mutated'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); + await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); + + await expectPgErrorCode( + f.pool.query("UPDATE provider_caveats SET caveat = 'mutated'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('DELETE FROM provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('TRUNCATE provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + + expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([insertedFinding]); + expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([insertedCaveat]); + }); + + test('findings round-trips every FiledFindingRecord field, defaults status, and accepts exact limit boundaries', async () => { + const f = await createIsolatedFixture(); + + const first = ( + await insertFinding(f.pool, { + id: 'finding-001', + kind: 'finding', + title: 'Earnings drift persists through day 3', + summary: 'Post-announcement drift remains positive across US large caps.', + createdAt: FIXED_TS, + trialRefs: ['42', '43'], + evidenceRefs: ['artifact:drift-v1'], + idempotencyKey: 'req-001', + }) + ).rows[0]; + + expect(first.id).toBe('finding-001'); + expect(first.kind).toBe('finding'); + expect(first.title).toBe('Earnings drift persists through day 3'); + expect(first.summary).toBe('Post-announcement drift remains positive across US large caps.'); + expect(first.status).toBe('pending_review'); + expect((first.created_at as Date).toISOString()).toBe(FIXED_TS); + expect(first.trial_refs).toEqual(['42', '43']); + expect(first.evidence_refs).toEqual(['artifact:drift-v1']); + expect(first.idempotency_key).toBe('req-001'); + + // Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities. + const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r')); + const boundary = ( + await insertFinding(f.pool, { + id: 'finding-002', + kind: 'dead_end', + title: ` ${'t'.repeat(256)} `, + summary: 's'.repeat(4096), + createdAt: '2026-02-01T00:00:00.000Z', + trialRefs: maxRefs, + evidenceRefs: [], + idempotencyKey: 'k'.repeat(128), + }) + ).rows[0]; + + expect(boundary.kind).toBe('dead_end'); + expect(boundary.status).toBe('pending_review'); + expect((boundary.created_at as Date).toISOString()).toBe('2026-02-01T00:00:00.000Z'); + expect(boundary.trial_refs).toEqual(maxRefs); + expect(boundary.evidence_refs).toEqual([]); + expect(boundary.idempotency_key).toBe('k'.repeat(128)); + + // 32 evidence_refs at 256 chars and 1-char idempotency key also succeed. + const maxEvidence = ( + await insertFinding(f.pool, { + id: 'finding-003', + trialRefs: [], + evidenceRefs: maxRefs, + idempotencyKey: 'x', + }) + ).rows[0]; + expect(maxEvidence.trial_refs).toEqual([]); + expect(maxEvidence.evidence_refs).toEqual(maxRefs); + expect(maxEvidence.idempotency_key).toBe('x'); + }); + + test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => { + const f = await createIsolatedFixture(); + + // Blank / whitespace-only id and status + await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514'); + + // Invalid kind + await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514'); + + // Blank, whitespace-only, or oversized title / summary + await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514'); + + // Cardinality > 32 + const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`); + await expectPgErrorCode(insertFinding(f.pool, { trialRefs: refs33 }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: refs33 }), '23514'); + + // Ref length > 256 + const ref257 = 'r'.repeat(257); + await expectPgErrorCode(insertFinding(f.pool, { trialRefs: [ref257] }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: ['ok', ref257] }), '23514'); + + // NULL array elements + await expectPgErrorCode(insertFinding(f.pool, { trialRefs: ['101', null] }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: [null] }), '23514'); + + // Multidimensional arrays + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) + VALUES ('f-2d-trial', 'finding', 'Title', 'Summary', $1::timestamptz, '{{a,b},{c,d}}'::text[], '{}'::text[])`, + [FIXED_TS] + ), + '23514' + ); + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) + VALUES ('f-2d-ev', 'finding', 'Title', 'Summary', $1::timestamptz, '{101}'::text[], '{{a,b},{c,d}}'::text[])`, + [FIXED_TS] + ), + '23514' + ); + + // Invalid idempotency_key (empty, whitespace-only, > 128 chars) + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514'); + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); + }); + + test('findings enforces unique non-NULL idempotency_key while allowing multiple NULL keys', async () => { + const f = await createIsolatedFixture(); + + await insertFinding(f.pool, { id: 'f-key-1', idempotencyKey: 'shared-key' }); + await expectPgErrorCode( + insertFinding(f.pool, { id: 'f-key-2', idempotencyKey: 'shared-key' }), + '23505' + ); + + await insertFinding(f.pool, { id: 'f-null-1', idempotencyKey: null }); + await insertFinding(f.pool, { id: 'f-null-2', idempotencyKey: null }); + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); + }); + + test('provider_caveats round-trips every ProviderCaveatRecord field, defaults created_at, and rejects blank fields', async () => { + const f = await createIsolatedFixture(); + + const explicit = ( + await insertProviderCaveat(f.pool, { + id: 'caveat-001', + provider: 'QuoteMedia', + dataset: 'qmSplits', + caveat: 'splitratio stores old_shares / new_shares; invert to canonical new / old.', + createdAt: FIXED_TS, + }) + ).rows[0]; + + expect(explicit.id).toBe('caveat-001'); + expect(explicit.provider).toBe('QuoteMedia'); + expect(explicit.dataset).toBe('qmSplits'); + expect(explicit.caveat).toBe( + 'splitratio stores old_shares / new_shares; invert to canonical new / old.' + ); + expect((explicit.created_at as Date).toISOString()).toBe(FIXED_TS); + + const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0]; + expect(defaulted.created_at).toBeInstanceOf(Date); + + for (const blank of ['', ' ', '\t\n\r']) { + await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514'); + await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514'); + await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514'); + await expectPgErrorCode(insertProviderCaveat(f.pool, { caveat: blank }), '23514'); + } + + expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( + 2 + ); + }); + + test('UPDATE, DELETE, and TRUNCATE are blocked on both findings and provider_caveats', async () => { + const f = await createIsolatedFixture(); + + const findingBefore = (await insertFinding(f.pool, { id: 'f-immutable' })).rows[0]; + const caveatBefore = ( + await insertProviderCaveat(f.pool, { id: 'c-immutable', createdAt: FIXED_TS }) + ).rows[0]; + + await expectPgErrorCode( + f.pool.query("UPDATE findings SET status = 'approved'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); + await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); + + await expectPgErrorCode( + f.pool.query("UPDATE provider_caveats SET provider = 'Other'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('DELETE FROM provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('TRUNCATE provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + + expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([findingBefore]); + expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([caveatBefore]); + }); +}); diff --git a/test/postgres/security-master-contract.test.ts b/test/postgres/security-master-contract.test.ts index eb140bb2..292bca21 100644 --- a/test/postgres/security-master-contract.test.ts +++ b/test/postgres/security-master-contract.test.ts @@ -274,12 +274,13 @@ describe('34-security-master.sql track registration', () => { expect(await runPostgresMigrations(postgres as never)).toEqual(research); }); - test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => { + test('all track runs 33, 34, 35, 36, 37 last in exact order and skips 06-08', async () => { const all = await filesForTrack('all'); - expect(all.at(-4)).toBe('33-candidate-decimal-normalization.sql'); - expect(all.at(-3)).toBe('34-security-master.sql'); - expect(all.at(-2)).toBe('35-security-master-exchange-seed.sql'); - expect(all.at(-1)).toBe('36-trial-ledger.sql'); + expect(all.at(-5)).toBe('33-candidate-decimal-normalization.sql'); + expect(all.at(-4)).toBe('34-security-master.sql'); + expect(all.at(-3)).toBe('35-security-master-exchange-seed.sql'); + expect(all.at(-2)).toBe('36-trial-ledger.sql'); + expect(all.at(-1)).toBe('37-research-findings.sql'); for (const bootstrap of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', From 310354b54a7ac1bf455d56c3cffbcdecf23c8ff7 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:19:26 -0500 Subject: [PATCH 22/26] =?UTF-8?q?T-151:=20M2.1i=20=E2=80=94=20`findings`?= =?UTF-8?q?=20+=20`provider=5Fcaveats`=20append-only=20PostgreSQL=20migrat?= =?UTF-8?q?ion=20(research=20track,=20`37-research-findings.sql`)=20with?= =?UTF-8?q?=20fresh-database=20schema=20tests=20(no=20adapters,=20no=20new?= =?UTF-8?q?=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../postgres/init/37-research-findings.sql | 32 +++++++---- design/DATA-CONTRACTS.md | 20 +++---- .../postgres/research-findings-schema.test.ts | 54 +++++++++++++++---- 3 files changed, 77 insertions(+), 29 deletions(-) diff --git a/database/postgres/init/37-research-findings.sql b/database/postgres/init/37-research-findings.sql index ac9d156f..b4c800ac 100644 --- a/database/postgres/init/37-research-findings.sql +++ b/database/postgres/init/37-research-findings.sql @@ -3,6 +3,20 @@ -- lookup/idempotency indexes, and immutability triggers reusing -- reject_research_evidence_mutation() from 17-research-retention.sql. +CREATE OR REPLACE FUNCTION research_trim_ecmascript(value TEXT) +RETURNS TEXT +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + -- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and + -- trimmed length caps match String.prototype.trim() regardless of DB collation. + SELECT btrim( + value, + U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF' + ); +$$; + CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER) RETURNS BOOLEAN LANGUAGE SQL @@ -20,15 +34,15 @@ $$; CREATE TABLE IF NOT EXISTS findings ( id TEXT PRIMARY KEY - CHECK (id ~ '\S'), + CHECK (research_trim_ecmascript(id) <> ''), kind TEXT NOT NULL CHECK (kind IN ('finding', 'dead_end')), title TEXT NOT NULL - CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256), + CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), summary TEXT NOT NULL - CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096), + CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), status TEXT NOT NULL DEFAULT 'pending_review' - CHECK (status ~ '\S'), + CHECK (research_trim_ecmascript(status) <> ''), created_at TIMESTAMPTZ NOT NULL, trial_refs TEXT[] NOT NULL CHECK (cardinality(trial_refs) <= 32) @@ -39,7 +53,7 @@ CREATE TABLE IF NOT EXISTS findings ( CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) CHECK (research_finding_refs_valid(evidence_refs, 256)), idempotency_key TEXT - CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128)) + CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) ); CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key @@ -51,13 +65,13 @@ CREATE INDEX IF NOT EXISTS idx_findings_created_at CREATE TABLE IF NOT EXISTS provider_caveats ( id TEXT PRIMARY KEY - CHECK (id ~ '\S'), + CHECK (research_trim_ecmascript(id) <> ''), provider TEXT NOT NULL - CHECK (provider ~ '\S'), + CHECK (research_trim_ecmascript(provider) <> ''), dataset TEXT NOT NULL - CHECK (dataset ~ '\S'), + CHECK (research_trim_ecmascript(dataset) <> ''), caveat TEXT NOT NULL - CHECK (caveat ~ '\S'), + CHECK (research_trim_ecmascript(caveat) <> ''), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index e119ac72..837da47a 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -200,20 +200,20 @@ Applied via `@stock-bot/postgres` (`research` migration track, `database/postgre - **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`. - **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt. -- **Character-length convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. +- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. ```sql CREATE TABLE IF NOT EXISTS findings ( id TEXT PRIMARY KEY - CHECK (id ~ '\S'), + CHECK (research_trim_ecmascript(id) <> ''), kind TEXT NOT NULL CHECK (kind IN ('finding', 'dead_end')), title TEXT NOT NULL - CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256), + CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), summary TEXT NOT NULL - CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096), + CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), status TEXT NOT NULL DEFAULT 'pending_review' - CHECK (status ~ '\S'), + CHECK (research_trim_ecmascript(status) <> ''), created_at TIMESTAMPTZ NOT NULL, trial_refs TEXT[] NOT NULL CHECK (cardinality(trial_refs) <= 32) @@ -224,7 +224,7 @@ CREATE TABLE IF NOT EXISTS findings ( CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) CHECK (research_finding_refs_valid(evidence_refs, 256)), idempotency_key TEXT - CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128)) + CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) ); CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key @@ -236,13 +236,13 @@ CREATE INDEX IF NOT EXISTS idx_findings_created_at CREATE TABLE IF NOT EXISTS provider_caveats ( id TEXT PRIMARY KEY - CHECK (id ~ '\S'), + CHECK (research_trim_ecmascript(id) <> ''), provider TEXT NOT NULL - CHECK (provider ~ '\S'), + CHECK (research_trim_ecmascript(provider) <> ''), dataset TEXT NOT NULL - CHECK (dataset ~ '\S'), + CHECK (research_trim_ecmascript(dataset) <> ''), caveat TEXT NOT NULL - CHECK (caveat ~ '\S'), + CHECK (research_trim_ecmascript(caveat) <> ''), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts index 651f2882..18c75c16 100644 --- a/test/postgres/research-findings-schema.test.ts +++ b/test/postgres/research-findings-schema.test.ts @@ -29,16 +29,26 @@ async function createIsolatedFixture() { const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ - connectionString: url, - options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, - }); + const poolUrl = new URL(url); + const existingOptions = poolUrl.searchParams.get('options')?.trim(); + const fixtureOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + poolUrl.searchParams.set( + 'options', + existingOptions ? `${existingOptions} ${fixtureOptions}` : fixtureOptions + ); + const pool = new Pool({ connectionString: poolUrl.toString() }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); + const activeSchema = (await pool.query<{ schema: string }>('SELECT current_schema() AS schema')) + .rows[0]?.schema; + if (activeSchema !== schema) { + throw new Error(`Expected active fixture schema ${schema}, got ${activeSchema ?? 'null'}`); + } + // Bootstrap pre-additive tables needed by the research migration track. for (const filename of [ '06-create-backtest-tables.sql', @@ -308,14 +318,15 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { expect(first.evidence_refs).toEqual(['artifact:drift-v1']); expect(first.idempotency_key).toBe('req-001'); - // Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities. + // Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities + // including Unicode NBSP / ideographic-space padding around max-length title and summary. const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r')); const boundary = ( await insertFinding(f.pool, { id: 'finding-002', kind: 'dead_end', - title: ` ${'t'.repeat(256)} `, - summary: 's'.repeat(4096), + title: `\u00A0${'t'.repeat(256)}\u00A0`, + summary: `\u00A0\u3000${'s'.repeat(4096)}\u00A0`, createdAt: '2026-02-01T00:00:00.000Z', trialRefs: maxRefs, evidenceRefs: [], @@ -347,24 +358,37 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => { const f = await createIsolatedFixture(); - // Blank / whitespace-only id and status + // Blank / whitespace-only (ASCII and ECMAScript Unicode) id and status + const unicodeBlanks = ['\u00A0', '\u00A0\u2003\u3000\uFEFF', '\u2028\u2029']; await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514'); + for (const blank of unicodeBlanks) { + await expectPgErrorCode(insertFinding(f.pool, { id: blank }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { status: blank }), '23514'); + } // Invalid kind await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514'); - // Blank, whitespace-only, or oversized title / summary + // Blank, whitespace-only (ASCII and ECMAScript Unicode), or oversized title / summary await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514'); + await expectPgErrorCode( + insertFinding(f.pool, { title: `\u00A0${'t'.repeat(257)}\u00A0` }), + '23514' + ); await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514'); + for (const blank of unicodeBlanks) { + await expectPgErrorCode(insertFinding(f.pool, { title: blank }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: blank }), '23514'); + } // Cardinality > 32 const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`); @@ -401,6 +425,9 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { // Invalid idempotency_key (empty, whitespace-only, > 128 chars) await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514'); await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514'); + for (const blank of unicodeBlanks) { + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: blank }), '23514'); + } await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514'); expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); @@ -445,7 +472,14 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0]; expect(defaulted.created_at).toBeInstanceOf(Date); - for (const blank of ['', ' ', '\t\n\r']) { + for (const blank of [ + '', + ' ', + '\t\n\r', + '\u00A0', + '\u00A0\u2003\u3000\uFEFF', + '\u2028\u2029', + ]) { await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514'); await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514'); await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514'); From 8816fca221728d37740235967e0f55f9009ceb32 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:25:49 -0500 Subject: [PATCH 23/26] T-151: tests --- .../research-findings-contract.test.ts | 180 ++++++++++++++++++ .../postgres/research-findings-schema.test.ts | 173 ++++++++++++++++- 2 files changed, 352 insertions(+), 1 deletion(-) create mode 100644 test/postgres/research-findings-contract.test.ts diff --git a/test/postgres/research-findings-contract.test.ts b/test/postgres/research-findings-contract.test.ts new file mode 100644 index 00000000..36c9d2e3 --- /dev/null +++ b/test/postgres/research-findings-contract.test.ts @@ -0,0 +1,180 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { setLoggerConfig } from '@stock-bot/logger'; +import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres'; +import { + FILE_FINDING_INITIAL_STATUS, + FILE_FINDING_KINDS, + FILE_FINDING_MAX_EVIDENCE_REFS, + FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + FILE_FINDING_MAX_REF_LENGTH, + FILE_FINDING_MAX_SUMMARY_LENGTH, + FILE_FINDING_MAX_TITLE_LENGTH, + FILE_FINDING_MAX_TRIAL_REFS, +} from '@stock-bot/research/mcp'; + +// Static contract checks for 37-research-findings.sql. No database needed, so these run in the +// sandbox as well as in Studio's unsandboxed run. They guard against drift between the SQL CHECKs, +// the MCP tool limits they mirror, and the design/DATA-CONTRACTS.md copy of the schema. + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); + +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const sqlPath = `${initDir}37-research-findings.sql`; +const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url)); + +const readSql = () => readFileSync(sqlPath, 'utf8'); +const readDoc = () => readFileSync(docPath, 'utf8'); + +function stripComments(sql: string): string { + return sql + .split('\n') + .map(line => line.replace(/--.*$/, '').trimEnd()) + .join('\n'); +} + +function normalize(sql: string): string { + return stripComments(sql).replace(/\s+/g, ' ').trim(); +} + +function tableBlock(sql: string, table: string): string { + const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec( + stripComments(sql) + ); + if (!match?.[1]) { + throw new Error(`CREATE TABLE ${table} not found`); + } + return match[1].replace(/\s+/g, ' ').trim(); +} + +function docSqlBlock(): string { + const doc = readDoc(); + const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS findings ('); + expect(tableStart).toBeGreaterThan(-1); + const fenceStart = doc.lastIndexOf('```sql', tableStart); + const fenceEnd = doc.indexOf('```', tableStart); + return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim(); +} + +function trimCodePointsFromSql(): number[] { + const match = /U&'([^']*)'/.exec(stripComments(readSql())); + if (!match?.[1]) { + throw new Error('research_trim_ecmascript U& character set not found'); + } + return match[1] + .split('\\') + .filter(part => part.length > 0) + .map(part => { + expect(part).toMatch(/^[0-9A-F]{4}$/i); + return Number.parseInt(part, 16); + }); +} + +async function filesForTrack(track: MigrationTrack): Promise { + const postgres = { + transaction: async (callback: (client: { query: (sql: string) => unknown }) => Promise) => + callback({ query: async () => ({ rows: [] }) }), + }; + return runPostgresMigrations(postgres as never, { track }); +} + +describe('37-research-findings.sql static contract', () => { + test('creates exactly findings and provider_caveats with IF NOT EXISTS and no schema qualifiers', () => { + const sql = stripComments(readSql()); + const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)]; + expect(created.map(m => m[2])).toEqual(['findings', 'provider_caveats']); + expect(created.every(m => m[1] !== undefined)).toBe(true); + expect(sql).not.toMatch(/CREATE\s+DATABASE/i); + expect(sql).not.toMatch(/^\s*\\c\b/m); + expect(sql).not.toMatch(/\bSET\s+search_path\b/i); + expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|ON|FROM)\s+"?\w+"?\."?\w+/i); + }); + + test('findings CHECKs mirror the file_finding tool limits exported from file-finding.ts', () => { + const findings = tableBlock(readSql(), 'findings'); + const kinds = FILE_FINDING_KINDS.map(kind => `'${kind}'`).join(', '); + + expect(findings).toContain(`CHECK (kind IN (${kinds}))`); + expect(findings).toContain(`DEFAULT '${FILE_FINDING_INITIAL_STATUS}'`); + expect(findings).toContain( + `CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND ${FILE_FINDING_MAX_TITLE_LENGTH})` + ); + expect(findings).toContain( + `CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND ${FILE_FINDING_MAX_SUMMARY_LENGTH})` + ); + expect(findings).toContain(`CHECK (cardinality(trial_refs) <= ${FILE_FINDING_MAX_TRIAL_REFS})`); + expect(findings).toContain( + `CHECK (cardinality(evidence_refs) <= ${FILE_FINDING_MAX_EVIDENCE_REFS})` + ); + expect(findings).toContain( + `CHECK (research_finding_refs_valid(trial_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` + ); + expect(findings).toContain( + `CHECK (research_finding_refs_valid(evidence_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` + ); + expect(findings).toContain( + `char_length(idempotency_key) BETWEEN 1 AND ${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH}` + ); + expect(findings).toContain('created_at TIMESTAMPTZ NOT NULL,'); + expect(findings).toMatch(/idempotency_key TEXT CHECK \(idempotency_key IS NULL OR/); + }); + + test('research_trim_ecmascript strips exactly the BMP code points String.prototype.trim() strips', () => { + const sqlSet = trimCodePointsFromSql(); + const jsSet: number[] = []; + for (let cp = 0; cp <= 0xffff; cp++) { + if (cp >= 0xd800 && cp <= 0xdfff) { + continue; + } + if (String.fromCharCode(cp).trim() === '') { + jsSet.push(cp); + } + } + + expect(new Set(sqlSet).size).toBe(sqlSet.length); + expect([...sqlSet].sort((a, b) => a - b)).toEqual(jsSet); + expect(sqlSet).toHaveLength(25); + }); + + test('both tables are append-only via reject_research_evidence_mutation row and TRUNCATE triggers', () => { + const sql = normalize(readSql()); + for (const table of ['findings', 'provider_caveats']) { + expect(sql).toContain( + `DROP TRIGGER IF EXISTS ${table}_retained ON ${table}; CREATE TRIGGER ${table}_retained BEFORE UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();` + ); + expect(sql).toContain( + `DROP TRIGGER IF EXISTS ${table}_no_truncate ON ${table}; CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();` + ); + } + // The migration must reuse the shared function, never redefine it. + expect(sql).not.toMatch(/FUNCTION reject_research_evidence_mutation\s*\(\s*\)\s*RETURNS/i); + }); + + test('design/DATA-CONTRACTS.md documents both tables and indexes exactly as the migration creates them', () => { + const doc = docSqlBlock(); + const sql = readSql(); + expect(tableBlock(doc, 'findings')).toBe(tableBlock(sql, 'findings')); + expect(tableBlock(doc, 'provider_caveats')).toBe(tableBlock(sql, 'provider_caveats')); + + const indexes = (text: string) => + [...normalize(text).matchAll(/CREATE (?:UNIQUE )?INDEX IF NOT EXISTS [^;]+;/g)].map( + m => m[0] + ); + expect(indexes(doc)).toEqual(indexes(sql)); + expect(indexes(sql)).toHaveLength(3); + }); + + test('37-research-findings.sql runs on research and all tracks right after 36 and never on master', async () => { + const research = await filesForTrack('research'); + const all = await filesForTrack('all'); + const master = await filesForTrack('master'); + + expect(research.indexOf('37-research-findings.sql')).toBe( + research.indexOf('36-trial-ledger.sql') + 1 + ); + expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(-1); + expect(all).toContain('37-research-findings.sql'); + expect(master).not.toContain('37-research-findings.sql'); + }); +}); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts index 18c75c16..60324763 100644 --- a/test/postgres/research-findings-schema.test.ts +++ b/test/postgres/research-findings-schema.test.ts @@ -119,7 +119,17 @@ function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) { id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key ) VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9) RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, - [id, kind, title, summary, overrides.status, createdAt, trialRefs, evidenceRefs, idempotencyKey] + [ + id, + kind, + title, + summary, + overrides.status, + createdAt, + trialRefs, + evidenceRefs, + idempotencyKey, + ] ); } @@ -527,3 +537,164 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([caveatBefore]); }); }); + +describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema edge cases (QA)', () => { + test('research_trim_ecmascript matches String.prototype.trim() for every ECMAScript blank and for look-alike non-blanks', async () => { + const f = await createIsolatedFixture(); + // 25 ECMAScript WhiteSpace + LineTerminator code points, plus characters JS trim() keeps: + // ZERO WIDTH SPACE, NEXT LINE, MONGOLIAN VOWEL SEPARATOR, WORD JOINER. + const codePoints = [ + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, + 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, + 0xfeff, 0x200b, 0x0085, 0x180e, 0x2060, + ]; + for (const cp of codePoints) { + const c = String.fromCodePoint(cp); + for (const input of [c, `${c}${c}a b${c}`]) { + const sqlTrimmed = ( + await f.pool.query<{ v: string }>('SELECT research_trim_ecmascript($1) AS v', [input]) + ).rows[0]?.v; + expect({ cp, input, trimmed: sqlTrimmed }).toEqual({ cp, input, trimmed: input.trim() }); + } + } + }); + + test('non-ECMAScript blanks the MCP tool accepts (U+200B, U+0085) are accepted, and text is stored untrimmed', async () => { + const f = await createIsolatedFixture(); + const paddedTitle = `\u00A0 Interior spacing\tkept \u3000`; + + const zwsp = (await insertFinding(f.pool, { id: 'f-zwsp', title: '\u200B' })).rows[0]; + const nel = (await insertFinding(f.pool, { id: 'f-nel', summary: '\u0085' })).rows[0]; + const padded = (await insertFinding(f.pool, { id: 'f-padded', title: paddedTitle })).rows[0]; + + expect(zwsp.title).toBe('\u200B'); + expect(nel.summary).toBe('\u0085'); + expect(padded.title).toBe(paddedTitle); + }); + + test('title/summary caps count code points: 256 astral characters accepted, 257 rejected', async () => { + const f = await createIsolatedFixture(); + const emoji = '\u{1F4C8}'; + + const ok = (await insertFinding(f.pool, { id: 'f-astral-ok', title: emoji.repeat(256) })) + .rows[0]; + expect(ok.title).toBe(emoji.repeat(256)); + await expectPgErrorCode( + insertFinding(f.pool, { id: 'f-astral-bad', title: emoji.repeat(257) }), + '23514' + ); + await expectPgErrorCode( + insertFinding(f.pool, { id: 'f-astral-ref', trialRefs: [emoji.repeat(257)] }), + '23514' + ); + }); + + test('NOT NULL columns reject NULL with SQLSTATE 23502 and leave no rows', async () => { + const f = await createIsolatedFixture(); + const base = { + id: 'f-null', + kind: 'finding', + title: 'Title', + summary: 'Summary', + created_at: FIXED_TS, + trial_refs: ['1'], + evidence_refs: [] as string[], + }; + for (const column of Object.keys(base) as (keyof typeof base)[]) { + const row = { ...base, [column]: null }; + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) + VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[])`, + [ + row.id, + row.kind, + row.title, + row.summary, + row.created_at, + row.trial_refs, + row.evidence_refs, + ] + ), + '23502' + ); + } + // created_at has no default on findings: the tool's clock must supply it. + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, trial_refs, evidence_refs) + VALUES ('f-no-ts', 'finding', 'Title', 'Summary', '{1}', '{}')` + ), + '23502' + ); + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs, status) + VALUES ('f-null-status', 'finding', 'Title', 'Summary', $1::timestamptz, '{1}', '{}', NULL)`, + [FIXED_TS] + ), + '23502' + ); + for (const column of ['id', 'provider', 'dataset', 'caveat', 'created_at']) { + const values: Record = { + id: 'c-null', + provider: 'EODHD', + dataset: 'eodPrices', + caveat: 'Caveat text', + created_at: FIXED_TS, + [column]: null, + }; + await expectPgErrorCode( + f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ($1, $2, $3, $4, $5::timestamptz)`, + [values.id, values.provider, values.dataset, values.caveat, values.created_at] + ), + '23502' + ); + } + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); + expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( + 0 + ); + }); + + test('duplicate ids are rejected (23505) on both tables and idempotency keys are case-sensitive', async () => { + const f = await createIsolatedFixture(); + + await insertFinding(f.pool, { id: 'dup-finding' }); + await expectPgErrorCode(insertFinding(f.pool, { id: 'dup-finding' }), '23505'); + await insertProviderCaveat(f.pool, { id: 'dup-caveat' }); + await expectPgErrorCode(insertProviderCaveat(f.pool, { id: 'dup-caveat' }), '23505'); + + // file_finding compares idempotency keys exactly; the unique index must not fold case. + await insertFinding(f.pool, { id: 'f-case-1', idempotencyKey: 'Retry-Key' }); + await insertFinding(f.pool, { id: 'f-case-2', idempotencyKey: 'retry-key' }); + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); + expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( + 1 + ); + }); + + test('a rejected UPDATE matching one row leaves every other row and column untouched', async () => { + const f = await createIsolatedFixture(); + await insertFinding(f.pool, { id: 'f-a', createdAt: '2026-01-01T00:00:00.000Z' }); + await insertFinding(f.pool, { id: 'f-b', createdAt: '2026-01-02T00:00:00.000Z' }); + const before = (await f.pool.query('SELECT * FROM findings ORDER BY id')).rows; + + await expectPgErrorCode( + f.pool.query("UPDATE findings SET status = 'approved' WHERE id = 'f-b'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query("DELETE FROM findings WHERE id = 'f-a'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + + expect((await f.pool.query('SELECT * FROM findings ORDER BY id')).rows).toEqual(before); + }); +}); From 18f1e6e471e135a2cac7a842ba92c3d3f58582c1 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:44:56 -0500 Subject: [PATCH 24/26] =?UTF-8?q?T-154:=20M2.3l=20=E2=80=94=20`libs/data/q?= =?UTF-8?q?uestdb`:=20pure=20TypeScript=20ILP=20v2=20batch=20writer=20for?= =?UTF-8?q?=20`bars=5F1m`=20/=20`fx=5F1m`=20(`ilp-v2-writer.ts`,=20binary?= =?UTF-8?q?=20doubles=20+=20microsecond=20timestamps=20over=20an=20injecte?= =?UTF-8?q?d=20sink,=20byte-parity=20with=20`tools/curate-etl/src/ilp.rs`;?= =?UTF-8?q?=20no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/data/questdb/src/ilp-v2-writer.ts | 521 +++++++++++++ libs/data/questdb/src/index.ts | 17 + libs/data/questdb/src/influx-writer.ts | 3 + libs/data/questdb/test/ilp-v2-writer.test.ts | 741 +++++++++++++++++++ 4 files changed, 1282 insertions(+) create mode 100644 libs/data/questdb/src/ilp-v2-writer.ts create mode 100644 libs/data/questdb/test/ilp-v2-writer.test.ts diff --git a/libs/data/questdb/src/ilp-v2-writer.ts b/libs/data/questdb/src/ilp-v2-writer.ts new file mode 100644 index 00000000..2d64a7c8 --- /dev/null +++ b/libs/data/questdb/src/ilp-v2-writer.ts @@ -0,0 +1,521 @@ +import type { Bar1mRow } from './types'; + +/** QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). */ +export const ILP_V2_DOUBLE_TYPE = 0x10; + +/** Default maximum buffered bytes before flushing a batch (1 MiB). */ +export const DEFAULT_ILP_MAX_BATCH_BYTES = 1_048_576; + +/** Default maximum buffered rows before flushing a batch. */ +export const DEFAULT_ILP_MAX_BATCH_ROWS = 10_000; + +const TABLE_BARS_1M = 'bars_1m'; +const TABLE_FX_1M = 'fx_1m'; + +const INT32_MIN = -2_147_483_648; +const INT32_MAX = 2_147_483_647; +const INT64_MIN = -(2n ** 63n); +const INT64_MAX = 2n ** 63n - 1n; + +const BYTE_SPACE = 0x20; +const BYTE_COMMA = 0x2c; +const BYTE_EQUALS = 0x3d; +const BYTE_LF = 0x0a; +const BYTE_CR = 0x0d; +const BYTE_BACKSLASH = 0x5c; + +const textEncoder = new TextEncoder(); + +const BARS_1M_OPEN_PREFIX = textEncoder.encode(' open=='); +const HIGH_PREFIX = textEncoder.encode(',high=='); +const LOW_PREFIX = textEncoder.encode(',low=='); +const CLOSE_PREFIX = textEncoder.encode(',close=='); +const VOLUME_PREFIX = textEncoder.encode(',volume=='); +const FX_1M_PREFIX = textEncoder.encode(`${TABLE_FX_1M},pair=`); +const FX_1M_SOURCE_PREFIX = textEncoder.encode(',source='); + +/** Valid intraday trading session tags for `bars_1m`. */ +export type Bar1mSession = 'PRE' | 'RTH' | 'POST'; + +/** + * Curated `bars_1m` row input for QuestDB ILP v2 encoding. + * + * Derived from read-side `Bar1mRow` with `vwap` omitted (left NULL in QuestDB) and + * `session` / `source` narrowed to required non-null write values matching `M2_INTRADAY_SCHEMAS.bars_1m`. + */ +export type Bar1mIlpV2Row = Omit & { + session: Bar1mSession; + source: string; +}; + +/** + * Curated `fx_1m` row input for QuestDB ILP v2 encoding. + * + * Matches `M2_INTRADAY_SCHEMAS.fx_1m`: symbols `pair`, `source`; binary doubles + * `open`, `high`, `low`, `close`; designated timestamp `ts` (UTC epoch microseconds). + */ +export interface Fx1mIlpV2Row { + pair: string; + source: string; + open: number; + high: number; + low: number; + close: number; + ts: bigint; +} + +/** Discriminated error kinds for `IlpV2EncodeError`. */ +export type IlpV2EncodeErrorKind = + | 'empty-symbol' + | 'invalid-session' + | 'invalid-listing-id' + | 'non-finite-double' + | 'negative-timestamp' + | 'timestamp-out-of-range'; + +/** + * Typed validation error thrown by `encodeBar1mIlpV2` and `encodeFx1mIlpV2`. + * + * Validation runs atomically before any bytes are encoded or buffered. + */ +export class IlpV2EncodeError extends Error { + public readonly kind: IlpV2EncodeErrorKind; + public readonly field: string; + public readonly value?: number | bigint | string; + + constructor( + kind: IlpV2EncodeErrorKind, + field: string, + message: string, + value?: number | bigint | string + ) { + super(message); + this.name = 'IlpV2EncodeError'; + this.kind = kind; + this.field = field; + if (value !== undefined) { + this.value = value; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Injected output port for `createIlpV2BatchWriter`. */ +export interface IlpV2BatchSink { + write(batch: Uint8Array): Promise; +} + +/** Configuration options for `createIlpV2BatchWriter`. */ +export interface IlpV2BatchWriterOptions { + sink: IlpV2BatchSink; + maxBatchBytes?: number; + maxBatchRows?: number; +} + +/** Write summary returned by `IlpV2BatchWriter.finish()`. */ +export interface IlpV2BatchWriterStats { + rows: number; + batches: number; + bytes: number; +} + +/** Pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. */ +export interface IlpV2BatchWriter { + writeBar1m(row: Bar1mIlpV2Row): Promise; + writeFx1m(row: Fx1mIlpV2Row): Promise; + flush(): Promise; + finish(): Promise; +} + +function validateNonEmptySymbol(field: string, value: string): void { + if (typeof value !== 'string' || value.length === 0) { + throw new IlpV2EncodeError('empty-symbol', field, `empty ILP symbol field '${field}'`); + } +} + +function validateSession(value: Bar1mSession): void { + if (typeof value !== 'string' || value.length === 0) { + throw new IlpV2EncodeError('empty-symbol', 'session', "empty ILP symbol field 'session'"); + } + if (value !== 'PRE' && value !== 'RTH' && value !== 'POST') { + throw new IlpV2EncodeError( + 'invalid-session', + 'session', + `invalid ILP session '${String(value)}' (expected PRE, RTH, or POST)`, + String(value) + ); + } +} + +function validateListingId(value: number): void { + if ( + typeof value !== 'number' || + !Number.isInteger(value) || + value < INT32_MIN || + value > INT32_MAX + ) { + throw new IlpV2EncodeError( + 'invalid-listing-id', + 'listing_id', + `invalid ILP listing_id '${String(value)}' (expected signed 32-bit integer)`, + value + ); + } +} + +function validateFiniteDouble(field: string, value: number): void { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new IlpV2EncodeError( + 'non-finite-double', + field, + `non-finite ILP double field '${field}': ${String(value)}`, + value + ); + } +} + +function validateInt64Timestamp(field: string, value: bigint): void { + if (typeof value !== 'bigint' || value < INT64_MIN || value > INT64_MAX) { + throw new IlpV2EncodeError( + 'timestamp-out-of-range', + field, + `ILP timestamp '${field}' out of signed 64-bit range: ${String(value)}`, + typeof value === 'bigint' ? value : undefined + ); + } +} + +function validateDesignatedTimestamp(field: string, value: bigint): void { + validateInt64Timestamp(field, value); + if (value < 0n) { + throw new IlpV2EncodeError( + 'negative-timestamp', + field, + `negative ILP designated timestamp '${field}': ${value.toString(10)} (must be >= 0)`, + value + ); + } +} + +function needsSymbolEscape(byte: number): boolean { + return ( + byte === BYTE_SPACE || + byte === BYTE_COMMA || + byte === BYTE_EQUALS || + byte === BYTE_LF || + byte === BYTE_CR || + byte === BYTE_BACKSLASH + ); +} + +/** + * Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. + */ +function encodeEscapedSymbol(value: string): Uint8Array { + const raw = textEncoder.encode(value); + let extra = 0; + for (const b of raw) { + if (needsSymbolEscape(b)) { + extra += 1; + } + } + if (extra === 0) { + return raw; + } + + const escaped = new Uint8Array(raw.length + extra); + let out = 0; + for (const b of raw) { + if (needsSymbolEscape(b)) { + escaped[out++] = BYTE_BACKSLASH; + } + escaped[out++] = b; + } + return escaped; +} + +function writeBinaryDoubleField( + out: Uint8Array, + view: DataView, + offset: number, + prefix: Uint8Array, + value: number +): number { + out.set(prefix, offset); + const typeOffset = offset + prefix.byteLength; + out[typeOffset] = ILP_V2_DOUBLE_TYPE; + view.setFloat64(typeOffset + 1, value, true); + return typeOffset + 9; +} + +/** + * Encodes one curated `bars_1m` row in QuestDB ILP v2 format. + * + * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_bar_1m`): + * - Table `bars_1m` + * - Symbols `listing_id` (decimal), `session` (`PRE`/`RTH`/`POST`), `source` (escaped) + * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close`, `volume` (`vwap` omitted) + * - Timestamp column `known_at=t` (signed 64-bit integer preserved as supplied) + * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) + */ +export function encodeBar1mIlpV2(row: Bar1mIlpV2Row): Uint8Array { + validateListingId(row.listing_id); + validateSession(row.session); + validateNonEmptySymbol('source', row.source); + validateFiniteDouble('open', row.open); + validateFiniteDouble('high', row.high); + validateFiniteDouble('low', row.low); + validateFiniteDouble('close', row.close); + validateFiniteDouble('volume', row.volume); + validateInt64Timestamp('known_at', row.known_at); + validateDesignatedTimestamp('ts', row.ts); + + const listingIdDecimal = row.listing_id === 0 ? '0' : String(row.listing_id); + const prefixBytes = textEncoder.encode( + `${TABLE_BARS_1M},listing_id=${listingIdDecimal},session=${row.session},source=` + ); + const escapedSourceBytes = encodeEscapedSymbol(row.source); + const suffixBytes = textEncoder.encode( + `,known_at=${row.known_at.toString(10)}t ${row.ts.toString(10)}t\n` + ); + + // Binary doubles section: ' open==\x10<8>,high==\x10<8>,low==\x10<8>,close==\x10<8>,volume==\x10<8>' + const binaryFieldsLen = + BARS_1M_OPEN_PREFIX.byteLength + + 9 + + HIGH_PREFIX.byteLength + + 9 + + LOW_PREFIX.byteLength + + 9 + + CLOSE_PREFIX.byteLength + + 9 + + VOLUME_PREFIX.byteLength + + 9; + + const out = new Uint8Array( + prefixBytes.byteLength + escapedSourceBytes.byteLength + binaryFieldsLen + suffixBytes.byteLength + ); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + + let offset = 0; + out.set(prefixBytes, offset); + offset += prefixBytes.byteLength; + out.set(escapedSourceBytes, offset); + offset += escapedSourceBytes.byteLength; + + offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); + offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); + offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); + offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); + offset = writeBinaryDoubleField(out, view, offset, VOLUME_PREFIX, row.volume); + + out.set(suffixBytes, offset); + return out; +} + +/** + * Encodes one `fx_1m` row in QuestDB ILP v2 format. + * + * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_fx_1m`): + * - Table `fx_1m` + * - Symbols `pair` (escaped), `source` (escaped) + * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close` + * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) + */ +export function encodeFx1mIlpV2(row: Fx1mIlpV2Row): Uint8Array { + validateNonEmptySymbol('pair', row.pair); + validateNonEmptySymbol('source', row.source); + validateFiniteDouble('open', row.open); + validateFiniteDouble('high', row.high); + validateFiniteDouble('low', row.low); + validateFiniteDouble('close', row.close); + validateDesignatedTimestamp('ts', row.ts); + + const escapedPairBytes = encodeEscapedSymbol(row.pair); + const escapedSourceBytes = encodeEscapedSymbol(row.source); + const suffixBytes = textEncoder.encode(` ${row.ts.toString(10)}t\n`); + + const binaryFieldsLen = + BARS_1M_OPEN_PREFIX.byteLength + + 9 + + HIGH_PREFIX.byteLength + + 9 + + LOW_PREFIX.byteLength + + 9 + + CLOSE_PREFIX.byteLength + + 9; + + const out = new Uint8Array( + FX_1M_PREFIX.byteLength + + escapedPairBytes.byteLength + + FX_1M_SOURCE_PREFIX.byteLength + + escapedSourceBytes.byteLength + + binaryFieldsLen + + suffixBytes.byteLength + ); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + + let offset = 0; + out.set(FX_1M_PREFIX, offset); + offset += FX_1M_PREFIX.byteLength; + out.set(escapedPairBytes, offset); + offset += escapedPairBytes.byteLength; + out.set(FX_1M_SOURCE_PREFIX, offset); + offset += FX_1M_SOURCE_PREFIX.byteLength; + out.set(escapedSourceBytes, offset); + offset += escapedSourceBytes.byteLength; + + offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); + offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); + offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); + offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); + + out.set(suffixBytes, offset); + return out; +} + +function assertPositiveIntegerOption(name: string, value: number): void { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) { + throw new RangeError(`ILP v2 batch writer option '${name}' must be a positive integer`); + } +} + +/** + * Creates a pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. + * + * Operations are serialized in call order so overlapping calls never reorder rows or overlap + * sink writes. Batches always end on whole-row boundaries, fail closed on sink errors, and + * reject writes after `finish()`. + */ +export function createIlpV2BatchWriter(options: IlpV2BatchWriterOptions): IlpV2BatchWriter { + if (!options || !options.sink || typeof options.sink.write !== 'function') { + throw new TypeError('ILP v2 batch writer requires a sink with a write(batch) method'); + } + + const maxBatchBytes = options.maxBatchBytes ?? DEFAULT_ILP_MAX_BATCH_BYTES; + const maxBatchRows = options.maxBatchRows ?? DEFAULT_ILP_MAX_BATCH_ROWS; + assertPositiveIntegerOption('maxBatchBytes', maxBatchBytes); + assertPositiveIntegerOption('maxBatchRows', maxBatchRows); + + const { sink } = options; + + const pendingChunks: Uint8Array[] = []; + let pendingBytes = 0; + let pendingRows = 0; + + let writtenRows = 0; + let writtenBatches = 0; + let writtenBytes = 0; + + let finished = false; + let hasSinkFailure = false; + let sinkFailure: unknown = null; + + let queueTail: Promise = Promise.resolve(); + + function enqueue(operation: () => Promise): Promise { + const result = queueTail.then(operation, operation); + queueTail = result.then( + () => undefined, + () => undefined + ); + return result; + } + + function assertHealthyForMutation(action: string): void { + if (hasSinkFailure) { + throw new Error(`ILP v2 batch writer is closed after a sink write failure (${action})`, { + cause: sinkFailure, + }); + } + if (finished) { + throw new Error(`ILP v2 batch writer is already finished (${action})`); + } + } + + async function flushPending(): Promise { + if (pendingChunks.length === 0) { + return; + } + + const batch = new Uint8Array(pendingBytes); + let offset = 0; + for (const chunk of pendingChunks) { + batch.set(chunk, offset); + offset += chunk.byteLength; + } + + const rowCount = pendingRows; + const byteCount = pendingBytes; + + try { + await sink.write(batch); + } catch (error) { + hasSinkFailure = true; + sinkFailure = error; + pendingChunks.length = 0; + pendingBytes = 0; + pendingRows = 0; + throw error; + } + + pendingChunks.length = 0; + pendingBytes = 0; + pendingRows = 0; + writtenRows += rowCount; + writtenBatches += 1; + writtenBytes += byteCount; + } + + async function enqueueEncodedRow(encoded: Uint8Array): Promise { + if (pendingChunks.length > 0 && pendingBytes + encoded.byteLength > maxBatchBytes) { + await flushPending(); + } + + pendingChunks.push(encoded); + pendingBytes += encoded.byteLength; + pendingRows += 1; + + if (pendingRows >= maxBatchRows || pendingBytes >= maxBatchBytes) { + await flushPending(); + } + } + + return { + writeBar1m(row: Bar1mIlpV2Row): Promise { + return enqueue(async () => { + assertHealthyForMutation('writeBar1m'); + const encoded = encodeBar1mIlpV2(row); + await enqueueEncodedRow(encoded); + }); + }, + + writeFx1m(row: Fx1mIlpV2Row): Promise { + return enqueue(async () => { + assertHealthyForMutation('writeFx1m'); + const encoded = encodeFx1mIlpV2(row); + await enqueueEncodedRow(encoded); + }); + }, + + flush(): Promise { + return enqueue(async () => { + assertHealthyForMutation('flush'); + await flushPending(); + }); + }, + + finish(): Promise { + return enqueue(async () => { + assertHealthyForMutation('finish'); + await flushPending(); + finished = true; + return { + rows: writtenRows, + batches: writtenBatches, + bytes: writtenBytes, + }; + }); + }, + }; +} diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 94841d60..6036ae94 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -9,6 +9,23 @@ export { QuestDBClient, readBars1m } from './client'; export { QuestDBHealthMonitor } from './health'; export { QuestDBQueryBuilder } from './query-builder'; export { QuestDBInfluxWriter } from './influx-writer'; +export { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + ILP_V2_DOUBLE_TYPE, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Bar1mSession, + type Fx1mIlpV2Row, + type IlpV2BatchSink, + type IlpV2BatchWriter, + type IlpV2BatchWriterOptions, + type IlpV2BatchWriterStats, + type IlpV2EncodeErrorKind, +} from './ilp-v2-writer'; export { formatCreateTableSQL, getM2IntradayDDL, diff --git a/libs/data/questdb/src/influx-writer.ts b/libs/data/questdb/src/influx-writer.ts index 90e6145b..6f48aae7 100644 --- a/libs/data/questdb/src/influx-writer.ts +++ b/libs/data/questdb/src/influx-writer.ts @@ -11,6 +11,9 @@ interface QuestDBClientInterface { * * Provides high-performance data ingestion using InfluxDB Line Protocol * which QuestDB supports natively for optimal time-series data insertion. + * + * @deprecated Legacy text-ILP writer. Use `createIlpV2BatchWriter` (from `./ilp-v2-writer`) + * for QuestDB ILP v2 binary-double ingestion into `bars_1m` and `fx_1m`. */ export class QuestDBInfluxWriter { private readonly logger: ReturnType; diff --git a/libs/data/questdb/test/ilp-v2-writer.test.ts b/libs/data/questdb/test/ilp-v2-writer.test.ts new file mode 100644 index 00000000..b271a920 --- /dev/null +++ b/libs/data/questdb/test/ilp-v2-writer.test.ts @@ -0,0 +1,741 @@ +import { describe, expect, it } from 'bun:test'; +import { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + ILP_V2_DOUBLE_TYPE, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Fx1mIlpV2Row, + type IlpV2BatchSink, +} from '../src/index'; + +const encoder = new TextEncoder(); + +function asciiBytes(text: string): number[] { + return Array.from(encoder.encode(text)); +} + +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { + const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function indexOfSubarray(haystack: Uint8Array, needle: Uint8Array): number { + outer: for (let i = 0; i <= haystack.length - needle.length; i++) { + for (let j = 0; j < needle.length; j++) { + if (haystack[i + j] !== needle[j]) { + continue outer; + } + } + return i; + } + return -1; +} + +function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { + return { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_000_000n, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: 'RTH', + source: 'eod_unadj', + ...overrides, + }; +} + +function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { + return { + pair: 'USD.CAD', + source: 'eod', + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + ts: 1_736_951_400_000_000n, + ...overrides, + }; +} + +function createMemorySink(): { sink: IlpV2BatchSink; batches: Uint8Array[] } { + const batches: Uint8Array[] = []; + const sink: IlpV2BatchSink = { + async write(batch: Uint8Array): Promise { + batches.push(batch.slice()); + }, + }; + return { sink, batches }; +} + +describe('ILP v2 writer constants', () => { + it('matches Rust tools/curate-etl/src/ilp.rs constants', () => { + expect(ILP_V2_DOUBLE_TYPE).toBe(0x10); + expect(DEFAULT_ILP_MAX_BATCH_BYTES).toBe(1_048_576); + expect(DEFAULT_ILP_MAX_BATCH_ROWS).toBe(10_000); + }); +}); + +describe('ILP v2 byte-parity with tools/curate-etl/src/ilp_tests.rs', () => { + it('matches golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract byte-for-byte', () => { + // Mirrors `golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract` + // in `tools/curate-etl/src/ilp_tests.rs`. + const row: Bar1mIlpV2Row = { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_123_456n, + open: 150.25, + high: 151.75, + low: 149.5, + close: 151.125, + volume: 12_345.0, + session: 'RTH', + source: 'eod_unadj', + }; + + const actual = encodeBar1mIlpV2(row); + + // Expected wire bytes written out literally (little-endian IEEE-754 doubles): + // 150.25 -> 0x4062c80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x62, 0x40] + // 151.75 -> 0x4062f80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x62, 0x40] + // 149.5 -> 0x4062b00000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x62, 0x40] + // 151.125 -> 0x4062e40000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x62, 0x40] + // 12345.0 -> 0x40c81c8000000000 -> [0x00, 0x00, 0x00, 0x00, 0x80, 0x1c, 0xc8, 0x40] + const expected = new Uint8Array([ + ...asciiBytes('bars_1m,listing_id=42,session=RTH,source=eod_unadj open=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xc8, + 0x62, + 0x40, + ...asciiBytes(',high=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf8, + 0x62, + 0x40, + ...asciiBytes(',low=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xb0, + 0x62, + 0x40, + ...asciiBytes(',close=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xe4, + 0x62, + 0x40, + ...asciiBytes(',volume=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x80, + 0x1c, + 0xc8, + 0x40, + ...asciiBytes(',known_at=1736951460123456t 1736951400000000t\n'), + ]); + + expect(actual).toEqual(expected); + expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1); + + // Verify PRE and POST session tags as in the Rust golden test. + const preBytes = encodeBar1mIlpV2({ ...row, session: 'PRE' }); + expect( + indexOfSubarray(preBytes, encoder.encode('bars_1m,listing_id=42,session=PRE,source=eod_unadj ')) + ).toBe(0); + + const postBytes = encodeBar1mIlpV2({ ...row, session: 'POST' }); + expect( + indexOfSubarray( + postBytes, + encoder.encode('bars_1m,listing_id=42,session=POST,source=eod_unadj ') + ) + ).toBe(0); + }); + + it('matches golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract byte-for-byte', () => { + // Mirrors `golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract` + // in `tools/curate-etl/src/ilp_tests.rs`. + const row: Fx1mIlpV2Row = { + pair: 'USD.CAD', + ts: 1_736_951_400_000_000n, + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + source: 'eod', + }; + + const actual = encodeFx1mIlpV2(row); + + // Expected wire bytes written out literally (little-endian IEEE-754 doubles): + // 1.3625 -> 0x3ff5cccccccccccc -> [0xcd, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xf5, 0x3f] + // 1.365 -> 0x3ff5d70a3d70a3d7 -> [0xd7, 0xa3, 0x70, 0x3d, 0x0a, 0xd7, 0xf5, 0x3f] + // 1.36125 -> 0x3ff5c7ae147ae148 -> [0x48, 0xe1, 0x7a, 0x14, 0xae, 0xc7, 0xf5, 0x3f] + // 1.364375 -> 0x3ff5d47ae147ae14 -> [0x14, 0xae, 0x47, 0xe1, 0x7a, 0xd4, 0xf5, 0x3f] + const expected = new Uint8Array([ + ...asciiBytes('fx_1m,pair=USD.CAD,source=eod open=='), + 0x10, + 0xcd, + 0xcc, + 0xcc, + 0xcc, + 0xcc, + 0xcc, + 0xf5, + 0x3f, + ...asciiBytes(',high=='), + 0x10, + 0xd7, + 0xa3, + 0x70, + 0x3d, + 0x0a, + 0xd7, + 0xf5, + 0x3f, + ...asciiBytes(',low=='), + 0x10, + 0x48, + 0xe1, + 0x7a, + 0x14, + 0xae, + 0xc7, + 0xf5, + 0x3f, + ...asciiBytes(',close=='), + 0x10, + 0x14, + 0xae, + 0x47, + 0xe1, + 0x7a, + 0xd4, + 0xf5, + 0x3f, + ...asciiBytes(' 1736951400000000t\n'), + ]); + + expect(actual).toEqual(expected); + expect(indexOfSubarray(actual, encoder.encode('known_at'))).toBe(-1); + expect(indexOfSubarray(actual, encoder.encode('volume'))).toBe(-1); + expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1); + }); +}); + +describe('ILP v2 escaping, timestamps, and atomic rejection', () => { + it('escapes all six ILP symbol characters and preserves UTF-8 and signed known_at', () => { + // Mirrors `symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection` + // in `tools/curate-etl/src/ilp_tests.rs`. + const rawSym = 'a b,c=d\\e\nf\rg caf\u00e9'; + const expectedEscaped = new Uint8Array([ + ...asciiBytes('a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf'), + 0xc3, + 0xa9, + ]); + + // Rust `encode_bar_1m` writes signed `known_at` via `write_i64_decimal` without rejecting < 0. + const barBytes = encodeBar1mIlpV2( + sampleBar({ + listing_id: 7, + ts: 0n, + known_at: -1n, + source: rawSym, + }) + ); + const expectedBarPrefix = concatBytes([ + encoder.encode('bars_1m,listing_id=7,session=RTH,source='), + expectedEscaped, + encoder.encode(' '), + ]); + expect(barBytes.slice(0, expectedBarPrefix.byteLength)).toEqual(expectedBarPrefix); + const expectedBarSuffix = encoder.encode(',known_at=-1t 0t\n'); + expect(barBytes.slice(barBytes.byteLength - expectedBarSuffix.byteLength)).toEqual( + expectedBarSuffix + ); + + // Also check signed 64-bit timestamp endpoints and INT32 listing_id endpoints. + const int64Min = -(2n ** 63n); + const int64Max = 2n ** 63n - 1n; + const endpointBar = encodeBar1mIlpV2( + sampleBar({ + listing_id: -2_147_483_648, + known_at: int64Min, + ts: int64Max, + }) + ); + expect( + indexOfSubarray(endpointBar, encoder.encode('bars_1m,listing_id=-2147483648,session=RTH,')) + ).toBe(0); + const endpointSuffix = encoder.encode( + `,known_at=${int64Min.toString(10)}t ${int64Max.toString(10)}t\n` + ); + expect(endpointBar.slice(endpointBar.byteLength - endpointSuffix.byteLength)).toEqual( + endpointSuffix + ); + + const maxListingBar = encodeBar1mIlpV2( + sampleBar({ + listing_id: 2_147_483_647, + known_at: int64Max, + ts: 0n, + }) + ); + expect( + indexOfSubarray(maxListingBar, encoder.encode('bars_1m,listing_id=2147483647,session=RTH,')) + ).toBe(0); + + // FX pair and source escaping. + const fxBytes = encodeFx1mIlpV2( + sampleFx({ + pair: rawSym, + source: 'src=1,2 3\\4\n\r', + ts: 123n, + }) + ); + const expectedFxPrefix = concatBytes([ + encoder.encode('fx_1m,pair='), + expectedEscaped, + encoder.encode(',source=src\\=1\\,2\\ 3\\\\4\\\n\\\r '), + ]); + expect(fxBytes.slice(0, expectedFxPrefix.byteLength)).toEqual(expectedFxPrefix); + const expectedFxSuffix = encoder.encode(' 123t\n'); + expect(fxBytes.slice(fxBytes.byteLength - expectedFxSuffix.byteLength)).toEqual( + expectedFxSuffix + ); + }); + + it('throws typed IlpV2EncodeError for negative ts, int64 overflow, non-finite doubles, empty symbols, and non-int32 listing_id', () => { + const expectEncodeError = ( + fn: () => unknown, + kind: IlpV2EncodeError['kind'], + field: string + ) => { + try { + fn(); + throw new Error('Expected IlpV2EncodeError to be thrown'); + } catch (err) { + expect(err).toBeInstanceOf(IlpV2EncodeError); + const encodeErr = err as IlpV2EncodeError; + expect(encodeErr.kind).toBe(kind); + expect(encodeErr.field).toBe(field); + } + }; + + // Negative designated timestamps. + expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ ts: -1n })), 'negative-timestamp', 'ts'); + expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ ts: -42n })), 'negative-timestamp', 'ts'); + + // Signed 64-bit timestamp overflow / underflow. + const overInt64 = 2n ** 63n; + const underInt64 = -(2n ** 63n) - 1n; + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: overInt64 })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: underInt64 })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: overInt64 })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: underInt64 })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ ts: overInt64 })), + 'timestamp-out-of-range', + 'ts' + ); + + // Non-finite doubles across every double column. + for (const badVal of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { + for (const field of ['open', 'high', 'low', 'close', 'volume'] as const) { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ [field]: badVal })), + 'non-finite-double', + field + ); + } + for (const field of ['open', 'high', 'low', 'close'] as const) { + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ [field]: badVal })), + 'non-finite-double', + field + ); + } + } + + // Empty symbols. + expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ source: '' })), 'empty-symbol', 'source'); + expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ pair: '' })), 'empty-symbol', 'pair'); + expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ source: '' })), 'empty-symbol', 'source'); + + // Non-INT32 listing_id. + for (const badId of [ + 1.5, + -0.25, + 2_147_483_648, + -2_147_483_649, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ listing_id: badId })), + 'invalid-listing-id', + 'listing_id' + ); + } + }); + + it('rejects invalid rows at a batch boundary without calling sink and preserves pending rows', async () => { + const validRow = sampleBar({ listing_id: 101 }); + const validBytes = encodeBar1mIlpV2(validRow); + const { sink, batches } = createMemorySink(); + + // Limit allows 1 row to sit pending right at the byte boundary so a second valid row would flush. + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: validBytes.byteLength + 1, + maxBatchRows: 2, + }); + + await writer.writeBar1m(validRow); + expect(batches).toHaveLength(0); + + // Rejected bar and FX rows must not flush the pending row or write anything to sink. + await expect(writer.writeBar1m(sampleBar({ ts: -1n }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeBar1m(sampleBar({ volume: Number.NaN }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeBar1m(sampleBar({ source: '' }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeBar1m(sampleBar({ listing_id: 3.14 }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeFx1m(sampleFx({ pair: '' }))).rejects.toBeInstanceOf(IlpV2EncodeError); + await expect(writer.writeFx1m(sampleFx({ ts: -5n }))).rejects.toBeInstanceOf(IlpV2EncodeError); + expect(batches).toHaveLength(0); + + // Pending valid row is still intact and flushes cleanly on finish(). + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 1, batches: 1, bytes: validBytes.byteLength }); + expect(batches).toEqual([validBytes]); + }); +}); + +describe('createIlpV2BatchWriter batching, boundaries, and option validation', () => { + it('validates maxBatchBytes and maxBatchRows at construction', () => { + const { sink } = createMemorySink(); + for (const invalid of [0, -1, -100, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: invalid })).toThrow(RangeError); + expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: invalid })).toThrow(RangeError); + } + }); + + it('flushes on exact maxBatchRows, exact maxBatchBytes, pre-overflow, oversized singleton, and explicit/empty flush', async () => { + // Include a finite double whose IEEE-754 LE payload contains 0x0a (LF) and a symbol with LF. + const lfDoubleBuf = new Uint8Array([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); + const doubleWithLf = new DataView(lfDoubleBuf.buffer).getFloat64(0, true); + expect(Number.isFinite(doubleWithLf)).toBe(true); + + const row = sampleBar({ open: doubleWithLf, source: 'eod\nwith_lf' }); + const oneLine = encodeBar1mIlpV2(row); + const rowLen = oneLine.byteLength; + + // 1. Exact row limit (maxBatchRows = 3) + 1 remainder row. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 100_000, + maxBatchRows: 3, + }); + for (let i = 0; i < 7; i++) { + await writer.writeBar1m(row); + } + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 7, batches: 3, bytes: 7 * rowLen }); + expect(batches).toHaveLength(3); + expect(batches[0]).toEqual(concatBytes([oneLine, oneLine, oneLine])); + expect(batches[1]).toEqual(concatBytes([oneLine, oneLine, oneLine])); + expect(batches[2]).toEqual(oneLine); + expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); + } + + // 2. Exact byte limit (2 * rowLen): flushes after every 2 rows. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 2 * rowLen, + maxBatchRows: 100, + }); + for (let i = 0; i < 5; i++) { + await writer.writeBar1m(row); + } + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen }); + expect(batches).toHaveLength(3); + expect(batches[0]).toEqual(concatBytes([oneLine, oneLine])); + expect(batches[1]).toEqual(concatBytes([oneLine, oneLine])); + expect(batches[2]).toEqual(oneLine); + } + + // 3. Row would exceed remaining capacity (2 * rowLen - 1): pre-flushes before appending. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 2 * rowLen - 1, + maxBatchRows: 100, + }); + for (let i = 0; i < 3; i++) { + await writer.writeBar1m(row); + } + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 3, batches: 3, bytes: 3 * rowLen }); + expect(batches).toEqual([oneLine, oneLine, oneLine]); + } + + // 4. Individually oversized row (maxBatchBytes = 16 < rowLen): sent alone, never split. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 16, + maxBatchRows: 100, + }); + await writer.writeBar1m(row); + await writer.writeBar1m(row); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 2, batches: 2, bytes: 2 * rowLen }); + expect(batches).toEqual([oneLine, oneLine]); + } + + // 5. Empty flush, explicit flush, and zero-row finish. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink, maxBatchBytes: 100_000, maxBatchRows: 10 }); + await writer.flush(); + expect(batches).toHaveLength(0); + await writer.writeBar1m(row); + await writer.flush(); + expect(batches).toEqual([oneLine]); + await writer.flush(); + expect(batches).toHaveLength(1); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 1, batches: 1, bytes: rowLen }); + } + + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink }); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 0, batches: 0, bytes: 0 }); + expect(batches).toHaveLength(0); + } + }); + + it('preserves mixed bars_1m and fx_1m input order and rejects writes after finish()', async () => { + const bar1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n }); + const fx1 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n }); + const bar2 = sampleBar({ listing_id: 2, ts: 1_700_000_120_000_000n }); + const fx2 = sampleFx({ pair: 'EUR.USD', ts: 1_700_000_180_000_000n }); + + const expectedAll = concatBytes([ + encodeBar1mIlpV2(bar1), + encodeFx1mIlpV2(fx1), + encodeBar1mIlpV2(bar2), + encodeFx1mIlpV2(fx2), + ]); + + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); + + await writer.writeBar1m(bar1); + await writer.writeFx1m(fx1); + await writer.writeBar1m(bar2); + await writer.writeFx1m(fx2); + + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 4, batches: 2, bytes: expectedAll.byteLength }); + expect(concatBytes(batches)).toEqual(expectedAll); + expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); + + // Writes, flush, and finish after finish() throw without calling sink. + await expect(writer.writeBar1m(bar1)).rejects.toThrow(/already finished/i); + await expect(writer.writeFx1m(fx1)).rejects.toThrow(/already finished/i); + await expect(writer.flush()).rejects.toThrow(/already finished/i); + await expect(writer.finish()).rejects.toThrow(/already finished/i); + expect(batches).toHaveLength(2); + }); +}); + +describe('createIlpV2BatchWriter serialization and fail-closed sink errors', () => { + it('serializes overlapping writes and finish() without overlapping sink calls', async () => { + let inFlight = 0; + let maxInFlight = 0; + const batches: Uint8Array[] = []; + const resolvers: Array<() => void> = []; + + const sink: IlpV2BatchSink = { + write(batch: Uint8Array): Promise { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + batches.push(batch.slice()); + return new Promise(resolve => { + resolvers.push(() => { + inFlight -= 1; + resolve(); + }); + }); + }, + }; + + const row1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n }); + const row2 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n }); + const row3 = sampleBar({ listing_id: 3, ts: 1_700_000_120_000_000n }); + + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); + + // Launch overlapping operations without awaiting between calls. + const p1 = writer.writeBar1m(row1); + const p2 = writer.writeFx1m(row2); + const p3 = writer.writeBar1m(row3); + const pFinish = writer.finish(); + + // Drain queued manual resolutions one by one as each sink.write starts. + await Promise.resolve(); + expect(resolvers).toHaveLength(1); + expect(inFlight).toBe(1); + resolvers[0]!(); + await p1; + + await Promise.resolve(); + expect(resolvers).toHaveLength(2); + expect(inFlight).toBe(1); + resolvers[1]!(); + await p2; + + await Promise.resolve(); + expect(resolvers).toHaveLength(3); + expect(inFlight).toBe(1); + resolvers[2]!(); + await p3; + + const stats = await pFinish; + expect(maxInFlight).toBe(1); + expect(stats).toEqual({ + rows: 3, + batches: 3, + bytes: + encodeBar1mIlpV2(row1).byteLength + + encodeFx1mIlpV2(row2).byteLength + + encodeBar1mIlpV2(row3).byteLength, + }); + expect(batches).toEqual([ + encodeBar1mIlpV2(row1), + encodeFx1mIlpV2(row2), + encodeBar1mIlpV2(row3), + ]); + }); + + it('propagates sink rejection and fails closed for queued and subsequent calls with zero extra sink writes', async () => { + const boom = new Error('simulated sink EPIPE'); + let sinkCalls = 0; + const acceptedBatches: Uint8Array[] = []; + let rejectSecondWrite: ((err: Error) => void) | null = null; + + const sink: IlpV2BatchSink = { + write(batch: Uint8Array): Promise { + sinkCalls += 1; + if (sinkCalls === 1) { + acceptedBatches.push(batch.slice()); + return Promise.resolve(); + } + return new Promise((_resolve, reject) => { + rejectSecondWrite = reject; + }); + }, + }; + + const row1 = sampleBar({ listing_id: 1 }); + const row2 = sampleBar({ listing_id: 2 }); + const row3 = sampleBar({ listing_id: 3 }); + + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); + + // First batch succeeds. + await writer.writeBar1m(row1); + expect(sinkCalls).toBe(1); + expect(acceptedBatches).toEqual([encodeBar1mIlpV2(row1)]); + + // Trigger second batch (in-flight) and queue a third write + finish behind it. + const failingWrite = writer.writeBar1m(row2); + const queuedWrite = writer.writeBar1m(row3); + const queuedFinish = writer.finish(); + + await Promise.resolve(); + expect(sinkCalls).toBe(2); + expect(rejectSecondWrite).not.toBeNull(); + rejectSecondWrite!(boom); + + // Triggering call receives the exact original error. + await expect(failingWrite).rejects.toBe(boom); + // Queued operations fail closed without invoking sink.write again. + await expect(queuedWrite).rejects.toThrow(/sink write failure/i); + await expect(queuedFinish).rejects.toThrow(/sink write failure/i); + + // Later calls also fail closed without invoking sink.write. + await expect(writer.writeBar1m(row3)).rejects.toThrow(/sink write failure/i); + await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); + await expect(writer.flush()).rejects.toThrow(/sink write failure/i); + await expect(writer.finish()).rejects.toThrow(/sink write failure/i); + + expect(sinkCalls).toBe(2); + }); +}); From 8ebc44251254c76b97f9c287ff47444ca1eddc48 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:52:12 -0500 Subject: [PATCH 25/26] =?UTF-8?q?T-154:=20M2.3l=20=E2=80=94=20`libs/data/q?= =?UTF-8?q?uestdb`:=20pure=20TypeScript=20ILP=20v2=20batch=20writer=20for?= =?UTF-8?q?=20`bars=5F1m`=20/=20`fx=5F1m`=20(`ilp-v2-writer.ts`,=20binary?= =?UTF-8?q?=20doubles=20+=20microsecond=20timestamps=20over=20an=20injecte?= =?UTF-8?q?d=20sink,=20byte-parity=20with=20`tools/curate-etl/src/ilp.rs`;?= =?UTF-8?q?=20no=20new=20deps,=20no=20live=20QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/data/questdb/src/ilp-v2-writer.ts | 33 ++++++- libs/data/questdb/test/ilp-v2-writer.test.ts | 91 ++++++++++++++++++-- 2 files changed, 116 insertions(+), 8 deletions(-) diff --git a/libs/data/questdb/src/ilp-v2-writer.ts b/libs/data/questdb/src/ilp-v2-writer.ts index 2d64a7c8..6917f5b7 100644 --- a/libs/data/questdb/src/ilp-v2-writer.ts +++ b/libs/data/questdb/src/ilp-v2-writer.ts @@ -481,19 +481,48 @@ export function createIlpV2BatchWriter(options: IlpV2BatchWriterOptions): IlpV2B } } + function snapshotBar1mRow(row: Bar1mIlpV2Row): Bar1mIlpV2Row { + return { + listing_id: row.listing_id, + ts: row.ts, + known_at: row.known_at, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + volume: row.volume, + session: row.session, + source: row.source, + }; + } + + function snapshotFx1mRow(row: Fx1mIlpV2Row): Fx1mIlpV2Row { + return { + pair: row.pair, + source: row.source, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + ts: row.ts, + }; + } + return { writeBar1m(row: Bar1mIlpV2Row): Promise { + const snapshot = snapshotBar1mRow(row); return enqueue(async () => { assertHealthyForMutation('writeBar1m'); - const encoded = encodeBar1mIlpV2(row); + const encoded = encodeBar1mIlpV2(snapshot); await enqueueEncodedRow(encoded); }); }, writeFx1m(row: Fx1mIlpV2Row): Promise { + const snapshot = snapshotFx1mRow(row); return enqueue(async () => { assertHealthyForMutation('writeFx1m'); - const encoded = encodeFx1mIlpV2(row); + const encoded = encodeFx1mIlpV2(snapshot); await enqueueEncodedRow(encoded); }); }, diff --git a/libs/data/questdb/test/ilp-v2-writer.test.ts b/libs/data/questdb/test/ilp-v2-writer.test.ts index b271a920..c7d4c6ca 100644 --- a/libs/data/questdb/test/ilp-v2-writer.test.ts +++ b/libs/data/questdb/test/ilp-v2-writer.test.ts @@ -506,7 +506,7 @@ describe('createIlpV2BatchWriter batching, boundaries, and option validation', ( expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); } - // 2. Exact byte limit (2 * rowLen): flushes after every 2 rows. + // 2. Exact byte limit (2 * rowLen): flushes immediately when the 2nd and 4th rows hit the limit. { const { sink, batches } = createMemorySink(); const writer = createIlpV2BatchWriter({ @@ -514,14 +514,21 @@ describe('createIlpV2BatchWriter batching, boundaries, and option validation', ( maxBatchBytes: 2 * rowLen, maxBatchRows: 100, }); - for (let i = 0; i < 5; i++) { - await writer.writeBar1m(row); - } + await writer.writeBar1m(row); + expect(batches).toHaveLength(0); + await writer.writeBar1m(row); + expect(batches).toHaveLength(1); + expect(batches[0]).toEqual(concatBytes([oneLine, oneLine])); + await writer.writeBar1m(row); + expect(batches).toHaveLength(1); + await writer.writeBar1m(row); + expect(batches).toHaveLength(2); + expect(batches[1]).toEqual(concatBytes([oneLine, oneLine])); + await writer.writeBar1m(row); + expect(batches).toHaveLength(2); const stats = await writer.finish(); expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen }); expect(batches).toHaveLength(3); - expect(batches[0]).toEqual(concatBytes([oneLine, oneLine])); - expect(batches[1]).toEqual(concatBytes([oneLine, oneLine])); expect(batches[2]).toEqual(oneLine); } @@ -684,6 +691,78 @@ describe('createIlpV2BatchWriter serialization and fail-closed sink errors', () ]); }); + it('snapshots row field values at submission when a caller reuses mutable row objects across overlapping writes', async () => { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); + + const mutableBar = sampleBar({ + listing_id: 10, + ts: 1_700_000_000_000_000n, + known_at: 1_700_000_060_000_000n, + open: 100.0, + high: 101.0, + low: 99.5, + close: 100.5, + volume: 1_000, + session: 'PRE', + source: 'bar_one', + }); + const expectedBar1 = encodeBar1mIlpV2(mutableBar); + + const mutableFx = sampleFx({ + pair: 'USD.CAD', + source: 'fx_one', + open: 1.35, + high: 1.36, + low: 1.34, + close: 1.355, + ts: 1_700_000_000_000_000n, + }); + const expectedFx1 = encodeFx1mIlpV2(mutableFx); + + // Submit first bar and FX row without awaiting, then mutate both objects in place. + const pBar1 = writer.writeBar1m(mutableBar); + const pFx1 = writer.writeFx1m(mutableFx); + + mutableBar.listing_id = 11; + mutableBar.ts = 1_700_000_060_000_000n; + mutableBar.known_at = 1_700_000_120_000_000n; + mutableBar.open = 200.0; + mutableBar.high = 202.0; + mutableBar.low = 199.0; + mutableBar.close = 201.5; + mutableBar.volume = 2_000; + mutableBar.session = 'RTH'; + mutableBar.source = 'bar_two'; + const expectedBar2 = encodeBar1mIlpV2(mutableBar); + + mutableFx.pair = 'EUR.USD'; + mutableFx.source = 'fx_two'; + mutableFx.open = 1.08; + mutableFx.high = 1.09; + mutableFx.low = 1.07; + mutableFx.close = 1.085; + mutableFx.ts = 1_700_000_060_000_000n; + const expectedFx2 = encodeFx1mIlpV2(mutableFx); + + const pBar2 = writer.writeBar1m(mutableBar); + const pFx2 = writer.writeFx1m(mutableFx); + + await Promise.all([pBar1, pFx1, pBar2, pFx2]); + const stats = await writer.finish(); + + expect(stats).toEqual({ + rows: 4, + batches: 4, + bytes: + expectedBar1.byteLength + + expectedFx1.byteLength + + expectedBar2.byteLength + + expectedFx2.byteLength, + }); + expect(batches).toEqual([expectedBar1, expectedFx1, expectedBar2, expectedFx2]); + }); + it('propagates sink rejection and fails closed for queued and subsequent calls with zero extra sink writes', async () => { const boom = new Error('simulated sink EPIPE'); let sinkCalls = 0; From 02eefd6e1f0e1b8d796ec2e648695e6065ff550b Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 01:03:29 -0500 Subject: [PATCH 26/26] T-154: tests --- .../questdb/test/ilp-v2-writer-edges.test.ts | 426 ++++++++++++++++++ 1 file changed, 426 insertions(+) create mode 100644 libs/data/questdb/test/ilp-v2-writer-edges.test.ts diff --git a/libs/data/questdb/test/ilp-v2-writer-edges.test.ts b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts new file mode 100644 index 00000000..d43bd8ae --- /dev/null +++ b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts @@ -0,0 +1,426 @@ +import { describe, expect, it } from 'bun:test'; +import { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Bar1mSession, + type Fx1mIlpV2Row, + type IlpV2BatchSink, +} from '../src/index'; + +const encoder = new TextEncoder(); + +function asciiBytes(text: string): number[] { + return Array.from(encoder.encode(text)); +} + +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { + const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { + return { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_000_000n, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: 'RTH', + source: 'eod_unadj', + ...overrides, + }; +} + +function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { + return { + pair: 'USD.CAD', + source: 'eod', + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + ts: 1_736_951_400_000_000n, + ...overrides, + }; +} + +function expectEncodeError(fn: () => unknown, kind: IlpV2EncodeError['kind'], field: string) { + let caught: unknown; + try { + fn(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(IlpV2EncodeError); + expect((caught as IlpV2EncodeError).kind).toBe(kind); + expect((caught as IlpV2EncodeError).field).toBe(field); +} + +describe('ILP v2 encoder edge cases', () => { + it('matches golden_bytes_literal_ieee754_little_endian_without_to_le_bytes with hand-written bytes', () => { + // Mirrors `golden_bytes_literal_ieee754_little_endian_without_to_le_bytes` + // in `tools/curate-etl/src/ilp_tests.rs` (key 7, source eod_unadj). + const actual = encodeBar1mIlpV2({ + listing_id: 7, + ts: 1_700_000_000_000_000n, + known_at: 1_700_000_060_000_000n, + open: 1.0, + high: 2.0, + low: 0.5, + close: 1.5, + volume: 0.0, + session: 'RTH', + source: 'eod_unadj', + }); + + const expected = new Uint8Array([ + ...asciiBytes('bars_1m,listing_id=7,session=RTH,source=eod_unadj '), + ...asciiBytes('open=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf0, + 0x3f, + ...asciiBytes(',high=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x40, + ...asciiBytes(',low=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xe0, + 0x3f, + ...asciiBytes(',close=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf8, + 0x3f, + ...asciiBytes(',volume=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ...asciiBytes(',known_at=1700000060000000t 1700000000000000t\n'), + ]); + + expect(actual).toEqual(expected); + }); + + it('preserves the negative-zero sign bit like Rust f64::to_le_bytes and emits -0 listing_id as 0', () => { + const bytes = encodeBar1mIlpV2(sampleBar({ listing_id: -0, volume: -0 })); + + expect(Array.from(bytes.slice(0, 22))).toEqual(asciiBytes('bars_1m,listing_id=0,s')); + const volumePrefix = encoder.encode(',volume=='); + const suffix = encoder.encode(',known_at=1736951460000000t 1736951400000000t\n'); + const volStart = bytes.byteLength - suffix.byteLength - 9 - volumePrefix.byteLength; + expect(bytes.slice(volStart, volStart + volumePrefix.byteLength)).toEqual(volumePrefix); + expect( + Array.from( + bytes.slice(volStart + volumePrefix.byteLength, volStart + volumePrefix.byteLength + 9) + ) + ).toEqual([0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]); + }); + + it('encodes extreme finite doubles (MAX_VALUE, MIN_VALUE subnormal, negative) without rejection', () => { + const bytes = encodeFx1mIlpV2( + sampleFx({ open: Number.MAX_VALUE, high: Number.MIN_VALUE, low: -1.5, close: 0 }) + ); + const head = encoder.encode('fx_1m,pair=USD.CAD,source=eod open=='); + expect(bytes.slice(0, head.byteLength)).toEqual(head); + let o = head.byteLength; + // MAX_VALUE = 0x7fefffffffffffff + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f, + ]); + o += 9 + ',high=='.length; + // MIN_VALUE = 0x0000000000000001 + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]); + o += 9 + ',low=='.length; + // -1.5 = 0xbff8000000000000 + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf, + ]); + }); + + it('returns a fresh buffer per call so mutating one encoding cannot corrupt another', () => { + const row = sampleFx(); + const a = encodeFx1mIlpV2(row); + const b = encodeFx1mIlpV2(row); + a.fill(0); + expect(b).toEqual(encodeFx1mIlpV2(row)); + expect(b[0]).toBe(0x66); // 'f' + }); + + it('escapes a symbol consisting only of special characters', () => { + const bytes = encodeFx1mIlpV2(sampleFx({ pair: ' ,=\\\n\r' })); + const expected = encoder.encode('fx_1m,pair=\\ \\,\\=\\\\\\\n\\\r,source=eod open=='); + expect(bytes.slice(0, expected.byteLength)).toEqual(expected); + }); + + it('rejects invalid or empty session tags with a typed error', () => { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: 'rth' as Bar1mSession })), + 'invalid-session', + 'session' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: 'RTH ' as Bar1mSession })), + 'invalid-session', + 'session' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: '' as Bar1mSession })), + 'empty-symbol', + 'session' + ); + }); + + it('rejects non-bigint timestamps (JS number) instead of silently encoding them', () => { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: 1_700_000_000_000_000 as unknown as bigint })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: 5 as unknown as bigint })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ ts: 0 as unknown as bigint })), + 'timestamp-out-of-range', + 'ts' + ); + }); + + it('accepts the fx_1m designated timestamp at INT64_MAX', () => { + const max = 2n ** 63n - 1n; + const bytes = encodeFx1mIlpV2(sampleFx({ ts: max })); + const suffix = encoder.encode(` ${max.toString(10)}t\n`); + expect(bytes.slice(bytes.byteLength - suffix.byteLength)).toEqual(suffix); + }); +}); + +describe('createIlpV2BatchWriter edge cases', () => { + it('rejects construction without a usable sink and rejects unsafe-integer limits', () => { + expect(() => createIlpV2BatchWriter(undefined as never)).toThrow(TypeError); + expect(() => createIlpV2BatchWriter({} as never)).toThrow(TypeError); + expect(() => createIlpV2BatchWriter({ sink: {} as IlpV2BatchSink })).toThrow(TypeError); + const sink: IlpV2BatchSink = { write: async () => {} }; + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 2 ** 53 })).toThrow(RangeError); + expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: '5' as unknown as number })).toThrow( + RangeError + ); + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 1, maxBatchRows: 1 })).not.toThrow(); + }); + + it('flushes at DEFAULT_ILP_MAX_BATCH_ROWS when no limits are supplied', async () => { + const batches: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ sink: { write: async b => void batches.push(b) } }); + const row = sampleFx({ ts: 0n }); + const rowLen = encodeFx1mIlpV2(row).byteLength; + // Row size keeps 10_000 rows well below the 1 MiB default, so only the row limit triggers. + expect(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS).toBeLessThan(DEFAULT_ILP_MAX_BATCH_BYTES); + + for (let i = 0; i < DEFAULT_ILP_MAX_BATCH_ROWS - 1; i++) { + await writer.writeFx1m(row); + } + expect(batches).toHaveLength(0); + await writer.writeFx1m(row); + expect(batches).toHaveLength(1); + expect(batches[0]!.byteLength).toBe(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS); + + await writer.writeFx1m(row); + const stats = await writer.finish(); + expect(stats).toEqual({ + rows: DEFAULT_ILP_MAX_BATCH_ROWS + 1, + batches: 2, + bytes: rowLen * (DEFAULT_ILP_MAX_BATCH_ROWS + 1), + }); + }); + + it('hands the sink a fresh batch buffer per flush so retained batches are never overwritten', async () => { + const retained: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ + sink: { write: async b => void retained.push(b) }, + maxBatchRows: 1, + }); + const r1 = sampleBar({ listing_id: 1 }); + const r2 = sampleBar({ listing_id: 2 }); + await writer.writeBar1m(r1); + await writer.writeBar1m(r2); + await writer.finish(); + expect(retained[0]).not.toBe(retained[1]); + expect(retained[0]!.buffer).not.toBe(retained[1]!.buffer); + expect(retained).toEqual([encodeBar1mIlpV2(r1), encodeBar1mIlpV2(r2)]); + }); + + it('a rejected row in the middle of overlapping writes does not block or reorder later queued rows', async () => { + const batches: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ + sink: { write: async b => void batches.push(b.slice()) }, + maxBatchRows: 2, + maxBatchBytes: 100_000, + }); + const a = sampleBar({ listing_id: 1 }); + const c = sampleFx({ pair: 'EUR.USD' }); + const d = sampleBar({ listing_id: 4 }); + + const pa = writer.writeBar1m(a); + const pb = writer.writeBar1m(sampleBar({ high: Number.NaN })); + const pc = writer.writeFx1m(c); + const pd = writer.writeBar1m(d); + const pFinish = writer.finish(); + + await pa; + await expect(pb).rejects.toBeInstanceOf(IlpV2EncodeError); + await pc; + await pd; + const stats = await pFinish; + + const expected = [encodeBar1mIlpV2(a), encodeFx1mIlpV2(c), encodeBar1mIlpV2(d)]; + expect(batches).toEqual([concatBytes(expected.slice(0, 2)), expected[2]!]); + expect(stats).toEqual({ + rows: 3, + batches: 2, + bytes: expected.reduce((s, e) => s + e.byteLength, 0), + }); + }); + + it('treats a synchronously throwing sink like a rejected write and fails closed', async () => { + const boom = new Error('sync sink failure'); + let calls = 0; + const sink: IlpV2BatchSink = { + write(): Promise { + calls += 1; + throw boom; + }, + }; + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1 }); + + await expect(writer.writeBar1m(sampleBar())).rejects.toBe(boom); + await expect(writer.writeBar1m(sampleBar())).rejects.toThrow(/sink write failure/i); + await expect(writer.flush()).rejects.toThrow(/sink write failure/i); + expect(calls).toBe(1); + }); + + it('propagates a sink failure on the finish() tail flush, excludes it from stats, and stays closed', async () => { + const boom = new Error('tail failure'); + let calls = 0; + const sink: IlpV2BatchSink = { + async write(): Promise { + calls += 1; + if (calls === 2) { + throw boom; + } + }, + }; + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); + await writer.writeBar1m(sampleBar({ listing_id: 1 })); + await writer.writeBar1m(sampleBar({ listing_id: 2 })); // batch 1 OK + await writer.writeBar1m(sampleBar({ listing_id: 3 })); // pending tail + + await expect(writer.finish()).rejects.toBe(boom); + expect(calls).toBe(2); + + const err = await writer.finish().then( + () => null, + (e: unknown) => e as Error + ); + expect(err).toBeInstanceOf(Error); + expect(err!.message).toMatch(/sink write failure/i); + // The original sink error is preserved as the cause for diagnostics. + expect(err!.cause).toBe(boom); + expect(calls).toBe(2); + }); + + it('flush() on an explicit call propagates sink failure and blocks the tail on finish()', async () => { + const boom = new Error('flush failure'); + let calls = 0; + const writer = createIlpV2BatchWriter({ + sink: { + async write(): Promise { + calls += 1; + throw boom; + }, + }, + }); + await writer.writeFx1m(sampleFx()); + await expect(writer.flush()).rejects.toBe(boom); + await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); + await expect(writer.finish()).rejects.toThrow(/sink write failure/i); + expect(calls).toBe(1); + }); + + it('serializes an overlapping explicit flush() behind in-flight writes', async () => { + const order: string[] = []; + let release: (() => void) | null = null; + const writer = createIlpV2BatchWriter({ + sink: { + write(b: Uint8Array): Promise { + order.push(`write:${b.byteLength}`); + if (release === null) { + return new Promise(resolve => { + release = resolve; + }); + } + return Promise.resolve(); + }, + }, + maxBatchRows: 1, + }); + const row = sampleFx(); + const len = encodeFx1mIlpV2(row).byteLength; + + const p1 = writer.writeFx1m(row); + const pFlush = writer.flush().then(() => order.push('flushed')); + const p2 = writer.writeFx1m(row); + + await Promise.resolve(); + expect(order).toEqual([`write:${len}`]); + release!(); + await Promise.all([p1, pFlush, p2]); + expect(order).toEqual([`write:${len}`, 'flushed', `write:${len}`]); + }); +});