diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 31e3ea8d..faf963c7 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1671,9 +1671,9 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m `run_curate_bars_1m` / `run_curate_bars_1m_with_readers` (`src/run_curate_bars_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a headerless 5-column `provider_mapping.tsv` (reusing `load_provider_mapping_tsv` and the shared `qmSplits` loader from `src/run_curate_bars.rs`) into per-shard QuestDB ILP v2 files (`/bars_1m.shard-.ilp`): -- **Bounded-memory chunking:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), calling `curate_and_write_bars_1m` once per framed chunk into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard. +- **Bounded-memory chunking & listing-keyed splits:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), resolving each bar's `listing_id` on its Eastern Time `session_date` before applying `listing_id`-keyed `qmSplits` un-adjustment (preventing split leakage across reused tickers) into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard. - **Cross-chunk semantics & reporting:** `mapping_source` must be `"eod"`. Collision collapse/drop and `(listing_id, ts)` ordering apply per chunk; the same `(listing_id, ts)` appearing in two chunks is emitted twice and relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. Aggregated `curate_stats.listings_out` and `curate_stats.builder.keys_out` are sums of per-chunk counts (not global distinct counts). `known_at_micros` is caller-supplied and supplies no evidence of earlier market availability. -- **Fail-closed publication:** Rejects pre-existing `bars_1m.shard-.ilp` files before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. CLI wiring, `--from-mongo`, and live QuestDB ingestion are separate follow-ups. +- **Fail-closed publication:** Preflight scans `out_dir` for any pre-existing `bars_1m.shard-.ilp` file (regardless of `shard_count`) and rejects before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. CLI wiring, `--from-mongo`, and live QuestDB ingestion are separate follow-ups. ## Lagged Macro Regime Series Builder (`M2.2n`) diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs index 849ebbc7..f8c7689f 100644 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ b/tools/curate-etl/src/curate_bars_1m.rs @@ -33,7 +33,7 @@ use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; use crate::ilp::{IlpShardedWriter, IlpWriterError}; use crate::provider_mapping::ProviderMappingTable; -use crate::split::SplitTable; +use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; /// Accounting summary produced alongside [`CurateBars1mOutput::rows`]. /// @@ -185,14 +185,36 @@ fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> bool { && a.session == b.session } +#[inline] +fn is_valid_price(price: f64) -> bool { + price.is_finite() && price > 0.0 +} + +#[inline] +fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { + high >= low && open >= low && open <= high && close >= low && close <= high +} + +#[inline] +fn decrement_builder_session_count(stats: &mut Bars1mStats, session: IntradaySession) { + match session { + IntradaySession::Pre => stats.pre_rows_out -= 1, + IntradaySession::Rth => stats.rth_rows_out -= 1, + IntradaySession::Post => stats.post_rows_out -= 1, + } +} + /// 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( +/// `provider_mapping` on each bar's Eastern Time `session_date`, optionally un-adjusts OHLCV via +/// `listing_splits` (keyed by permanent `listing_id`, preventing split leakage across reused +/// tickers), stamps `source`, re-sorts in place by `(listing_id, ts)`, and compacts +/// cross-`source_id` collisions. +fn map_bars_1m_impl( built: Bars1mBuild, provider_mapping: &ProviderMappingTable, mapping_source: &str, source: &'static str, + listing_splits: Option<&SplitTable>, ) -> CurateBars1mOutput where K: Eq + AsRef, @@ -222,25 +244,84 @@ where continue; } + let mut key_kept_or_unmapped = false; for bar in &built.rows[run_start..run_end] { let Some(listing_id) = cursor.resolve(bar.session_date) else { stats.dropped_unmapped += 1; + key_kept_or_unmapped = true; continue; }; + let (open, high, low, close, volume) = if let Some(splits) = listing_splits { + let factor = splits.cum_factor_after(&listing_id, bar.session_date); + if factor != 1.0 { + let mut unadj = unadjust_ohlcv( + OhlcvBar { + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + }, + factor, + ); + if !is_valid_price(unadj.open) + || !is_valid_price(unadj.high) + || !is_valid_price(unadj.low) + || !is_valid_price(unadj.close) + { + stats.builder.dropped_invalid_ohlc += 1; + stats.builder.rows_out -= 1; + decrement_builder_session_count(&mut stats.builder, bar.session); + stats.rows_in -= 1; + continue; + } + if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { + stats.builder.dropped_inconsistent_ohlc += 1; + stats.builder.rows_out -= 1; + decrement_builder_session_count(&mut stats.builder, bar.session); + stats.rows_in -= 1; + continue; + } + if !unadj.volume.is_finite() + || unadj.volume < 0.0 + || (bar.volume > 0.0 && unadj.volume == 0.0) + { + stats.builder.dropped_invalid_volume += 1; + stats.builder.rows_out -= 1; + decrement_builder_session_count(&mut stats.builder, bar.session); + stats.rows_in -= 1; + continue; + } + if unadj.volume == 0.0 { + unadj.volume = 0.0; + } + (unadj.open, unadj.high, unadj.low, unadj.close, unadj.volume) + } else { + (bar.open, bar.high, bar.low, bar.close, bar.volume) + } + } else { + (bar.open, bar.high, bar.low, bar.close, bar.volume) + }; + + key_kept_or_unmapped = true; rows.push(Bar1mRow { key: listing_id, ts: bar.ts, session_date: bar.session_date, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, + open, + high, + low, + close, + volume, session: bar.session, source, }); } + + if !key_kept_or_unmapped { + stats.builder.keys_out -= 1; + } } // Free builder rows before sorting/compacting mapped rows to cut peak RAM. @@ -306,6 +387,21 @@ where CurateBars1mOutput { rows, stats } } +/// 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, + source: &'static str, +) -> CurateBars1mOutput +where + K: Eq + AsRef, +{ + map_bars_1m_impl(built, provider_mapping, mapping_source, source, None) +} + /// 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`] @@ -389,6 +485,51 @@ where }) } +/// Variant of [`curate_and_write_bars_1m`] that takes a [`SplitTable`] keyed by permanent +/// `listing_id` and resolves `(mapping_source, source_id, session_date) -> listing_id` on each +/// bar's Eastern Time `session_date` **before** applying split un-adjustment. +/// +/// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022 +/// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation +/// invariants and cross-`source_id` collision handling. +pub(crate) fn curate_and_write_bars_1m_by_listing( + bars: B, + listing_splits: &SplitTable, + 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>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateBars1mError::EmptyMappingSource.into()); + } + + let empty_splits: SplitTable = SplitTable::default(); + let built = build_bars_1m(bars, &empty_splits); + let curated = map_bars_1m_impl( + built, + provider_mapping, + mapping_source, + BARS_1M_SOURCE_EOD, + Some(listing_splits), + ); + 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 `eodIntraday1M` stream via [`decode_eod_intraday_stream`], /// converts each valid document via [`crate::bson_eod_intraday::RawEodIntradayBar::into_eod_intraday_bar`], /// and runs [`curate_and_write_bars_1m`] against the caller-owned [`IlpShardedWriter`]. diff --git a/tools/curate-etl/src/run_curate_bars.rs b/tools/curate-etl/src/run_curate_bars.rs index 9b7b7d2c..c45eec76 100644 --- a/tools/curate-etl/src/run_curate_bars.rs +++ b/tools/curate-etl/src/run_curate_bars.rs @@ -528,6 +528,14 @@ pub(crate) struct EodMappingIndex { pub(crate) eod_ranges_by_listing: HashMap>, } +pub(crate) struct DecodedQmSplits { + pub(crate) compacted_splits: Vec<(i32, SplitEvent)>, + pub(crate) splits_docs_framed: u64, + pub(crate) splits_bytes_read: u64, + pub(crate) splits_decode: BsonQmActionDecodeStats, + pub(crate) split_rekey: SplitRekeyStats, +} + pub(crate) struct LoadedQmSplits { pub(crate) splits: SplitTable>, pub(crate) splits_docs_framed: u64, @@ -597,15 +605,15 @@ pub(crate) fn build_eod_mapping_index( } } -/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, compacts -/// cross-key QM aliases per `(listing_id, ex_date)`, fans out to `"eod"` partners, and builds -/// [`SplitTable>`]. -pub(crate) fn load_qm_splits_from_reader( +/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, filters out +/// listings without an `"eod"` partner, and compacts cross-key QM aliases per `(listing_id, ex_date)` +/// while retaining permanent `listing_id` identity. +pub(crate) fn decode_and_compact_qm_splits_from_reader( splits_stream: R, qm_splits_path: &Path, mapping: &ProviderMappingTable, eod_by_listing: &HashMap>>, -) -> Result { +) -> Result { let mut splits_reader = RawBsonChunkReader::new(splits_stream); let mut split_rekey = SplitRekeyStats::default(); let mut mapped_splits: Vec = Vec::new(); @@ -646,11 +654,42 @@ pub(crate) fn load_qm_splits_from_reader( let splits_bytes_read = splits_reader.bytes_read(); split_rekey.splits_in = splits_decode.docs_in; - // Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys. + // Compact cross-key QM aliases per `(listing_id, ex_date)`. let (compacted_splits, splits_collision_collapsed) = compact_mapped_qm_splits(qm_splits_path, mapped_splits)?; split_rekey.splits_collision_collapsed = splits_collision_collapsed; + Ok(DecodedQmSplits { + compacted_splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + split_rekey, + }) +} + +/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, compacts +/// cross-key QM aliases per `(listing_id, ex_date)`, fans out to `"eod"` partners, and builds +/// [`SplitTable>`]. +pub(crate) fn load_qm_splits_from_reader( + splits_stream: R, + qm_splits_path: &Path, + mapping: &ProviderMappingTable, + eod_by_listing: &HashMap>>, +) -> Result { + let DecodedQmSplits { + compacted_splits, + splits_docs_framed, + splits_bytes_read, + splits_decode, + mut split_rekey, + } = decode_and_compact_qm_splits_from_reader( + splits_stream, + qm_splits_path, + mapping, + eod_by_listing, + )?; + let mut split_events: Vec<(Arc, SplitEvent)> = Vec::with_capacity(compacted_splits.len()); for (listing_id, event) in compacted_splits { let partners = &eod_by_listing[&listing_id]; diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs index c92e804e..3803f847 100644 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -2,7 +2,7 @@ //! //! Streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a //! headerless 5-column `provider_mapping.tsv` into per-shard QuestDB ILP v2 files -//! (`/bars_1m.shard-.ilp`) via [`curate_and_write_bars_1m`]. +//! (`/bars_1m.shard-.ilp`) via listing-keyed [`crate::curate_bars_1m`] curation. //! //! # Bounded-Memory Chunking //! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and @@ -10,8 +10,9 @@ //! `crate::bson_stream::decode_eod_intraday_chunks`, whose callback API hides chunk boundaries. //! - Each framed chunk is decoded into a chunk-local `Vec>>` (reusing //! interned `"eod"` keys from `provider_mapping.tsv` and retaining unknown codes so -//! `curate_bars_1m` counts them in `dropped_unmapped`) and passed to -//! [`curate_and_write_bars_1m`] against one shared [`IlpShardedWriter`]. +//! `curate_bars_1m` counts them in `dropped_unmapped`) and curated per chunk against one shared +//! [`IlpShardedWriter`] (resolving `listing_id` on each bar's Eastern Time `session_date` before +//! applying listing-keyed splits). //! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF. //! - Peak memory is bounded by the reference tables (`provider_mapping` + `SplitTable`), the //! current BSON chunk (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single @@ -26,14 +27,18 @@ //! - `CurateBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its //! nested [`Bars1mStats`] across chunks. In particular, `curate_stats.listings_out` and //! `curate_stats.builder.keys_out` are **sums of per-chunk counts**, not global distinct counts. -//! - `mapping_source` must be `"eod"` because the shared `qmSplits` re-keying helper -//! (`run_curate_bars::load_qm_splits_from_reader`) builds `SplitTable>` keyed for -//! `"eod"` `source_id`s. +//! - `mapping_source` must be `"eod"` because the shared `qmSplits` loader +//! (`run_curate_bars::decode_and_compact_qm_splits_from_reader`) filters to listings with `"eod"` +//! partners. Split events retain permanent `listing_id: i32` identity (`SplitTable`), and +//! each bar's listing is resolved via `provider_mapping` on its Eastern Time `session_date` +//! **before** choosing the split factor so reused tickers cannot leak splits across listings. //! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's //! `known_at` column; it supplies no evidence of earlier market availability. //! //! # File Publication & Fail-Closed Guarantees -//! - Pre-existing `bars_1m.shard-.ilp` files in `out_dir` are rejected before staging. +//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m.shard-.ilp` file +//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards +//! from a prior larger-shard-count run cannot survive alongside a new export. //! - Each shard writes into an exclusively created staging file in `out_dir` //! (`.bars_1m.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes to //! `bars_1m.shard-.ilp` via same-directory `hard_link` followed by removing the staged name @@ -45,6 +50,7 @@ use std::collections::{HashMap, HashSet}; use std::error::Error; +use std::ffi::OsStr; use std::fmt; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufWriter, Write}; @@ -57,7 +63,7 @@ use crate::bson_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecode use crate::bson_qm_actions::BsonQmActionDecodeStats; use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; use crate::curate_bars_1m::{ - curate_and_write_bars_1m, CurateBars1mStats, CurateBars1mWriteError, + curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError, }; use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions}; use crate::parquet_bars::RollbackFailure; @@ -66,8 +72,8 @@ use crate::parquet_publish::{ }; use crate::provider_mapping::ProviderMappingTable; use crate::run_curate_bars::{ - build_eod_mapping_index, load_provider_mapping_tsv, load_qm_splits_from_reader, - EodMappingIndex, LoadedQmSplits, RunCurateBarsError, SplitRekeyStats, + build_eod_mapping_index, decode_and_compact_qm_splits_from_reader, load_provider_mapping_tsv, + DecodedQmSplits, EodMappingIndex, RunCurateBarsError, SplitRekeyStats, }; use crate::split::SplitTable; @@ -148,7 +154,7 @@ pub enum RunCurateBars1mError { path: PathBuf, source: BsonStreamError, }, - /// Curation or per-row ILP write error inside [`curate_and_write_bars_1m`]. + /// Curation or per-row ILP write error inside the per-chunk `bars_1m` curation stage. CurateWrite(CurateBars1mWriteError), /// ILP writer initialization or final flush error. Ilp(IlpWriterError), @@ -234,7 +240,7 @@ impl Error for RunCurateBars1mError { struct LoadedReferenceInputs { mapping: ProviderMappingTable, eod_keys: HashSet>, - splits: SplitTable>, + splits: SplitTable, splits_docs_framed: u64, splits_bytes_read: u64, splits_decode: BsonQmActionDecodeStats, @@ -271,21 +277,51 @@ fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1 if args.ilp_options.max_batch_rows == 0 { return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)); } - if args.out_dir.exists() && !args.out_dir.is_dir() { - return Err(RunCurateBars1mError::InvalidOutDir { + if args.out_dir.exists() { + if !args.out_dir.is_dir() { + return Err(RunCurateBars1mError::InvalidOutDir { + path: args.out_dir.clone(), + detail: "path exists and is not a directory".to_string(), + }); + } + let entries = fs::read_dir(&args.out_dir).map_err(|source| RunCurateBars1mError::Io { path: args.out_dir.clone(), - detail: "path exists and is not a directory".to_string(), - }); - } - for shard_idx in 0..args.shard_count { - let final_path = final_shard_path(&args.out_dir, shard_idx); - if final_path.exists() { - return Err(RunCurateBars1mError::OutputFileExists { path: final_path }); + source, + })?; + let mut existing_shards: Vec = Vec::new(); + for entry in entries { + let entry = entry.map_err(|source| RunCurateBars1mError::Io { + path: args.out_dir.clone(), + source, + })?; + if is_final_shard_file_name(&entry.file_name()) { + existing_shards.push(entry.path()); + } + } + if !existing_shards.is_empty() { + existing_shards.sort(); + return Err(RunCurateBars1mError::OutputFileExists { + path: existing_shards.remove(0), + }); } } Ok(()) } +#[inline] +fn is_final_shard_file_name(name: &OsStr) -> bool { + let Some(s) = name.to_str() else { + return false; + }; + let Some(rest) = s.strip_prefix("bars_1m.shard-") else { + return false; + }; + let Some(digits) = rest.strip_suffix(".ilp") else { + return false; + }; + !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) +} + #[inline] fn final_shard_path(out_dir: &Path, shard_idx: usize) -> PathBuf { out_dir.join(format!("bars_1m.shard-{shard_idx:02}.ilp")) @@ -311,14 +347,29 @@ fn load_reference_inputs( }) })?; - let LoadedQmSplits { - splits, + let DecodedQmSplits { + compacted_splits, splits_docs_framed, splits_bytes_read, splits_decode, - split_rekey, - } = load_qm_splits_from_reader(splits_reader, splits_path, &mapping, &eod_by_listing) - .map_err(RunCurateBars1mError::LoadReference)?; + mut split_rekey, + } = decode_and_compact_qm_splits_from_reader( + splits_reader, + splits_path, + &mapping, + &eod_by_listing, + ) + .map_err(RunCurateBars1mError::LoadReference)?; + + split_rekey.splits_applied = compacted_splits.len(); + split_rekey.split_events_attached = compacted_splits.len(); + + let splits = SplitTable::::from_events(compacted_splits).map_err(|source| { + RunCurateBars1mError::LoadReference(RunCurateBarsError::SplitTable { + path: splits_path.to_path_buf(), + source, + }) + })?; Ok(LoadedReferenceInputs { mapping, @@ -426,7 +477,7 @@ where max_rows_per_chunk = chunk_len; } - let write_report = curate_and_write_bars_1m( + let write_report = curate_and_write_bars_1m_by_listing( chunk_bars.drain(..), &reference.splits, &reference.mapping, @@ -467,8 +518,8 @@ where /// /// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits` /// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] + -/// [`decode_eod_intraday_buffer`] calling [`curate_and_write_bars_1m`] once per chunk, and calls -/// [`IlpShardedWriter::finish`] exactly once after EOF. +/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits, +/// and calls [`IlpShardedWriter::finish`] exactly once after EOF. pub fn run_curate_bars_1m_with_readers( args: &CurateBars1mArgs, intraday: RI, diff --git a/tools/curate-etl/src/run_curate_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_bars_1m_tests.rs index 7fe11279..ea33bdee 100644 --- a/tools/curate-etl/src/run_curate_bars_1m_tests.rs +++ b/tools/curate-etl/src/run_curate_bars_1m_tests.rs @@ -374,6 +374,27 @@ fn assert_report_conservation(report: &CurateBars1mRunReport) { assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); } +/// Split-boundary replay fixture (`run_curate_bars_1m_tests::split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`): +/// +/// Provenance & unavailable-evidence note: +/// - Offline synthetic BSON inputs pinned to the empirical split-boundary figures documented in +/// `design/DATA-CONTRACTS.md` §1 (lines 13, 15, 25) and `tools/curate-etl/src/curate_bars_1m_tests.rs`: +/// - `NVDA.US` (`listing_id=1001`, `eod: NVDA.US`, `qm: NVDA`, 10:1 forward split ex-date +/// `2024-06-10`, `forfactor=1, tofactor=10, splitratio=0.1`): +/// - `2024-06-07` (pre-split): adj 1m close `120.888`, adj vol `412_390.0` -> raw `1208.88`, +/// vol `41_239.0`; raw `bars_1d` close baseline `1208.88` (`DATA-CONTRACTS.md` §1 line 13). +/// - `2024-06-10` (ex-date): 1m close `121.79`, vol `350_000.0` (unchanged); raw `bars_1d` +/// close baseline `121.79`. +/// - `NEXM.V` (`listing_id=2002`, `eod: NEXM.V`, `qm: NEXM:VNX`, 1:20 reverse split ex-date +/// `2025-06-18`, `forfactor=20, tofactor=1, splitratio=20.0`): +/// - `2025-06-17` (pre-split): adj 1m close `24.29`, adj vol `5_000.0` -> raw `1.2145`, +/// vol `100_000.0`; raw `bars_1d` close baseline `1.215` (~0.041% rel diff, matching +/// `24.29` vs `~1.21` in `DATA-CONTRACTS.md` §1 line 15). +/// - `2025-06-18` (ex-date): 1m close `24.30`, vol `12_500.0` (unchanged); raw `bars_1d` +/// close baseline `24.30`. +/// - Live QA MongoDB extracts (`stock.eodIntraday1M`, `stock.qmSplits`) and curated `bars_1d` +/// Parquet baselines are not committed in this repository and are unavailable in the offline +/// sandbox; independent live-extract comparison remains for the live-host verification follow-up. #[test] fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { let dir = TempDirGuard::new("bars1m-split"); @@ -398,65 +419,60 @@ fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { make_split_doc("NEXM:VNX", "2025-06-18", 20.0, 1.0), ]); - // Pinned split-adjusted `eodIntraday1M` bars spanning each ex-date: - // - NVDA 2024-06-07 (pre-10:1): raw daily close = 1208.88 -> adj close = 120.888, adj vol = 5000 -> raw vol = 500 - // - NVDA 2024-06-10 (ex-date): raw daily close = 121.79 -> adj close = 121.79, adj vol = 4200 -> raw vol = 4200 - // - NEXM 2025-06-17 (pre-1:20): raw daily close = 0.42 -> adj close = 8.40, adj vol = 1000 -> raw vol = 20000 - // - NEXM 2025-06-18 (ex-date): raw daily close = 8.35 -> adj close = 8.35, adj vol = 1500 -> raw vol = 1500 let intraday_bytes = concat_docs(&[ make_intraday_doc( "NVDA.US", et_ts_sec(2024, 6, 7, 15, 58), - 120.50, + 120.45, 120.95, - 120.40, + 120.35, 120.75, - 3_000.0, + 300_000.0, ), make_intraday_doc( "NVDA.US", et_ts_sec(2024, 6, 7, 15, 59), - 120.75, - 120.92, - 120.70, + 120.50, + 121.00, + 120.40, 120.888, - 5_000.0, + 412_390.0, ), make_intraday_doc( "NVDA.US", et_ts_sec(2024, 6, 10, 15, 59), - 121.60, - 121.85, - 121.55, + 121.50, + 121.95, + 121.40, 121.79, - 4_200.0, + 350_000.0, ), make_intraday_doc( "NEXM.V", - et_ts_sec(2025, 6, 17, 15, 58), - 8.20, - 8.50, - 8.10, - 8.30, - 500.0, + et_ts_sec(2025, 6, 17, 9, 30), + 24.00, + 24.60, + 23.80, + 24.20, + 2_000.0, ), make_intraday_doc( "NEXM.V", et_ts_sec(2025, 6, 17, 15, 59), - 8.30, - 8.45, - 8.25, - 8.40, - 1_000.0, + 24.20, + 24.40, + 24.10, + 24.29, + 5_000.0, ), make_intraday_doc( "NEXM.V", et_ts_sec(2025, 6, 18, 15, 59), - 8.30, - 8.40, - 8.25, - 8.35, - 1_500.0, + 24.10, + 24.50, + 23.90, + 24.30, + 12_500.0, ), ]); @@ -466,7 +482,7 @@ fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { IlpShardedWriter::new(vec![&mut sink0, &mut sink1], IlpWriterOptions::default()).unwrap(); let args = make_args( - mapping_path, + mapping_path.clone(), dir.path().join("qmSplits.bson"), dir.path().join("eodIntraday1M.bson"), dir.path().join("out"), @@ -505,25 +521,25 @@ fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { let nvda_pre = find_row(nvda_id, et_ts_sec(2024, 6, 7, 15, 59)); assert!((nvda_pre.close - 1208.88).abs() < 1e-9); - assert!((nvda_pre.volume - 500.0).abs() < 1e-9); + assert!((nvda_pre.volume - 41_239.0).abs() < 1e-9); let nvda_ex = find_row(nvda_id, et_ts_sec(2024, 6, 10, 15, 59)); - assert_eq!(nvda_ex.open.to_bits(), 121.60_f64.to_bits()); - assert_eq!(nvda_ex.high.to_bits(), 121.85_f64.to_bits()); - assert_eq!(nvda_ex.low.to_bits(), 121.55_f64.to_bits()); + assert_eq!(nvda_ex.open.to_bits(), 121.50_f64.to_bits()); + assert_eq!(nvda_ex.high.to_bits(), 121.95_f64.to_bits()); + assert_eq!(nvda_ex.low.to_bits(), 121.40_f64.to_bits()); assert_eq!(nvda_ex.close.to_bits(), 121.79_f64.to_bits()); - assert_eq!(nvda_ex.volume.to_bits(), 4_200.0_f64.to_bits()); + assert_eq!(nvda_ex.volume.to_bits(), 350_000.0_f64.to_bits()); let nexm_pre = find_row(nexm_id, et_ts_sec(2025, 6, 17, 15, 59)); - assert!((nexm_pre.close - 0.42).abs() < 1e-9); - assert!((nexm_pre.volume - 20_000.0).abs() < 1e-9); + assert!((nexm_pre.close - 1.2145).abs() < 1e-9); + assert!((nexm_pre.volume - 100_000.0).abs() < 1e-9); let nexm_ex = find_row(nexm_id, et_ts_sec(2025, 6, 18, 15, 59)); - assert_eq!(nexm_ex.open.to_bits(), 8.30_f64.to_bits()); - assert_eq!(nexm_ex.high.to_bits(), 8.40_f64.to_bits()); - assert_eq!(nexm_ex.low.to_bits(), 8.25_f64.to_bits()); - assert_eq!(nexm_ex.close.to_bits(), 8.35_f64.to_bits()); - assert_eq!(nexm_ex.volume.to_bits(), 1_500.0_f64.to_bits()); + assert_eq!(nexm_ex.open.to_bits(), 24.10_f64.to_bits()); + assert_eq!(nexm_ex.high.to_bits(), 24.50_f64.to_bits()); + assert_eq!(nexm_ex.low.to_bits(), 23.90_f64.to_bits()); + assert_eq!(nexm_ex.close.to_bits(), 24.30_f64.to_bits()); + assert_eq!(nexm_ex.volume.to_bits(), 12_500.0_f64.to_bits()); // Check all four RTH session closes against raw daily baselines within 0.5%. let mut rows_1m: Vec> = decoded.iter().map(DecodedIlpBar1m::to_bar_1m_row).collect(); @@ -533,38 +549,38 @@ fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { Bar1dRow { key: nvda_id, session_date: day(2024, 6, 7), - open: 1200.0, - high: 1215.0, - low: 1195.0, + open: 1197.7, + high: 1216.92, + low: 1180.22, close: 1208.88, - volume: 40_000_000.0, + volume: 41_239_000.0, }, Bar1dRow { key: nvda_id, session_date: day(2024, 6, 10), - open: 120.5, - high: 123.0, - low: 119.5, + open: 120.37, + high: 123.10, + low: 117.01, close: 121.79, - volume: 300_000_000.0, + volume: 314_162_700.0, }, Bar1dRow { key: nexm_id, session_date: day(2025, 6, 17), - open: 0.41, - high: 0.43, - low: 0.40, - close: 0.42, + open: 1.20, + high: 1.23, + low: 1.19, + close: 1.215, // ~0.041% rel diff vs 1.2145 (DATA-CONTRACTS.md §1: ~1.21 raw) volume: 100_000.0, }, Bar1dRow { key: nexm_id, session_date: day(2025, 6, 18), - open: 8.30, - high: 8.45, - low: 8.20, - close: 8.35, - volume: 10_000.0, + open: 24.10, + high: 24.50, + low: 23.90, + close: 24.30, + volume: 12_500.0, }, ]; @@ -578,6 +594,138 @@ fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes() { assert_eq!(check.stats.checked, 4); assert_eq!(check.stats.within_tolerance, 4); assert_eq!(check.stats.mismatched, 0); + assert!(check.stats.max_rel_diff < 0.005); + + // Negative control: omitting qmSplits leaves pre-split bars retroactively adjusted and fails + // the 0.5% check on both pre-split sessions (NVDA 2024-06-07 and NEXM 2025-06-17). + let mut neg_sink = Vec::new(); + let neg_writer = + IlpShardedWriter::new(vec![&mut neg_sink], IlpWriterOptions::default()).unwrap(); + let neg_args = make_args( + mapping_path, + dir.path().join("empty_splits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out-neg"), + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + let _ = run_curate_bars_1m_with_readers( + &neg_args, + Cursor::new(&intraday_bytes), + Cursor::new(Vec::::new()), + neg_writer, + ) + .expect("negative-control run should succeed"); + let mut neg_rows: Vec> = decode_ilp_bars_1m(&neg_sink) + .iter() + .map(DecodedIlpBar1m::to_bar_1m_row) + .collect(); + neg_rows.sort_by_key(|r| (r.key, r.ts)); + let neg_check = check_curated_session_closes( + &neg_rows, + &bars_1d, + &SessionCloseCutoffPolicy::standard_rth(), + 0.005, + ) + .expect("negative-control close check should succeed"); + assert_eq!(neg_check.stats.checked, 4); + assert_eq!(neg_check.stats.within_tolerance, 2); + assert_eq!(neg_check.stats.mismatched, 2); +} + +#[test] +fn reused_ticker_does_not_leak_later_listing_split_to_earlier_listing() { + let dir = TempDirGuard::new("bars1m-reused-ticker"); + let known_at_micros: i64 = 1_750_550_000_000_000; + + // Same non-overlapping FB.US reuse layout as the daily runner fixture: + // listing 10 through 2022-06-08, gap, listing 20 starting 2025-01-01. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "eod\tFB.US\t2012-01-01\t2022-06-08\t10", + "qm\tFB:US\t2012-01-01\t2022-06-08\t10", + "eod\tFB.US\t2025-01-01\t\t20", + "qm\tFBETF:US\t2025-01-01\t\t20", + ], + ); + + // 2:1 forward split belonging strictly to listing 20 (ex-date 2025-06-02). + let splits_bytes = concat_docs(&[make_split_doc("FBETF:US", "2025-06-02", 1.0, 2.0)]); + + let ts_old = et_ts_sec(2022, 6, 8, 15, 59); + let ts_new_pre = et_ts_sec(2025, 5, 30, 15, 59); + let ts_new_ex = et_ts_sec(2025, 6, 2, 15, 59); + + let intraday_bytes = concat_docs(&[ + // Listing 10 bar in 2022: must NOT receive listing 20's 2025 2:1 split. + make_intraday_doc("FB.US", ts_old, 190.0, 195.0, 188.0, 192.0, 1_000.0), + // Listing 20 pre-split bar in May 2025: MUST be un-adjusted by 2:1 (price * 2, vol / 2). + make_intraday_doc("FB.US", ts_new_pre, 25.0, 26.0, 24.5, 25.5, 5_000.0), + // Listing 20 ex-date bar on 2025-06-02: MUST remain unchanged. + make_intraday_doc("FB.US", ts_new_ex, 25.5, 26.5, 25.0, 26.0, 4_000.0), + ]); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + mapping_path, + dir.path().join("qmSplits.bson"), + dir.path().join("eodIntraday1M.bson"), + dir.path().join("out"), + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_bars_1m_with_readers( + &args, + Cursor::new(&intraday_bytes), + Cursor::new(&splits_bytes), + writer, + ) + .expect("reused-ticker run should succeed"); + + assert_report_conservation(&report); + assert_eq!(report.rows_written, 3); + assert_eq!(report.split_rekey.splits_applied, 1); + + let rows = decode_ilp_bars_1m(&sink); + assert_eq!(rows.len(), 3); + + // Listing 10 (2022): bitwise unchanged — no split leakage from listing 20. + let old_row = rows + .iter() + .find(|r| r.listing_id == 10 && r.ts == ts_old * 1_000_000) + .expect("listing 10 row"); + assert_eq!(old_row.open.to_bits(), 190.0_f64.to_bits()); + assert_eq!(old_row.high.to_bits(), 195.0_f64.to_bits()); + assert_eq!(old_row.low.to_bits(), 188.0_f64.to_bits()); + assert_eq!(old_row.close.to_bits(), 192.0_f64.to_bits()); + assert_eq!(old_row.volume.to_bits(), 1_000.0_f64.to_bits()); + + // Listing 20 (2025-05-30 pre-split): un-adjusted by 2:1. + let new_pre = rows + .iter() + .find(|r| r.listing_id == 20 && r.ts == ts_new_pre * 1_000_000) + .expect("listing 20 pre-split row"); + assert!((new_pre.open - 50.0).abs() < 1e-9); + assert!((new_pre.high - 52.0).abs() < 1e-9); + assert!((new_pre.low - 49.0).abs() < 1e-9); + assert!((new_pre.close - 51.0).abs() < 1e-9); + assert!((new_pre.volume - 2_500.0).abs() < 1e-9); + + // Listing 20 (2025-06-02 ex-date): bitwise unchanged. + let new_ex = rows + .iter() + .find(|r| r.listing_id == 20 && r.ts == ts_new_ex * 1_000_000) + .expect("listing 20 ex-date row"); + assert_eq!(new_ex.open.to_bits(), 25.5_f64.to_bits()); + assert_eq!(new_ex.high.to_bits(), 26.5_f64.to_bits()); + assert_eq!(new_ex.low.to_bits(), 25.0_f64.to_bits()); + assert_eq!(new_ex.close.to_bits(), 26.0_f64.to_bits()); + assert_eq!(new_ex.volume.to_bits(), 4_000.0_f64.to_bits()); } #[test] @@ -1235,6 +1383,32 @@ fn fail_closed_preexisting_and_post_preflight_rollback() { )); assert_eq!(fs::read(&expected_race_path).unwrap(), race_sentinel); assert_eq!(list_dir_names(&out_race), vec!["bars_1m.shard-01.ilp"]); + + // Case C: stale final shard OUTSIDE the requested shard_count range (e.g. bars_1m.shard-03.ilp + // left over from a prior 4-shard export when retrying with shard_count = 2). Preflight must + // reject it, preserve its bytes, and create no new files. + let out_stale = dir.path().join("out-stale-shard"); + fs::create_dir_all(&out_stale).unwrap(); + let stale_sentinel = b"stale-shard-03-from-prior-four-shard-export"; + let stale_path = out_stale.join("bars_1m.shard-03.ilp"); + fs::write(&stale_path, stale_sentinel).unwrap(); + + let args_c = make_args( + dir.path().join("provider_mapping.tsv"), + dir.path().join("splits.bson"), + dir.path().join("intraday.bson"), + out_stale.clone(), + 2, + 1_750_000_000_000_000, + BsonStreamOptions::default(), + ); + let err_c = run_curate_bars_1m(&args_c).unwrap_err(); + assert!(matches!( + err_c, + RunCurateBars1mError::OutputFileExists { ref path } if path == &stale_path + )); + assert_eq!(fs::read(&stale_path).unwrap(), stale_sentinel); + assert_eq!(list_dir_names(&out_stale), vec!["bars_1m.shard-03.ilp"]); } #[test]