From 95875dc87da6867709e7d37313cd27818f86cfe9 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 00:39:51 -0500 Subject: [PATCH] =?UTF-8?q?T-153:=20M2.3k=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20pure=20`fx=5F1m`=20curation=20stage=20(`CAD.FOREX`=20`eodIn?= =?UTF-8?q?traday1M`=20=E2=86=92=20validated/deduped=20`Fx1mRow`=20?= =?UTF-8?q?=E2=86=92=20`IlpShardedWriter`)=20with=20tests=20(full=20pipeli?= =?UTF-8?q?ne;=20no=20new=20crates,=20no=20CLI/bench=20changes,=20no=20liv?= =?UTF-8?q?e=20Mongo/QuestDB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/curate_fx_1m.rs | 327 ++++++++++++ tools/curate-etl/src/curate_fx_1m_tests.rs | 560 +++++++++++++++++++++ tools/curate-etl/src/lib.rs | 7 + 3 files changed, 894 insertions(+) create mode 100644 tools/curate-etl/src/curate_fx_1m.rs create mode 100644 tools/curate-etl/src/curate_fx_1m_tests.rs diff --git a/tools/curate-etl/src/curate_fx_1m.rs b/tools/curate-etl/src/curate_fx_1m.rs new file mode 100644 index 00000000..0bdcc390 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_1m.rs @@ -0,0 +1,327 @@ +//! Pure, in-memory `fx_1m` curation stage for EODHD `CAD.FOREX` 1-minute FX bars (`M2.3k`), +//! joining [`crate::bson_eod_intraday::RawEodIntradayBar`], +//! [`crate::bson_stream::decode_eod_intraday_stream`], and [`crate::ilp::IlpShardedWriter`]. +//! +//! # Contract & Point-in-Time Rules +//! - **Source selection:** accepts only rows whose `eod_search_code` matches +//! [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`) verbatim. Any other code is dropped and counted in +//! [`CurateFx1mStats::dropped_wrong_code`] without erroring. +//! - **No split un-adjustment, listing mapping, or session tagging:** FX trades ~24h and is not +//! subject to equity splits or `provider_mapping` ranges. Every valid `CAD.FOREX` bar is kept +//! with its UTC microsecond bar-start `ts` unchanged (preserving the source clock without +//! implying the bar's close was observable at bar start). +//! - **Rate direction & bitwise preservation:** OHLC values pass through bit-identical in CAD per +//! 1 USD (matching `fx_1d`); `volume` is ignored at the curation layer. +//! - **Canonical labels:** emits `pair = FX_PAIR_USDCAD` (`"USDCAD"`, shared with `fx_1d` so +//! daily and intraday FX tables join on the same label) and `source = FX_1M_SOURCE_EOD` +//! (`"eod"`, fitting QuestDB `SYMBOL CAPACITY 8`). +//! - **Validation precedence:** bad single bars never panic or abort the stage; each bar is +//! classified once in strict priority order: +//! 1. `dropped_wrong_code` (`eod_search_code != "CAD.FOREX"`) +//! 2. `dropped_negative_ts` (`ts < 0`) +//! 3. `dropped_invalid_ohlc` (any of `open`, `high`, `low`, `close` non-finite or `<= 0.0`) +//! 4. `dropped_high_below_bound` (`high < max(open, close, low)`) +//! 5. `dropped_low_above_bound` (`low > min(open, close)`) +//! - **Ordering & deduplication:** surviving rows are sorted ascending by `ts` and compacted in +//! place per timestamp group using `f64::to_bits` equality across all four OHLC fields: +//! bitwise-identical groups of size `n` emit one row (`duplicate_collapsed += n - 1`), while +//! conflicting groups emit zero rows (`duplicate_conflict_dropped += n`). +//! - **Writer lifecycle:** [`curate_and_write_fx_1m`] and [`curate_and_write_fx_1m_from_bson`] +//! stream sorted [`Fx1mRow`]s into a caller-owned [`IlpShardedWriter`] via +//! [`IlpShardedWriter::write_fx_1m`] without calling [`IlpShardedWriter::finish`], allowing +//! multiple chunks to share one writer. +//! +//! # Memory, Chunking & BSON Validation Boundary +//! - **In-memory sort & per-call deduplication:** sorting buffers accepted `CAD.FOREX` rows for a +//! single call in memory, and deduplication applies within that call only. Callers splitting +//! large inputs across calls must keep all copies of a timestamp in the same call and submit +//! chunks in chronological order when global ordering is required. +//! - **BSON validation boundary:** [`curate_and_write_fx_1m_from_bson`] decodes via +//! [`decode_eod_intraday_stream`], which validates non-empty `eodSearchCode`, non-negative +//! integral `timestamp`, finite positive OHLC, and finite non-negative `volume` before invoking +//! the curation accumulator. Document-level decode rejects are accounted in +//! [`BsonEodIntradayDecodeStats`] (so `decode_stats.rows_decoded == write_report.curate_stats.bars_in`), +//! while direct in-memory calls to [`build_fx_1m`] / [`curate_and_write_fx_1m`] exercise the full +//! builder validation rules and ignore `volume`. + +use std::error::Error; +use std::fmt; +use std::io::{self, Write}; + +use crate::bson_eod_intraday::{BsonEodIntradayDecodeStats, RawEodIntradayBar}; +use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; +use crate::fx::FX_PAIR_USDCAD; +use crate::ilp::{Fx1mRow, IlpShardedWriter, IlpWriterError}; +use crate::run_curate_fx::EOD_CAD_FOREX_CODE; + +/// Canonical provenance label written to [`Fx1mRow::source`] for EODHD `eodIntraday1M` FX bars +/// (`SYMBOL CAPACITY 8`). +pub const FX_1M_SOURCE_EOD: &str = "eod"; + +/// Accounting summary produced alongside [`CurateFx1mOutput::rows`]. +/// +/// Conservation invariant: +/// `bars_in == rows_out + dropped_wrong_code + dropped_negative_ts + dropped_invalid_ohlc + dropped_high_below_bound + dropped_low_above_bound + duplicate_collapsed + duplicate_conflict_dropped` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mStats { + pub bars_in: usize, + pub rows_out: usize, + pub dropped_wrong_code: usize, + pub dropped_negative_ts: usize, + pub dropped_invalid_ohlc: usize, + pub dropped_high_below_bound: usize, + pub dropped_low_above_bound: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, +} + +/// Output of [`build_fx_1m`]: curated `fx_1m` rows sorted and unique by `ts`, plus exact +/// accounting statistics. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1mOutput { + pub rows: Vec>, + pub stats: CurateFx1mStats, +} + +/// Summary returned by [`curate_and_write_fx_1m`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mWriteReport { + pub curate_stats: CurateFx1mStats, + /// Number of curated rows accepted by [`IlpShardedWriter::write_fx_1m`] in this call. + pub rows_written: usize, +} + +/// Combined decode and write summary returned by [`curate_and_write_fx_1m_from_bson`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mBsonReport { + pub decode_stats: BsonEodIntradayDecodeStats, + pub write_report: CurateFx1mWriteReport, +} + +/// Typed error returned by [`curate_and_write_fx_1m_from_bson`]. +#[derive(Debug)] +pub enum CurateFx1mBsonError { + Stream(BsonStreamError), + Write(IlpWriterError), +} + +impl fmt::Display for CurateFx1mBsonError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "fx_1m BSON stream failed: {err}"), + Self::Write(err) => write!(f, "fx_1m ILP write failed: {err}"), + } + } +} + +impl Error for CurateFx1mBsonError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Write(err) => Some(err), + } + } +} + +impl From for CurateFx1mBsonError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for CurateFx1mBsonError { + fn from(err: IlpWriterError) -> Self { + Self::Write(err) + } +} + +#[inline] +fn is_valid_rate(rate: f64) -> bool { + rate.is_finite() && rate > 0.0 +} + +#[inline] +fn fx_1m_ohlc_bit_eq(a: &Fx1mRow<'_>, b: &Fx1mRow<'_>) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() +} + +#[derive(Default)] +struct Fx1mAccumulator { + rows: Vec>, + stats: CurateFx1mStats, +} + +impl Fx1mAccumulator { + #[inline] + fn push(&mut self, bar: RawEodIntradayBar<'_>) { + self.stats.bars_in += 1; + + if bar.eod_search_code != EOD_CAD_FOREX_CODE { + self.stats.dropped_wrong_code += 1; + return; + } + if bar.ts < 0 { + self.stats.dropped_negative_ts += 1; + return; + } + if !is_valid_rate(bar.open) + || !is_valid_rate(bar.high) + || !is_valid_rate(bar.low) + || !is_valid_rate(bar.close) + { + self.stats.dropped_invalid_ohlc += 1; + return; + } + if bar.high < bar.open || bar.high < bar.close || bar.high < bar.low { + self.stats.dropped_high_below_bound += 1; + return; + } + if bar.low > bar.open || bar.low > bar.close { + self.stats.dropped_low_above_bound += 1; + return; + } + + self.rows.push(Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: bar.ts, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + source: FX_1M_SOURCE_EOD, + }); + } + + fn finish(mut self) -> CurateFx1mOutput { + self.rows.sort_unstable_by_key(|row| row.ts); + + let len = self.rows.len(); + let mut write_idx = 0usize; + let mut read_idx = 0usize; + + while read_idx < len { + let ts = self.rows[read_idx].ts; + let mut group_end = read_idx + 1; + while group_end < len && self.rows[group_end].ts == ts { + group_end += 1; + } + let group_len = group_end - read_idx; + let first = self.rows[read_idx]; + let all_identical = self.rows[read_idx + 1..group_end] + .iter() + .all(|other| fx_1m_ohlc_bit_eq(&first, other)); + + if all_identical { + self.stats.duplicate_collapsed += group_len - 1; + if write_idx != read_idx { + self.rows[write_idx] = first; + } + write_idx += 1; + } else { + self.stats.duplicate_conflict_dropped += group_len; + } + + read_idx = group_end; + } + + self.rows.truncate(write_idx); + self.stats.rows_out = self.rows.len(); + + CurateFx1mOutput { + rows: self.rows, + stats: self.stats, + } + } +} + +fn write_curated_fx_1m( + curated: CurateFx1mOutput, + writer: &mut IlpShardedWriter, +) -> Result { + let mut rows_written = 0usize; + for row in &curated.rows { + writer.write_fx_1m(row)?; + rows_written += 1; + } + + Ok(CurateFx1mWriteReport { + curate_stats: curated.stats, + rows_written, + }) +} + +/// Pure `eodIntraday1M` (`CAD.FOREX`) -> `fx_1m` curation builder. +/// +/// Filters to exact [`EOD_CAD_FOREX_CODE`] rows, validates timestamps and OHLC in strict priority +/// order (ignoring `volume`), sorts ascending by `ts`, and deduplicates same-`ts` groups using +/// bitwise OHLC equality. Valid OHLC and UTC microsecond `ts` pass through unchanged, stamped +/// with `pair = FX_PAIR_USDCAD` and `source = FX_1M_SOURCE_EOD`. +pub fn build_fx_1m<'a, B>(bars: B) -> CurateFx1mOutput +where + B: IntoIterator>, +{ + let mut acc = Fx1mAccumulator::default(); + for bar in bars { + acc.push(bar); + } + acc.finish() +} + +/// Runs [`build_fx_1m`] and streams every curated row in ascending `ts` order into the +/// caller-owned [`IlpShardedWriter`] via [`IlpShardedWriter::write_fx_1m`]. +/// +/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple +/// chunks through a single writer before flushing and collecting aggregate +/// [`crate::ilp::IlpWriteStats`]. +pub fn curate_and_write_fx_1m<'a, W, B>( + bars: B, + writer: &mut IlpShardedWriter, +) -> Result +where + W: Write + Send, + B: IntoIterator>, +{ + let curated = build_fx_1m(bars); + write_curated_fx_1m(curated, writer) +} + +/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], +/// feeds every decoded [`RawEodIntradayBar`] directly into the `fx_1m` curation accumulator, and +/// streams sorted curated rows into the caller-owned [`IlpShardedWriter`]. +/// +/// - Per-document semantic decode errors are counted and skipped in +/// [`BsonEodIntradayDecodeStats`]; fatal stream framing or I/O errors abort before any row from +/// this call is written to `writer`. +/// - Intentionally does **not** call [`IlpShardedWriter::finish`]. +pub fn curate_and_write_fx_1m_from_bson( + reader: R, + options: BsonStreamOptions, + writer: &mut IlpShardedWriter, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let mut acc = Fx1mAccumulator::default(); + let decode_stats = decode_eod_intraday_stream( + reader, + options, + |raw| acc.push(raw), + |_offset, _err| {}, + )?; + + let curated = acc.finish(); + let write_report = write_curated_fx_1m(curated, writer)?; + + Ok(CurateFx1mBsonReport { + decode_stats, + write_report, + }) +} + +#[cfg(test)] +#[path = "curate_fx_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_fx_1m_tests.rs b/tools/curate-etl/src/curate_fx_1m_tests.rs new file mode 100644 index 00000000..8a5622d3 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_1m_tests.rs @@ -0,0 +1,560 @@ +use std::error::Error; +use std::io::{self, Cursor, Write}; + +use bson::raw::{cstr, RawDocumentBuf}; + +use super::*; +use crate::ilp::{encode_fx_1m, shard_for_fx_pair, IlpWriterOptions}; + +fn raw_bar<'a>( + code: &'a str, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawEodIntradayBar<'a> { + RawEodIntradayBar { + eod_search_code: code, + ts, + open, + high, + low, + close, + volume, + } +} + +fn make_eod_intraday_bson_doc( + code: &str, + ts_seconds: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), ts_seconds); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn assert_conservation_and_order(out: &CurateFx1mOutput) { + let s = &out.stats; + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.bars_in, + s.rows_out + + s.dropped_wrong_code + + s.dropped_negative_ts + + s.dropped_invalid_ohlc + + s.dropped_high_below_bound + + s.dropped_low_above_bound + + s.duplicate_collapsed + + s.duplicate_conflict_dropped, + "curate_fx_1m conservation invariant failed: {s:?}" + ); + + for pair in out.rows.windows(2) { + assert!( + pair[0].ts < pair[1].ts, + "rows not strictly ascending by ts: {} >= {}", + pair[0].ts, + pair[1].ts + ); + } + + for row in &out.rows { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + } +} + +struct FailingSink; + +impl Write for FailingSink { + fn write(&mut self, _buf: &[u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "sink failure")) + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "flush failure")) + } +} + +#[test] +fn empty_input_returns_empty_rows_and_zeroed_stats() { + let out = build_fx_1m(std::iter::empty()); + assert!(out.rows.is_empty()); + assert_eq!(out.stats, CurateFx1mStats::default()); + assert_conservation_and_order(&out); +} + +#[test] +fn valid_out_of_order_bars_sort_preserve_ohlc_bits_keep_off_session_and_ignore_volume() { + // 2024-06-09 22:15:00 UTC (Sunday evening FX open, off equity RTH). + let ts_sunday_utc = 1_717_971_300_000_000_i64; + // 2024-06-10 03:00:00 UTC (overnight). + let ts_overnight_utc = 1_717_988_400_000_000_i64; + // Exact epoch start ts = 0 must be accepted. + let ts_zero = 0_i64; + + let b_late = raw_bar( + EOD_CAD_FOREX_CODE, + ts_overnight_utc, + 1.37654321, + 1.37712345, + 1.37611111, + 1.37689012, + -99.0, // invalid volume ignored by builder + ); + let b_zero = raw_bar( + EOD_CAD_FOREX_CODE, + ts_zero, + 1.0725, + 1.0731, + 1.0720, + 1.0728, + f64::NAN, // NaN volume ignored by builder + ); + let b_mid = raw_bar( + EOD_CAD_FOREX_CODE, + ts_sunday_utc, + 1.3750, + 1.3755, + 1.3745, + 1.3752, + f64::INFINITY, // inf volume ignored by builder + ); + // Exact-match failures (case mismatch, trailing space, different ticker) -> dropped, not errored. + let b_lowercase = raw_bar("cad.forex", ts_sunday_utc + 60_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); + let b_padded = raw_bar("CAD.FOREX ", ts_sunday_utc + 120_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); + let b_other = raw_bar("AAPL.US", ts_sunday_utc + 180_000_000, 195.0, 196.0, 194.5, 195.5, 1000.0); + + let out = build_fx_1m([b_late, b_lowercase, b_zero, b_other, b_mid, b_padded]); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.bars_in, 6); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.dropped_wrong_code, 3); + assert_eq!(out.stats.dropped_negative_ts, 0); + assert_eq!(out.stats.dropped_invalid_ohlc, 0); + assert_eq!(out.stats.dropped_high_below_bound, 0); + assert_eq!(out.stats.dropped_low_above_bound, 0); + assert_eq!(out.stats.duplicate_collapsed, 0); + assert_eq!(out.stats.duplicate_conflict_dropped, 0); + + let expected_inputs = [b_zero, b_mid, b_late]; + for (row, src) in out.rows.iter().zip(expected_inputs) { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + assert_eq!(row.ts, src.ts); + assert_eq!(row.open.to_bits(), src.open.to_bits()); + assert_eq!(row.high.to_bits(), src.high.to_bits()); + assert_eq!(row.low.to_bits(), src.low.to_bits()); + assert_eq!(row.close.to_bits(), src.close.to_bits()); + } +} + +#[test] +fn every_reject_reason_counted_separately_with_strict_precedence() { + let base_ts = 1_718_000_000_000_000_i64; + let bars = vec![ + // 1. Wrong code (also has negative ts and NaN OHLC to verify wrong_code precedence). + raw_bar("USD.FOREX", -1, f64::NAN, 1.0, 2.0, 0.0, 0.0), + // 2. Negative timestamps (second also has NaN OHLC to verify negative_ts precedence). + raw_bar(EOD_CAD_FOREX_CODE, -1, 1.35, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, i64::MIN, f64::NAN, 1.36, 1.34, 1.35, 0.0), + // 3. Invalid OHLC: NaN, +inf, -inf, +0.0, -0.0, negative price. + raw_bar(EOD_CAD_FOREX_CODE, base_ts, f64::NAN, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 1, 1.35, f64::INFINITY, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 2, 1.35, 1.36, f64::NEG_INFINITY, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 3, 1.35, 1.36, 1.34, 0.0, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 4, -0.0, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 5, 1.35, 1.36, -1.34, 1.35, 0.0), + // 4. high < max(open, close, low): + // - high < open + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 6, 1.37, 1.36, 1.34, 1.35, 0.0), + // - high < close + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 7, 1.35, 1.36, 1.34, 1.37, 0.0), + // - high < low (while high >= open/close is impossible if low > open/close, test open=close=1.35, high=1.35, low=1.36) + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 8, 1.35, 1.35, 1.36, 1.35, 0.0), + // - overlapping high < open AND low > close -> pinned to dropped_high_below_bound + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 9, 1.38, 1.36, 1.37, 1.35, 0.0), + // 5. low > min(open, close) (with high >= max(open, close, low)): + // - low > open + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 10, 1.33, 1.36, 1.34, 1.35, 0.0), + // - low > close + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 11, 1.35, 1.36, 1.34, 1.33, 0.0), + // Valid bar. + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 12, 1.35, 1.36, 1.34, 1.355, 0.0), + ]; + + let out = build_fx_1m(bars); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.bars_in, 16); + assert_eq!(out.stats.dropped_wrong_code, 1); + assert_eq!(out.stats.dropped_negative_ts, 2); + assert_eq!(out.stats.dropped_invalid_ohlc, 6); + assert_eq!(out.stats.dropped_high_below_bound, 4); + assert_eq!(out.stats.dropped_low_above_bound, 2); + assert_eq!(out.stats.duplicate_collapsed, 0); + assert_eq!(out.stats.duplicate_conflict_dropped, 0); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.rows[0].ts, base_ts + 12); +} + +#[test] +fn dedup_collapses_identical_ohlc_drops_conflicting_group_and_is_permutation_invariant() { + let ts_identical = 1_718_000_060_000_000_i64; + let ts_conflict = 1_718_000_120_000_000_i64; + let ts_valid_plus_bad = 1_718_000_180_000_000_i64; + + // Group 1: three bitwise-identical OHLC bars with differing volumes -> collapse to 1. + let id1 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 0.0); + let id2 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 42.0); + let id3 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, f64::NAN); + + // Group 2: two identical rows + one conflicting close -> drop all 3. + let cf1 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); + let cf2 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); + let cf3 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3626, 1.0); + + // Group 3: one valid row + one invalid row at same ts -> invalid rejected early, valid survives. + let ok = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, 1.3630, 1.3640, 1.3625, 1.3635, 0.0); + let bad = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, f64::NAN, 1.3640, 1.3625, 1.3635, 0.0); + + let perm_a = [id1, id2, id3, cf1, cf2, cf3, ok, bad]; + let perm_b = [cf3, bad, id3, cf1, ok, id1, cf2, id2]; + let perm_c = [ok, cf2, id2, cf3, id1, bad, cf1, id3]; + + let out_a = build_fx_1m(perm_a); + let out_b = build_fx_1m(perm_b); + let out_c = build_fx_1m(perm_c); + + assert_conservation_and_order(&out_a); + assert_conservation_and_order(&out_b); + assert_conservation_and_order(&out_c); + assert_eq!(out_a, out_b); + assert_eq!(out_a, out_c); + + assert_eq!(out_a.stats.bars_in, 8); + assert_eq!(out_a.stats.dropped_invalid_ohlc, 1); + assert_eq!(out_a.stats.duplicate_collapsed, 2); + assert_eq!(out_a.stats.duplicate_conflict_dropped, 3); + assert_eq!(out_a.stats.rows_out, 2); + + assert_eq!(out_a.rows[0].ts, ts_identical); + assert_eq!(out_a.rows[0].close.to_bits(), 1.3615_f64.to_bits()); + assert_eq!(out_a.rows[1].ts, ts_valid_plus_bad); + assert_eq!(out_a.rows[1].close.to_bits(), 1.3635_f64.to_bits()); +} + +#[test] +fn writer_streams_two_chunks_through_one_writer_matches_encode_fx_1m_and_routes_one_shard() { + let ts1 = 1_718_000_000_000_000_i64; + let ts2 = 1_718_000_060_000_000_i64; + let ts3 = 1_718_000_120_000_000_i64; + + // Chunk 1 given out of order plus an unrelated ticker. + let chunk1 = [ + raw_bar(EOD_CAD_FOREX_CODE, ts2, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), + raw_bar("EUR.FOREX", ts1, 1.0800, 1.0810, 1.0790, 1.0805, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), + ]; + // Chunk 2 chronologically after chunk 1. + let chunk2 = [raw_bar( + EOD_CAD_FOREX_CODE, + ts3, + 1.3715, + 1.3725, + 1.3710, + 1.3722, + 0.0, + )]; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let mut s2 = Vec::new(); + let mut s3 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1, &mut s2, &mut s3], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = curate_and_write_fx_1m(chunk1, &mut writer).unwrap(); + // Writer remains open (finish was NOT called) so chunk 2 streams into the same writer. + let rep2 = curate_and_write_fx_1m(chunk2, &mut writer).unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + assert_eq!(rep1.curate_stats.bars_in, 3); + assert_eq!(rep1.curate_stats.dropped_wrong_code, 1); + assert_eq!(rep1.curate_stats.rows_out, 2); + assert_eq!(rep1.rows_written, 2); + + assert_eq!(rep2.curate_stats.bars_in, 1); + assert_eq!(rep2.curate_stats.rows_out, 1); + assert_eq!(rep2.rows_written, 1); + + assert_eq!(ilp_stats.rows, rep1.rows_written + rep2.rows_written); + assert_eq!(ilp_stats.rows, 3); + + let expected_rows = [ + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts1, + open: 1.3700, + high: 1.3710, + low: 1.3695, + close: 1.3705, + source: FX_1M_SOURCE_EOD, + }, + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts2, + open: 1.3710, + high: 1.3720, + low: 1.3705, + close: 1.3715, + source: FX_1M_SOURCE_EOD, + }, + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts3, + open: 1.3715, + high: 1.3725, + low: 1.3710, + close: 1.3722, + source: FX_1M_SOURCE_EOD, + }, + ]; + let mut expected_bytes = Vec::new(); + for row in &expected_rows { + encode_fx_1m(&mut expected_bytes, row).unwrap(); + } + + let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 4); + let actual_shards = [&s0, &s1, &s2, &s3]; + for (idx, shard_bytes) in actual_shards.iter().enumerate() { + if idx == target_shard { + assert_eq!(*shard_bytes, &expected_bytes, "target shard ILP mismatch"); + } else { + assert!( + shard_bytes.is_empty(), + "non-target shard {idx} should be empty" + ); + } + } + assert_eq!(ilp_stats.per_shard_rows[target_shard], 3); +} + +#[test] +fn bson_stream_handles_mixed_docs_matches_builder_and_supports_writer_reuse() { + let ts1_sec = 1_718_000_000_i64; + let ts2_sec = 1_718_000_060_i64; + let ts3_sec = 1_718_000_120_i64; + + // Out-of-order CAD.FOREX docs + an identical duplicate + a decodable other code + a malformed doc. + let doc_late = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts2_sec, 1.3720, 1.3730, 1.3715, 1.3725, 0.0); + let doc_other = + make_eod_intraday_bson_doc("AAPL.US", ts1_sec, 195.0, 196.0, 194.5, 195.5, 1200.0); + // Correctly framed BSON document missing required field `close`. + let mut doc_missing_close = RawDocumentBuf::new(); + doc_missing_close.append(cstr!("eodSearchCode"), EOD_CAD_FOREX_CODE); + doc_missing_close.append(cstr!("timestamp"), ts1_sec); + doc_missing_close.append(cstr!("open"), 1.3700_f64); + doc_missing_close.append(cstr!("high"), 1.3710_f64); + doc_missing_close.append(cstr!("low"), 1.3695_f64); + doc_missing_close.append(cstr!("volume"), 0.0_f64); + + let doc_early = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 0.0); + let doc_early_dup = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 5.0); + + let mut chunk1_bytes = Vec::new(); + chunk1_bytes.extend_from_slice(doc_late.as_bytes()); + chunk1_bytes.extend_from_slice(doc_other.as_bytes()); + chunk1_bytes.extend_from_slice(doc_missing_close.as_bytes()); + chunk1_bytes.extend_from_slice(doc_early.as_bytes()); + chunk1_bytes.extend_from_slice(doc_early_dup.as_bytes()); + + let doc_chunk2 = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts3_sec, 1.3725, 1.3735, 1.3720, 1.3731, 0.0); + let chunk2_bytes = doc_chunk2.as_bytes().to_vec(); + + // Small chunk capacity forces multi-chunk framing across documents. + let stream_opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = + curate_and_write_fx_1m_from_bson(Cursor::new(&chunk1_bytes), stream_opts, &mut writer) + .unwrap(); + let rep2 = + curate_and_write_fx_1m_from_bson(Cursor::new(&chunk2_bytes), stream_opts, &mut writer) + .unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + // Decode accounting: 5 docs seen = 4 decoded + 1 missing_field reject. + assert_eq!(rep1.decode_stats.docs_seen, 5); + assert_eq!(rep1.decode_stats.rows_decoded, 4); + assert_eq!(rep1.decode_stats.rejected_missing_field, 1); + assert_eq!( + rep1.decode_stats.docs_seen, + rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() + ); + + // Builder input equals rows_decoded. + assert_eq!( + rep1.write_report.curate_stats.bars_in, + rep1.decode_stats.rows_decoded + ); + assert_eq!(rep1.write_report.curate_stats.dropped_wrong_code, 1); + assert_eq!(rep1.write_report.curate_stats.duplicate_collapsed, 1); + assert_eq!(rep1.write_report.curate_stats.rows_out, 2); + assert_eq!(rep1.write_report.rows_written, 2); + + // Compare chunk 1 curation stats directly against `build_fx_1m` on the same decoded inputs. + let direct_expected = build_fx_1m([ + raw_bar(EOD_CAD_FOREX_CODE, ts2_sec * 1_000_000, 1.3720, 1.3730, 1.3715, 1.3725, 0.0), + raw_bar("AAPL.US", ts1_sec * 1_000_000, 195.0, 196.0, 194.5, 195.5, 1200.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 5.0), + ]); + assert_eq!(rep1.write_report.curate_stats, direct_expected.stats); + + // Chunk 2 stats & aggregate ILP stats. + assert_eq!(rep2.decode_stats.docs_seen, 1); + assert_eq!(rep2.decode_stats.rows_decoded, 1); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!(ilp_stats.rows, 3); + + // Exact ILP bytes match `encode_fx_1m` of chunk 1 + chunk 2 expected rows in order. + let mut expected_bytes = Vec::new(); + for row in &direct_expected.rows { + encode_fx_1m(&mut expected_bytes, row).unwrap(); + } + encode_fx_1m( + &mut expected_bytes, + &Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts3_sec * 1_000_000, + open: 1.3725, + high: 1.3735, + low: 1.3720, + close: 1.3731, + source: FX_1M_SOURCE_EOD, + }, + ) + .unwrap(); + + let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 2); + let other_shard = 1 - target_shard; + let shards = [&s0, &s1]; + assert_eq!(shards[target_shard], &expected_bytes); + assert!(shards[other_shard].is_empty()); +} + +#[test] +fn truncated_bson_stream_fails_closed_with_zero_rows_written_and_typed_errors_format() { + let doc1 = make_eod_intraday_bson_doc( + EOD_CAD_FOREX_CODE, + 1_718_000_000, + 1.3700, + 1.3710, + 1.3695, + 1.3705, + 0.0, + ); + let doc2 = make_eod_intraday_bson_doc( + EOD_CAD_FOREX_CODE, + 1_718_000_060, + 1.3710, + 1.3720, + 1.3705, + 1.3715, + 0.0, + ); + + let mut truncated_bytes = Vec::new(); + truncated_bytes.extend_from_slice(doc1.as_bytes()); + let doc2_bytes = doc2.as_bytes(); + truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (stream_err, stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_fx_1m_from_bson( + Cursor::new(&truncated_bytes), + BsonStreamOptions::default(), + &mut writer, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + + assert!(matches!( + stream_err, + CurateFx1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert!(stream_err.source().is_some()); + assert!(stream_err.to_string().contains("fx_1m BSON stream failed")); + assert_eq!(stats.rows, 0); + assert!(s0.is_empty()); + assert!(s1.is_empty()); + + // Writer I/O failure surfaces as `CurateFx1mBsonError::Write(IlpWriterError::Io { .. })`. + let mut failing_writer = IlpShardedWriter::new( + vec![FailingSink], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let write_err = curate_and_write_fx_1m_from_bson( + Cursor::new(doc1.as_bytes()), + BsonStreamOptions::default(), + &mut failing_writer, + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFx1mBsonError::Write(IlpWriterError::Io { shard: 0, .. }) + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("fx_1m ILP write failed")); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index c174442b..1a8ff478 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -256,6 +256,13 @@ pub use curate_qm_bars_1m::{ CurateQmBars1mBsonError, CurateQmBars1mBsonReport, }; +pub mod curate_fx_1m; +pub use curate_fx_1m::{ + build_fx_1m, curate_and_write_fx_1m, curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, + CurateFx1mBsonReport, CurateFx1mOutput, CurateFx1mStats, CurateFx1mWriteReport, + FX_1M_SOURCE_EOD, +}; + pub mod run_curate_bars; pub use run_curate_bars::{ default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv,