diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 6fea2441..d76fb2a8 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -17,8 +17,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; use crate::bars_1m::{ - build_bars_1m, check_session_closes, Bars1mError, Bars1mStats, DailySessionClose, - EodIntradayBar, IntradaySession, SessionCloseStats, + build_bars_1m, check_session_closes, Bar1mRow, Bars1mError, Bars1mStats, DailySessionClose, + EodIntradayBar, IntradaySession, SessionCloseStats, BARS_1M_SOURCE_EOD, }; use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; use crate::bson_qm_actions::{ @@ -39,6 +39,7 @@ use crate::events::{ KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD}; +use crate::ilp::{IlpShardedWriter, IlpWriterError, IlpWriterOptions}; use crate::parquet_adj::{ write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError, }; @@ -72,6 +73,8 @@ pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000; +pub const DEFAULT_ILP_BARS_1M_BENCH_ROWS: usize = DEFAULT_BARS_1M_BENCH_ROWS; +pub const ILP_BARS_1M_BENCH_SHARDS: usize = 4; pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000; pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000; pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000; @@ -112,6 +115,7 @@ const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71; const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00; const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100; +const ILP_BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_119B_A451; const BARS_1M_BENCH_KEY_COUNT: usize = 2_000; const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000; const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE; @@ -1168,6 +1172,108 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result, +} + +/// Runs the fixed-seed QuestDB ILP v2 `bars_1m` encoding + sharded batching benchmark for `rows` +/// curated 1-minute equity bars across four `std::io::sink()` shards. +/// +/// Generates `rows` deterministic curated [`Bar1mRow`] records and `known_at` timestamps +/// across `2_000` `i32` listing IDs spanning `2024-01-02..=2025-12-31` (`PRE`/`RTH`/`POST`), then +/// times encoding and batching through [`IlpShardedWriter`] including [`IlpShardedWriter::finish`]. +pub fn run_ilp_bars_1m_benchmark(rows: usize) -> Result { + let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let date_span = (max_date - min_date + 1) as u64; + + let mut rng = SplitMix64::new(ILP_BARS_1M_BENCH_SEED); + let mut input_rows: Vec<(Bar1mRow, i64)> = Vec::with_capacity(rows); + + for _ in 0..rows { + let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; + let session_date = min_date + (rng.next_u64() % date_span) as i32; + let et_minute = (480 + (rng.next_u64() % 720)) as u16; + let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); + let ts = close_1600_utc + (i64::from(et_minute) - 960) * 60_000_000; + let known_at = ts + 60_000_000; + + let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; + let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; + let high = low + spread; + let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let volume = ((rng.next_u64() % 500_000) + 10) as f64; + + input_rows.push(( + Bar1mRow { + key, + ts, + session_date, + open, + high, + low, + close, + volume, + session: IntradaySession::from_et_minute(et_minute), + source: BARS_1M_SOURCE_EOD, + }, + known_at, + )); + } + + let sinks: Vec = (0..ILP_BARS_1M_BENCH_SHARDS).map(|_| io::sink()).collect(); + let mut writer = IlpShardedWriter::new(sinks, IlpWriterOptions::default())?; + + let start = Instant::now(); + for (row, known_at) in &input_rows { + writer.write_bar_1m(row, *known_at)?; + } + let stats = black_box(writer.finish()?); + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + let (rows_per_sec, ns_per_row) = compute_rates(stats.rows, elapsed_secs); + let bytes_per_row = if stats.rows == 0 { + 0.0 + } else { + stats.bytes as f64 / stats.rows as f64 + }; + let mb_per_sec = if elapsed_secs <= 0.0 || !elapsed_secs.is_finite() { + 0.0 + } else { + (stats.bytes as f64 / 1_000_000.0) / elapsed_secs + }; + + Ok(IlpBars1mBenchReport { + rows, + rows_encoded: stats.rows, + key_count: BARS_1M_BENCH_KEY_COUNT, + shards: ILP_BARS_1M_BENCH_SHARDS, + bytes: stats.bytes, + flushes: stats.flushes, + elapsed_ms, + rows_per_sec, + ns_per_row, + bytes_per_row, + mb_per_sec, + per_shard_rows: stats.per_shard_rows, + }) +} + /// Summary metrics produced by [`run_fx_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FxBenchReport { @@ -13077,4 +13183,35 @@ mod tests { assert_eq!(report.rows_per_sec, 0.0); assert_eq!(report.ns_per_row, 0.0); } + + #[test] + fn ilp_bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { + let a = run_ilp_bars_1m_benchmark(5_000).unwrap(); + let b = run_ilp_bars_1m_benchmark(5_000).unwrap(); + + assert_eq!(a.rows, 5_000); + assert_eq!(a.rows_encoded, a.rows); + assert_eq!(a.shards, ILP_BARS_1M_BENCH_SHARDS); + assert_eq!(a.bytes, b.bytes); + assert_eq!(a.flushes, b.flushes); + assert_eq!(a.per_shard_rows, b.per_shard_rows); + assert_eq!(a.per_shard_rows.len(), ILP_BARS_1M_BENCH_SHARDS); + assert_eq!(a.per_shard_rows.iter().sum::(), a.rows_encoded); + assert!(a.bytes > 0); + assert!(a.bytes_per_row > 100.0); + assert!(a.flushes >= ILP_BARS_1M_BENCH_SHARDS); + } + + #[test] + fn ilp_bars_1m_benchmark_zero_rows_handles_cleanly() { + let report = run_ilp_bars_1m_benchmark(0).unwrap(); + assert_eq!(report.rows, 0); + assert_eq!(report.rows_encoded, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.flushes, 0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + assert_eq!(report.per_shard_rows, vec![0; ILP_BARS_1M_BENCH_SHARDS]); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 64a26b81..7f399ac9 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -19,7 +19,7 @@ use crate::bench::{ DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, - DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, + DEFAULT_ILP_BARS_1M_BENCH_ROWS, DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, @@ -72,6 +72,7 @@ pub enum CliAction { BenchCorporateActions(usize), BenchBars(usize), BenchBars1m(usize), + BenchIlpBars1m(usize), BenchFx(usize), BenchShorts(usize), BenchEvents(usize), @@ -131,6 +132,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ {name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\ {name} bench-bars-1m [rows] Run fixed-seed bars_1m build + session-close cross-check benchmark (default: {DEFAULT_BARS_1M_BENCH_ROWS})\n\ + {name} bench-ilp-bars-1m [rows] Run fixed-seed QuestDB ILP v2 bars_1m encode + sharded batch benchmark (default: {DEFAULT_ILP_BARS_1M_BENCH_ROWS})\n\ {name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\ {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ @@ -177,6 +179,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-corporate-actions [events]\n\ {name} bench-bars [rows]\n\ {name} bench-bars-1m [rows]\n\ + {name} bench-ilp-bars-1m [rows]\n\ {name} bench-fx [rows]\n\ {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ @@ -1474,6 +1477,14 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()), + ["bench-ilp-bars-1m"] => Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)), + ["bench-ilp-bars-1m", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchIlpBars1m(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-ilp-bars-1m", _, ..] => Err("too many arguments for bench-ilp-bars-1m".to_string()), ["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)), ["bench-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)), @@ -3404,5 +3415,19 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-events-cmd", "0"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err()); + + // bench-ilp-bars-1m + assert_eq!( + parse_args(&to_args(&["bench-ilp-bars-1m"])), + Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-ilp-bars-1m", "2500"])), + Ok(CliAction::BenchIlpBars1m(2_500)) + ); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "1", "2"])).is_err()); } } diff --git a/tools/curate-etl/src/ilp.rs b/tools/curate-etl/src/ilp.rs new file mode 100644 index 00000000..54a5691e --- /dev/null +++ b/tools/curate-etl/src/ilp.rs @@ -0,0 +1,567 @@ +//! Pure, socket-free QuestDB ILP v2 line encoder and sharded batch writer for +//! `bars_1m` and `fx_1m`. +//! +//! # Wire format (QuestDB ILP Protocol Version 2) +//! +//! Verified against the official `questdb-rs` client source in +//! `questdb/c-questdb-client` (`main` branch, `questdb-rs`): +//! - Binary `DOUBLE` type tag (`DOUBLE_TYPE = 16` / `0x10`): +//! `questdb-rs/src/ingress.rs` lines 157–159. +//! - Tag/field separators and binary `f64` field encoding (`==\x10<8 LE IEEE-754 bytes>`): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 569–713. +//! - ILP escaping for `SYMBOL` values (space, `,`, `=`, `\n`, `\r`, and `\` prefixed with `\`): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 36–84. +//! - Timestamp column microsecond suffix (`=t`): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1026–1047. +//! - Designated timestamp microsecond suffix (` t\n`, non-negative): +//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1087–1116. +//! +//! # Table contracts +//! +//! Column names and types match `M2_INTRADAY_SCHEMAS` in `libs/data/questdb/src/schema.ts` +//! and `design/DATA-CONTRACTS.md` §3.B: +//! - `bars_1m`: symbols `listing_id`, `session`, `source`; binary doubles `open`, `high`, `low`, +//! `close`, `volume` (`vwap` is omitted / NULL); timestamp column `known_at`; designated +//! timestamp `ts` (UTC microseconds). +//! - `fx_1m`: symbols `pair`, `source`; binary doubles `open`, `high`, `low`, `close`; +//! designated timestamp `ts` (UTC microseconds). +//! +//! # Deterministic sharding +//! +//! [`IlpShardedWriter`] routes rows deterministically using 64-bit FNV-1a modulo shard count +//! (`fnv1a_64(key_bytes) % shard_count`): +//! - `bars_1m` hashes `listing_id` as its 4-byte little-endian representation +//! (`listing_id.to_le_bytes()`). +//! - `fx_1m` hashes `pair` as its raw UTF-8 bytes (`pair.as_bytes()`). +//! +//! All rows for a given key always land on the same shard in their exact input order, preserving +//! the per-key ordering required by `DEDUP UPSERT KEYS(ts, listing_id)` / `KEYS(ts, pair)`. + +use std::error::Error; +use std::fmt; +use std::io::{self, Write}; + +use crate::bars_1m::Bar1mRow; + +/// QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). +pub const ILP_V2_DOUBLE_TYPE: u8 = 0x10; + +/// Canonical QuestDB table name for 1-minute equity bars. +pub const TABLE_BARS_1M: &str = "bars_1m"; + +/// Canonical QuestDB table name for 1-minute FX bars. +pub const TABLE_FX_1M: &str = "fx_1m"; + +/// 64-bit FNV-1a offset basis used for deterministic shard routing. +pub const FNV1A_64_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + +/// 64-bit FNV-1a prime used for deterministic shard routing. +pub const FNV1A_64_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// Default maximum buffered bytes per shard before flushing a batch (1 MiB). +pub const DEFAULT_ILP_MAX_BATCH_BYTES: usize = 1_048_576; + +/// Default maximum buffered rows per shard before flushing a batch. +pub const DEFAULT_ILP_MAX_BATCH_ROWS: usize = 10_000; + +/// A single `fx_1m` 1-minute FX bar input for QuestDB ILP v2 encoding. +/// +/// Matches `M2_INTRADAY_SCHEMAS.fx_1m` in `libs/data/questdb/src/schema.ts`: +/// `pair` (SYMBOL), `open`/`high`/`low`/`close` (DOUBLE), `source` (SYMBOL), `ts` (TIMESTAMP). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Fx1mRow<'a> { + pub pair: &'a str, + /// Bar start timestamp in UTC microseconds since the Unix epoch (must be `>= 0`). + pub ts: i64, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub source: &'a str, +} + +/// Typed validation errors returned by [`encode_bar_1m`] and [`encode_fx_1m`]. +/// +/// Encoding is atomic: when an error is returned, the caller's destination buffer is left +/// completely unmodified. +#[derive(Debug, Clone, PartialEq)] +pub enum IlpEncodeError { + /// A `DOUBLE` field was non-finite (`NaN`, `+inf`, or `-inf`). + NonFiniteDouble { field: &'static str, value: f64 }, + /// The designated timestamp `ts` was negative (QuestDB ILP requires `ts >= 0`). + NegativeTimestamp { field: &'static str, value: i64 }, + /// A required `SYMBOL` column value was empty. + EmptySymbol { field: &'static str }, +} + +impl fmt::Display for IlpEncodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::NonFiniteDouble { field, value } => { + write!(f, "non-finite ILP double field '{field}': {value}") + } + Self::NegativeTimestamp { field, value } => { + write!( + f, + "negative ILP designated timestamp '{field}': {value} (must be >= 0)" + ) + } + Self::EmptySymbol { field } => { + write!(f, "empty ILP symbol field '{field}'") + } + } + } +} + +impl Error for IlpEncodeError {} + +/// Batching limits for [`IlpShardedWriter`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IlpWriterOptions { + /// Maximum buffered bytes per shard before flushing (must be `>= 1`). + pub max_batch_bytes: usize, + /// Maximum buffered rows per shard before flushing (must be `>= 1`). + pub max_batch_rows: usize, +} + +impl Default for IlpWriterOptions { + fn default() -> Self { + Self { + max_batch_bytes: DEFAULT_ILP_MAX_BATCH_BYTES, + max_batch_rows: DEFAULT_ILP_MAX_BATCH_ROWS, + } + } +} + +/// Summary statistics returned by [`IlpShardedWriter::finish`]. +/// +/// Conservation invariants: +/// - `per_shard_rows.iter().sum::() == rows` +/// - `bytes` equals the exact sum of bytes written across all successful shard `write_all` calls. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IlpWriteStats { + pub rows: usize, + pub bytes: usize, + pub flushes: usize, + pub per_shard_rows: Vec, +} + +/// Typed errors returned by [`IlpShardedWriter`]. +#[derive(Debug)] +pub enum IlpWriterError { + /// No sinks were provided to [`IlpShardedWriter::new`]. + EmptySinks, + /// [`IlpWriterOptions::max_batch_bytes`] was `0`. + ZeroMaxBatchBytes, + /// [`IlpWriterOptions::max_batch_rows`] was `0`. + ZeroMaxBatchRows, + /// Row encoding failed before mutating any shard buffer. + Encode(IlpEncodeError), + /// A sink `write_all` or `flush` call failed on `shard`. + Io { shard: usize, source: io::Error }, + /// A previous I/O failure on `failed_shard` poisoned the writer; no further writes are allowed. + Poisoned { failed_shard: usize }, +} + +impl fmt::Display for IlpWriterError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptySinks => write!(f, "ILP sharded writer requires at least one sink"), + Self::ZeroMaxBatchBytes => { + write!(f, "ILP writer max_batch_bytes must be >= 1") + } + Self::ZeroMaxBatchRows => { + write!(f, "ILP writer max_batch_rows must be >= 1") + } + Self::Encode(err) => write!(f, "ILP encode error: {err}"), + Self::Io { shard, source } => { + write!(f, "ILP writer I/O error on shard {shard}: {source}") + } + Self::Poisoned { failed_shard } => write!( + f, + "ILP writer is poisoned after prior I/O error on shard {failed_shard}" + ), + } + } +} + +impl Error for IlpWriterError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Encode(err) => Some(err), + Self::Io { source, .. } => Some(source), + Self::EmptySinks + | Self::ZeroMaxBatchBytes + | Self::ZeroMaxBatchRows + | Self::Poisoned { .. } => None, + } + } +} + +impl From for IlpWriterError { + fn from(err: IlpEncodeError) -> Self { + Self::Encode(err) + } +} + +/// Computes the 64-bit FNV-1a hash of `bytes`. +#[inline] +pub fn fnv1a_64(bytes: &[u8]) -> u64 { + let mut hash = FNV1A_64_OFFSET_BASIS; + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(FNV1A_64_PRIME); + } + hash +} + +/// Deterministic shard index for an equity `listing_id` (`i32` hashed as 4 little-endian bytes). +#[inline] +pub fn shard_for_listing_id(listing_id: i32, shard_count: usize) -> usize { + debug_assert!(shard_count > 0); + (fnv1a_64(&listing_id.to_le_bytes()) % (shard_count as u64)) as usize +} + +/// Deterministic shard index for an FX `pair` (hashed as raw UTF-8 bytes). +#[inline] +pub fn shard_for_fx_pair(pair: &str, shard_count: usize) -> usize { + debug_assert!(shard_count > 0); + (fnv1a_64(pair.as_bytes()) % (shard_count as u64)) as usize +} + +#[inline] +fn validate_finite(field: &'static str, value: f64) -> Result<(), IlpEncodeError> { + if value.is_finite() { + Ok(()) + } else { + Err(IlpEncodeError::NonFiniteDouble { field, value }) + } +} + +#[inline] +fn validate_non_negative_ts(field: &'static str, value: i64) -> Result<(), IlpEncodeError> { + if value >= 0 { + Ok(()) + } else { + Err(IlpEncodeError::NegativeTimestamp { field, value }) + } +} + +/// Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. +#[inline] +fn write_escaped_symbol(buf: &mut Vec, value: &str) { + let bytes = value.as_bytes(); + let mut last = 0usize; + for (i, &b) in bytes.iter().enumerate() { + if matches!(b, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\') { + if last < i { + buf.extend_from_slice(&bytes[last..i]); + } + buf.push(b'\\'); + buf.push(b); + last = i + 1; + } + } + if last < bytes.len() { + buf.extend_from_slice(&bytes[last..]); + } +} + +#[inline] +fn write_i64_decimal(buf: &mut Vec, value: i64) { + let mut tmp = [0u8; 20]; + let negative = value < 0; + let mut mag = value.unsigned_abs(); + let mut pos = tmp.len(); + if mag == 0 { + pos -= 1; + tmp[pos] = b'0'; + } else { + while mag > 0 { + pos -= 1; + tmp[pos] = b'0' + (mag % 10) as u8; + mag /= 10; + } + } + if negative { + pos -= 1; + tmp[pos] = b'-'; + } + buf.extend_from_slice(&tmp[pos..]); +} + +#[inline] +fn write_binary_f64(buf: &mut Vec, name: &str, value: f64) { + buf.extend_from_slice(name.as_bytes()); + buf.extend_from_slice(&[b'=', b'=', ILP_V2_DOUBLE_TYPE]); + buf.extend_from_slice(&value.to_le_bytes()); +} + +/// Encodes one curated `bars_1m` row in QuestDB ILP v2 format into `buf`. +/// +/// Emits: +/// - Table `bars_1m` +/// - Symbols `listing_id` (decimal `row.key`), `session` (`PRE`/`RTH`/`POST`), `source` +/// - Binary `f64` columns `open`, `high`, `low`, `close`, `volume` (`vwap` omitted / NULL) +/// - Timestamp column `known_at=t` +/// - Designated timestamp ` t\n` +/// +/// Validates all doubles, `source`, and non-negative `row.ts` before appending any bytes so +/// `buf` is left untouched on error. +pub fn encode_bar_1m( + buf: &mut Vec, + row: &Bar1mRow, + known_at_micros: i64, +) -> Result<(), IlpEncodeError> { + if row.source.is_empty() { + return Err(IlpEncodeError::EmptySymbol { field: "source" }); + } + validate_finite("open", row.open)?; + validate_finite("high", row.high)?; + validate_finite("low", row.low)?; + validate_finite("close", row.close)?; + validate_finite("volume", row.volume)?; + validate_non_negative_ts("ts", row.ts)?; + + buf.extend_from_slice(TABLE_BARS_1M.as_bytes()); + buf.extend_from_slice(b",listing_id="); + write_i64_decimal(buf, i64::from(row.key)); + buf.extend_from_slice(b",session="); + buf.extend_from_slice(row.session.as_str().as_bytes()); + buf.extend_from_slice(b",source="); + write_escaped_symbol(buf, row.source); + + buf.push(b' '); + write_binary_f64(buf, "open", row.open); + buf.push(b','); + write_binary_f64(buf, "high", row.high); + buf.push(b','); + write_binary_f64(buf, "low", row.low); + buf.push(b','); + write_binary_f64(buf, "close", row.close); + buf.push(b','); + write_binary_f64(buf, "volume", row.volume); + buf.extend_from_slice(b",known_at="); + write_i64_decimal(buf, known_at_micros); + buf.extend_from_slice(b"t "); + + write_i64_decimal(buf, row.ts); + buf.extend_from_slice(b"t\n"); + Ok(()) +} + +/// Encodes one `fx_1m` row in QuestDB ILP v2 format into `buf`. +/// +/// Emits: +/// - Table `fx_1m` +/// - Symbols `pair`, `source` +/// - Binary `f64` columns `open`, `high`, `low`, `close` +/// - Designated timestamp ` t\n` +/// +/// Validates `pair`, `source`, all doubles, and non-negative `row.ts` before appending any bytes +/// so `buf` is left untouched on error. +pub fn encode_fx_1m(buf: &mut Vec, row: &Fx1mRow<'_>) -> Result<(), IlpEncodeError> { + if row.pair.is_empty() { + return Err(IlpEncodeError::EmptySymbol { field: "pair" }); + } + if row.source.is_empty() { + return Err(IlpEncodeError::EmptySymbol { field: "source" }); + } + validate_finite("open", row.open)?; + validate_finite("high", row.high)?; + validate_finite("low", row.low)?; + validate_finite("close", row.close)?; + validate_non_negative_ts("ts", row.ts)?; + + buf.extend_from_slice(TABLE_FX_1M.as_bytes()); + buf.extend_from_slice(b",pair="); + write_escaped_symbol(buf, row.pair); + buf.extend_from_slice(b",source="); + write_escaped_symbol(buf, row.source); + + buf.push(b' '); + write_binary_f64(buf, "open", row.open); + buf.push(b','); + write_binary_f64(buf, "high", row.high); + buf.push(b','); + write_binary_f64(buf, "low", row.low); + buf.push(b','); + write_binary_f64(buf, "close", row.close); + + buf.push(b' '); + write_i64_decimal(buf, row.ts); + buf.extend_from_slice(b"t\n"); + Ok(()) +} + +struct ShardState { + sink: W, + buf: Vec, + pending_rows: usize, + written_rows: usize, +} + +/// Deterministic, sink-agnostic sharded QuestDB ILP v2 batch writer. +/// +/// Buffers complete ILP lines per shard and flushes whole-line batches to injected [`Write`] +/// sinks when either `max_batch_rows` or `max_batch_bytes` is reached, or on [`Self::finish`]. +pub struct IlpShardedWriter { + shards: Vec>, + options: IlpWriterOptions, + scratch: Vec, + rows_written: usize, + bytes_written: usize, + flushes: usize, + poisoned_shard: Option, +} + +impl IlpShardedWriter { + /// Creates a new sharded writer over `sinks` with the given batching `options`. + /// + /// Returns an error if `sinks` is empty or either batch limit is zero. + pub fn new(sinks: Vec, options: IlpWriterOptions) -> Result { + if sinks.is_empty() { + return Err(IlpWriterError::EmptySinks); + } + if options.max_batch_bytes == 0 { + return Err(IlpWriterError::ZeroMaxBatchBytes); + } + if options.max_batch_rows == 0 { + return Err(IlpWriterError::ZeroMaxBatchRows); + } + + let initial_buf_cap = options.max_batch_bytes.min(DEFAULT_ILP_MAX_BATCH_BYTES); + let shards = sinks + .into_iter() + .map(|sink| ShardState { + sink, + buf: Vec::with_capacity(initial_buf_cap), + pending_rows: 0, + written_rows: 0, + }) + .collect(); + + Ok(Self { + shards, + options, + scratch: Vec::with_capacity(256), + rows_written: 0, + bytes_written: 0, + flushes: 0, + poisoned_shard: None, + }) + } + + /// Returns the number of configured shards. + #[inline] + pub fn shard_count(&self) -> usize { + self.shards.len() + } + + /// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`. + pub fn write_bar_1m( + &mut self, + row: &Bar1mRow, + known_at_micros: i64, + ) -> Result<(), IlpWriterError> { + if let Some(failed_shard) = self.poisoned_shard { + return Err(IlpWriterError::Poisoned { failed_shard }); + } + self.scratch.clear(); + encode_bar_1m(&mut self.scratch, row, known_at_micros)?; + let shard_idx = shard_for_listing_id(row.key, self.shards.len()); + self.enqueue_scratch_row(shard_idx) + } + + /// Encodes and buffers one `fx_1m` row on the shard determined by `row.pair`. + pub fn write_fx_1m(&mut self, row: &Fx1mRow<'_>) -> Result<(), IlpWriterError> { + if let Some(failed_shard) = self.poisoned_shard { + return Err(IlpWriterError::Poisoned { failed_shard }); + } + self.scratch.clear(); + encode_fx_1m(&mut self.scratch, row)?; + let shard_idx = shard_for_fx_pair(row.pair, self.shards.len()); + self.enqueue_scratch_row(shard_idx) + } + + /// Flushes all remaining buffered batches and underlying sinks, returning write statistics. + pub fn finish(mut self) -> Result { + if let Some(failed_shard) = self.poisoned_shard { + return Err(IlpWriterError::Poisoned { failed_shard }); + } + + for shard_idx in 0..self.shards.len() { + if !self.shards[shard_idx].buf.is_empty() { + self.flush_shard(shard_idx)?; + } + if let Err(source) = self.shards[shard_idx].sink.flush() { + self.poisoned_shard = Some(shard_idx); + return Err(IlpWriterError::Io { + shard: shard_idx, + source, + }); + } + } + + let per_shard_rows = self.shards.iter().map(|s| s.written_rows).collect(); + Ok(IlpWriteStats { + rows: self.rows_written, + bytes: self.bytes_written, + flushes: self.flushes, + per_shard_rows, + }) + } + + fn enqueue_scratch_row(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { + let row_len = self.scratch.len(); + let needs_preflush = { + let shard = &self.shards[shard_idx]; + !shard.buf.is_empty() + && shard.buf.len().saturating_add(row_len) > self.options.max_batch_bytes + }; + if needs_preflush { + self.flush_shard(shard_idx)?; + } + + let needs_postflush = { + let shard = &mut self.shards[shard_idx]; + shard.buf.extend_from_slice(&self.scratch); + shard.pending_rows += 1; + shard.pending_rows >= self.options.max_batch_rows + || shard.buf.len() >= self.options.max_batch_bytes + }; + if needs_postflush { + self.flush_shard(shard_idx)?; + } + + Ok(()) + } + + fn flush_shard(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { + let shard = &mut self.shards[shard_idx]; + if shard.buf.is_empty() { + return Ok(()); + } + if let Err(source) = shard.sink.write_all(&shard.buf) { + self.poisoned_shard = Some(shard_idx); + return Err(IlpWriterError::Io { + shard: shard_idx, + source, + }); + } + + let bytes = shard.buf.len(); + let rows = shard.pending_rows; + shard.buf.clear(); + shard.pending_rows = 0; + shard.written_rows += rows; + self.rows_written += rows; + self.bytes_written += bytes; + self.flushes += 1; + Ok(()) + } +} + +#[cfg(test)] +#[path = "ilp_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/ilp_tests.rs b/tools/curate-etl/src/ilp_tests.rs new file mode 100644 index 00000000..5ff705ed --- /dev/null +++ b/tools/curate-etl/src/ilp_tests.rs @@ -0,0 +1,765 @@ +use std::collections::HashMap; +use std::io::{self, Write}; +use std::sync::{Arc, Mutex}; + +use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD}; + +use super::{ + encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, + IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, ILP_V2_DOUBLE_TYPE, +}; + +fn sample_bar(listing_id: i32, ts: i64) -> Bar1mRow { + Bar1mRow { + key: listing_id, + ts, + session_date: 20_100, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + } +} + +fn sample_fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { + Fx1mRow { + pair, + ts, + open: 1.3625, + high: 1.3650, + low: 1.3610, + close: 1.3642, + source: "eod", + } +} + +/// Minimal ILP v2 frame splitter that respects escaped symbols and fixed-width 8-byte binary +/// `DOUBLE` payloads (`==\x10<8 bytes>`), so embedded `0x0a` bytes inside binary doubles or +/// escaped `\n` in symbols never falsely split a row. +fn split_ilp_v2_rows(data: &[u8]) -> Vec<&[u8]> { + let mut rows = Vec::new(); + let mut i = 0usize; + let len = data.len(); + + while i < len { + let start = i; + // 1. Tag set (table + symbols) ends at unescaped ASCII space. + while i < len { + match data[i] { + b'\\' => { + assert!(i + 1 < len, "dangling backslash in ILP tag set"); + i += 2; + } + b' ' => { + i += 1; + break; + } + _ => i += 1, + } + } + assert!(i < len, "unexpected EOF after ILP tag set"); + + // 2. Field set ends at ASCII space; skip fixed 8-byte binary double payloads after `==\x10`. + while i < len { + if data[i] == b' ' { + i += 1; + break; + } + if data[i] == b'=' && i + 2 < len && data[i + 1] == b'=' && data[i + 2] == ILP_V2_DOUBLE_TYPE + { + assert!( + i + 3 + 8 <= len, + "truncated binary DOUBLE payload in ILP field set" + ); + i += 3 + 8; + } else { + i += 1; + } + } + assert!(i < len, "unexpected EOF after ILP field set"); + + // 3. Designated timestamp runs to unescaped LF. + while i < len && data[i] != b'\n' { + i += 1; + } + assert!(i < len && data[i] == b'\n', "ILP row missing trailing LF"); + i += 1; + rows.push(&data[start..i]); + } + + rows +} + +fn extract_tag_value<'a>(row: &'a [u8], tag_prefix: &[u8]) -> &'a [u8] { + let mut i = 0usize; + let tag_end = loop { + assert!(i < row.len(), "missing space after tag set"); + match row[i] { + b'\\' => i += 2, + b' ' => break i, + _ => i += 1, + } + }; + let tag_section = &row[..tag_end]; + let pos = tag_section + .windows(tag_prefix.len()) + .position(|w| w == tag_prefix) + .expect("expected tag prefix in row"); + let val_start = pos + tag_prefix.len(); + let mut j = val_start; + while j < tag_end { + match tag_section[j] { + b'\\' => j += 2, + b',' => break, + _ => j += 1, + } + } + &tag_section[val_start..j] +} + +#[derive(Clone, Default)] +struct RecordingSink { + writes: Arc>>>, + flush_calls: Arc>, + fail_on_write_call: Option, + fail_on_flush: bool, +} + +impl RecordingSink { + fn new() -> Self { + Self::default() + } + + fn failing_on_write(call_index: usize) -> Self { + Self { + fail_on_write_call: Some(call_index), + ..Self::default() + } + } + + fn failing_on_flush() -> Self { + Self { + fail_on_flush: true, + ..Self::default() + } + } + + fn captured_writes(&self) -> Vec> { + self.writes.lock().unwrap().clone() + } + + fn captured_flushes(&self) -> usize { + *self.flush_calls.lock().unwrap() + } +} + +impl Write for RecordingSink { + fn write(&mut self, buf: &[u8]) -> io::Result { + let mut writes = self.writes.lock().unwrap(); + let call_idx = writes.len(); + if self.fail_on_write_call == Some(call_idx) { + return Err(io::Error::new( + io::ErrorKind::BrokenPipe, + format!("injected write failure on call {call_idx}"), + )); + } + writes.push(buf.to_vec()); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + let mut flushes = self.flush_calls.lock().unwrap(); + *flushes += 1; + if self.fail_on_flush { + return Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "injected flush failure", + )); + } + Ok(()) + } +} + +#[test] +fn golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract() { + let row = Bar1mRow { + key: 42, + ts: 1_736_951_400_000_000, + session_date: 20_103, + open: 150.25, + high: 151.75, + low: 149.5, + close: 151.125, + volume: 12_345.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + }; + let known_at_micros = 1_736_951_460_123_456_i64; + + let mut actual = Vec::new(); + encode_bar_1m(&mut actual, &row, known_at_micros).expect("encode bar_1m"); + + let mut expected = Vec::new(); + expected.extend_from_slice(b"bars_1m,listing_id=42,session=RTH,source=eod_unadj "); + expected.extend_from_slice(b"open==\x10"); + expected.extend_from_slice(&150.25_f64.to_le_bytes()); + expected.extend_from_slice(b",high==\x10"); + expected.extend_from_slice(&151.75_f64.to_le_bytes()); + expected.extend_from_slice(b",low==\x10"); + expected.extend_from_slice(&149.5_f64.to_le_bytes()); + expected.extend_from_slice(b",close==\x10"); + expected.extend_from_slice(&151.125_f64.to_le_bytes()); + expected.extend_from_slice(b",volume==\x10"); + expected.extend_from_slice(&12_345.0_f64.to_le_bytes()); + expected.extend_from_slice(b",known_at=1736951460123456t 1736951400000000t\n"); + + assert_eq!(actual, expected); + assert!( + !actual.windows(4).any(|w| w == b"vwap"), + "vwap must be omitted for bars_1m" + ); + + // Round-trip every binary DOUBLE payload bit-exactly via f64::from_le_bytes. + for (prefix, expected_val) in [ + (&b"open==\x10"[..], row.open), + (&b",high==\x10"[..], row.high), + (&b",low==\x10"[..], row.low), + (&b",close==\x10"[..], row.close), + (&b",volume==\x10"[..], row.volume), + ] { + let pos = actual + .windows(prefix.len()) + .position(|w| w == prefix) + .expect("binary double column present"); + let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] + .try_into() + .unwrap(); + let decoded = f64::from_le_bytes(raw); + assert_eq!(decoded.to_bits(), expected_val.to_bits()); + } + + // Verify PRE and POST session tags as well. + let mut pre_buf = Vec::new(); + let mut pre_row = row.clone(); + pre_row.session = IntradaySession::Pre; + encode_bar_1m(&mut pre_buf, &pre_row, known_at_micros).unwrap(); + assert!(pre_buf.starts_with(b"bars_1m,listing_id=42,session=PRE,source=eod_unadj ")); + + let mut post_buf = Vec::new(); + let mut post_row = row; + post_row.session = IntradaySession::Post; + encode_bar_1m(&mut post_buf, &post_row, known_at_micros).unwrap(); + assert!(post_buf.starts_with(b"bars_1m,listing_id=42,session=POST,source=eod_unadj ")); +} + +#[test] +fn golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract() { + let row = Fx1mRow { + pair: "USD.CAD", + ts: 1_736_951_400_000_000, + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + source: "eod", + }; + + let mut actual = Vec::new(); + encode_fx_1m(&mut actual, &row).expect("encode fx_1m"); + + let mut expected = Vec::new(); + expected.extend_from_slice(b"fx_1m,pair=USD.CAD,source=eod "); + expected.extend_from_slice(b"open==\x10"); + expected.extend_from_slice(&1.3625_f64.to_le_bytes()); + expected.extend_from_slice(b",high==\x10"); + expected.extend_from_slice(&1.365_f64.to_le_bytes()); + expected.extend_from_slice(b",low==\x10"); + expected.extend_from_slice(&1.36125_f64.to_le_bytes()); + expected.extend_from_slice(b",close==\x10"); + expected.extend_from_slice(&1.364375_f64.to_le_bytes()); + expected.extend_from_slice(b" 1736951400000000t\n"); + + assert_eq!(actual, expected); + assert!(!actual.windows(8).any(|w| w == b"known_at")); + assert!(!actual.windows(6).any(|w| w == b"volume")); + + for (prefix, expected_val) in [ + (&b"open==\x10"[..], row.open), + (&b",high==\x10"[..], row.high), + (&b",low==\x10"[..], row.low), + (&b",close==\x10"[..], row.close), + ] { + let pos = actual + .windows(prefix.len()) + .position(|w| w == prefix) + .expect("binary double column present"); + let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] + .try_into() + .unwrap(); + assert_eq!(f64::from_le_bytes(raw).to_bits(), expected_val.to_bits()); + } +} + +#[test] +fn symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection() { + // Escaping: space, comma, '=', backslash, LF, CR, and UTF-8. + let raw_sym = "a b,c=d\\e\nf\rg caf\u{00e9}"; + let expected_escaped = b"a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf\xc3\xa9"; + + let mut bar = sample_bar(7, 0); + bar.source = raw_sym; + let mut bar_buf = Vec::new(); + encode_bar_1m(&mut bar_buf, &bar, -500).expect("encode escaped bar_1m"); + let mut expected_prefix = b"bars_1m,listing_id=7,session=RTH,source=".to_vec(); + expected_prefix.extend_from_slice(expected_escaped); + expected_prefix.push(b' '); + assert!(bar_buf.starts_with(&expected_prefix)); + assert!(bar_buf.ends_with(b",known_at=-500t 0t\n")); + + let fx = Fx1mRow { + pair: raw_sym, + source: "src=1,2 3\\4\n\r", + ..sample_fx("USD.CAD", 123) + }; + let mut fx_buf = Vec::new(); + encode_fx_1m(&mut fx_buf, &fx).expect("encode escaped fx_1m"); + let mut expected_fx_prefix = b"fx_1m,pair=".to_vec(); + expected_fx_prefix.extend_from_slice(expected_escaped); + expected_fx_prefix.extend_from_slice(b",source=src\\=1\\,2\\ 3\\\\4\\\n\\\r "); + assert!(fx_buf.starts_with(&expected_fx_prefix)); + assert!(fx_buf.ends_with(b" 123t\n")); + + // Non-finite doubles in a late field must fail atomically and preserve existing buffer bytes. + let sentinel = b"EXISTING_PREFIX_BYTES".to_vec(); + for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut buf = sentinel.clone(); + let mut bad_bar = sample_bar(1, 100); + bad_bar.volume = bad_val; + let err = encode_bar_1m(&mut buf, &bad_bar, 200).unwrap_err(); + assert!(matches!( + err, + IlpEncodeError::NonFiniteDouble { + field: "volume", + .. + } + )); + assert_eq!(buf, sentinel, "buffer must be untouched on bars_1m error"); + + let mut fx_buf = sentinel.clone(); + let mut bad_fx = sample_fx("USD.CAD", 100); + bad_fx.close = bad_val; + let err = encode_fx_1m(&mut fx_buf, &bad_fx).unwrap_err(); + assert!(matches!( + err, + IlpEncodeError::NonFiniteDouble { field: "close", .. } + )); + assert_eq!(fx_buf, sentinel, "buffer must be untouched on fx_1m error"); + } + + // Negative designated timestamp fails atomically. + let mut buf = sentinel.clone(); + let bad_ts_bar = sample_bar(1, -1); + assert_eq!( + encode_bar_1m(&mut buf, &bad_ts_bar, 500), + Err(IlpEncodeError::NegativeTimestamp { + field: "ts", + value: -1 + }) + ); + assert_eq!(buf, sentinel); + + let mut fx_buf = sentinel.clone(); + let bad_ts_fx = sample_fx("USD.CAD", -42); + assert_eq!( + encode_fx_1m(&mut fx_buf, &bad_ts_fx), + Err(IlpEncodeError::NegativeTimestamp { + field: "ts", + value: -42 + }) + ); + assert_eq!(fx_buf, sentinel); + + // Empty symbol fails atomically. + let mut buf = sentinel.clone(); + let mut empty_src = sample_bar(1, 100); + empty_src.source = ""; + assert_eq!( + encode_bar_1m(&mut buf, &empty_src, 100), + Err(IlpEncodeError::EmptySymbol { field: "source" }) + ); + assert_eq!(buf, sentinel); + + let mut fx_buf = sentinel.clone(); + let empty_pair = sample_fx("", 100); + assert_eq!( + encode_fx_1m(&mut fx_buf, &empty_pair), + Err(IlpEncodeError::EmptySymbol { field: "pair" }) + ); + assert_eq!(fx_buf, sentinel); +} + +#[test] +fn sharded_writer_routes_deterministically_preserves_per_key_order_and_handles_embedded_lf() { + // Build a finite double whose IEEE-754 little-endian representation contains 0x0a (LF). + let double_with_lf = f64::from_le_bytes([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); + assert!(double_with_lf.is_finite()); + + let num_shards = 4usize; + let num_listings = 64i32; + let rows_per_listing = 20usize; // 64 * 20 = 1,280 interleaved rows >= 1,000 + + let mut input_rows: Vec<(Bar1mRow, i64)> = + Vec::with_capacity(num_listings as usize * rows_per_listing + 2); + for step in 0..rows_per_listing { + for listing_id in 1..=num_listings { + let ts = 1_700_000_000_000_000 + (step as i64) * 60_000_000 + i64::from(listing_id); + let known_at = ts + 60_000_000; + let mut row = sample_bar(listing_id, ts); + row.open = double_with_lf; + row.close = 100.0 + (step as f64) * 0.25 + f64::from(listing_id) * 0.01; + row.volume = (step as f64 + 1.0) * 100.0; + if step == 5 && listing_id == 10 { + row.source = "eod\nwith_lf"; + } + input_rows.push((row, known_at)); + } + } + // Append a second version of an existing (ts, listing_id) to verify DEDUP UPSERT ordering. + let (mut revision, rev_known_at) = input_rows[0].clone(); + revision.close += 0.5; + input_rows.push((revision, rev_known_at + 120_000_000)); + + // Expected per-listing byte sequences in input order. + let mut expected_by_listing: HashMap>> = HashMap::new(); + for (row, known_at) in &input_rows { + let mut line = Vec::new(); + encode_bar_1m(&mut line, row, *known_at).unwrap(); + expected_by_listing.entry(row.key).or_default().push(line); + } + + let opts = IlpWriterOptions { + max_batch_bytes: 2048, + max_batch_rows: 17, + }; + + let run_once = || { + let mut sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); + let stats = { + let sink_refs: Vec<&mut Vec> = sinks.iter_mut().collect(); + let mut writer = IlpShardedWriter::new(sink_refs, opts).unwrap(); + for (row, known_at) in &input_rows { + writer.write_bar_1m(row, *known_at).unwrap(); + } + writer.finish().unwrap() + }; + (sinks, stats) + }; + + let (sinks_a, stats_a) = run_once(); + let (sinks_b, stats_b) = run_once(); + + // Byte-for-byte determinism across runs. + assert_eq!(sinks_a, sinks_b); + assert_eq!(stats_a, stats_b); + + // Conservation invariants. + assert_eq!(stats_a.rows, input_rows.len()); + assert_eq!( + stats_a.per_shard_rows.iter().sum::(), + stats_a.rows + ); + let total_sink_bytes: usize = sinks_a.iter().map(Vec::len).sum(); + assert_eq!(stats_a.bytes, total_sink_bytes); + + // Parse every shard with the binary-aware ILP v2 splitter and verify routing + order. + let mut seen_shard_for_listing: HashMap = HashMap::new(); + let mut observed_by_listing: HashMap>> = HashMap::new(); + let mut total_parsed_rows = 0usize; + + for (shard_idx, shard_bytes) in sinks_a.iter().enumerate() { + let parsed = split_ilp_v2_rows(shard_bytes); + assert_eq!(parsed.len(), stats_a.per_shard_rows[shard_idx]); + total_parsed_rows += parsed.len(); + + for row_bytes in parsed { + let id_bytes = extract_tag_value(row_bytes, b",listing_id="); + let listing_id: i32 = std::str::from_utf8(id_bytes).unwrap().parse().unwrap(); + assert_eq!( + shard_idx, + shard_for_listing_id(listing_id, num_shards), + "listing_id {listing_id} routed to unexpected shard" + ); + if let Some(&prev_shard) = seen_shard_for_listing.get(&listing_id) { + assert_eq!(prev_shard, shard_idx); + } else { + seen_shard_for_listing.insert(listing_id, shard_idx); + } + observed_by_listing + .entry(listing_id) + .or_default() + .push(row_bytes.to_vec()); + } + } + + assert_eq!(total_parsed_rows, input_rows.len()); + assert_eq!(seen_shard_for_listing.len(), num_listings as usize); + assert_eq!(observed_by_listing, expected_by_listing); + + // Repeated FX pairs across batches route by `pair` and preserve order. + let pairs = ["USD.CAD", "EUR.USD", "GBP.USD", "USD.JPY", "AUD.USD", "USD.CHF"]; + let mut fx_sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); + let mut expected_by_pair: HashMap<&str, Vec>> = HashMap::new(); + let fx_stats = { + let refs: Vec<&mut Vec> = fx_sinks.iter_mut().collect(); + let mut writer = IlpShardedWriter::new( + refs, + IlpWriterOptions { + max_batch_bytes: 512, + max_batch_rows: 3, + }, + ) + .unwrap(); + for step in 0..10 { + for &pair in &pairs { + let mut row = sample_fx(pair, 1_700_000_000_000_000 + step * 60_000_000); + row.close += (step as f64) * 0.0001; + let mut line = Vec::new(); + encode_fx_1m(&mut line, &row).unwrap(); + expected_by_pair.entry(pair).or_default().push(line); + writer.write_fx_1m(&row).unwrap(); + } + } + writer.finish().unwrap() + }; + assert_eq!(fx_stats.rows, pairs.len() * 10); + assert_eq!(fx_stats.per_shard_rows.iter().sum::(), fx_stats.rows); + assert_eq!(fx_stats.bytes, fx_sinks.iter().map(Vec::len).sum::()); + + let mut observed_by_pair: HashMap>> = HashMap::new(); + for (shard_idx, shard_bytes) in fx_sinks.iter().enumerate() { + for row_bytes in split_ilp_v2_rows(shard_bytes) { + let pair_str = + std::str::from_utf8(extract_tag_value(row_bytes, b",pair=")).unwrap(); + assert_eq!(shard_idx, shard_for_fx_pair(pair_str, num_shards)); + observed_by_pair + .entry(pair_str.to_string()) + .or_default() + .push(row_bytes.to_vec()); + } + } + for (pair, expected) in expected_by_pair { + assert_eq!(observed_by_pair.get(pair).unwrap(), &expected); + } +} + +#[test] +fn batching_limits_oversized_lines_remainder_and_whole_line_boundaries() { + let row = sample_bar(42, 1_736_951_400_000_000); + let known_at = 1_736_951_460_000_000; + let mut one_line = Vec::new(); + encode_bar_1m(&mut one_line, &row, known_at).unwrap(); + let row_len = one_line.len(); + + // 1. Exact row limit (max_batch_rows = 3) + 1 remainder row. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 100_000, + max_batch_rows: 3, + }, + ) + .unwrap(); + for _ in 0..7 { + writer.write_bar_1m(&row, known_at).unwrap(); + } + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 3); + assert_eq!(stats.flushes, 3); + assert_eq!(stats.rows, 7); + assert_eq!(stats.bytes, 7 * row_len); + assert_eq!(sink.captured_flushes(), 1); + assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 3); + assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 3); + assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); + assert!(writes.iter().all(|w| w.ends_with(b"\n"))); + + // 2. Exact byte limit (2 * row_len): flushes after every 2 rows. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 2 * row_len, + max_batch_rows: 100, + }, + ) + .unwrap(); + for _ in 0..5 { + writer.write_bar_1m(&row, known_at).unwrap(); + } + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 3); + assert_eq!(stats.flushes, 3); + assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 2); + assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 2); + assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); + + // 3. Next line would exceed remaining capacity (2 * row_len - 1): flushes before appending. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 2 * row_len - 1, + max_batch_rows: 100, + }, + ) + .unwrap(); + for _ in 0..3 { + writer.write_bar_1m(&row, known_at).unwrap(); + } + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 3); + assert_eq!(stats.flushes, 3); + for w in &writes { + assert_eq!(w.len(), row_len); + assert_eq!(split_ilp_v2_rows(w).len(), 1); + } + + // 4. Individually oversized line (max_batch_bytes = 16 < row_len) sent alone, never split. + let sink = RecordingSink::new(); + let mut writer = IlpShardedWriter::new( + vec![sink.clone()], + IlpWriterOptions { + max_batch_bytes: 16, + max_batch_rows: 100, + }, + ) + .unwrap(); + writer.write_bar_1m(&row, known_at).unwrap(); + writer.write_bar_1m(&row, known_at).unwrap(); + let stats = writer.finish().unwrap(); + let writes = sink.captured_writes(); + assert_eq!(writes.len(), 2); + assert_eq!(stats.flushes, 2); + assert_eq!(writes[0], one_line); + assert_eq!(writes[1], one_line); +} + +#[test] +fn writer_validates_options_handles_zero_rows_and_poisons_on_io_error() { + assert!(matches!( + IlpShardedWriter::>::new(Vec::new(), IlpWriterOptions::default()), + Err(IlpWriterError::EmptySinks) + )); + assert!(matches!( + IlpShardedWriter::new( + vec![Vec::new()], + IlpWriterOptions { + max_batch_bytes: 0, + max_batch_rows: 10, + } + ), + Err(IlpWriterError::ZeroMaxBatchBytes) + )); + assert!(matches!( + IlpShardedWriter::new( + vec![Vec::new()], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 0, + } + ), + Err(IlpWriterError::ZeroMaxBatchRows) + )); + + // Zero rows written -> clean stats and sink flush still called. + let s0 = RecordingSink::new(); + let s1 = RecordingSink::new(); + let writer = IlpShardedWriter::new(vec![s0.clone(), s1.clone()], IlpWriterOptions::default()) + .unwrap(); + let stats = writer.finish().unwrap(); + assert_eq!(stats.rows, 0); + assert_eq!(stats.bytes, 0); + assert_eq!(stats.flushes, 0); + assert_eq!(stats.per_shard_rows, vec![0, 0]); + assert_eq!(s0.captured_flushes(), 1); + assert_eq!(s1.captured_flushes(), 1); + + // Find a listing_id that routes to shard 2 out of 4. + let target_listing = (1..1000) + .find(|&id| shard_for_listing_id(id, 4) == 2) + .expect("listing for shard 2"); + + // Failing write_all on shard 2 after 1 successful batch: returns Io { shard: 2 } and poisons. + let failing_sink = RecordingSink::failing_on_write(1); + let mut writer = IlpShardedWriter::new( + vec![ + RecordingSink::new(), + RecordingSink::new(), + failing_sink.clone(), + RecordingSink::new(), + ], + IlpWriterOptions { + max_batch_bytes: 100_000, + max_batch_rows: 1, + }, + ) + .unwrap(); + let row = sample_bar(target_listing, 1_700_000_000_000_000); + writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); + let err = writer + .write_bar_1m(&row, 1_700_000_120_000_000) + .unwrap_err(); + assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); + + // Subsequent writes and finish fail with Poisoned { failed_shard: 2 }. + let err2 = writer + .write_bar_1m(&row, 1_700_000_180_000_000) + .unwrap_err(); + assert!(matches!(err2, IlpWriterError::Poisoned { failed_shard: 2 })); + let err3 = writer.write_fx_1m(&sample_fx("USD.CAD", 100)).unwrap_err(); + assert!(matches!(err3, IlpWriterError::Poisoned { failed_shard: 2 })); + let err4 = writer.finish().unwrap_err(); + assert!(matches!(err4, IlpWriterError::Poisoned { failed_shard: 2 })); + assert_eq!(failing_sink.captured_writes().len(), 1); + + // Failing flush() during finish() reports shard index. + let mut writer = IlpShardedWriter::new( + vec![RecordingSink::new(), RecordingSink::failing_on_flush()], + IlpWriterOptions::default(), + ) + .unwrap(); + writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); + let flush_err = writer.finish().unwrap_err(); + assert!(matches!(flush_err, IlpWriterError::Io { shard: 1, .. })); + + // Encode error does not poison the writer. + let mut sinks = [Vec::new(), Vec::new()]; + let stats = { + let refs: Vec<&mut Vec> = sinks.iter_mut().collect(); + let mut writer = IlpShardedWriter::new(refs, IlpWriterOptions::default()).unwrap(); + let mut bad = sample_bar(42, 100); + bad.close = f64::NAN; + assert!(matches!( + writer.write_bar_1m(&bad, 200), + Err(IlpWriterError::Encode(IlpEncodeError::NonFiniteDouble { + field: "close", + .. + })) + )); + writer + .write_bar_1m(&sample_bar(42, 100), 200) + .expect("writer still healthy after encode error"); + writer.finish().unwrap() + }; + assert_eq!(stats.rows, 1); + + // Sanity check FNV-1a 64-bit known test vector ("foobar" -> 0x85944171f73967e8). + assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index eaefb854..cd76c47d 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -15,6 +15,7 @@ pub mod cli; pub mod corporate_actions; pub mod events; pub mod fx; +pub mod ilp; pub mod mongo_safety; pub mod mongo_stream; pub mod parquet_adj; @@ -104,6 +105,12 @@ pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, }; +pub use ilp::{ + encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, + IlpEncodeError, IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, + DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS, + FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, +}; pub use mongo_safety::{ assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts, MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index aa9acace..1c66d48e 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -11,7 +11,8 @@ use curate_etl::bench::{ run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, - run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, + run_fx_benchmark, run_ilp_bars_1m_benchmark, run_mongo_stream_benchmark, + run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, @@ -378,6 +379,33 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchIlpBars1m(rows)) => { + let report = match run_ilp_bars_1m_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: ilp bars_1m benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-ilp-bars-1m"); + println!( + " input: rows={} keys={} shards={}", + report.rows, report.key_count, report.shards + ); + println!( + " output: rows_encoded={} bytes={} flushes={} per_shard_rows={:?}", + report.rows_encoded, report.bytes, report.flushes, report.per_shard_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row size={:.2} bytes/row write={:.2} MB/s", + report.elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.bytes_per_row, + report.mb_per_sec + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchFx(rows)) => { let report = run_fx_benchmark(rows); println!("curate-etl bench-fx"); diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 055232fc..8902eb10 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -46,6 +46,7 @@ fn no_args_and_help_print_usage_and_succeed() { "{args:?}: {text}" ); assert!(text.contains("bench-split"), "{args:?}: {text}"); + assert!(text.contains("bench-ilp-bars-1m"), "{args:?}: {text}"); assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); assert!(text.contains("bench-events"), "{args:?}: {text}"); @@ -90,6 +91,10 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-curate-fx", "0"][..], &["bench-curate-fx", "-5"][..], &["bench-curate-fx", "10", "20"][..], + &["bench-ilp-bars-1m", "abc"][..], + &["bench-ilp-bars-1m", "0"][..], + &["bench-ilp-bars-1m", "-5"][..], + &["bench-ilp-bars-1m", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -260,6 +265,33 @@ fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); } +#[test] +fn bench_ilp_bars_1m_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-ilp-bars-1m", "2000"]); + let b = run(&["bench-ilp-bars-1m", "2000"]); + assert!(a.status.success(), "{}", stderr(&a)); + assert!(b.status.success(), "{}", stderr(&b)); + assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); + assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); + + let text_a = stdout(&a); + let text_b = stdout(&b); + assert!(text_a.contains("curate-etl bench-ilp-bars-1m"), "{text_a}"); + assert!(text_a.contains("rows=2000 "), "{text_a}"); + assert!(text_a.contains("rows_encoded=2000 "), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("bytes/row"), "{text_a}"); + assert!(text_a.contains("MB/s"), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); + assert_eq!(field(&text_a, "flushes="), field(&text_b, "flushes=")); +} + static CLI_TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); struct CliTempDir {