903 lines
31 KiB
Rust
903 lines
31 KiB
Rust
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<i32> {
|
|
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<Mutex<Vec<Vec<u8>>>>,
|
|
flush_calls: Arc<Mutex<usize>>,
|
|
fail_on_write_call: Option<usize>,
|
|
/// `(call_index, prefix_bytes)`: on `call_index`, accept only `prefix_bytes` and then fail
|
|
/// on the subsequent `write()` call inside `write_all()`.
|
|
partial_then_fail_on_write_call: Option<(usize, usize)>,
|
|
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_after_partial_write(call_index: usize, prefix_bytes: usize) -> Self {
|
|
Self {
|
|
partial_then_fail_on_write_call: Some((call_index, prefix_bytes)),
|
|
..Self::default()
|
|
}
|
|
}
|
|
|
|
fn failing_on_flush() -> Self {
|
|
Self {
|
|
fail_on_flush: true,
|
|
..Self::default()
|
|
}
|
|
}
|
|
|
|
fn captured_writes(&self) -> Vec<Vec<u8>> {
|
|
self.writes.lock().unwrap().clone()
|
|
}
|
|
|
|
fn captured_bytes(&self) -> Vec<u8> {
|
|
self.writes
|
|
.lock()
|
|
.unwrap()
|
|
.iter()
|
|
.flat_map(|w| w.iter().copied())
|
|
.collect()
|
|
}
|
|
|
|
fn captured_flushes(&self) -> usize {
|
|
*self.flush_calls.lock().unwrap()
|
|
}
|
|
}
|
|
|
|
impl Write for RecordingSink {
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
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}"),
|
|
));
|
|
}
|
|
if let Some((partial_call, prefix_bytes)) = self.partial_then_fail_on_write_call {
|
|
if call_idx == partial_call {
|
|
let n = prefix_bytes.min(buf.len());
|
|
writes.push(buf[..n].to_vec());
|
|
return Ok(n);
|
|
}
|
|
if call_idx > partial_call {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::BrokenPipe,
|
|
format!("injected write failure after partial write 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<i32>, 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<i32, Vec<Vec<u8>>> = 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<Vec<u8>> = (0..num_shards).map(|_| Vec::new()).collect();
|
|
let stats = {
|
|
let sink_refs: Vec<&mut Vec<u8>> = 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::<usize>(),
|
|
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<i32, usize> = HashMap::new();
|
|
let mut observed_by_listing: HashMap<i32, Vec<Vec<u8>>> = 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<Vec<u8>> = (0..num_shards).map(|_| Vec::new()).collect();
|
|
let mut expected_by_pair: HashMap<&str, Vec<Vec<u8>>> = HashMap::new();
|
|
let fx_stats = {
|
|
let refs: Vec<&mut Vec<u8>> = 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::<usize>(), fx_stats.rows);
|
|
assert_eq!(fx_stats.bytes, fx_sinks.iter().map(Vec::len).sum::<usize>());
|
|
|
|
let mut observed_by_pair: HashMap<String, Vec<Vec<u8>>> = 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::<Vec<u8>>::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<u8>> = 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);
|
|
}
|
|
|
|
#[test]
|
|
fn partial_write_failure_poisons_writer_and_freezes_sink_bytes() {
|
|
let target_listing = (1..1000)
|
|
.find(|&id| shard_for_listing_id(id, 4) == 2)
|
|
.expect("listing for shard 2");
|
|
let other_listing = (1..1000)
|
|
.find(|&id| shard_for_listing_id(id, 4) == 0)
|
|
.expect("listing for shard 0");
|
|
|
|
let row1 = sample_bar(target_listing, 1_700_000_000_000_000);
|
|
let row2 = sample_bar(target_listing, 1_700_000_060_000_000);
|
|
let other_row = sample_bar(other_listing, 1_700_000_000_000_000);
|
|
let known_at = 1_700_000_120_000_000;
|
|
|
|
let mut expected_row1 = Vec::new();
|
|
encode_bar_1m(&mut expected_row1, &row1, known_at).unwrap();
|
|
let mut expected_row2 = Vec::new();
|
|
encode_bar_1m(&mut expected_row2, &row2, known_at).unwrap();
|
|
let partial_prefix_len = 32;
|
|
assert!(partial_prefix_len < expected_row2.len());
|
|
|
|
let healthy_sink = RecordingSink::new();
|
|
let failing_sink = RecordingSink::failing_after_partial_write(1, partial_prefix_len);
|
|
let mut writer = IlpShardedWriter::new(
|
|
vec![
|
|
healthy_sink.clone(),
|
|
RecordingSink::new(),
|
|
failing_sink.clone(),
|
|
RecordingSink::new(),
|
|
],
|
|
IlpWriterOptions {
|
|
max_batch_bytes: 100_000,
|
|
max_batch_rows: 1,
|
|
},
|
|
)
|
|
.unwrap();
|
|
|
|
// First batch on shard 2 succeeds completely.
|
|
writer.write_bar_1m(&row1, known_at).unwrap();
|
|
|
|
// Second batch on shard 2 writes a partial prefix, then hits BrokenPipe.
|
|
let err = writer.write_bar_1m(&row2, known_at).unwrap_err();
|
|
assert!(matches!(err, IlpWriterError::Io { shard: 2, .. }));
|
|
|
|
let mut expected_captured = expected_row1.clone();
|
|
expected_captured.extend_from_slice(&expected_row2[..partial_prefix_len]);
|
|
assert_eq!(failing_sink.captured_bytes(), expected_captured);
|
|
|
|
// Subsequent writes (both on the failed shard and on another shard) and finish() are rejected,
|
|
// leaving all sink bytes frozen without replaying or appending anything.
|
|
assert!(matches!(
|
|
writer.write_bar_1m(&row2, known_at),
|
|
Err(IlpWriterError::Poisoned { failed_shard: 2 })
|
|
));
|
|
assert!(matches!(
|
|
writer.write_bar_1m(&other_row, known_at),
|
|
Err(IlpWriterError::Poisoned { failed_shard: 2 })
|
|
));
|
|
assert!(matches!(
|
|
writer.write_fx_1m(&sample_fx("USD.CAD", 100)),
|
|
Err(IlpWriterError::Poisoned { failed_shard: 2 })
|
|
));
|
|
assert!(matches!(
|
|
writer.finish(),
|
|
Err(IlpWriterError::Poisoned { failed_shard: 2 })
|
|
));
|
|
|
|
assert_eq!(failing_sink.captured_bytes(), expected_captured);
|
|
assert!(healthy_sink.captured_bytes().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn golden_bytes_literal_ieee754_little_endian_without_to_le_bytes() {
|
|
let row = Bar1mRow {
|
|
key: 7,
|
|
ts: 1_700_000_000_000_000,
|
|
session_date: 20_000,
|
|
open: 1.0,
|
|
high: 2.0,
|
|
low: 0.5,
|
|
close: 1.5,
|
|
volume: 0.0,
|
|
session: IntradaySession::Rth,
|
|
source: BARS_1M_SOURCE_EOD,
|
|
};
|
|
let mut actual = Vec::new();
|
|
encode_bar_1m(&mut actual, &row, 1_700_000_060_000_000).unwrap();
|
|
|
|
// Hand-written little-endian IEEE-754 bytes (no f64::to_le_bytes):
|
|
// 1.0 -> 00 00 00 00 00 00 f0 3f
|
|
// 2.0 -> 00 00 00 00 00 00 00 40
|
|
// 0.5 -> 00 00 00 00 00 00 e0 3f
|
|
// 1.5 -> 00 00 00 00 00 00 f8 3f
|
|
// 0.0 -> 00 00 00 00 00 00 00 00
|
|
let mut expected: Vec<u8> = Vec::new();
|
|
expected.extend_from_slice(b"bars_1m,listing_id=7,session=RTH,source=eod_unadj ");
|
|
expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f");
|
|
expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40");
|
|
expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f");
|
|
expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\x3f");
|
|
expected.extend_from_slice(b",volume==\x10\x00\x00\x00\x00\x00\x00\x00\x00");
|
|
expected.extend_from_slice(b",known_at=1700000060000000t 1700000000000000t\n");
|
|
|
|
assert_eq!(actual, expected);
|
|
}
|