From e45889c525de6a5189ce69d5e5b76e44b3aea3e5 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 18:41:38 -0500 Subject: [PATCH] =?UTF-8?q?T-183:=20M2.3l=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20file-to-file=20`fx=5F1m`=20runner=20(`run=5Fcurate=5Ffx=5F1?= =?UTF-8?q?m.rs`:=20raw=20`eodIntraday1M`=20BSON=20dump=20=E2=86=92=20`cur?= =?UTF-8?q?ate=5Fand=5Fwrite=5Ffx=5F1m=5Ffrom=5Fbson`=20=E2=86=92=20per-sh?= =?UTF-8?q?ard=20`fx=5F1m.shard-.ilp`=20ILP=20v2=20files,=20fail-close?= =?UTF-8?q?d=20publish)=20with=20tests=20(no=20new=20crates,=20no=20CLI/be?= =?UTF-8?q?nch=20changes,=20no=20live=20Mongo/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 | 6 + tools/curate-etl/src/run_curate_bars_1m.rs | 120 +- .../src/run_curate_bars_1m_tests.rs | 6 +- tools/curate-etl/src/run_curate_fx_1m.rs | 414 +++++++ .../curate-etl/src/run_curate_fx_1m_tests.rs | 1104 +++++++++++++++++ 6 files changed, 1620 insertions(+), 38 deletions(-) create mode 100644 tools/curate-etl/src/run_curate_fx_1m.rs create mode 100644 tools/curate-etl/src/run_curate_fx_1m_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index faf963c7..3c24f001 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1675,6 +1675,14 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **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:** 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. +## `run_curate_fx_1m` File-to-File Runner (`M2.3l`) + +`run_curate_fx_1m` / `run_curate_fx_1m_with_readers` (`src/run_curate_fx_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files (`/fx_1m.shard-.ilp`) via `curate_and_write_fx_1m_from_bson` (`src/curate_fx_1m.rs`): + +- **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers. +- **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. + ## 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 385a9e34..82777e68 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -328,6 +328,12 @@ pub use run_curate_bars_1m::{ DEFAULT_BARS_1M_MAPPING_SOURCE, }; +pub mod run_curate_fx_1m; +pub use run_curate_fx_1m::{ + format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs, + CurateFx1mRunReport, RunCurateFx1mError, +}; + 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 3803f847..f30e8e19 100644 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -65,7 +65,9 @@ use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader} use crate::curate_bars_1m::{ curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError, }; -use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions}; +use crate::ilp::{ + IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M, +}; use crate::parquet_bars::RollbackFailure; use crate::parquet_publish::{ next_run_id, rollback_published, PublishedPartition, StagingFileGuard, FILE_BUF_CAPACITY_BYTES, @@ -269,6 +271,32 @@ fn validate_common_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mEr Ok(()) } +pub(crate) enum ShardPublishError { + InvalidOutDir { path: PathBuf, detail: String }, + OutputFileExists { path: PathBuf }, + Io { path: PathBuf, source: io::Error }, + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl From for RunCurateBars1mError { + 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, + }, + } + } +} + fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> { validate_common_args(args)?; if args.ilp_options.max_batch_bytes == 0 { @@ -277,30 +305,38 @@ 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() { - if !args.out_dir.is_dir() { - return Err(RunCurateBars1mError::InvalidOutDir { - path: args.out_dir.clone(), + preflight_shard_out_dir(&args.out_dir, TABLE_BARS_1M)?; + Ok(()) +} + +pub(crate) fn preflight_shard_out_dir( + out_dir: &Path, + table: &str, +) -> Result<(), ShardPublishError> { + if out_dir.exists() { + if !out_dir.is_dir() { + return Err(ShardPublishError::InvalidOutDir { + path: out_dir.to_path_buf(), 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(), + let entries = fs::read_dir(out_dir).map_err(|source| ShardPublishError::Io { + path: out_dir.to_path_buf(), 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(), + let entry = entry.map_err(|source| ShardPublishError::Io { + path: out_dir.to_path_buf(), source, })?; - if is_final_shard_file_name(&entry.file_name()) { + if is_final_shard_file_name_for_table(table, &entry.file_name()) { existing_shards.push(entry.path()); } } if !existing_shards.is_empty() { existing_shards.sort(); - return Err(RunCurateBars1mError::OutputFileExists { + return Err(ShardPublishError::OutputFileExists { path: existing_shards.remove(0), }); } @@ -309,11 +345,14 @@ fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1 } #[inline] -fn is_final_shard_file_name(name: &OsStr) -> bool { +pub(crate) fn is_final_shard_file_name_for_table(table: &str, name: &OsStr) -> bool { let Some(s) = name.to_str() else { return false; }; - let Some(rest) = s.strip_prefix("bars_1m.shard-") else { + let Some(after_table) = s.strip_prefix(table) else { + return false; + }; + let Some(rest) = after_table.strip_prefix(".shard-") else { return false; }; let Some(digits) = rest.strip_suffix(".ilp") else { @@ -323,8 +362,12 @@ fn is_final_shard_file_name(name: &OsStr) -> bool { } #[inline] -fn final_shard_path(out_dir: &Path, shard_idx: usize) -> PathBuf { - out_dir.join(format!("bars_1m.shard-{shard_idx:02}.ilp")) +pub(crate) fn final_shard_path_for_table( + out_dir: &Path, + table: &str, + shard_idx: usize, +) -> PathBuf { + out_dir.join(format!("{table}.shard-{shard_idx:02}.ilp")) } fn load_reference_inputs( @@ -546,12 +589,12 @@ where /// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once /// per shard by [`IlpShardedWriter::finish`]). -struct SyncedBufFile { +pub(crate) struct SyncedBufFile { inner: BufWriter, } impl SyncedBufFile { - fn new(file: File) -> Self { + pub(crate) fn new(file: File) -> Self { Self { inner: BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file), } @@ -573,16 +616,17 @@ impl Write for SyncedBufFile { } } -fn create_exclusive_shard_tmp_file( +pub(crate) fn create_exclusive_shard_tmp_file_for_table( out_dir: &Path, + table: &str, shard_idx: usize, run_id: &str, -) -> Result<(PathBuf, File), RunCurateBars1mError> { +) -> Result<(PathBuf, File), ShardPublishError> { for attempt in 0..1024u32 { let file_name = if attempt == 0 { - format!(".bars_1m.shard-{shard_idx:02}.{run_id}.tmp") + format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp") } else { - format!(".bars_1m.shard-{shard_idx:02}.{run_id}.{attempt}.tmp") + format!(".{table}.shard-{shard_idx:02}.{run_id}.{attempt}.tmp") }; let tmp_path = out_dir.join(file_name); match OpenOptions::new() @@ -593,15 +637,15 @@ fn create_exclusive_shard_tmp_file( Ok(file) => return Ok((tmp_path, file)), Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, Err(source) => { - return Err(RunCurateBars1mError::Io { + return Err(ShardPublishError::Io { path: tmp_path, source, }); } } } - Err(RunCurateBars1mError::Io { - path: out_dir.join(format!(".bars_1m.shard-{shard_idx:02}.{run_id}.tmp")), + Err(ShardPublishError::Io { + path: out_dir.join(format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")), source: io::Error::new( io::ErrorKind::AlreadyExists, "exhausted unique staging file names", @@ -609,32 +653,33 @@ fn create_exclusive_shard_tmp_file( }) } -fn publish_staged_shards( +pub(crate) fn publish_staged_shards_for_table( out_dir: &Path, + table: &str, mut staged: Vec<(PathBuf, StagingFileGuard)>, mut before_link: F, -) -> Result<(), RunCurateBars1mError> +) -> Result<(), ShardPublishError> where F: FnMut(usize, &Path), { let mut published: Vec = Vec::with_capacity(staged.len()); for (shard_idx, (tmp_path, guard)) in staged.iter_mut().enumerate() { - let final_path = final_shard_path(out_dir, shard_idx); + let final_path = final_shard_path_for_table(out_dir, table, shard_idx); before_link(shard_idx, &final_path); if let Err(source) = fs::hard_link(&tmp_path, &final_path) { let cause = if source.kind() == io::ErrorKind::AlreadyExists { - RunCurateBars1mError::OutputFileExists { path: final_path } + ShardPublishError::OutputFileExists { path: final_path } } else { - RunCurateBars1mError::Io { + ShardPublishError::Io { path: final_path, source, } }; let rollback_failures = rollback_published(&published); if !rollback_failures.is_empty() { - return Err(RunCurateBars1mError::RollbackFailed { + return Err(ShardPublishError::RollbackFailed { cause: Box::new(cause), failures: rollback_failures, }); @@ -648,13 +693,13 @@ where }); if let Err(source) = fs::remove_file(&tmp_path) { - let cause = RunCurateBars1mError::Io { + let cause = ShardPublishError::Io { path: tmp_path.clone(), source, }; let rollback_failures = rollback_published(&published); if !rollback_failures.is_empty() { - return Err(RunCurateBars1mError::RollbackFailed { + return Err(ShardPublishError::RollbackFailed { cause: Box::new(cause), failures: rollback_failures, }); @@ -698,7 +743,12 @@ where 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) = create_exclusive_shard_tmp_file(&args.out_dir, shard_idx, &run_id)?; + let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + TABLE_BARS_1M, + shard_idx, + &run_id, + )?; let guard = StagingFileGuard::new(tmp_path.clone()); staged.push((tmp_path, guard)); sinks.push(make_sink(shard_idx, file)); @@ -707,7 +757,7 @@ where let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?; let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?; - publish_staged_shards(&args.out_dir, staged, before_link)?; + publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, staged, before_link)?; Ok(report) } @@ -839,4 +889,4 @@ pub fn format_curate_bars_1m_report(report: &CurateBars1mRunReport) -> String { #[cfg(test)] #[path = "run_curate_bars_1m_tests.rs"] -mod tests; +pub(crate) mod tests; 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 2309c724..6cf6c065 100644 --- a/tools/curate-etl/src/run_curate_bars_1m_tests.rs +++ b/tools/curate-etl/src/run_curate_bars_1m_tests.rs @@ -20,12 +20,12 @@ use crate::split::ymd_to_epoch_days; static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); -struct TempDirGuard { +pub(crate) struct TempDirGuard { path: PathBuf, } impl TempDirGuard { - fn new(prefix: &str) -> Self { + pub(crate) fn new(prefix: &str) -> Self { let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); let path = std::env::temp_dir().join(format!( "curate-etl-{prefix}-{}-{seq}", @@ -35,7 +35,7 @@ impl TempDirGuard { Self { path } } - fn path(&self) -> &Path { + pub(crate) fn path(&self) -> &Path { &self.path } } diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs new file mode 100644 index 00000000..bda78712 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fx_1m.rs @@ -0,0 +1,414 @@ +//! File-to-file `fx_1m` runner (`M2.3l`). +//! +//! Streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files +//! (`/fx_1m.shard-.ilp`) via [`crate::curate_fx_1m::curate_and_write_fx_1m_from_bson`]. +//! +//! # Global Sort, Deduplication & Memory Bound +//! - Calls [`curate_and_write_fx_1m_from_bson`] **once** over the entire input stream so timestamp +//! sorting and `ts` deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) +//! are global across all BSON stream chunks, then calls [`IlpShardedWriter::finish`] exactly +//! once after clean EOF. +//! - **Memory bound:** `Fx1mAccumulator::push` in `src/curate_fx_1m.rs` counts non-`CAD.FOREX` +//! rows in `dropped_wrong_code` and returns immediately without appending or allocating. Peak +//! memory is therefore bounded by: +//! - accepted `CAD.FOREX` rows (`Vec>`), +//! - the configured BSON stream chunk buffer (`BsonStreamOptions::chunk_capacity_bytes`, +//! growing only for a single document up to `max_doc_bytes`), and +//! - bounded ILP output batch buffers per shard (`IlpWriterOptions`) plus per-shard file +//! buffering in file mode. +//! +//! Non-`CAD.FOREX` rows from the full `eodIntraday1M` dump are never buffered. +//! - **Single-pair sharding:** every curated row carries `pair = "USDCAD"` and `source = "eod"`, +//! so [`IlpShardedWriter`] routes all rows deterministically to +//! `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. +//! - **Timestamp provenance:** preserves EODHD's UTC microsecond bar-start `ts` and CAD-per-USD +//! OHLC bits verbatim; bar-start `ts` alone does not establish when the bar's close was +//! observable. +//! - **Omitted framing counters:** [`CurateFx1mRunReport`] omits `intraday_docs_framed` and +//! `intraday_bytes_read` because [`curate_and_write_fx_1m_from_bson`] owns the underlying +//! `RawBsonChunkReader` internally and returns [`BsonEodIntradayDecodeStats`] only. +//! +//! # File Publication & Fail-Closed Guarantees +//! - Preflight scans `out_dir` for **any** pre-existing `fx_1m.shard-.ilp` file +//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards +//! from a prior run cannot survive alongside a new export. +//! - Each shard writes into an exclusively created staging file in `out_dir` +//! (`.fx_1m.shard-..tmp`), flushes and `sync_all`s on `finish`, and publishes to +//! `fx_1m.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 input, fatal BSON framing/I/O, ILP write/flush, or +//! publication collision) 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 [`BsonEodIntradayDecodeStats`]. + +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::bson_eod_intraday::BsonEodIntradayDecodeStats; +use crate::bson_stream::{BsonStreamError, BsonStreamOptions}; +use crate::curate_fx_1m::{ + curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, CurateFx1mStats, +}; +use crate::ilp::{ + IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_FX_1M, +}; +use crate::parquet_bars::RollbackFailure; +use crate::parquet_publish::{next_run_id, StagingFileGuard}; +use crate::run_curate_bars_1m::{ + create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir, + publish_staged_shards_for_table, ShardPublishError, SyncedBufFile, +}; + +/// Arguments for [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFx1mArgs { + pub intraday_path: PathBuf, + pub out_dir: PathBuf, + pub shard_count: usize, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +/// Full run report produced by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. +/// +/// `intraday_docs_framed` and `intraday_bytes_read` are intentionally omitted because +/// [`curate_and_write_fx_1m_from_bson`] owns the underlying `RawBsonChunkReader` and returns +/// [`BsonEodIntradayDecodeStats`] only. +/// +/// Conservation invariants: +/// - `decode.docs_seen == decode.rows_decoded + decode.rejected_total()` +/// - `decode.rows_decoded == curate_stats.bars_in` +/// - `curate_stats.bars_in == curate_stats.rows_out + curate_stats.dropped_wrong_code + curate_stats.dropped_negative_ts + curate_stats.dropped_invalid_ohlc + curate_stats.dropped_high_below_bound + curate_stats.dropped_low_above_bound + curate_stats.duplicate_collapsed + curate_stats.duplicate_conflict_dropped` +/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::()` +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1mRunReport { + pub decode: BsonEodIntradayDecodeStats, + pub curate_stats: CurateFx1mStats, + pub rows_written: usize, + pub ilp_stats: IlpWriteStats, + pub shard_count: usize, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`]. +#[derive(Debug)] +pub enum RunCurateFx1mError { + /// `shard_count` was `0`. + ZeroShardCount, + /// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`. + ShardCountMismatch { expected: usize, actual: usize }, + /// `out_dir` exists and is not a directory. + InvalidOutDir { path: PathBuf, detail: String }, + /// A final shard output file (`fx_1m.shard-.ilp`) already existed. + OutputFileExists { path: PathBuf }, + /// Failed to open the input `eodIntraday1M` dump file. + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + /// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`. + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + /// ILP writer initialization, per-row write, 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 failed and rolling back one or more already-published shards also failed. + RollbackFailed { + cause: Box, + failures: Vec, + }, +} + +impl From for RunCurateFx1mError { + 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 RunCurateFx1mError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ZeroShardCount => write!(f, "shard_count must be >= 1"), + Self::ShardCountMismatch { expected, actual } => write!( + f, + "ILP writer shard count mismatch: expected {expected}, got {actual}" + ), + 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::BsonStream { + label, + path, + source, + } => write!(f, "failed reading {label} '{}': {source}", path.display()), + Self::Ilp(err) => write!(f, "fx_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 RunCurateFx1mError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::Ilp(err) => Some(err), + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::ZeroShardCount + | Self::ShardCountMismatch { .. } + | Self::InvalidOutDir { .. } + | Self::OutputFileExists { .. } => None, + } + } +} + +fn validate_common_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> { + if args.shard_count == 0 { + return Err(RunCurateFx1mError::ZeroShardCount); + } + args.stream_options + .validate() + .map_err(|source| RunCurateFx1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + })?; + Ok(()) +} + +fn validate_file_mode_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> { + validate_common_args(args)?; + if args.ilp_options.max_batch_bytes == 0 { + return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)); + } + if args.ilp_options.max_batch_rows == 0 { + return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)); + } + preflight_shard_out_dir(&args.out_dir, TABLE_FX_1M)?; + Ok(()) +} + +fn run_curate_fx_1m_with_readers_inner( + args: &CurateFx1mArgs, + intraday: R, + mut writer: IlpShardedWriter, + start: Instant, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let bson_report = + curate_and_write_fx_1m_from_bson(intraday, args.stream_options, &mut writer).map_err( + |err| match err { + CurateFx1mBsonError::Stream(source) => RunCurateFx1mError::BsonStream { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + }, + CurateFx1mBsonError::Write(err) => RunCurateFx1mError::Ilp(err), + }, + )?; + + let ilp_stats = writer.finish().map_err(RunCurateFx1mError::Ilp)?; + + Ok(CurateFx1mRunReport { + decode: bson_report.decode_stats, + curate_stats: bson_report.write_report.curate_stats, + rows_written: bson_report.write_report.rows_written, + ilp_stats, + shard_count: args.shard_count, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the `fx_1m` curation pipeline from an arbitrary [`io::Read`] stream into a caller-owned +/// [`IlpShardedWriter`]. +/// +/// Validates `args` and writer shard-count agreement, calls [`curate_and_write_fx_1m_from_bson`] +/// once over the entire stream for global sort and `ts` deduplication, and calls +/// [`IlpShardedWriter::finish`] exactly once after clean EOF. +pub fn run_curate_fx_1m_with_readers( + args: &CurateFx1mArgs, + intraday: R, + writer: IlpShardedWriter, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let start = Instant::now(); + validate_common_args(args)?; + if writer.shard_count() != args.shard_count { + return Err(RunCurateFx1mError::ShardCountMismatch { + expected: args.shard_count, + actual: writer.shard_count(), + }); + } + + run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) +} + +/// 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_fx_1m_to_dir_with_hooks( + args: &CurateFx1mArgs, + intraday: R, + mut make_sink: SF, + before_link: BL, +) -> Result +where + R: io::Read, + W: Write + Send, + SF: FnMut(usize, File) -> W, + BL: FnMut(usize, &Path), +{ + let start = Instant::now(); + validate_file_mode_args(args)?; + + fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateFx1mError::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) = create_exclusive_shard_tmp_file_for_table( + &args.out_dir, + TABLE_FX_1M, + shard_idx, + &run_id, + )?; + let guard = StagingFileGuard::new(tmp_path.clone()); + staged.push((tmp_path, guard)); + sinks.push(make_sink(shard_idx, file)); + } + + let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateFx1mError::Ilp)?; + let report = run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)?; + + publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, staged, before_link)?; + Ok(report) +} + +/// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB +/// ILP v2 files (`/fx_1m.shard-.ilp`). +pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result { + validate_file_mode_args(args)?; + + let intraday_file = File::open(&args.intraday_path).map_err(|source| { + RunCurateFx1mError::OpenInput { + label: "eod-intraday", + path: args.intraday_path.clone(), + source, + } + })?; + + run_curate_fx_1m_to_dir_with_hooks( + args, + intraday_file, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + +/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_fx_1m_report(report: &CurateFx1mRunReport) -> 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 d = &report.decode; + let c = &report.curate_stats; + + format!( + "curate-etl curate-fx-1m\n\ + \x20 intraday_bson: docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\ + \x20 curate: bars_in={} rows_out={} wrong_code={} negative_ts={} invalid_ohlc={} high_below_bound={} low_above_bound={} dup_collapsed={} dup_conflict_dropped={}\n\ + \x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\ + \x20 timing: elapsed_secs={:.6}", + 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, + c.bars_in, + c.rows_out, + c.dropped_wrong_code, + c.dropped_negative_ts, + c.dropped_invalid_ohlc, + c.dropped_high_below_bound, + c.dropped_low_above_bound, + c.duplicate_collapsed, + c.duplicate_conflict_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_fx_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_fx_1m_tests.rs b/tools/curate-etl/src/run_curate_fx_1m_tests.rs new file mode 100644 index 00000000..807605dd --- /dev/null +++ b/tools/curate-etl/src/run_curate_fx_1m_tests.rs @@ -0,0 +1,1104 @@ +use std::error::Error; +use std::fs; +use std::io::{self, Cursor, Write}; +use std::path::{Path, PathBuf}; + +use bson::raw::{cstr, RawDocumentBuf}; + +use super::*; +use crate::bson_eod_intraday::decode_eod_intraday_buffer; +use crate::bson_stream::{RawBsonChunkReader, MIN_BSON_DOC_BYTES}; +use crate::curate_fx_1m::{curate_and_write_fx_1m, FX_1M_SOURCE_EOD}; +use crate::fx::FX_PAIR_USDCAD; +use crate::ilp::{shard_for_fx_pair, ILP_V2_DOUBLE_TYPE, TABLE_FX_1M}; +use crate::run_curate_bars_1m::tests::TempDirGuard; +use crate::run_curate_fx::EOD_CAD_FOREX_CODE; + +fn make_intraday_doc( + code: &str, + timestamp_sec: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), timestamp_sec); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn make_malformed_missing_open_doc(code: &str, timestamp_sec: i64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), timestamp_sec); + doc.append(cstr!("high"), 1.3755_f64); + doc.append(cstr!("low"), 1.3745_f64); + doc.append(cstr!("close"), 1.3752_f64); + doc.append(cstr!("volume"), 0.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 make_args( + intraday_path: PathBuf, + out_dir: PathBuf, + shard_count: usize, + stream_options: BsonStreamOptions, +) -> CurateFx1mArgs { + CurateFx1mArgs { + intraday_path, + out_dir, + shard_count, + stream_options, + ilp_options: IlpWriterOptions::default(), + } +} + +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 +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedIlpFx1m { + pair: String, + source: String, + open: f64, + high: f64, + low: f64, + close: f64, + ts: i64, +} + +/// Decodes QuestDB ILP v2 `fx_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_fx_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_FX_1M), "expected fx_1m table"); + let pair_tag = tags.next().expect("pair tag"); + let source_tag = tags.next().expect("source tag"); + assert!(tags.next().is_none(), "unexpected extra ILP tag"); + + let pair = pair_tag + .strip_prefix("pair=") + .expect("pair= prefix") + .to_string(); + 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' ', "missing space after close field"); + 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(DecodedIlpFx1m { + pair, + source, + open, + high, + low, + close, + ts, + }); + } + + rows +} + +fn assert_report_conservation(report: &CurateFx1mRunReport) { + let d = &report.decode; + assert_eq!( + d.docs_seen, + d.rows_decoded + d.rejected_total(), + "decode conservation failed: {d:?}" + ); + + let c = &report.curate_stats; + assert_eq!( + d.rows_decoded, c.bars_in, + "rows_decoded != curate_stats.bars_in" + ); + assert_eq!( + c.bars_in, + c.rows_out + + c.dropped_wrong_code + + c.dropped_negative_ts + + c.dropped_invalid_ohlc + + c.dropped_high_below_bound + + c.dropped_low_above_bound + + c.duplicate_collapsed + + c.duplicate_conflict_dropped, + "curate_stats conservation failed: {c:?}" + ); + 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); +} + +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(()) + } + } +} + +#[test] +fn happy_path_matches_curate_and_write_fx_1m_bytes_and_preserves_conservation() { + let dir = TempDirGuard::new("fx1m-happy"); + let ts1 = 1_717_971_300_i64; // 2024-06-09 22:15:00 UTC + let ts2 = 1_717_971_360_i64; + let ts3 = 1_717_988_400_i64; + + let docs = vec![ + // Out-of-order valid CAD.FOREX bars + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3, 1.37654321, 1.37712345, 1.37611111, 1.37689012, 0.0), + make_intraday_doc("AAPL.US", ts1, 195.0, 196.0, 194.5, 195.5, 1000.0), + make_malformed_missing_open_doc(EOD_CAD_FOREX_CODE, ts1 + 10), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3750, 1.3755, 1.3745, 1.3752, 5.0), + make_intraday_doc("cad.forex", ts2, 1.3750, 1.3755, 1.3745, 1.3752, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3752, 1.3760, 1.3750, 1.3758, 12.0), + // Valid BSON bar that fails FX builder high-below-bound rule + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3 + 60, 1.3800, 1.3750, 1.3700, 1.3720, 0.0), + // Valid BSON bar that fails FX builder low-above-bound rule + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3 + 120, 1.3700, 1.3800, 1.3750, 1.3780, 0.0), + ]; + let intraday_bytes = concat_docs(&docs); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + // Run file-mode runner with 4 shards. + let out_dir = dir.path().join("out"); + let args = make_args( + intraday_path, + out_dir.clone(), + 4, + BsonStreamOptions::default(), + ); + let report = run_curate_fx_1m(&args).expect("happy-path run should succeed"); + assert_report_conservation(&report); + + assert_eq!(report.decode.docs_seen, 8); + assert_eq!(report.decode.rows_decoded, 7); + assert_eq!(report.decode.rejected_missing_field, 1); + assert_eq!(report.curate_stats.bars_in, 7); + assert_eq!(report.curate_stats.rows_out, 3); + assert_eq!(report.curate_stats.dropped_wrong_code, 2); + assert_eq!(report.curate_stats.dropped_high_below_bound, 1); + assert_eq!(report.curate_stats.dropped_low_above_bound, 1); + assert_eq!(report.rows_written, 3); + + // Reference output from `curate_and_write_fx_1m` on the fixture's decoded bars. + let mut ref_sinks = [Vec::new(), Vec::new(), Vec::new(), Vec::new()]; + let mut ref_writer = IlpShardedWriter::new( + ref_sinks.iter_mut().collect(), + IlpWriterOptions::default(), + ) + .unwrap(); + let mut decoded_bars = Vec::new(); + let ref_decode = decode_eod_intraday_buffer( + &intraday_bytes, + |raw| decoded_bars.push(raw), + |_offset, _err| {}, + ); + assert_eq!(ref_decode, report.decode); + let ref_write = curate_and_write_fx_1m(decoded_bars, &mut ref_writer).unwrap(); + let ref_ilp = ref_writer.finish().unwrap(); + assert_eq!(ref_write.curate_stats, report.curate_stats); + assert_eq!(ref_write.rows_written, report.rows_written); + assert_eq!(ref_ilp, report.ilp_stats); + + let mut total_file_bytes = 0usize; + let mut all_decoded = Vec::new(); + for (shard_idx, expected_bytes) in ref_sinks.iter().enumerate() { + let path = out_dir.join(format!("fx_1m.shard-{shard_idx:02}.ilp")); + let file_bytes = fs::read(&path).expect("read shard file"); + assert_eq!( + &file_bytes, expected_bytes, + "shard {shard_idx:02} bytes differ from curate_and_write_fx_1m" + ); + total_file_bytes += file_bytes.len(); + all_decoded.extend(decode_ilp_fx_1m(&file_bytes)); + } + assert_eq!(total_file_bytes, report.ilp_stats.bytes); + + // Verify decoded fields, ascending ts, and exact OHLC bits. + assert_eq!(all_decoded.len(), 3); + let expected = [ + (ts1 * 1_000_000, 1.3750_f64, 1.3755_f64, 1.3745_f64, 1.3752_f64), + (ts2 * 1_000_000, 1.3752_f64, 1.3760_f64, 1.3750_f64, 1.3758_f64), + (ts3 * 1_000_000, 1.37654321_f64, 1.37712345_f64, 1.37611111_f64, 1.37689012_f64), + ]; + for (row, (ts, o, h, l, c)) in all_decoded.iter().zip(expected) { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + assert_eq!(row.ts, ts); + assert_eq!(row.open.to_bits(), o.to_bits()); + assert_eq!(row.high.to_bits(), h.to_bits()); + assert_eq!(row.low.to_bits(), l.to_bits()); + assert_eq!(row.close.to_bits(), c.to_bits()); + } + for pair in all_decoded.windows(2) { + assert!(pair[0].ts < pair[1].ts, "rows not strictly ascending by ts"); + } +} + +#[test] +fn cross_chunk_global_dedup_collapses_identical_and_drops_conflicts() { + let ts_collapse = 1_718_000_000_i64; + let ts_conflict = 1_718_000_060_i64; + let ts_unique = 1_718_000_120_i64; + + let docs = vec![ + // Chunk 1: first copy of collapse + first copy of conflict + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_collapse, 1.3700, 1.3710, 1.3690, 1.3705, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_conflict, 1.3705, 1.3715, 1.3700, 1.3710, 0.0), + // Intervening filler docs to push second copies into later chunks + make_intraday_doc("MSFT.US", ts_unique, 420.0, 421.0, 419.0, 420.5, 500.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_unique, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), + // Later chunks: identical duplicate of ts_collapse + conflicting duplicate of ts_conflict + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_collapse, 1.3700, 1.3710, 1.3690, 1.3705, 99.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts_conflict, 1.3705, 1.3715, 1.3700, 1.3712, 0.0), + ]; + let intraday_bytes = concat_docs(&docs); + let doc_size = docs[0].as_bytes().len(); + + // Force at most 1 document per chunk so every document sits in its own BSON chunk. + let tiny_opts = BsonStreamOptions { + chunk_capacity_bytes: doc_size, + ..BsonStreamOptions::default() + }; + + // Explicitly verify that the duplicate pairs occupy distinct BSON chunks. + let mut chunk_reader = + RawBsonChunkReader::with_options(Cursor::new(&intraday_bytes), tiny_opts).unwrap(); + let mut chunk_idx = 0usize; + let mut collapse_chunks = Vec::new(); + let mut conflict_chunks = Vec::new(); + while let Some(chunk) = chunk_reader.next_chunk().unwrap() { + decode_eod_intraday_buffer( + chunk.bytes, + |raw| { + if raw.ts == ts_collapse * 1_000_000 { + collapse_chunks.push(chunk_idx); + } else if raw.ts == ts_conflict * 1_000_000 { + conflict_chunks.push(chunk_idx); + } + }, + |_offset, _err| {}, + ); + chunk_idx += 1; + } + assert!( + chunk_idx >= 5, + "expected >= 5 chunks for 6 docs with tiny chunk_capacity_bytes={doc_size}, got {chunk_idx}" + ); + assert_eq!(collapse_chunks.len(), 2); + assert_ne!( + collapse_chunks[0], collapse_chunks[1], + "identical duplicates must sit in distinct BSON chunks" + ); + assert_eq!(conflict_chunks.len(), 2); + assert_ne!( + conflict_chunks[0], conflict_chunks[1], + "conflicting duplicates must sit in distinct BSON chunks" + ); + + let mut sink = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); + let args = make_args( + PathBuf::from("in-memory-eodIntraday1M.bson"), + PathBuf::from("unused-out"), + 1, + tiny_opts, + ); + + let report = run_curate_fx_1m_with_readers(&args, Cursor::new(&intraday_bytes), writer) + .expect("cross-chunk dedup run should succeed"); + assert_report_conservation(&report); + assert_eq!(report.curate_stats.bars_in, 6); + assert_eq!(report.curate_stats.dropped_wrong_code, 1); + assert_eq!(report.curate_stats.duplicate_collapsed, 1); + assert_eq!(report.curate_stats.duplicate_conflict_dropped, 2); + assert_eq!(report.curate_stats.rows_out, 2); + assert_eq!(report.rows_written, 2); + + let decoded = decode_ilp_fx_1m(&sink); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded[0].ts, ts_collapse * 1_000_000); + assert_eq!(decoded[0].close.to_bits(), 1.3705_f64.to_bits()); + assert_eq!(decoded[1].ts, ts_unique * 1_000_000); + assert_eq!(decoded[1].close.to_bits(), 1.3715_f64.to_bits()); +} + +#[test] +fn shuffled_input_produces_byte_identical_shards_and_identical_report() { + let dir = TempDirGuard::new("fx1m-shuffle"); + let ts1 = 1_718_100_000_i64; + let ts2 = 1_718_100_060_i64; + let ts3 = 1_718_100_120_i64; + let ts4 = 1_718_100_180_i64; + + let docs = vec![ + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3600, 1.3610, 1.3595, 1.3605, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts1, 1.3600, 1.3610, 1.3595, 1.3605, 10.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3605, 1.3615, 1.3600, 1.3610, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts2, 1.3605, 1.3615, 1.3600, 1.3611, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts3, 1.3610, 1.3620, 1.3605, 1.3615, 0.0), + make_intraday_doc("NVDA.US", ts3, 120.0, 121.0, 119.0, 120.5, 1000.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, ts4, 1.3615, 1.3625, 1.3610, 1.3620, 0.0), + make_malformed_missing_open_doc(EOD_CAD_FOREX_CODE, ts4 + 60), + ]; + // Deterministic permutation. + let perm = [6, 3, 7, 1, 5, 0, 4, 2]; + let shuffled_docs: Vec = perm.iter().map(|&idx| docs[idx].clone()).collect(); + + let in_a = dir.path().join("in_a.bson"); + let in_b = dir.path().join("in_b.bson"); + fs::write(&in_a, concat_docs(&docs)).unwrap(); + fs::write(&in_b, concat_docs(&shuffled_docs)).unwrap(); + + let tiny_opts = BsonStreamOptions { + chunk_capacity_bytes: docs[0].as_bytes().len() * 2, + ..BsonStreamOptions::default() + }; + + let run = |input: PathBuf, out_name: &str| { + let out_dir = dir.path().join(out_name); + let args = make_args(input, out_dir.clone(), 4, tiny_opts); + let report = run_curate_fx_1m(&args).expect("run should succeed"); + let files: Vec<(String, Vec)> = list_dir_names(&out_dir) + .into_iter() + .map(|name| { + let bytes = fs::read(out_dir.join(&name)).unwrap(); + (name, bytes) + }) + .collect(); + (report, files) + }; + + let (mut r_a, f_a) = run(in_a, "out_a"); + let (mut r_b, f_b) = run(in_b, "out_b"); + assert_report_conservation(&r_a); + assert_eq!(f_a, f_b, "shuffled input produced different shard bytes"); + + r_a.elapsed_secs = 0.0; + r_b.elapsed_secs = 0.0; + assert_eq!(r_a, r_b, "shuffled input produced different report counters"); +} + +#[test] +fn shard_file_sets_for_one_and_four_shards_route_usdcad_deterministically() { + let dir = TempDirGuard::new("fx1m-shards"); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write( + &intraday_path, + concat_docs(&[ + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_200_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0), + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_200_060, 1.3705, 1.3715, 1.3700, 1.3710, 0.0), + ]), + ) + .unwrap(); + + // 1 shard: all USDCAD rows land in shard 00. + assert_eq!(shard_for_fx_pair(FX_PAIR_USDCAD, 1), 0); + let out1 = dir.path().join("out-1"); + let rep1 = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out1.clone(), + 1, + BsonStreamOptions::default(), + )) + .unwrap(); + assert_report_conservation(&rep1); + assert_eq!(list_dir_names(&out1), vec!["fx_1m.shard-00.ilp"]); + assert_eq!(rep1.ilp_stats.per_shard_rows, vec![2]); + assert_eq!( + fs::read(out1.join("fx_1m.shard-00.ilp")).unwrap().len(), + rep1.ilp_stats.bytes + ); + + // 4 shards: all USDCAD rows land in shard 01; shards 00, 02, 03 exist and are empty. + assert_eq!(shard_for_fx_pair(FX_PAIR_USDCAD, 4), 1); + let out4 = dir.path().join("out-4"); + let rep4 = run_curate_fx_1m(&make_args( + intraday_path, + out4.clone(), + 4, + BsonStreamOptions::default(), + )) + .unwrap(); + assert_report_conservation(&rep4); + assert_eq!( + list_dir_names(&out4), + vec![ + "fx_1m.shard-00.ilp", + "fx_1m.shard-01.ilp", + "fx_1m.shard-02.ilp", + "fx_1m.shard-03.ilp", + ] + ); + assert_eq!(rep4.ilp_stats.per_shard_rows, vec![0, 2, 0, 0]); + for shard_idx in 0..4usize { + let bytes = fs::read(out4.join(format!("fx_1m.shard-{shard_idx:02}.ilp"))).unwrap(); + if shard_idx == 1 { + assert_eq!(bytes.len(), rep4.ilp_stats.bytes); + assert_eq!(decode_ilp_fx_1m(&bytes).len(), 2); + } else { + assert!(bytes.is_empty(), "shard {shard_idx:02} should be empty"); + } + } +} + +#[test] +fn empty_and_wrong_code_only_inputs_publish_empty_shard_files() { + let dir = TempDirGuard::new("fx1m-empty"); + + // 1. Empty BSON input + let empty_in = dir.path().join("empty.bson"); + fs::write(&empty_in, []).unwrap(); + let out_empty = dir.path().join("out-empty"); + let rep_empty = run_curate_fx_1m(&make_args( + empty_in, + out_empty.clone(), + 3, + BsonStreamOptions::default(), + )) + .expect("empty input should succeed"); + assert_report_conservation(&rep_empty); + assert_eq!(rep_empty.decode.docs_seen, 0); + assert_eq!(rep_empty.curate_stats.bars_in, 0); + assert_eq!(rep_empty.rows_written, 0); + assert_eq!(rep_empty.ilp_stats.bytes, 0); + assert_eq!(rep_empty.ilp_stats.per_shard_rows, vec![0, 0, 0]); + assert_eq!( + list_dir_names(&out_empty), + vec![ + "fx_1m.shard-00.ilp", + "fx_1m.shard-01.ilp", + "fx_1m.shard-02.ilp", + ] + ); + for idx in 0..3usize { + assert!( + fs::read(out_empty.join(format!("fx_1m.shard-{idx:02}.ilp"))) + .unwrap() + .is_empty() + ); + } + + // 2. Valid dump with zero CAD.FOREX rows + let other_in = dir.path().join("other_only.bson"); + fs::write( + &other_in, + concat_docs(&[ + make_intraday_doc("AAPL.US", 1_718_200_000, 195.0, 196.0, 194.5, 195.5, 100.0), + make_intraday_doc("EURUSD.FOREX", 1_718_200_060, 1.08, 1.09, 1.07, 1.085, 0.0), + ]), + ) + .unwrap(); + let out_other = dir.path().join("out-other"); + let rep_other = run_curate_fx_1m(&make_args( + other_in, + out_other.clone(), + 2, + BsonStreamOptions::default(), + )) + .expect("wrong-code-only input should succeed"); + assert_report_conservation(&rep_other); + assert_eq!(rep_other.decode.docs_seen, 2); + assert_eq!(rep_other.decode.rows_decoded, 2); + assert_eq!(rep_other.curate_stats.bars_in, 2); + assert_eq!(rep_other.curate_stats.dropped_wrong_code, 2); + assert_eq!(rep_other.rows_written, 0); + assert_eq!(rep_other.ilp_stats.bytes, 0); + assert_eq!( + list_dir_names(&out_other), + vec!["fx_1m.shard-00.ilp", "fx_1m.shard-01.ilp"] + ); + for idx in 0..2usize { + assert!( + fs::read(out_other.join(format!("fx_1m.shard-{idx:02}.ilp"))) + .unwrap() + .is_empty() + ); + } +} + +#[test] +fn fail_closed_validation_missing_input_truncated_bson_and_sink_errors() { + let dir = TempDirGuard::new("fx1m-fail-closed"); + let valid_doc = + make_intraday_doc(EOD_CAD_FOREX_CODE, 1_718_300_000, 1.3700, 1.3710, 1.3690, 1.3705, 0.0); + let valid_in = dir.path().join("valid.bson"); + fs::write(&valid_in, concat_docs(&[valid_doc.clone()])).unwrap(); + + // 1. shard_count == 0 + { + let out_dir = dir.path().join("out-zero-shards"); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_dir.clone(), + 0, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!(matches!(err, RunCurateFx1mError::ZeroShardCount), "{err:?}"); + assert!(!out_dir.exists()); + } + + // 2. Invalid BsonStreamOptions (chunk_capacity_bytes == 0, max_doc_bytes < MIN_BSON_DOC_BYTES) + { + let out_dir = dir.path().join("out-zero-chunk-cap"); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions { + chunk_capacity_bytes: 0, + ..BsonStreamOptions::default() + }, + )) + .unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::BsonStream { + label: "eod-intraday", + source: BsonStreamError::InvalidChunkCapacity, + .. + } + ), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + { + let out_dir = dir.path().join("out-small-max-doc"); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions { + max_doc_bytes: MIN_BSON_DOC_BYTES - 1, + ..BsonStreamOptions::default() + }, + )) + .unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::BsonStream { + label: "eod-intraday", + source: BsonStreamError::InvalidMaxDocBytes, + .. + } + ), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + + // 3. Invalid IlpWriterOptions (max_batch_bytes == 0, max_batch_rows == 0) + { + let out_dir = dir.path().join("out-zero-batch-bytes"); + let mut args = make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_bytes = 0; + let err = run_curate_fx_1m(&args).unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes)), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + { + let out_dir = dir.path().join("out-zero-batch-rows"); + let mut args = make_args( + valid_in.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_rows = 0; + let err = run_curate_fx_1m(&args).unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows)), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + + // 4. Writer shard_count mismatch in with_readers + { + let mut sink0 = Vec::new(); + let writer = IlpShardedWriter::new(vec![&mut sink0], IlpWriterOptions::default()).unwrap(); + let args = make_args( + valid_in.clone(), + dir.path().join("unused"), + 2, + BsonStreamOptions::default(), + ); + let err = run_curate_fx_1m_with_readers(&args, Cursor::new(b""), writer).unwrap_err(); + assert!( + matches!( + err, + RunCurateFx1mError::ShardCountMismatch { + expected: 2, + actual: 1 + } + ), + "{err:?}" + ); + } + + // 5. Missing input file fails before creating out_dir + { + let out_dir = dir.path().join("out-missing-input"); + let err = run_curate_fx_1m(&make_args( + dir.path().join("does-not-exist.bson"), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::OpenInput { label: "eod-intraday", .. }), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(!out_dir.exists()); + } + + // 6. out_dir exists as a regular file + { + let out_file = dir.path().join("out-is-file"); + fs::write(&out_file, b"not a dir").unwrap(); + let err = run_curate_fx_1m(&make_args( + valid_in.clone(), + out_file.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!(matches!(err, RunCurateFx1mError::InvalidOutDir { .. }), "{err:?}"); + assert_eq!(fs::read(&out_file).unwrap(), b"not a dir"); + } + + // 7. Truncated BSON mid-document after a valid CAD.FOREX bar + { + let doc2 = make_intraday_doc( + EOD_CAD_FOREX_CODE, + 1_718_300_060, + 1.3705, + 1.3715, + 1.3700, + 1.3710, + 0.0, + ); + let mut trunc_bytes = concat_docs(&[valid_doc.clone(), doc2]); + trunc_bytes.truncate(trunc_bytes.len() - 7); + let trunc_in = dir.path().join("truncated.bson"); + fs::write(&trunc_in, &trunc_bytes).unwrap(); + + let out_dir = dir.path().join("out-trunc"); + fs::create_dir_all(&out_dir).unwrap(); + let keep_path = out_dir.join("keep.txt"); + fs::write(&keep_path, b"keep-me").unwrap(); + + let err = run_curate_fx_1m(&make_args( + trunc_in, + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::BsonStream { label: "eod-intraday", .. }), + "{err:?}" + ); + assert!(err.source().is_some()); + assert_eq!(list_dir_names(&out_dir), vec!["keep.txt"]); + assert_eq!(fs::read(&keep_path).unwrap(), b"keep-me"); + } + + // 8. Sink failure on write -> Ilp(Io), no final or temp files left + { + let out_dir = dir.path().join("out-write-fail"); + let mut args = make_args( + valid_in.clone(), + out_dir.clone(), + 1, + BsonStreamOptions::default(), + ); + args.ilp_options.max_batch_rows = 1; + let err = run_curate_fx_1m_to_dir_with_hooks( + &args, + Cursor::new(concat_docs(&[valid_doc.clone()])), + |_idx, _file| FailingWriteSink { + fail_on_write: true, + fail_on_flush: false, + }, + |_idx, _path| {}, + ) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::Io { .. })), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } + + // 9. Sink failure on flush during finish() -> Ilp(Io), no final or temp files left + { + let out_dir = dir.path().join("out-flush-fail"); + let args = make_args( + valid_in, + out_dir.clone(), + 1, + BsonStreamOptions::default(), + ); + let err = run_curate_fx_1m_to_dir_with_hooks( + &args, + Cursor::new(concat_docs(&[valid_doc])), + |_idx, _file| FailingWriteSink { + fail_on_write: false, + fail_on_flush: true, + }, + |_idx, _path| {}, + ) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::Ilp(IlpWriterError::Io { .. })), + "{err:?}" + ); + assert!(err.source().is_some()); + assert!(list_dir_names(&out_dir).is_empty()); + } +} + +#[test] +fn fail_closed_preexisting_shards_coexistence_and_post_preflight_rollback() { + let dir = TempDirGuard::new("fx1m-no-overwrite"); + let intraday_bytes = concat_docs(&[make_intraday_doc( + EOD_CAD_FOREX_CODE, + 1_718_400_000, + 1.3700, + 1.3710, + 1.3690, + 1.3705, + 0.0, + )]); + let intraday_path = dir.path().join("eodIntraday1M.bson"); + fs::write(&intraday_path, &intraday_bytes).unwrap(); + + // Case A: pre-existing fx_1m.shard-07.ilp with shard_count = 2 -> rejected, bytes preserved. + { + let out_dir = dir.path().join("out-stale-07"); + fs::create_dir_all(&out_dir).unwrap(); + let sentinel = b"stale-fx-shard-07"; + let stale_path = out_dir.join("fx_1m.shard-07.ilp"); + fs::write(&stale_path, sentinel).unwrap(); + + let err = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &stale_path), + "{err:?}" + ); + assert_eq!(fs::read(&stale_path).unwrap(), sentinel); + assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-07.ilp"]); + } + + // Case B: pre-existing digit-only name of another width (fx_1m.shard-3.ilp) -> rejected. + { + let out_dir = dir.path().join("out-stale-width1"); + fs::create_dir_all(&out_dir).unwrap(); + let sentinel = b"stale-fx-shard-width1"; + let stale_path = out_dir.join("fx_1m.shard-3.ilp"); + fs::write(&stale_path, sentinel).unwrap(); + + let err = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .unwrap_err(); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &stale_path), + "{err:?}" + ); + assert_eq!(fs::read(&stale_path).unwrap(), sentinel); + assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-3.ilp"]); + } + + // Case C: a pre-existing bars_1m shard in out_dir coexists untouched. + { + let out_dir = dir.path().join("out-coexist-bars"); + fs::create_dir_all(&out_dir).unwrap(); + let bars_sentinel = b"bars-1m-shard-00-untouched"; + let bars_path = out_dir.join("bars_1m.shard-00.ilp"); + fs::write(&bars_path, bars_sentinel).unwrap(); + + let rep = run_curate_fx_1m(&make_args( + intraday_path.clone(), + out_dir.clone(), + 2, + BsonStreamOptions::default(), + )) + .expect("bars_1m shard should coexist untouched"); + assert_report_conservation(&rep); + assert_eq!(rep.rows_written, 1); + assert_eq!(fs::read(&bars_path).unwrap(), bars_sentinel); + assert_eq!( + list_dir_names(&out_dir), + vec![ + "bars_1m.shard-00.ilp", + "fx_1m.shard-00.ilp", + "fx_1m.shard-01.ilp", + ] + ); + } + + // Case D: post-preflight collision on shard 01 after shard 00 is linked. + // Shard 00 must be rolled back, staging files removed, external shard 01 untouched. + { + let out_dir = dir.path().join("out-race"); + let args = make_args( + intraday_path, + out_dir.clone(), + 3, + BsonStreamOptions::default(), + ); + let race_sentinel = b"concurrent-writer-fx-shard-01"; + let err = run_curate_fx_1m_to_dir_with_hooks( + &args, + Cursor::new(&intraday_bytes), + |_idx, file| SyncedBufFile::new(file), + |shard_idx, final_path| { + if shard_idx == 1 { + fs::write(final_path, race_sentinel).expect("inject concurrent final shard"); + } + }, + ) + .unwrap_err(); + let expected_race_path = out_dir.join("fx_1m.shard-01.ilp"); + assert!( + matches!(err, RunCurateFx1mError::OutputFileExists { ref path } if path == &expected_race_path), + "{err:?}" + ); + assert_eq!(fs::read(&expected_race_path).unwrap(), race_sentinel); + assert_eq!(list_dir_names(&out_dir), vec!["fx_1m.shard-01.ilp"]); + } +} + +#[test] +fn format_curate_fx_1m_report_includes_every_counter_and_isolates_timing() { + let report = CurateFx1mRunReport { + decode: BsonEodIntradayDecodeStats { + docs_seen: 100, + rows_decoded: 90, + rejected_missing_field: 1, + rejected_empty_field: 2, + rejected_wrong_type: 3, + rejected_invalid_timestamp: 1, + rejected_invalid_number: 2, + rejected_corrupt_document: 1, + }, + curate_stats: CurateFx1mStats { + bars_in: 90, + rows_out: 50, + dropped_wrong_code: 20, + dropped_negative_ts: 1, + dropped_invalid_ohlc: 2, + dropped_high_below_bound: 3, + dropped_low_above_bound: 4, + duplicate_collapsed: 5, + duplicate_conflict_dropped: 5, + }, + rows_written: 50, + ilp_stats: IlpWriteStats { + rows: 50, + bytes: 4096, + flushes: 2, + per_shard_rows: vec![0, 50, 0, 0], + }, + shard_count: 4, + elapsed_secs: 0.123456, + }; + assert_report_conservation(&report); + + let formatted = format_curate_fx_1m_report(&report); + let lines: Vec<&str> = formatted.lines().collect(); + assert_eq!(lines.len(), 5, "expected 5 report lines, got:\n{formatted}"); + assert_eq!(lines[0], "curate-etl curate-fx-1m"); + assert!( + lines[1].contains("docs_seen=100") + && lines[1].contains("rows_decoded=90") + && lines[1].contains("rejected=10") + && lines[1].contains("missing=1") + && lines[1].contains("empty=2") + && lines[1].contains("wrong_type=3") + && lines[1].contains("invalid_ts=1") + && lines[1].contains("invalid_num=2") + && lines[1].contains("corrupt=1"), + "missing decode counters in line 1: {}", + lines[1] + ); + assert!( + lines[2].contains("bars_in=90") + && lines[2].contains("rows_out=50") + && lines[2].contains("wrong_code=20") + && lines[2].contains("negative_ts=1") + && lines[2].contains("invalid_ohlc=2") + && lines[2].contains("high_below_bound=3") + && lines[2].contains("low_above_bound=4") + && lines[2].contains("dup_collapsed=5") + && lines[2].contains("dup_conflict_dropped=5"), + "missing curate counters in line 2: {}", + lines[2] + ); + assert!( + lines[3].contains("shards=4") + && lines[3].contains("rows_written=50") + && lines[3].contains("ilp_rows=50") + && lines[3].contains("bytes=4096") + && lines[3].contains("flushes=2") + && lines[3].contains("per_shard_rows=00=0,01=50,02=0,03=0"), + "missing ilp counters in line 3: {}", + lines[3] + ); + assert_eq!(lines[4].trim(), "timing: elapsed_secs=0.123456"); + // Ensure elapsed_secs appears only on the timing line. + for line in &lines[..4] { + assert!(!line.contains("elapsed_secs"), "timing leaked into: {line}"); + } +}