From 859453edd7aa4b54bf38f851fb334cb2ef2f2967 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 19:14:29 -0500 Subject: [PATCH] =?UTF-8?q?T-185:=20M2.3m=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20bounded-memory=20file-to-file=20`qmIntraday`=20=E2=86=92=20?= =?UTF-8?q?`bars=5F1m`=20runner=20(`run=5Fcurate=5Fqm=5Fbars=5F1m.rs`:=20r?= =?UTF-8?q?aw=20`qmIntraday`=20BSON=20dump=20+=20`provider=5Fmapping.tsv`?= =?UTF-8?q?=20=E2=86=92=20chunked=20`curate=5Fand=5Fwrite=5Fqm=5Fbars=5F1m?= =?UTF-8?q?`=20=E2=86=92=20per-shard=20`bars=5F1m=5Fqm.shard-.ilp`=20I?= =?UTF-8?q?LP=20v2=20files,=20fail-closed=20publish)=20with=20tests=20(no?= =?UTF-8?q?=20new=20crates,=20no=20CLI/bench=20changes,=20no=20live=20Mong?= =?UTF-8?q?o/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 8 + tools/curate-etl/src/lib.rs | 7 + tools/curate-etl/src/run_curate_bars_1m.rs | 2 +- tools/curate-etl/src/run_curate_fx_1m.rs | 2 +- tools/curate-etl/src/run_curate_qm_bars_1m.rs | 643 ++++++++ .../src/run_curate_qm_bars_1m_tests.rs | 1430 +++++++++++++++++ 6 files changed, 2090 insertions(+), 2 deletions(-) create mode 100644 tools/curate-etl/src/run_curate_qm_bars_1m.rs create mode 100644 tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 3c24f001..338f0ae8 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1683,6 +1683,14 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files. - **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, 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 error. CLI wiring, `--from-mongo`, and live QuestDB load remain follow-ups. +## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`) + +`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`): + +- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). +- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-.ilp` prefix so QM and EOD (`bars_1m.shard-.ilp`) exports can share `out_dir` safely. +- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups. + ## Lagged Macro Regime Series Builder (`M2.2n`) `build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation` inputs and a caller-supplied `(country_iso, indicator) -> Option` lookup into sorted, unique `MacroRow` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A). diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 82777e68..09128b37 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -334,6 +334,13 @@ pub use run_curate_fx_1m::{ CurateFx1mRunReport, RunCurateFx1mError, }; +pub mod run_curate_qm_bars_1m; +pub use run_curate_qm_bars_1m::{ + format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers, + CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, +}; + pub mod run_curate_adj; pub use run_curate_adj::{ format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced, diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs index 2b2a781f..86c6c8e5 100644 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -442,7 +442,7 @@ fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) { } #[inline] -fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) { +pub(crate) fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) { add_bars_1m_stats(&mut total.builder, &chunk.builder); total.rows_in += chunk.rows_in; total.rows_out += chunk.rows_out; diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs index 35cb3f3a..7c938c0b 100644 --- a/tools/curate-etl/src/run_curate_fx_1m.rs +++ b/tools/curate-etl/src/run_curate_fx_1m.rs @@ -311,7 +311,7 @@ where run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) } -fn cleanup_armed_staged_shards( +pub(crate) fn cleanup_armed_staged_shards( staged: &mut [(PathBuf, StagingFileGuard)], remove_file: &mut RF, ) -> Vec diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m.rs b/tools/curate-etl/src/run_curate_qm_bars_1m.rs new file mode 100644 index 00000000..0d6ec861 --- /dev/null +++ b/tools/curate-etl/src/run_curate_qm_bars_1m.rs @@ -0,0 +1,643 @@ +//! Bounded-memory file-to-file `qmIntraday` -> `bars_1m` runner (`M2.3m`). +//! +//! Streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column +//! `provider_mapping.tsv` into per-shard QuestDB ILP v2 files +//! (`/bars_1m_qm.shard-.ilp`) via [`crate::curate_qm_bars_1m`]. +//! +//! # Bounded-Memory Chunking & Zero Split Un-Adjustment +//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and +//! [`decode_qm_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by +//! `crate::bson_stream::decode_qm_intraday_chunks`, whose callback API hides chunk boundaries. +//! - Each framed chunk is decoded into a chunk-local `Vec>` borrowing +//! `qmSearchCode` directly from the chunk slice, then curated per chunk via +//! [`curate_and_write_qm_bars_1m`] against one shared [`IlpShardedWriter`]. Borrows are +//! consumed before advancing the chunk reader. +//! - Takes no splits input: `qmIntraday` raw fields (`open..close`, `sharevolume`) are already +//! un-adjusted (`design/DATA-CONTRACTS.md` §1) and pass through bit-identical (aside from +//! `-0.0 -> +0.0` volume normalization). +//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF. +//! - Peak memory is bounded by the `provider_mapping` table, the current BSON chunk +//! (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single document up to +//! `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per shard— +//! independent of the total `qmIntraday` input size. +//! +//! # Cross-Chunk Semantics, Output Naming & Reporting +//! - Collision collapse/drop in `curate_qm_bars_1m` and row ordering apply **per chunk**: output +//! is sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing +//! in two different chunks is emitted twice (with zero within-chunk collapse between them) and +//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. +//! - `CurateQmBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its +//! nested [`crate::bars_1m::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. +//! - Output files use the distinct shard prefix `bars_1m_qm` (`bars_1m_qm.shard-.ilp`) so a +//! QM run can share `out_dir` with `run_curate_bars_1m` (`bars_1m.shard-.ilp`) without +//! tripping either preflight, while every emitted ILP v2 row still targets QuestDB table +//! `bars_1m` (`TABLE_BARS_1M`) with `source=qm_raw` (`BARS_1M_SOURCE_QM`). +//! - `mapping_source` is caller-supplied and forwarded verbatim to `curate_and_write_qm_bars_1m` +//! after rejecting empty or whitespace-only values (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). +//! - `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 +//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m_qm.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_qm.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes +//! to `bars_1m_qm.shard-.ilp` via same-directory `hard_link` followed by removing the staged +//! name (preserving no-overwrite semantics even if a final file appears after preflight). +//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or +//! publication collision) drops open sinks, rolls back only final files created by this run, +//! removes this run's staging files, and leaves pre-existing files untouched. Per-document +//! semantic decode errors stay counted-and-skipped in [`BsonQmIntradayDecodeStats`]. + +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use crate::bars_1m::EodIntradayBar; +use crate::bson_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats}; +use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}; +use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError}; +use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m; +use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions}; +use crate::parquet_bars::RollbackFailure; +use crate::parquet_publish::{next_run_id, StagingFileGuard}; +use crate::provider_mapping::ProviderMappingTable; +use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; +use crate::run_curate_bars_1m::{ + add_curate_bars_1m_stats, create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, + publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, +}; +use crate::run_curate_fx_1m::cleanup_armed_staged_shards; + +/// Default `provider_mapping` source namespace for `qmSearchCode` rows in `qmIntraday`. +pub const DEFAULT_QM_BARS_1M_MAPPING_SOURCE: &str = "qm"; + +/// Output filename prefix for QM intraday shard files (`bars_1m_qm.shard-.ilp`). +/// +/// Distinct from `TABLE_BARS_1M` (`bars_1m`) so QM and EOD intraday exports can share `out_dir` +/// without colliding in preflight or publication while both emit ILP v2 rows into `bars_1m`. +const QM_BARS_1M_SHARD_PREFIX: &str = "bars_1m_qm"; + +/// Arguments for [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateQmBars1mArgs { + pub intraday_path: PathBuf, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +/// Full run report produced by [`run_curate_qm_bars_1m`] and +/// [`run_curate_qm_bars_1m_with_readers`]. +/// +/// Conservation invariants: +/// - `intraday_docs_framed as usize == intraday_decode.docs_seen` +/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()` +/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in` +/// - `curate_stats.rows_in == curate_stats.builder.rows_out` +/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped` +/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out` +/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` +/// +/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks +/// (not global distinct counts). +#[derive(Debug, Clone, PartialEq)] +pub struct CurateQmBars1mRunReport { + pub intraday_docs_framed: u64, + pub intraday_bytes_read: u64, + pub intraday_decode: BsonQmIntradayDecodeStats, + pub chunks: usize, + pub max_rows_per_chunk: usize, + pub curate_stats: CurateBars1mStats, + pub rows_written: usize, + pub ilp_stats: IlpWriteStats, + pub shard_count: usize, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`]. +#[derive(Debug)] +pub enum RunCurateQmBars1mError { + /// `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, + /// `shard_count` was `0`. + ZeroShardCount, + /// `out_dir` exists and is not a directory. + InvalidOutDir { path: PathBuf, detail: String }, + /// A final shard output file (`bars_1m_qm.shard-.ilp`) already existed. + OutputFileExists { path: PathBuf }, + /// Failed to open the input `qmIntraday` dump file. + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + /// Failed to load `provider_mapping.tsv` via the shared reference loader. + LoadReference(RunCurateBarsError), + /// Fatal BSON framing, option validation, or I/O error while reading `qmIntraday`. + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + /// Curation or per-row ILP write error inside the per-chunk `qmIntraday` curation stage. + CurateWrite(CurateBars1mWriteError), + /// ILP writer initialization or final flush error. + Ilp(IlpWriterError), + /// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files. + Io { path: PathBuf, source: io::Error }, + /// Publication or failure cleanup failed and removing one or more final or staging files also + /// failed. + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl From for RunCurateQmBars1mError { + fn from(err: ShardPublishError) -> Self { + match err { + ShardPublishError::InvalidOutDir { path, detail } => { + Self::InvalidOutDir { path, detail } + } + ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path }, + ShardPublishError::Io { path, source } => Self::Io { path, source }, + ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed { + cause: Box::new((*cause).into()), + failures, + }, + } + } +} + +impl fmt::Display for RunCurateQmBars1mError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"), + Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), + Self::InvalidOutDir { path, detail } => { + write!(f, "invalid out_dir '{}': {detail}", path.display()) + } + Self::OutputFileExists { path } => write!( + f, + "refusing to overwrite existing output file '{}'", + path.display() + ), + Self::OpenInput { + label, + path, + source, + } => write!(f, "failed to open {label} '{}': {source}", path.display()), + Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"), + Self::BsonStream { + label, + path, + source, + } => write!(f, "failed reading {label} '{}': {source}", path.display()), + Self::CurateWrite(err) => write!(f, "{err}"), + Self::Ilp(err) => write!(f, "qm bars_1m ILP writer failed: {err}"), + Self::Io { path, source } => { + write!(f, "I/O error on '{}': {source}", path.display()) + } + Self::RollbackFailed { cause, failures } => { + write!(f, "{cause}; rollback also failed for: ")?; + for (i, failure) in failures.iter().enumerate() { + if i > 0 { + write!(f, ", ")?; + } + write!(f, "{failure}")?; + } + Ok(()) + } + } + } +} + +impl Error for RunCurateQmBars1mError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), + Self::LoadReference(err) => Some(err), + Self::BsonStream { source, .. } => Some(source), + Self::CurateWrite(err) => Some(err), + Self::Ilp(err) => Some(err), + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::EmptyMappingSource + | Self::ZeroShardCount + | Self::InvalidOutDir { .. } + | Self::OutputFileExists { .. } => None, + } + } +} + +fn validate_common_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> { + if args.mapping_source.trim().is_empty() { + return Err(RunCurateQmBars1mError::EmptyMappingSource); + } + if args.shard_count == 0 { + return Err(RunCurateQmBars1mError::ZeroShardCount); + } + args.stream_options + .validate() + .map_err(|source| RunCurateQmBars1mError::BsonStream { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + })?; + if args.ilp_options.max_batch_bytes == 0 { + return Err(RunCurateQmBars1mError::Ilp( + IlpWriterError::ZeroMaxBatchBytes, + )); + } + if args.ilp_options.max_batch_rows == 0 { + return Err(RunCurateQmBars1mError::Ilp( + IlpWriterError::ZeroMaxBatchRows, + )); + } + Ok(()) +} + +fn validate_file_mode_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> { + validate_common_args(args)?; + preflight_shard_out_dir(&args.out_dir, QM_BARS_1M_SHARD_PREFIX)?; + Ok(()) +} + +fn load_provider_mapping_table( + provider_mapping_path: &Path, +) -> Result { + let mapping_rows = load_provider_mapping_tsv(provider_mapping_path) + .map_err(RunCurateQmBars1mError::LoadReference)?; + ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCurateQmBars1mError::LoadReference(RunCurateBarsError::ProviderMapping { + path: provider_mapping_path.to_path_buf(), + source, + }) + }) +} + +fn stream_qm_intraday_chunks_to_writer( + args: &CurateQmBars1mArgs, + mapping: &ProviderMappingTable, + intraday: R, + mut writer: IlpShardedWriter, + start: Instant, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err( + |source| RunCurateQmBars1mError::BsonStream { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + }, + )?; + + let mut intraday_decode = BsonQmIntradayDecodeStats::default(); + let mut curate_stats = CurateBars1mStats::default(); + let mut chunks: usize = 0; + let mut max_rows_per_chunk: usize = 0; + let mut rows_written: usize = 0; + + while let Some(chunk) = + reader + .next_chunk() + .map_err(|source| RunCurateQmBars1mError::BsonStream { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + })? + { + let mut chunk_bars: Vec> = Vec::new(); + let chunk_decode = decode_qm_intraday_buffer( + chunk.bytes, + |raw| { + chunk_bars.push(raw.into_eod_intraday_bar(|key, _| key)); + }, + |_local_offset, _err| {}, + ); + intraday_decode.merge(&chunk_decode); + + chunks += 1; + let chunk_len = chunk_bars.len(); + if chunk_len > max_rows_per_chunk { + max_rows_per_chunk = chunk_len; + } + + let write_report = curate_and_write_qm_bars_1m( + chunk_bars, + mapping, + &args.mapping_source, + &mut writer, + args.known_at_micros, + ) + .map_err(RunCurateQmBars1mError::CurateWrite)?; + + add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats); + rows_written += write_report.rows_written; + } + + let intraday_docs_framed = reader.docs_framed(); + let intraday_bytes_read = reader.bytes_read(); + let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?; + + Ok(CurateQmBars1mRunReport { + intraday_docs_framed, + intraday_bytes_read, + intraday_decode, + chunks, + max_rows_per_chunk, + curate_stats, + rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary +/// [`io::Read`] stream into per-shard sinks created by `make_sink`. +/// +/// Validates `args` (rejecting blank `mapping_source` first, then `shard_count`, stream options, +/// and ILP options) and loads `provider_mapping.tsv` from `args.provider_mapping_path` before +/// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through +/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once +/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once +/// after clean EOF. +pub fn run_curate_qm_bars_1m_with_readers( + args: &CurateQmBars1mArgs, + intraday: R, + mut make_sink: F, +) -> Result +where + R: io::Read, + W: Write + Send, + F: FnMut(usize) -> W, +{ + let start = Instant::now(); + validate_common_args(args)?; + + let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; + + let mut sinks = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + sinks.push(make_sink(shard_idx)); + } + let writer = + IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?; + + stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) +} + +fn fail_with_staging_cleanup( + cause: RunCurateQmBars1mError, + staged: &mut [(PathBuf, StagingFileGuard)], + remove_file: &mut RF, +) -> RunCurateQmBars1mError +where + RF: FnMut(&Path) -> io::Result<()>, +{ + let staging_failures = cleanup_armed_staged_shards(staged, remove_file); + if staging_failures.is_empty() { + return cause; + } + match cause { + RunCurateQmBars1mError::RollbackFailed { + cause: inner_cause, + mut failures, + } => { + failures.extend(staging_failures); + RunCurateQmBars1mError::RollbackFailed { + cause: inner_cause, + failures, + } + } + other => RunCurateQmBars1mError::RollbackFailed { + cause: Box::new(other), + failures: staging_failures, + }, + } +} + +/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging +/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging +/// unlink failure reporting deterministically. +fn run_curate_qm_bars_1m_to_dir_with_cleanup_hook( + args: &CurateQmBars1mArgs, + intraday: R, + mut make_sink: SF, + before_link: BL, + mut remove_staged_file: RF, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), + RF: FnMut(&Path) -> io::Result<()>, +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + let mapping = load_provider_mapping_table(&args.provider_mapping_path)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateQmBars1mError::Io { + path: args.out_dir.clone(), + source, + })?; + + let run_id = next_run_id(); + let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count); + let mut sinks: Vec = Vec::with_capacity(args.shard_count); + for shard_idx in 0..args.shard_count { + let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + QM_BARS_1M_SHARD_PREFIX, + shard_idx, + &run_id, + ) { + Ok(pair) => pair, + Err(err) => { + drop(sinks); + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(make_sink(shard_idx, file)); + } + + let writer = match IlpShardedWriter::new(sinks, args.ilp_options) { + Ok(writer) => writer, + Err(err) => { + return Err(fail_with_staging_cleanup( + RunCurateQmBars1mError::Ilp(err), + &mut staged, + &mut remove_staged_file, + )); + } + }; + let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start) + { + Ok(report) => report, + Err(err) => { + return Err(fail_with_staging_cleanup( + err, + &mut staged, + &mut remove_staged_file, + )); + } + }; + + if let Err(err) = publish_staged_shards_for_table( + &args.out_dir, + QM_BARS_1M_SHARD_PREFIX, + &mut staged, + before_link, + ) { + return Err(fail_with_staging_cleanup( + err.into(), + &mut staged, + &mut remove_staged_file, + )); + } + Ok(report) +} + +/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests +/// can exercise staging, writer failure, and post-preflight publication rollback through the exact +/// file publication path. +fn run_curate_qm_bars_1m_to_dir_with_hooks( + args: &CurateQmBars1mArgs, + intraday: R, + make_sink: SF, + before_link: BL, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), +{ + run_curate_qm_bars_1m_to_dir_with_cleanup_hook( + args, + intraday, + make_sink, + before_link, + |path| fs::remove_file(path), + ) +} + +/// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing +/// exactly `args.shard_count` QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`). +pub fn run_curate_qm_bars_1m( + args: &CurateQmBars1mArgs, +) -> Result { + validate_file_mode_args(args)?; + + let intraday_file = + File::open(&args.intraday_path).map_err(|source| RunCurateQmBars1mError::OpenInput { + label: "qm-intraday", + path: args.intraday_path.clone(), + source, + })?; + + run_curate_qm_bars_1m_to_dir_with_hooks( + args, + intraday_file, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + +/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_qm_bars_1m_report(report: &CurateQmBars1mRunReport) -> String { + let per_shard = if report.ilp_stats.per_shard_rows.is_empty() { + "none".to_string() + } else { + report + .ilp_stats + .per_shard_rows + .iter() + .enumerate() + .map(|(idx, count)| format!("{idx:02}={count}")) + .collect::>() + .join(",") + }; + + let b = &report.curate_stats.builder; + let c = &report.curate_stats; + let d = &report.intraday_decode; + + format!( + "curate-etl curate-qm-bars-1m\n\ + \x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ + \x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\ + \x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\ + \x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\ + \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ + \x20 timing: elapsed_secs={:.6}", + report.intraday_docs_framed, + report.intraday_bytes_read, + d.docs_seen, + d.rows_decoded, + d.rejected_total(), + d.rejected_missing_field, + d.rejected_empty_field, + d.rejected_wrong_type, + d.rejected_invalid_timestamp, + d.rejected_invalid_number, + d.rejected_corrupt_document, + report.chunks, + report.max_rows_per_chunk, + b.bars_in, + b.rows_out, + b.keys_out, + b.pre_rows_out, + b.rth_rows_out, + b.post_rows_out, + b.dropped_invalid_ohlc, + b.dropped_inconsistent_ohlc, + b.dropped_invalid_volume, + b.dropped_ts_out_of_range, + b.duplicate_collapsed, + b.duplicate_conflict_dropped, + c.rows_in, + c.rows_out, + c.listings_out, + c.pre_rows_out, + c.rth_rows_out, + c.post_rows_out, + c.dropped_unmapped, + c.listing_collision_collapsed, + c.listing_collision_dropped, + report.shard_count, + report.rows_written, + report.ilp_stats.rows, + report.ilp_stats.bytes, + report.ilp_stats.flushes, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_qm_bars_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs new file mode 100644 index 00000000..59393f54 --- /dev/null +++ b/tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs @@ -0,0 +1,1430 @@ +use std::error::Error; +use std::fs; +use std::io::{self, Cursor, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; + +use super::*; +use crate::bars_1m::{IntradaySession, BARS_1M_SOURCE_QM}; +use crate::bson_stream::MIN_BSON_DOC_BYTES; +use crate::ilp::{shard_for_listing_id, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; +use crate::run_curate_bars_1m::tests::TempDirGuard; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts_millis(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); + assert_eq!(micros % 1_000, 0); + micros / 1_000 +} + +fn make_qm_intraday_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"), BsonDateTime::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 +} + +/// Builds a `qmIntraday` document that also carries distinct split-adjusted fields +/// (`adjustedopen..adjustedclose`, `avolume`) to prove the runner ignores them and preserves raw +/// OHLCV bit-identically. +#[allow(clippy::too_many_arguments)] +fn make_qm_intraday_doc_with_adjusted( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, + adj_scale: f64, +) -> RawDocumentBuf { + let mut doc = make_qm_intraday_doc(code, timestamp_ms, open, high, low, close, sharevolume); + doc.append(cstr!("adjustedopen"), open / adj_scale); + doc.append(cstr!("adjustedhigh"), high / adj_scale); + doc.append(cstr!("adjustedlow"), low / adj_scale); + doc.append(cstr!("adjustedclose"), close / adj_scale); + doc.append(cstr!("avolume"), sharevolume * adj_scale); + doc +} + +fn make_malformed_missing_open_doc(code: &str, timestamp_ms: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); + doc.append(cstr!("high"), 102.0_f64); + doc.append(cstr!("low"), 99.0_f64); + doc.append(cstr!("close"), 101.0_f64); + doc.append(cstr!("sharevolume"), 500.0_f64); + doc +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for doc in docs { + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn write_mapping_tsv(dir: &Path, lines: &[&str]) -> PathBuf { + let path = dir.join("provider_mapping.tsv"); + let mut body = lines.join("\n"); + if !body.is_empty() { + body.push('\n'); + } + fs::write(&path, body).expect("write provider_mapping.tsv"); + path +} + +fn list_dir_names(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + let mut names: Vec = fs::read_dir(dir) + .expect("read_dir") + .map(|entry| { + entry + .expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + names.sort(); + names +} + +fn make_args( + intraday_path: PathBuf, + provider_mapping_path: PathBuf, + out_dir: PathBuf, + mapping_source: &str, + shard_count: usize, + known_at_micros: i64, + stream_options: BsonStreamOptions, +) -> CurateQmBars1mArgs { + CurateQmBars1mArgs { + intraday_path, + provider_mapping_path, + out_dir, + mapping_source: mapping_source.to_string(), + shard_count, + known_at_micros, + stream_options, + ilp_options: IlpWriterOptions::default(), + } +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedIlpBar1m { + listing_id: i32, + session: IntradaySession, + source: String, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, + known_at: i64, + ts: i64, +} + +impl DecodedIlpBar1m { + fn sort_key(&self) -> (i32, i64, u64, u64, u64, u64, u64, i64) { + ( + self.listing_id, + self.ts, + self.open.to_bits(), + self.high.to_bits(), + self.low.to_bits(), + self.close.to_bits(), + self.volume.to_bits(), + self.known_at, + ) + } +} + +/// Decodes QuestDB ILP v2 `bars_1m` records respecting fixed-width 8-byte binary `DOUBLE` +/// payloads (`==\x10<8 LE bytes>`) so embedded `0x0a` bytes inside doubles never split rows. +fn decode_ilp_bars_1m(data: &[u8]) -> Vec { + let mut rows = Vec::new(); + let mut i = 0usize; + let len = data.len(); + + while i < len { + let tag_start = i; + while i < len { + match data[i] { + b'\\' => { + assert!(i + 1 < len, "dangling backslash in ILP tag set"); + i += 2; + } + b' ' => break, + _ => i += 1, + } + } + assert!(i < len && data[i] == b' ', "missing space after ILP tag set"); + let tag_str = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tag set"); + i += 1; + + let mut tags = tag_str.split(','); + assert_eq!(tags.next(), Some(TABLE_BARS_1M), "expected bars_1m table"); + let listing_tag = tags.next().expect("listing_id tag"); + let session_tag = tags.next().expect("session tag"); + let source_tag = tags.next().expect("source tag"); + assert!(tags.next().is_none(), "unexpected extra ILP tag"); + + let listing_id: i32 = listing_tag + .strip_prefix("listing_id=") + .expect("listing_id= prefix") + .parse() + .expect("i32 listing_id"); + let session = match session_tag + .strip_prefix("session=") + .expect("session= prefix") + { + "PRE" => IntradaySession::Pre, + "RTH" => IntradaySession::Rth, + "POST" => IntradaySession::Post, + other => panic!("unexpected session '{other}'"), + }; + let source = source_tag + .strip_prefix("source=") + .expect("source= prefix") + .to_string(); + + let read_bin_f64 = |pos: &mut usize, name: &str| -> f64 { + let prefix = format!("{name}=="); + assert!( + data[*pos..].starts_with(prefix.as_bytes()), + "expected field prefix '{prefix}' at offset {}", + *pos + ); + *pos += prefix.len(); + assert_eq!( + data[*pos], ILP_V2_DOUBLE_TYPE, + "expected binary DOUBLE type tag for '{name}'" + ); + *pos += 1; + let bytes: [u8; 8] = data[*pos..*pos + 8] + .try_into() + .expect("8 bytes for binary double"); + *pos += 8; + f64::from_le_bytes(bytes) + }; + + let open = read_bin_f64(&mut i, "open"); + assert_eq!(data[i], b','); + i += 1; + let high = read_bin_f64(&mut i, "high"); + assert_eq!(data[i], b','); + i += 1; + let low = read_bin_f64(&mut i, "low"); + assert_eq!(data[i], b','); + i += 1; + let close = read_bin_f64(&mut i, "close"); + assert_eq!(data[i], b','); + i += 1; + let volume = read_bin_f64(&mut i, "volume"); + assert_eq!(data[i], b','); + i += 1; + + let ka_prefix = b"known_at="; + assert!( + data[i..].starts_with(ka_prefix), + "expected known_at= at offset {i}" + ); + i += ka_prefix.len(); + let ka_start = i; + while i < len && data[i] != b' ' { + i += 1; + } + assert!(i < len && data[i] == b' ', "missing space after known_at"); + let ka_str = std::str::from_utf8(&data[ka_start..i]).expect("valid UTF-8 known_at"); + let known_at: i64 = ka_str + .strip_suffix('t') + .expect("known_at trailing t") + .parse() + .expect("i64 known_at"); + i += 1; + + let ts_start = i; + while i < len && data[i] != b'\n' { + i += 1; + } + assert!(i < len && data[i] == b'\n', "missing trailing LF"); + let ts_str = std::str::from_utf8(&data[ts_start..i]).expect("valid UTF-8 ts"); + let ts: i64 = ts_str + .strip_suffix('t') + .expect("ts trailing t") + .parse() + .expect("i64 ts"); + i += 1; + + rows.push(DecodedIlpBar1m { + listing_id, + session, + source, + open, + high, + low, + close, + volume, + known_at, + ts, + }); + } + + rows +} + +fn assert_report_conservation(report: &CurateQmBars1mRunReport) { + let d = &report.intraday_decode; + assert_eq!( + report.intraday_docs_framed as usize, d.docs_seen, + "docs_framed != docs_seen" + ); + assert_eq!( + d.docs_seen, + d.rows_decoded + d.rejected_total(), + "decode conservation failed: {d:?}" + ); + + let c = &report.curate_stats; + let b = &c.builder; + assert_eq!(d.rows_decoded, b.bars_in, "rows_decoded != builder.bars_in"); + assert_eq!(c.rows_in, b.rows_out, "curate.rows_in != builder.rows_out"); + assert_eq!( + c.rows_in, + c.rows_out + + c.dropped_unmapped + + c.listing_collision_collapsed + + c.listing_collision_dropped, + "curate_stats conservation failed: {c:?}" + ); + assert_eq!( + c.pre_rows_out + c.rth_rows_out + c.post_rows_out, + c.rows_out, + "session breakdown != rows_out" + ); + assert_eq!(report.rows_written, c.rows_out, "rows_written != rows_out"); + assert_eq!( + report.rows_written, report.ilp_stats.rows, + "rows_written != ilp_stats.rows" + ); + assert_eq!( + report.ilp_stats.per_shard_rows.iter().sum::(), + report.ilp_stats.rows, + "sum(per_shard_rows) != ilp_stats.rows" + ); + assert_eq!(report.ilp_stats.per_shard_rows.len(), report.shard_count); +} + +#[derive(Clone)] +struct RecordingSink { + bytes: Arc>>, + flushes: Arc, +} + +impl RecordingSink { + fn new() -> Self { + Self { + bytes: Arc::new(Mutex::new(Vec::new())), + flushes: Arc::new(AtomicUsize::new(0)), + } + } +} + +impl Write for RecordingSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.bytes.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.flushes.fetch_add(1, Ordering::SeqCst); + Ok(()) + } +} + +struct FailingWriteSink { + fail_on_write: bool, + fail_on_flush: bool, +} + +impl Write for FailingWriteSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.fail_on_write { + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "injected write failure", + )) + } else { + Ok(buf.len()) + } + } + + fn flush(&mut self) -> io::Result<()> { + if self.fail_on_flush { + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "injected flush failure", + )) + } else { + Ok(()) + } + } +} + +struct PanicReader; + +impl Read for PanicReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + panic!("reader must not be called when validation fails"); + } +} + +struct PrefixThenIoErrorReader { + prefix: Vec, + pos: usize, + failed: bool, +} + +impl PrefixThenIoErrorReader { + fn new(prefix: Vec) -> Self { + Self { + prefix, + pos: 0, + failed: false, + } + } +} + +impl Read for PrefixThenIoErrorReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.prefix.len() { + let n = (self.prefix.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + if !self.failed { + self.failed = true; + return Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "injected reader failure after prefix", + )); + } + Ok(0) + } +} + +#[test] +fn happy_path_file_mode_decodes_bit_identical_raw_ohlcv_date_boundary_and_deterministic_replay() { + let dir = TempDirGuard::new("qm-bars1m-happy"); + + // Date-effective mapping boundary for QM code "REUSE": + // 2024-06-01..=2024-06-10 -> listing 101 + // 2024-06-11.. -> listing 202 + // Plus a second symbol "AAPL" -> listing 303. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tREUSE\t2024-06-01\t2024-06-10\t101", + "qm\tREUSE\t2024-06-11\t\t202", + "qm\tAAPL\t2024-01-01\t\t303", + ], + ); + + // Choose a raw close whose LE IEEE-754 bytes include 0x0a to prove binary ILP decoding does + // not split on embedded newlines. + let raw_close_with_lf = f64::from_le_bytes([0x0a, 0x11, 0x22, 0x33, 0x44, 0x55, 0x59, 0x40]); + assert!(raw_close_with_lf.is_finite() && raw_close_with_lf > 100.0 && raw_close_with_lf < 102.0); + + let ts_pre = et_ts_millis(2024, 6, 10, 8, 15); + let ts_rth_old = et_ts_millis(2024, 6, 10, 10, 30); + let ts_rth_new = et_ts_millis(2024, 6, 11, 9, 30); + let ts_post = et_ts_millis(2024, 6, 11, 17, 5); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + + // Include distinct adjusted fields (scale 10.0) to verify raw fields pass through bit-identical + // with no split un-adjustment, and include -0.0 sharevolume to verify +0.0 normalization. + let docs = vec![ + make_qm_intraday_doc_with_adjusted( + "REUSE", + ts_rth_old, + 100.125, + 102.5, + 99.75, + raw_close_with_lf, + 12_345.0, + 10.0, + ), + make_qm_intraday_doc_with_adjusted("REUSE", ts_pre, 99.5, 100.0, 99.0, 99.8, -0.0, 10.0), + make_qm_intraday_doc_with_adjusted( + "REUSE", + ts_rth_new, + 15.25, + 15.75, + 15.0, + 15.5, + 8_000.0, + 4.0, + ), + make_qm_intraday_doc_with_adjusted( + "AAPL", + ts_post, + 210.0, + 211.25, + 209.5, + 210.75, + 4_200.0, + 2.0, + ), + ]; + let intraday_bytes = concat_docs(&docs); + let intraday_path = dir.path().join("qmIntraday.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + let shard_count = 4; + let out_dir_1 = dir.path().join("out-1"); + let args_1 = make_args( + intraday_path.clone(), + mapping_path.clone(), + out_dir_1.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report_1 = run_curate_qm_bars_1m(&args_1).expect("happy-path run should succeed"); + assert_report_conservation(&report_1); + assert_eq!(report_1.intraday_docs_framed, 4); + assert_eq!(report_1.intraday_bytes_read, intraday_bytes.len() as u64); + assert_eq!(report_1.chunks, 1); + assert_eq!(report_1.max_rows_per_chunk, 4); + assert_eq!(report_1.rows_written, 4); + + // Output directory contains exactly bars_1m_qm.shard-00..03.ilp and no staging .tmp files. + assert_eq!( + list_dir_names(&out_dir_1), + vec![ + "bars_1m_qm.shard-00.ilp", + "bars_1m_qm.shard-01.ilp", + "bars_1m_qm.shard-02.ilp", + "bars_1m_qm.shard-03.ilp", + ] + ); + + // Decode every shard and assert shard routing, table, source, timestamps, known_at, and raw OHLCV bits. + let mut decoded_all = Vec::new(); + for shard_idx in 0..shard_count { + let path = out_dir_1.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp")); + let bytes = fs::read(&path).expect("read shard file"); + let shard_rows = decode_ilp_bars_1m(&bytes); + assert_eq!(shard_rows.len(), report_1.ilp_stats.per_shard_rows[shard_idx]); + for row in &shard_rows { + assert_eq!(row.source, BARS_1M_SOURCE_QM); + assert_eq!(row.known_at, known_at_micros); + assert_eq!(shard_for_listing_id(row.listing_id, shard_count), shard_idx); + } + decoded_all.extend(shard_rows); + } + decoded_all.sort_by_key(DecodedIlpBar1m::sort_key); + + assert_eq!(decoded_all.len(), 4); + // Listing 101 PRE bar (2024-06-10, -0.0 volume normalized to +0.0) + assert_eq!(decoded_all[0].listing_id, 101); + assert_eq!(decoded_all[0].ts, ts_pre * 1_000); + assert_eq!(decoded_all[0].session, IntradaySession::Pre); + assert_eq!(decoded_all[0].open.to_bits(), 99.5_f64.to_bits()); + assert_eq!(decoded_all[0].high.to_bits(), 100.0_f64.to_bits()); + assert_eq!(decoded_all[0].low.to_bits(), 99.0_f64.to_bits()); + assert_eq!(decoded_all[0].close.to_bits(), 99.8_f64.to_bits()); + assert_eq!(decoded_all[0].volume.to_bits(), 0.0_f64.to_bits()); + + // Listing 101 RTH bar (2024-06-10, raw close with embedded 0x0a byte) + assert_eq!(decoded_all[1].listing_id, 101); + assert_eq!(decoded_all[1].ts, ts_rth_old * 1_000); + assert_eq!(decoded_all[1].session, IntradaySession::Rth); + assert_eq!(decoded_all[1].open.to_bits(), 100.125_f64.to_bits()); + assert_eq!(decoded_all[1].high.to_bits(), 102.5_f64.to_bits()); + assert_eq!(decoded_all[1].low.to_bits(), 99.75_f64.to_bits()); + assert_eq!(decoded_all[1].close.to_bits(), raw_close_with_lf.to_bits()); + assert_eq!(decoded_all[1].volume.to_bits(), 12_345.0_f64.to_bits()); + + // Listing 202 RTH bar (2024-06-11, after mapping boundary) + assert_eq!(decoded_all[2].listing_id, 202); + assert_eq!(decoded_all[2].ts, ts_rth_new * 1_000); + assert_eq!(decoded_all[2].session, IntradaySession::Rth); + assert_eq!(decoded_all[2].open.to_bits(), 15.25_f64.to_bits()); + assert_eq!(decoded_all[2].close.to_bits(), 15.5_f64.to_bits()); + assert_eq!(decoded_all[2].volume.to_bits(), 8_000.0_f64.to_bits()); + + // Listing 303 POST bar + assert_eq!(decoded_all[3].listing_id, 303); + assert_eq!(decoded_all[3].ts, ts_post * 1_000); + assert_eq!(decoded_all[3].session, IntradaySession::Post); + assert_eq!(decoded_all[3].open.to_bits(), 210.0_f64.to_bits()); + assert_eq!(decoded_all[3].close.to_bits(), 210.75_f64.to_bits()); + assert_eq!(decoded_all[3].volume.to_bits(), 4_200.0_f64.to_bits()); + + // Compare against pure single-chunk baseline `curate_and_write_qm_bars_1m`. + let mapping = load_provider_mapping_table(&mapping_path).unwrap(); + let baseline_sinks: Vec> = (0..shard_count).map(|_| Vec::new()).collect(); + let mut baseline_writer = + IlpShardedWriter::new(baseline_sinks, IlpWriterOptions::default()).unwrap(); + let mut baseline_bars = Vec::new(); + decode_qm_intraday_buffer( + &intraday_bytes, + |raw| baseline_bars.push(raw.into_eod_intraday_bar(|k, _| k)), + |_, _| {}, + ); + curate_and_write_qm_bars_1m( + baseline_bars, + &mapping, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + &mut baseline_writer, + known_at_micros, + ) + .unwrap(); + let baseline_stats = baseline_writer.finish().unwrap(); + assert_eq!(report_1.ilp_stats, baseline_stats); + + // Deterministic replay: identical settings into a second out_dir yield byte-identical shards + // and identical report fields (excluding elapsed_secs). + let out_dir_2 = dir.path().join("out-2"); + let args_2 = make_args( + intraday_path, + mapping_path, + out_dir_2.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions::default(), + ); + let report_2 = run_curate_qm_bars_1m(&args_2).expect("replay run should succeed"); + for shard_idx in 0..shard_count { + let b1 = fs::read(out_dir_1.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp"))).unwrap(); + let b2 = fs::read(out_dir_2.join(format!("bars_1m_qm.shard-{shard_idx:02}.ilp"))).unwrap(); + assert_eq!(b1, b2, "shard {shard_idx} bytes differed across replay"); + } + let mut r1 = report_1; + let mut r2 = report_2; + r1.elapsed_secs = 0.0; + r2.elapsed_secs = 0.0; + assert_eq!(r1, r2); +} + +#[test] +fn bounded_chunk_streaming_matches_single_chunk_and_calls_finish_flush_once_per_shard() { + let dir = TempDirGuard::new("qm-bars1m-chunked"); + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tAAA\t2024-01-01\t\t11", + "qm\tBBB\t2024-01-01\t\t22", + ], + ); + + let known_at_micros = et_to_utc_micros(day(2024, 7, 2), 18, 0, 0).unwrap(); + let mut docs = Vec::new(); + for minute in 0..12u8 { + let code = if minute % 2 == 0 { "AAA" } else { "BBB" }; + let base = 50.0 + f64::from(minute); + docs.push(make_qm_intraday_doc( + code, + et_ts_millis(2024, 7, 1, 9, 30 + minute), + base, + base + 0.5, + base - 0.25, + base + 0.25, + 100.0 + f64::from(minute), + )); + } + let single_doc_len = docs[0].as_bytes().len(); + let intraday_bytes = concat_docs(&docs); + + // Use 4 shards so at least 2 shards are empty (only 2 listings), verifying finish() flushes + // empty shards once too. + let shard_count = 4; + + let run_with_capacity = |chunk_capacity_bytes: usize| { + let sinks: Vec = (0..shard_count).map(|_| RecordingSink::new()).collect(); + let sinks_ref = sinks.clone(); + let args = make_args( + dir.path().join("in-memory.bson"), + mapping_path.clone(), + dir.path().join("unused-out"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + shard_count, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes, + max_doc_bytes: 1024 * 1024, + }, + ); + let report = run_curate_qm_bars_1m_with_readers( + &args, + Cursor::new(intraday_bytes.as_slice()), + |shard_idx| sinks_ref[shard_idx].clone(), + ) + .expect("stream run should succeed"); + assert_report_conservation(&report); + + let mut rows = Vec::new(); + for (idx, sink) in sinks.iter().enumerate() { + assert_eq!( + sink.flushes.load(Ordering::SeqCst), + 1, + "shard {idx} must observe exactly one finish() flush" + ); + rows.extend(decode_ilp_bars_1m(&sink.bytes.lock().unwrap())); + } + rows.sort_by_key(DecodedIlpBar1m::sort_key); + (report, rows) + }; + + let (single_report, single_rows) = run_with_capacity(64 * 1024); + let (tiny_report, tiny_rows) = run_with_capacity(single_doc_len * 2 + 4); + + assert_eq!(single_report.chunks, 1); + assert_eq!(single_report.max_rows_per_chunk, 12); + assert!( + tiny_report.chunks > 1, + "expected multiple chunks, got {}", + tiny_report.chunks + ); + assert!( + tiny_report.max_rows_per_chunk < single_report.max_rows_per_chunk, + "expected lower high-water mark: tiny={} vs single={}", + tiny_report.max_rows_per_chunk, + single_report.max_rows_per_chunk + ); + assert_eq!(single_rows, tiny_rows); + assert_eq!(single_report.rows_written, tiny_report.rows_written); + assert_eq!(single_report.ilp_stats.rows, tiny_report.ilp_stats.rows); + assert_eq!( + single_report.ilp_stats.per_shard_rows, + tiny_report.ilp_stats.per_shard_rows + ); +} + +#[test] +fn conservation_counts_unmapped_semantic_decode_errors_collisions_and_cross_chunk_duplicates() { + let dir = TempDirGuard::new("qm-bars1m-conservation"); + // ALIAS_A and ALIAS_B both map to listing 500 to test identical collapse and conflict drop. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tALIAS_A\t2024-01-01\t\t500", + "qm\tALIAS_B\t2024-01-01\t\t500", + ], + ); + + let known_at_micros = et_to_utc_micros(day(2024, 8, 2), 18, 0, 0).unwrap(); + let ts_pre = et_ts_millis(2024, 8, 1, 8, 0); + let ts_rth_same = et_ts_millis(2024, 8, 1, 10, 0); + let ts_rth_conflict = et_ts_millis(2024, 8, 1, 10, 1); + let ts_post = et_ts_millis(2024, 8, 1, 16, 30); + let ts_bad_ohlc = et_ts_millis(2024, 8, 1, 10, 2); + + let docs = vec![ + // 1. Valid PRE bar + make_qm_intraday_doc("ALIAS_A", ts_pre, 10.0, 10.5, 9.8, 10.2, 100.0), + // 2. Semantically invalid BSON doc (missing `open`) -> counted and skipped + make_malformed_missing_open_doc("ALIAS_A", ts_pre + 60_000), + // 3. Unmapped qmSearchCode -> dropped_unmapped + make_qm_intraday_doc("UNKNOWN_CODE", ts_rth_same, 20.0, 21.0, 19.5, 20.5, 50.0), + // 4 & 5. Identical alias collision -> 1 row emitted, 1 listing_collision_collapsed + make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0), + make_qm_intraday_doc("ALIAS_B", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0), + // 6 & 7. Conflicting alias collision -> both dropped (2 listing_collision_dropped) + make_qm_intraday_doc("ALIAS_A", ts_rth_conflict, 12.0, 12.5, 11.8, 12.2, 300.0), + make_qm_intraday_doc("ALIAS_B", ts_rth_conflict, 12.0, 12.6, 11.8, 12.2, 300.0), + // 8. Builder-inconsistent OHLC (high < low) -> dropped_inconsistent_ohlc + make_qm_intraday_doc("ALIAS_A", ts_bad_ohlc, 10.0, 9.0, 11.0, 10.0, 10.0), + // 9. Valid POST bar + make_qm_intraday_doc("ALIAS_A", ts_post, 13.0, 13.4, 12.9, 13.1, 400.0), + ]; + let intraday_bytes = concat_docs(&docs); + let args = make_args( + dir.path().join("conservation.bson"), + mapping_path.clone(), + dir.path().join("unused-out"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_qm_bars_1m_with_readers( + &args, + Cursor::new(intraday_bytes.as_slice()), + |_shard_idx| Vec::::new(), + ) + .expect("conservation run should succeed"); + assert_report_conservation(&report); + + assert_eq!(report.intraday_docs_framed, 9); + assert_eq!(report.intraday_decode.docs_seen, 9); + assert_eq!(report.intraday_decode.rows_decoded, 8); + assert_eq!(report.intraday_decode.rejected_missing_field, 1); + assert_eq!(report.curate_stats.builder.bars_in, 8); + assert_eq!(report.curate_stats.builder.dropped_inconsistent_ohlc, 1); + assert_eq!(report.curate_stats.rows_in, 7); + assert_eq!(report.curate_stats.dropped_unmapped, 1); + assert_eq!(report.curate_stats.listing_collision_collapsed, 1); + assert_eq!(report.curate_stats.listing_collision_dropped, 2); + assert_eq!(report.curate_stats.rows_out, 3); + assert_eq!(report.curate_stats.pre_rows_out, 1); + assert_eq!(report.curate_stats.rth_rows_out, 1); + assert_eq!(report.curate_stats.post_rows_out, 1); + assert_eq!(report.rows_written, 3); + + // Cross-chunk duplicate semantics: the same (listing_id, ts) in two separate chunks emits both + // rows (relying on QuestDB DEDUP UPSERT KEYS(ts, listing_id)) and sums listings_out/keys_out. + let dup_doc = make_qm_intraday_doc("ALIAS_A", ts_rth_same, 11.0, 11.5, 10.8, 11.2, 200.0); + let doc_len = dup_doc.as_bytes().len(); + let cross_chunk_bytes = concat_docs(&[dup_doc.clone(), dup_doc]); + let sinks = vec![RecordingSink::new()]; + let sinks_ref = sinks.clone(); + let cross_args = make_args( + dir.path().join("cross-chunk.bson"), + mapping_path, + dir.path().join("unused-out-2"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 1, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: doc_len, + max_doc_bytes: 1024 * 1024, + }, + ); + let cross_report = run_curate_qm_bars_1m_with_readers( + &cross_args, + Cursor::new(cross_chunk_bytes.as_slice()), + |idx| sinks_ref[idx].clone(), + ) + .expect("cross-chunk duplicate run should succeed"); + assert_report_conservation(&cross_report); + assert_eq!(cross_report.chunks, 2); + assert_eq!(cross_report.rows_written, 2); + assert_eq!(cross_report.curate_stats.listings_out, 2); + assert_eq!(cross_report.curate_stats.builder.keys_out, 2); + let emitted = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); + assert_eq!(emitted.len(), 2); + assert_eq!(emitted[0], emitted[1]); +} + +#[test] +fn blank_mapping_source_rejected_before_opening_inputs_or_creating_out_dir_and_custom_namespace_works() +{ + let dir = TempDirGuard::new("qm-bars1m-source"); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + + for blank in ["", " ", "\t\n "] { + let out_dir = dir.path().join(format!("should-not-exist-{}", blank.len())); + let args = make_args( + dir.path().join("nonexistent-intraday.bson"), + dir.path().join("nonexistent-mapping.tsv"), + out_dir.clone(), + blank, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let file_err = run_curate_qm_bars_1m(&args).expect_err("blank source must fail file mode"); + assert!( + matches!(file_err, RunCurateQmBars1mError::EmptyMappingSource), + "expected EmptyMappingSource, got {file_err:?}" + ); + assert!( + !out_dir.exists(), + "out_dir must not be created on blank mapping_source" + ); + + let reader_err = run_curate_qm_bars_1m_with_readers(&args, PanicReader, |_idx| -> Vec { + panic!("sink factory must not be called on blank mapping_source"); + }) + .expect_err("blank source must fail reader mode"); + assert!(matches!( + reader_err, + RunCurateQmBars1mError::EmptyMappingSource + )); + } + + // Custom nonblank namespace forwarded verbatim alongside "qm" in the same TSV. + let mapping_path = write_mapping_tsv( + dir.path(), + &[ + "qm\tSYM\t2024-01-01\t\t10", + "qm_custom\tSYM\t2024-01-01\t\t99", + ], + ); + let docs = vec![make_qm_intraday_doc( + "SYM", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.9, + 10.2, + 100.0, + )]; + let intraday_bytes = concat_docs(&docs); + let sinks = vec![RecordingSink::new()]; + let sinks_ref = sinks.clone(); + let custom_args = make_args( + dir.path().join("custom.bson"), + mapping_path, + dir.path().join("unused"), + "qm_custom", + 1, + known_at_micros, + BsonStreamOptions::default(), + ); + let report = run_curate_qm_bars_1m_with_readers( + &custom_args, + Cursor::new(intraday_bytes.as_slice()), + |idx| sinks_ref[idx].clone(), + ) + .expect("custom mapping_source should succeed"); + assert_report_conservation(&report); + let decoded = decode_ilp_bars_1m(&sinks[0].bytes.lock().unwrap()); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].listing_id, 99); +} + +#[test] +fn missing_inputs_and_invalid_options_fail_closed_without_creating_out_dir() { + let dir = TempDirGuard::new("qm-bars1m-missing"); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let valid_mapping = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t1"]); + let valid_bson = dir.path().join("valid.bson"); + fs::write(&valid_bson, b"").unwrap(); + + // Missing BSON input + let out_missing_bson = dir.path().join("out-missing-bson"); + let err = run_curate_qm_bars_1m(&make_args( + dir.path().join("does-not-exist.bson"), + valid_mapping.clone(), + out_missing_bson.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("missing BSON must fail"); + assert!(matches!( + err, + RunCurateQmBars1mError::OpenInput { + label: "qm-intraday", + .. + } + )); + assert!(err.source().is_some()); + assert!(!out_missing_bson.exists()); + + // Missing provider_mapping.tsv + let out_missing_map = dir.path().join("out-missing-map"); + let err = run_curate_qm_bars_1m(&make_args( + valid_bson.clone(), + dir.path().join("does-not-exist.tsv"), + out_missing_map.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("missing mapping must fail"); + assert!(matches!(err, RunCurateQmBars1mError::LoadReference(_))); + assert!(!out_missing_map.exists()); + + // Zero shard_count + let err = run_curate_qm_bars_1m(&make_args( + valid_bson.clone(), + valid_mapping.clone(), + dir.path().join("out-zero-shard"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 0, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("zero shard_count must fail"); + assert!(matches!(err, RunCurateQmBars1mError::ZeroShardCount)); + + // Invalid stream_options + let err = run_curate_qm_bars_1m(&make_args( + valid_bson.clone(), + valid_mapping.clone(), + dir.path().join("out-bad-stream"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: 0, + max_doc_bytes: MIN_BSON_DOC_BYTES, + }, + )) + .expect_err("zero chunk_capacity_bytes must fail"); + assert!(matches!(err, RunCurateQmBars1mError::BsonStream { .. })); + + // out_dir exists as a regular file + let file_as_dir = dir.path().join("not-a-dir"); + fs::write(&file_as_dir, b"file").unwrap(); + let err = run_curate_qm_bars_1m(&make_args( + valid_bson, + valid_mapping, + file_as_dir, + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("file out_dir must fail"); + assert!(matches!(err, RunCurateQmBars1mError::InvalidOutDir { .. })); +} + +#[test] +fn preflight_rejects_high_numbered_qm_shard_and_allows_eod_bars_1m_shard_coexistence() { + let dir = TempDirGuard::new("qm-bars1m-preflight"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let intraday_bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + let intraday_path = dir.path().join("qmIntraday.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + // (a) Pre-existing bars_1m_qm.shard-07.ilp (index >= requested shard_count=2) fails preflight + // and stays byte-identical. + let out_conflict = dir.path().join("out-conflict"); + fs::create_dir_all(&out_conflict).unwrap(); + let stale_qm_shard = out_conflict.join("bars_1m_qm.shard-07.ilp"); + let stale_bytes = b"pre-existing-stale-qm-shard\n"; + fs::write(&stale_qm_shard, stale_bytes).unwrap(); + + let err = run_curate_qm_bars_1m(&make_args( + intraday_path.clone(), + mapping_path.clone(), + out_conflict.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect_err("pre-existing high-numbered QM shard must fail preflight"); + assert!(matches!( + err, + RunCurateQmBars1mError::OutputFileExists { ref path } if path == &stale_qm_shard + )); + assert_eq!(fs::read(&stale_qm_shard).unwrap(), stale_bytes); + assert_eq!(list_dir_names(&out_conflict), vec!["bars_1m_qm.shard-07.ilp"]); + + // (b) Pre-existing bars_1m.shard-00.ilp (EOD runner output) does NOT block the QM run and is + // left byte-identical. + let out_shared = dir.path().join("out-shared"); + fs::create_dir_all(&out_shared).unwrap(); + let eod_shard = out_shared.join("bars_1m.shard-00.ilp"); + let eod_bytes = b"pre-existing-eod-bars-1m-shard-bytes\n"; + fs::write(&eod_shard, eod_bytes).unwrap(); + + let report = run_curate_qm_bars_1m(&make_args( + intraday_path, + mapping_path, + out_shared.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + )) + .expect("QM run should coexist with EOD bars_1m.shard-00.ilp"); + assert_report_conservation(&report); + assert_eq!(report.rows_written, 1); + assert_eq!(fs::read(&eod_shard).unwrap(), eod_bytes); + assert_eq!( + list_dir_names(&out_shared), + vec![ + "bars_1m.shard-00.ilp", + "bars_1m_qm.shard-00.ilp", + "bars_1m_qm.shard-01.ilp", + ] + ); +} + +#[test] +fn fatal_bson_framing_and_reader_io_errors_report_absolute_offset_and_leave_out_dir_clean() { + let dir = TempDirGuard::new("qm-bars1m-bson-errors"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + + let valid_prefix = make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + ); + let prefix_len = valid_prefix.as_bytes().len() as u64; + + // 1. Truncated document after valid prefix. + let mut truncated_bytes = valid_prefix.as_bytes().to_vec(); + truncated_bytes.extend_from_slice(&20_i32.to_le_bytes()); + truncated_bytes.extend_from_slice(&[0u8; 4]); + let trunc_path = dir.path().join("truncated.bson"); + fs::write(&trunc_path, &truncated_bytes).unwrap(); + let out_trunc = dir.path().join("out-trunc"); + let err = run_curate_qm_bars_1m(&make_args( + trunc_path, + mapping_path.clone(), + out_trunc.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: prefix_len as usize, + max_doc_bytes: 1024 * 1024, + }, + )) + .expect_err("truncated BSON must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::TruncatedDocument { offset, .. }, + .. + } if offset == prefix_len + ), + "expected TruncatedDocument at offset {prefix_len}, got {err:?}" + ); + assert!( + list_dir_names(&out_trunc).is_empty(), + "staging/final files leaked on truncated BSON: {:?}", + list_dir_names(&out_trunc) + ); + + // 2. Corrupt declared document length (< 5) after valid prefix. + let mut corrupt_bytes = valid_prefix.as_bytes().to_vec(); + corrupt_bytes.extend_from_slice(&3_i32.to_le_bytes()); + corrupt_bytes.push(0); + let corrupt_path = dir.path().join("corrupt.bson"); + fs::write(&corrupt_path, &corrupt_bytes).unwrap(); + let out_corrupt = dir.path().join("out-corrupt"); + let err = run_curate_qm_bars_1m(&make_args( + corrupt_path, + mapping_path.clone(), + out_corrupt.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: prefix_len as usize, + max_doc_bytes: 1024 * 1024, + }, + )) + .expect_err("corrupt document length must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::CorruptDocumentLength { offset, declared_len: 3, .. }, + .. + } if offset == prefix_len + ), + "expected CorruptDocumentLength at offset {prefix_len}, got {err:?}" + ); + assert!(list_dir_names(&out_corrupt).is_empty()); + + // 3. Reader I/O failure after valid prefix. + let out_io = dir.path().join("out-io"); + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &make_args( + dir.path().join("io-fail.bson"), + mapping_path, + out_io.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions { + chunk_capacity_bytes: prefix_len as usize, + max_doc_bytes: 1024 * 1024, + }, + ), + PrefixThenIoErrorReader::new(valid_prefix.as_bytes().to_vec()), + |_idx, file| SyncedBufFile::new(file), + |_idx, _path| {}, + ) + .expect_err("reader I/O error must fail"); + assert!( + matches!( + err, + RunCurateQmBars1mError::BsonStream { + source: BsonStreamError::Io { offset, .. }, + .. + } if offset == prefix_len + ), + "expected BsonStreamError::Io at offset {prefix_len}, got {err:?}" + ); + assert!(list_dir_names(&out_io).is_empty()); +} + +#[test] +fn injected_sink_write_flush_and_post_preflight_hard_link_collision_roll_back_cleanly() { + let dir = TempDirGuard::new("qm-bars1m-rollback"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let intraday_bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + + // 1. Injected sink write failure (tiny batch triggers write during chunk curation). + let out_write_fail = dir.path().join("out-write-fail"); + let mut write_fail_args = make_args( + dir.path().join("in.bson"), + mapping_path.clone(), + out_write_fail.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + write_fail_args.ilp_options.max_batch_rows = 1; + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &write_fail_args, + Cursor::new(intraday_bytes.as_slice()), + |_idx, _file| FailingWriteSink { + fail_on_write: true, + fail_on_flush: false, + }, + |_idx, _path| {}, + ) + .expect_err("injected write failure must abort"); + assert!(matches!(err, RunCurateQmBars1mError::CurateWrite(_))); + assert!(list_dir_names(&out_write_fail).is_empty()); + + // 2. Injected final flush failure during IlpShardedWriter::finish(). + let out_flush_fail = dir.path().join("out-flush-fail"); + let flush_fail_args = make_args( + dir.path().join("in.bson"), + mapping_path.clone(), + out_flush_fail.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &flush_fail_args, + Cursor::new(intraday_bytes.as_slice()), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + ) + .expect_err("injected flush failure must abort"); + assert!(matches!(err, RunCurateQmBars1mError::Ilp(_))); + assert!(list_dir_names(&out_flush_fail).is_empty()); + + // 3. Post-preflight hard-link collision on shard 1 after shard 0 already published. + // Verify shard 0 is rolled back, competing shard 1 and unrelated bars_1m.shard-00.ilp stay + // byte-identical, and no .tmp files remain. + let out_link_collision = dir.path().join("out-link-collision"); + fs::create_dir_all(&out_link_collision).unwrap(); + let eod_existing = out_link_collision.join("bars_1m.shard-00.ilp"); + fs::write(&eod_existing, b"keep-eod-shard").unwrap(); + let competing_shard_1 = out_link_collision.join("bars_1m_qm.shard-01.ilp"); + let competing_bytes = b"competing-writer-shard-1"; + + let err = run_curate_qm_bars_1m_to_dir_with_hooks( + &make_args( + dir.path().join("in.bson"), + mapping_path.clone(), + out_link_collision.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 3, + known_at_micros, + BsonStreamOptions::default(), + ), + Cursor::new(intraday_bytes.as_slice()), + |_idx, file| SyncedBufFile::new(file), + |shard_idx, final_path| { + if shard_idx == 1 { + fs::write(final_path, competing_bytes).expect("create competing shard 1"); + } + }, + ) + .expect_err("post-preflight collision must fail"); + assert!(matches!( + err, + RunCurateQmBars1mError::OutputFileExists { ref path } if path == &competing_shard_1 + )); + assert_eq!(fs::read(&competing_shard_1).unwrap(), competing_bytes); + assert_eq!(fs::read(&eod_existing).unwrap(), b"keep-eod-shard"); + assert_eq!( + list_dir_names(&out_link_collision), + vec!["bars_1m.shard-00.ilp", "bars_1m_qm.shard-01.ilp"] + ); + + // 4. Staging unlink failure preserves original cause and reports failed staging paths. + let out_cleanup_fail = dir.path().join("out-cleanup-fail"); + let err = run_curate_qm_bars_1m_to_dir_with_cleanup_hook( + &make_args( + dir.path().join("in.bson"), + mapping_path, + out_cleanup_fail.clone(), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ), + Cursor::new(intraday_bytes.as_slice()), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + |path| { + // Simulate permission denied on cleanup while still cleaning up in TempDirGuard drop. + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("injected unlink failure for {}", path.display()), + )) + }, + ) + .expect_err("cleanup failure must surface RollbackFailed"); + match err { + RunCurateQmBars1mError::RollbackFailed { cause, failures } => { + assert!(matches!(*cause, RunCurateQmBars1mError::Ilp(_))); + assert_eq!(failures.len(), 2); + for failure in &failures { + assert!(failure.final_path.starts_with(&out_cleanup_fail)); + } + } + other => panic!("expected RollbackFailed, got {other:?}"), + } +} + +#[test] +fn report_formatter_exposes_every_counter_and_isolates_elapsed_secs_on_timing_line() { + let dir = TempDirGuard::new("qm-bars1m-format"); + let mapping_path = write_mapping_tsv(dir.path(), &["qm\tAAA\t2024-01-01\t\t7"]); + let known_at_micros = et_to_utc_micros(day(2024, 6, 12), 18, 0, 0).unwrap(); + let intraday_bytes = concat_docs(&[make_qm_intraday_doc( + "AAA", + et_ts_millis(2024, 6, 10, 10, 0), + 10.0, + 10.5, + 9.8, + 10.2, + 100.0, + )]); + let args = make_args( + dir.path().join("fmt.bson"), + mapping_path, + dir.path().join("unused"), + DEFAULT_QM_BARS_1M_MAPPING_SOURCE, + 2, + known_at_micros, + BsonStreamOptions::default(), + ); + + let report = run_curate_qm_bars_1m_with_readers( + &args, + Cursor::new(intraday_bytes.as_slice()), + |_idx| Vec::::new(), + ) + .expect("format run should succeed"); + + let text = format_curate_qm_bars_1m_report(&report); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 7, "unexpected report line count:\n{text}"); + assert_eq!(lines[0], "curate-etl curate-qm-bars-1m"); + + for token in [ + "docs_framed=1", + &format!("bytes_read={}", intraday_bytes.len()), + "docs_seen=1", + "rows_decoded=1", + "rejected=0", + "missing=0", + "empty=0", + "wrong_type=0", + "invalid_ts=0", + "invalid_num=0", + "corrupt=0", + "chunks=1", + "max_rows_per_chunk=1", + "cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)", + "bars_in=1", + "keys_out_per_chunk_sum=1", + "invalid_ohlc=0", + "inconsistent_ohlc=0", + "invalid_vol=0", + "ts_out_of_range=0", + "dup_collapsed=0", + "dup_conflict_dropped=0", + "rows_in=1", + "rows_out=1", + "listings_out_per_chunk_sum=1", + "dropped_unmapped=0", + "listing_collision_collapsed=0", + "listing_collision_dropped=0", + "shards=2", + "rows_written=1", + "ilp_rows=1", + &format!("bytes={}", report.ilp_stats.bytes), + "flushes=1", + "per_shard_rows=", + ] { + assert!(text.contains(token), "report missing '{token}':\n{text}"); + } + + // Only the final timing: line carries elapsed_secs. + for line in &lines[..lines.len() - 1] { + assert!( + !line.contains("elapsed_secs"), + "non-timing line must not contain elapsed_secs: {line}" + ); + } + assert!(lines.last().unwrap().trim_start().starts_with("timing:")); + assert!(lines.last().unwrap().contains("elapsed_secs=")); +}