T-212: M2.3t — Add --qm-financials-old merge and Option B --from-mongo streaming for M2 collections in curate-etl

This commit is contained in:
Studio 2026-12-05 18:33:29 -05:00
parent 58216f7820
commit 0caaac16a0
9 changed files with 1588 additions and 137 deletions

View file

@ -0,0 +1,808 @@
//! Shared bounded-memory external sort and k-way merge for 1-minute bar runners
//! (`run_curate_bars_1m` and `run_curate_qm_bars_1m`).
//!
//! # Memory Bound & Determinism
//! - Decoded bars are validated and mapped to `(is_mapped, listing_id, ts, key_id)` immediately
//! into a fixed-size `CompactBar1mRecord` buffer (64 bytes/row in RAM, 62 bytes/row on disk).
//! - Whenever the in-memory run buffer reaches `max_run_rows` (default `2_000_000` rows ≈ 128 MiB),
//! it is sorted in place and spilled to an exclusively created binary run file
//! (`.<prefix>.sort-run-<run_id>-<seq>.tmp`, never BSON) guarded by [`StagingFileGuard`].
//! - At EOF:
//! - If no run spilled, the in-memory buffer is sorted once and merged with zero disk I/O.
//! - If runs spilled, the sort buffer and key-interner map are freed before k-way merging at most
//! `max_merge_fan_in` (default `64`) run files at once (`~4 MiB` read buffers), using multi-pass
//! merges when `runs.len() > max_merge_fan_in` so file descriptors and RAM remain strictly
//! bounded even on 3.40B+ row backfills.
//! - Because every `(key_id, ts)` deterministically maps to one `Option<listing_id>` (via Eastern
//! Time `session_date`), sorting by `(is_mapped, listing_id, ts, key_id)` guarantees that all
//! same-key duplicates sit contiguously inside each `(is_mapped, listing_id, ts)` group, allowing
//! exact Stage-B same-key deduplication, listing-keyed split un-adjustment, and Stage-C
//! cross-`source_id` collision resolution in a single streaming merge pass.
use std::cmp::{Ordering, Reverse};
use std::collections::{BinaryHeap, HashMap};
use std::fs::{File, OpenOptions};
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use crate::bars_1m::{Bar1mRow, Bars1mStats, IntradaySession};
use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteReport};
use crate::ilp::{IlpShardedWriter, IlpWriterError};
use crate::parquet_publish::{next_run_id, StagingFileGuard};
use crate::provider_mapping::ProviderMappingTable;
use crate::session_close::utc_micros_to_et_local;
use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable};
/// Fixed on-disk binary record size for spilled sorted runs (zero padding, little-endian).
pub(crate) const COMPACT_BAR_RECORD_BYTES: usize = 62;
/// Default maximum rows buffered in RAM per sorted run (`2_000_000 * 64 B ≈ 128 MiB`).
pub(crate) const DEFAULT_SORT_RUN_MAX_ROWS: usize = 2_000_000;
/// Default maximum number of run files opened simultaneously during a k-way merge pass.
pub(crate) const DEFAULT_MERGE_FAN_IN: usize = 64;
/// Per-run buffered I/O capacity during spill and k-way merge (`64 KiB`).
const RUN_IO_BUF_BYTES: usize = 64 * 1024;
/// Configuration for [`Bars1mExternalSorter`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Bars1mSortConfig {
/// Directory for temporary binary run files when spilling (`None` falls back to `std::env::temp_dir()`).
pub spill_dir: Option<PathBuf>,
/// Filename prefix for temporary run files (e.g. `"bars_1m"` or `"bars_1m_qm"`).
pub spill_prefix: &'static str,
/// Maximum validated records held in RAM before spilling a sorted run.
pub max_run_rows: usize,
/// Maximum run files opened simultaneously per k-way merge pass (`>= 2`).
pub max_merge_fan_in: usize,
}
impl Bars1mSortConfig {
pub(crate) fn new(spill_dir: Option<PathBuf>, spill_prefix: &'static str) -> Self {
Self {
spill_dir,
spill_prefix,
max_run_rows: DEFAULT_SORT_RUN_MAX_ROWS,
max_merge_fan_in: DEFAULT_MERGE_FAN_IN,
}
}
}
/// Typed error returned by [`Bars1mExternalSorter`].
#[derive(Debug)]
pub(crate) enum Bars1mExternalSortError {
Io { path: PathBuf, source: io::Error },
Ilp(IlpWriterError),
}
/// Diagnostic summary of external-sort execution (used by tests to verify bounded memory/spilling).
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct ExternalSortMetrics {
pub peak_buffer_rows: usize,
pub runs_spilled: usize,
pub merge_passes: usize,
}
/// Output of [`Bars1mExternalSorter::finish_and_write`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct ExternalSortWriteOutcome {
pub write_report: CurateBars1mWriteReport,
#[allow(dead_code)]
pub metrics: ExternalSortMetrics,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct CompactBar1mRecord {
/// `0` = unmapped, `1` = mapped to `listing_id`.
is_mapped: u8,
/// `0` = Pre, `1` = Rth, `2` = Post.
session: u8,
listing_id: i32,
ts: i64,
key_id: u32,
session_date: i32,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
}
impl CompactBar1mRecord {
#[inline]
fn sort_key(&self) -> (u8, i32, i64, u32) {
(self.is_mapped, self.listing_id, self.ts, self.key_id)
}
#[inline]
fn values_bit_eq(&self, other: &Self) -> bool {
self.open.to_bits() == other.open.to_bits()
&& self.high.to_bits() == other.high.to_bits()
&& self.low.to_bits() == other.low.to_bits()
&& self.close.to_bits() == other.close.to_bits()
&& self.volume.to_bits() == other.volume.to_bits()
}
#[inline]
fn intraday_session(self) -> IntradaySession {
match self.session {
0 => IntradaySession::Pre,
1 => IntradaySession::Rth,
_ => IntradaySession::Post,
}
}
#[inline]
fn encode_to(&self, buf: &mut [u8; COMPACT_BAR_RECORD_BYTES]) {
buf[0] = self.is_mapped;
buf[1] = self.session;
buf[2..6].copy_from_slice(&self.listing_id.to_le_bytes());
buf[6..14].copy_from_slice(&self.ts.to_le_bytes());
buf[14..18].copy_from_slice(&self.key_id.to_le_bytes());
buf[18..22].copy_from_slice(&self.session_date.to_le_bytes());
buf[22..30].copy_from_slice(&self.open.to_le_bytes());
buf[30..38].copy_from_slice(&self.high.to_le_bytes());
buf[38..46].copy_from_slice(&self.low.to_le_bytes());
buf[46..54].copy_from_slice(&self.close.to_le_bytes());
buf[54..62].copy_from_slice(&self.volume.to_le_bytes());
}
#[inline]
fn decode_from(buf: &[u8; COMPACT_BAR_RECORD_BYTES]) -> Self {
Self {
is_mapped: buf[0],
session: buf[1],
listing_id: i32::from_le_bytes(buf[2..6].try_into().unwrap()),
ts: i64::from_le_bytes(buf[6..14].try_into().unwrap()),
key_id: u32::from_le_bytes(buf[14..18].try_into().unwrap()),
session_date: i32::from_le_bytes(buf[18..22].try_into().unwrap()),
open: f64::from_le_bytes(buf[22..30].try_into().unwrap()),
high: f64::from_le_bytes(buf[30..38].try_into().unwrap()),
low: f64::from_le_bytes(buf[38..46].try_into().unwrap()),
close: f64::from_le_bytes(buf[46..54].try_into().unwrap()),
volume: f64::from_le_bytes(buf[54..62].try_into().unwrap()),
}
}
}
struct SpilledRun {
path: PathBuf,
_guard: StagingFileGuard,
record_count: u64,
}
struct RunReader {
path: PathBuf,
reader: BufReader<File>,
remaining: u64,
}
impl RunReader {
fn open(run: &SpilledRun) -> Result<Self, Bars1mExternalSortError> {
let file = File::open(&run.path).map_err(|source| Bars1mExternalSortError::Io {
path: run.path.clone(),
source,
})?;
Ok(Self {
path: run.path.clone(),
reader: BufReader::with_capacity(RUN_IO_BUF_BYTES, file),
remaining: run.record_count,
})
}
fn read_next(&mut self) -> Result<Option<CompactBar1mRecord>, Bars1mExternalSortError> {
if self.remaining == 0 {
return Ok(None);
}
let mut buf = [0u8; COMPACT_BAR_RECORD_BYTES];
self.reader
.read_exact(&mut buf)
.map_err(|source| Bars1mExternalSortError::Io {
path: self.path.clone(),
source,
})?;
self.remaining -= 1;
Ok(Some(CompactBar1mRecord::decode_from(&buf)))
}
}
struct HeapEntry {
record: CompactBar1mRecord,
run_idx: usize,
}
impl PartialEq for HeapEntry {
fn eq(&self, other: &Self) -> bool {
self.record.sort_key() == other.record.sort_key() && self.run_idx == other.run_idx
}
}
impl Eq for HeapEntry {}
impl PartialOrd for HeapEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for HeapEntry {
fn cmp(&self, other: &Self) -> Ordering {
self.record
.sort_key()
.cmp(&other.record.sort_key())
.then_with(|| self.run_idx.cmp(&other.run_idx))
}
}
#[inline]
fn is_valid_price(price: f64) -> bool {
price.is_finite() && price > 0.0
}
#[inline]
fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool {
high >= low && open >= low && open <= high && close >= low && close <= high
}
#[inline]
fn increment_builder_session_count(stats: &mut Bars1mStats, session: IntradaySession) {
match session {
IntradaySession::Pre => stats.pre_rows_out += 1,
IntradaySession::Rth => stats.rth_rows_out += 1,
IntradaySession::Post => stats.post_rows_out += 1,
}
}
#[inline]
fn bar_1m_values_bit_eq(a: &Bar1mRow<i32>, b: &Bar1mRow<i32>) -> 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()
&& a.volume.to_bits() == b.volume.to_bits()
&& a.session == b.session
}
fn create_exclusive_spill_file(
dir: &Path,
prefix: &str,
run_id: &str,
seq: u64,
) -> Result<(PathBuf, File), Bars1mExternalSortError> {
for attempt in 0..1024u32 {
let file_name = if attempt == 0 {
format!(".{prefix}.sort-run-{run_id}-{seq:06}.tmp")
} else {
format!(".{prefix}.sort-run-{run_id}-{seq:06}.{attempt}.tmp")
};
let path = dir.join(file_name);
match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => return Ok((path, file)),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(source) => return Err(Bars1mExternalSortError::Io { path, source }),
}
}
let path = dir.join(format!(".{prefix}.sort-run-{run_id}-{seq:06}.tmp"));
Err(Bars1mExternalSortError::Io {
path,
source: io::Error::new(
io::ErrorKind::AlreadyExists,
"exhausted unique sort-run spill filenames",
),
})
}
fn merge_runs_to_spill(
runs: &[SpilledRun],
spill_dir: &Path,
spill_prefix: &str,
run_id: &str,
seq: u64,
) -> Result<SpilledRun, Bars1mExternalSortError> {
let mut readers = Vec::with_capacity(runs.len());
let mut heap: BinaryHeap<Reverse<HeapEntry>> = BinaryHeap::with_capacity(runs.len());
for (run_idx, run) in runs.iter().enumerate() {
let mut reader = RunReader::open(run)?;
if let Some(record) = reader.read_next()? {
heap.push(Reverse(HeapEntry { record, run_idx }));
}
readers.push(reader);
}
let (out_path, out_file) = create_exclusive_spill_file(spill_dir, spill_prefix, run_id, seq)?;
let guard = StagingFileGuard::new(out_path.clone());
let mut writer = BufWriter::with_capacity(RUN_IO_BUF_BYTES, out_file);
let mut rec_buf = [0u8; COMPACT_BAR_RECORD_BYTES];
let mut record_count = 0u64;
while let Some(Reverse(HeapEntry { record, run_idx })) = heap.pop() {
record.encode_to(&mut rec_buf);
writer
.write_all(&rec_buf)
.map_err(|source| Bars1mExternalSortError::Io {
path: out_path.clone(),
source,
})?;
record_count += 1;
if let Some(next_rec) = readers[run_idx].read_next()? {
heap.push(Reverse(HeapEntry {
record: next_rec,
run_idx,
}));
}
}
writer.flush().map_err(|source| Bars1mExternalSortError::Io {
path: out_path.clone(),
source,
})?;
drop(writer);
Ok(SpilledRun {
path: out_path,
_guard: guard,
record_count,
})
}
struct GroupMerger<'a> {
curate_stats: CurateBars1mStats,
rows_written: usize,
key_had_row_out: Vec<bool>,
last_listing_id: Option<i32>,
current_group_key: Option<(u8, i32, i64)>,
current_group: Vec<CompactBar1mRecord>,
listing_survivors: Vec<Bar1mRow<i32>>,
listing_splits: Option<&'a SplitTable<i32>>,
source: &'static str,
known_at_micros: i64,
}
impl<'a> GroupMerger<'a> {
fn new(
builder_stats: Bars1mStats,
num_keys: usize,
listing_splits: Option<&'a SplitTable<i32>>,
source: &'static str,
known_at_micros: i64,
) -> Self {
Self {
curate_stats: CurateBars1mStats {
builder: builder_stats,
..CurateBars1mStats::default()
},
rows_written: 0,
key_had_row_out: vec![false; num_keys],
last_listing_id: None,
current_group_key: None,
current_group: Vec::new(),
listing_survivors: Vec::new(),
listing_splits,
source,
known_at_micros,
}
}
fn push<W: Write + Send>(
&mut self,
record: CompactBar1mRecord,
writer: &mut IlpShardedWriter<W>,
) -> Result<(), Bars1mExternalSortError> {
let gk = (record.is_mapped, record.listing_id, record.ts);
if self.current_group_key != Some(gk) {
self.flush_group(writer)?;
self.current_group_key = Some(gk);
}
self.current_group.push(record);
Ok(())
}
fn flush_group<W: Write + Send>(
&mut self,
writer: &mut IlpShardedWriter<W>,
) -> Result<(), Bars1mExternalSortError> {
if self.current_group.is_empty() {
return Ok(());
}
let (is_mapped, listing_id, ts) = self.current_group_key.unwrap();
self.listing_survivors.clear();
let len = self.current_group.len();
let mut i = 0usize;
while i < len {
let key_id = self.current_group[i].key_id;
let sub_start = i;
i += 1;
while i < len && self.current_group[i].key_id == key_id {
i += 1;
}
let sub_len = i - sub_start;
let first = self.current_group[sub_start];
let all_identical = self.current_group[sub_start + 1..i]
.iter()
.all(|other| first.values_bit_eq(other));
if !all_identical {
self.curate_stats.builder.duplicate_conflict_dropped += sub_len;
continue;
}
self.curate_stats.builder.duplicate_collapsed += sub_len - 1;
let session = first.intraday_session();
if is_mapped == 0 {
self.curate_stats.builder.rows_out += 1;
increment_builder_session_count(&mut self.curate_stats.builder, session);
self.curate_stats.rows_in += 1;
self.curate_stats.dropped_unmapped += 1;
self.key_had_row_out[key_id as usize] = true;
continue;
}
let (open, high, low, close, volume) = if let Some(splits) = self.listing_splits {
let factor = splits.cum_factor_after(&listing_id, first.session_date);
if factor != 1.0 {
let mut unadj = unadjust_ohlcv(
OhlcvBar {
open: first.open,
high: first.high,
low: first.low,
close: first.close,
volume: first.volume,
},
factor,
);
if !is_valid_price(unadj.open)
|| !is_valid_price(unadj.high)
|| !is_valid_price(unadj.low)
|| !is_valid_price(unadj.close)
{
self.curate_stats.builder.dropped_invalid_ohlc += 1;
continue;
}
if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) {
self.curate_stats.builder.dropped_inconsistent_ohlc += 1;
continue;
}
if !unadj.volume.is_finite()
|| unadj.volume < 0.0
|| (first.volume > 0.0 && unadj.volume == 0.0)
{
self.curate_stats.builder.dropped_invalid_volume += 1;
continue;
}
if unadj.volume == 0.0 {
unadj.volume = 0.0;
}
(unadj.open, unadj.high, unadj.low, unadj.close, unadj.volume)
} else {
(first.open, first.high, first.low, first.close, first.volume)
}
} else {
(first.open, first.high, first.low, first.close, first.volume)
};
self.curate_stats.builder.rows_out += 1;
increment_builder_session_count(&mut self.curate_stats.builder, session);
self.curate_stats.rows_in += 1;
self.key_had_row_out[key_id as usize] = true;
self.listing_survivors.push(Bar1mRow {
key: listing_id,
ts,
session_date: first.session_date,
open,
high,
low,
close,
volume,
session,
source: self.source,
});
}
if !self.listing_survivors.is_empty() {
let retain = if self.listing_survivors.len() == 1 {
true
} else {
let first = &self.listing_survivors[0];
let all_identical = self.listing_survivors[1..]
.iter()
.all(|other| bar_1m_values_bit_eq(first, other));
if all_identical {
self.curate_stats.listing_collision_collapsed +=
self.listing_survivors.len() - 1;
true
} else {
self.curate_stats.listing_collision_dropped += self.listing_survivors.len();
false
}
};
if retain {
let row = &self.listing_survivors[0];
writer
.write_bar_1m(row, self.known_at_micros)
.map_err(Bars1mExternalSortError::Ilp)?;
self.rows_written += 1;
self.curate_stats.rows_out += 1;
if self.last_listing_id != Some(listing_id) {
self.curate_stats.listings_out += 1;
self.last_listing_id = Some(listing_id);
}
match row.session {
IntradaySession::Pre => self.curate_stats.pre_rows_out += 1,
IntradaySession::Rth => self.curate_stats.rth_rows_out += 1,
IntradaySession::Post => self.curate_stats.post_rows_out += 1,
}
}
self.listing_survivors.clear();
}
self.current_group.clear();
Ok(())
}
fn finish<W: Write + Send>(
mut self,
writer: &mut IlpShardedWriter<W>,
) -> Result<CurateBars1mWriteReport, Bars1mExternalSortError> {
self.flush_group(writer)?;
self.curate_stats.builder.keys_out = self.key_had_row_out.iter().filter(|&&b| b).count();
Ok(CurateBars1mWriteReport {
curate_stats: self.curate_stats,
rows_written: self.rows_written,
})
}
}
/// Bounded-memory external sorter/merger shared by `bars_1m` and `bars_1m_qm` runners.
pub(crate) struct Bars1mExternalSorter<'a> {
mapping: &'a ProviderMappingTable,
mapping_source: &'a str,
config: Bars1mSortConfig,
run_id: String,
next_spill_seq: u64,
key_ids: HashMap<String, u32>,
buffer: Vec<CompactBar1mRecord>,
runs: Vec<SpilledRun>,
builder_stats: Bars1mStats,
metrics: ExternalSortMetrics,
}
impl<'a> Bars1mExternalSorter<'a> {
pub(crate) fn new(
mapping: &'a ProviderMappingTable,
mapping_source: &'a str,
mut config: Bars1mSortConfig,
) -> Self {
config.max_run_rows = config.max_run_rows.max(1);
config.max_merge_fan_in = config.max_merge_fan_in.max(2);
Self {
mapping,
mapping_source,
config,
run_id: next_run_id(),
next_spill_seq: 0,
key_ids: HashMap::new(),
buffer: Vec::new(),
runs: Vec::new(),
builder_stats: Bars1mStats::default(),
metrics: ExternalSortMetrics::default(),
}
}
fn effective_spill_dir(&self) -> PathBuf {
self.config
.spill_dir
.clone()
.unwrap_or_else(std::env::temp_dir)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn push_raw(
&mut self,
source_key: &str,
ts: i64,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
) -> Result<(), Bars1mExternalSortError> {
self.builder_stats.bars_in += 1;
if !is_valid_price(open)
|| !is_valid_price(high)
|| !is_valid_price(low)
|| !is_valid_price(close)
{
self.builder_stats.dropped_invalid_ohlc += 1;
return Ok(());
}
if !is_consistent_ohlc(open, high, low, close) {
self.builder_stats.dropped_inconsistent_ohlc += 1;
return Ok(());
}
if !volume.is_finite() || volume < 0.0 {
self.builder_stats.dropped_invalid_volume += 1;
return Ok(());
}
let Ok(et_local) = utc_micros_to_et_local(ts) else {
self.builder_stats.dropped_ts_out_of_range += 1;
return Ok(());
};
let volume = if volume == 0.0 { 0.0 } else { volume };
let session = match IntradaySession::from_et_minute(et_local.minute_of_day) {
IntradaySession::Pre => 0u8,
IntradaySession::Rth => 1u8,
IntradaySession::Post => 2u8,
};
let (is_mapped, listing_id) =
match self
.mapping
.resolve(self.mapping_source, source_key, et_local.session_date)
{
Some(id) => (1u8, id),
None => (0u8, 0i32),
};
let key_id = if let Some(&id) = self.key_ids.get(source_key) {
id
} else {
let id = u32::try_from(self.key_ids.len()).map_err(|_| Bars1mExternalSortError::Io {
path: self.effective_spill_dir(),
source: io::Error::other("exceeded u32::MAX distinct intraday source keys"),
})?;
self.key_ids.insert(source_key.to_owned(), id);
id
};
self.buffer.push(CompactBar1mRecord {
is_mapped,
session,
listing_id,
ts,
key_id,
session_date: et_local.session_date,
open,
high,
low,
close,
volume,
});
if self.buffer.len() > self.metrics.peak_buffer_rows {
self.metrics.peak_buffer_rows = self.buffer.len();
}
if self.buffer.len() >= self.config.max_run_rows {
self.spill_buffer()?;
}
Ok(())
}
fn spill_buffer(&mut self) -> Result<(), Bars1mExternalSortError> {
if self.buffer.is_empty() {
return Ok(());
}
self.buffer.sort_unstable_by_key(CompactBar1mRecord::sort_key);
let spill_dir = self.effective_spill_dir();
let seq = self.next_spill_seq;
self.next_spill_seq += 1;
let (path, file) =
create_exclusive_spill_file(&spill_dir, self.config.spill_prefix, &self.run_id, seq)?;
let guard = StagingFileGuard::new(path.clone());
let mut writer = BufWriter::with_capacity(RUN_IO_BUF_BYTES, file);
let mut rec_buf = [0u8; COMPACT_BAR_RECORD_BYTES];
for rec in &self.buffer {
rec.encode_to(&mut rec_buf);
writer
.write_all(&rec_buf)
.map_err(|source| Bars1mExternalSortError::Io {
path: path.clone(),
source,
})?;
}
writer
.flush()
.map_err(|source| Bars1mExternalSortError::Io {
path: path.clone(),
source,
})?;
drop(writer);
self.runs.push(SpilledRun {
path,
_guard: guard,
record_count: self.buffer.len() as u64,
});
self.metrics.runs_spilled += 1;
self.buffer.clear();
Ok(())
}
pub(crate) fn finish_and_write<W: Write + Send>(
mut self,
listing_splits: Option<&SplitTable<i32>>,
source: &'static str,
writer: &mut IlpShardedWriter<W>,
known_at_micros: i64,
) -> Result<ExternalSortWriteOutcome, Bars1mExternalSortError> {
let num_keys = self.key_ids.len();
drop(self.key_ids);
let mut merger = GroupMerger::new(
self.builder_stats,
num_keys,
listing_splits,
source,
known_at_micros,
);
if self.runs.is_empty() {
self.buffer.sort_unstable_by_key(CompactBar1mRecord::sort_key);
for rec in self.buffer {
merger.push(rec, writer)?;
}
let write_report = merger.finish(writer)?;
return Ok(ExternalSortWriteOutcome {
write_report,
metrics: self.metrics,
});
}
if !self.buffer.is_empty() {
self.spill_buffer()?;
}
// Release the in-memory sort buffer before opening k-way merge readers.
self.buffer = Vec::new();
let spill_dir = self.effective_spill_dir();
let fan_in = self.config.max_merge_fan_in;
while self.runs.len() > fan_in {
let batch: Vec<SpilledRun> = self.runs.drain(..fan_in).collect();
let seq = self.next_spill_seq;
self.next_spill_seq += 1;
let merged = merge_runs_to_spill(
&batch,
&spill_dir,
self.config.spill_prefix,
&self.run_id,
seq,
)?;
// Dropping `batch` unlinks its consumed temporary run files immediately.
drop(batch);
self.runs.push(merged);
self.metrics.merge_passes += 1;
}
let mut readers = Vec::with_capacity(self.runs.len());
let mut heap: BinaryHeap<Reverse<HeapEntry>> = BinaryHeap::with_capacity(self.runs.len());
for (run_idx, run) in self.runs.iter().enumerate() {
let mut reader = RunReader::open(run)?;
if let Some(record) = reader.read_next()? {
heap.push(Reverse(HeapEntry { record, run_idx }));
}
readers.push(reader);
}
self.metrics.merge_passes += 1;
while let Some(Reverse(HeapEntry { record, run_idx })) = heap.pop() {
merger.push(record, writer)?;
if let Some(next_rec) = readers[run_idx].read_next()? {
heap.push(Reverse(HeapEntry {
record: next_rec,
run_idx,
}));
}
}
let write_report = merger.finish(writer)?;
Ok(ExternalSortWriteOutcome {
write_report,
metrics: self.metrics,
})
}
}

View file

@ -492,6 +492,7 @@ where
/// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022
/// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation
/// invariants and cross-`source_id` collision handling.
#[cfg(test)]
pub(crate) fn curate_and_write_bars_1m_by_listing<W, K, B>(
bars: B,
listing_splits: &SplitTable<i32>,

View file

@ -639,36 +639,69 @@ where
continue;
}
let linked_micros = filing_index
.get(&(obs.key.clone(), obs.fiscal_period))
.and_then(|bucket| match obs.report_date {
Some(rd) => {
// Earliest matching periodic filing (amended or unamended) on Eastern day `rd`.
// `rd > obs.period_end` is guaranteed by validation above.
let pos = bucket.partition_point(|f| f.et_date < rd);
bucket
.get(pos)
.filter(|f| f.et_date == rd)
.map(|f| f.utc_micros)
}
None if obs.is_legacy => {
// Never treat an undated legacy observation as filing-backed without a
// `report_date` linking it to the inferred filing.
None
}
None => {
// Earliest matching non-amended periodic filing strictly after `period_end`
// and within the inclusive calendar-day inference window.
let (linked_micros, legacy_filing_lower_bound_micros) = if obs.is_legacy
&& obs.report_date.is_none()
{
// Never treat an undated legacy observation as filing-backed without a `report_date`
// linking it to the inferred filing, but still use any later plausible periodic filing
// (or in-window amendment) as a conservative lower bound on `known_at_utc_micros` so a
// late release is never exposed early at the statutory deadline.
let lower_bound = filing_index
.get(&(obs.key.clone(), obs.fiscal_period))
.and_then(|bucket| {
let window_end = i64::from(obs.period_end)
+ i64::from(obs.fiscal_period.undated_link_window_days());
let pos = bucket.partition_point(|f| f.et_date <= obs.period_end);
bucket[pos..]
let mut earliest_unamended: Option<i64> = None;
let mut latest_amendment: Option<i64> = None;
for f in bucket[pos..]
.iter()
.take_while(|f| i64::from(f.et_date) <= window_end)
.find(|f| !f.is_amendment)
.map(|f| f.utc_micros)
}
});
{
if f.is_amendment {
latest_amendment = Some(
latest_amendment.map_or(f.utc_micros, |m| m.max(f.utc_micros)),
);
} else if earliest_unamended.is_none() {
earliest_unamended = Some(f.utc_micros);
}
}
match (earliest_unamended, latest_amendment) {
(Some(u), Some(a)) => Some(u.max(a)),
(Some(u), None) => Some(u),
(None, Some(a)) => Some(a),
(None, None) => None,
}
});
(None, lower_bound)
} else {
let linked = filing_index
.get(&(obs.key.clone(), obs.fiscal_period))
.and_then(|bucket| match obs.report_date {
Some(rd) => {
// Earliest matching periodic filing (amended or unamended) on Eastern day
// `rd`. `rd > obs.period_end` is guaranteed by validation above.
let pos = bucket.partition_point(|f| f.et_date < rd);
bucket
.get(pos)
.filter(|f| f.et_date == rd)
.map(|f| f.utc_micros)
}
None => {
// Earliest matching non-amended periodic filing strictly after `period_end`
// and within the inclusive calendar-day inference window.
let window_end = i64::from(obs.period_end)
+ i64::from(obs.fiscal_period.undated_link_window_days());
let pos = bucket.partition_point(|f| f.et_date <= obs.period_end);
bucket[pos..]
.iter()
.take_while(|f| i64::from(f.et_date) <= window_end)
.find(|f| !f.is_amendment)
.map(|f| f.utc_micros)
}
});
(linked, None)
};
let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros {
(micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP)
@ -687,7 +720,7 @@ where
stats.observations_dropped_date_out_of_range += 1;
continue;
};
let Ok(micros) = et_to_utc_micros(
let Ok(lag_micros) = et_to_utc_micros(
lag_date,
FUNDAMENTALS_FALLBACK_HOUR_ET,
FUNDAMENTALS_FALLBACK_MINUTE_ET,
@ -696,6 +729,10 @@ where
stats.observations_dropped_date_out_of_range += 1;
continue;
};
let micros = match legacy_filing_lower_bound_micros {
Some(lb) => lag_micros.max(lb),
None => lag_micros,
};
(micros, KNOWN_AT_SOURCE_STATUTORY_LAG)
};

View file

@ -1445,3 +1445,96 @@ fn legacy_merge_restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwritin
assert_eq!(at_restated.periods[1].fields.revenue, Some(125.0));
assert_eq!(at_restated.ttm.as_ref().unwrap().flows.revenue, Some(465.0));
}
#[test]
fn undated_legacy_only_late_filing_bounds_availability_without_claiming_filing_backed() {
let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]);
let q2_23 = day(2023, 6, 30);
let q3_23 = day(2023, 9, 30);
let q4_23 = day(2023, 12, 31);
let q1_24 = day(2024, 3, 31);
// US/TSX quarterly statutory deadline for 2024-03-31 is 2024-05-15 (+45d),
// but the first matching 10-Q was filed late on 2024-05-29 (within the 75-day window).
let filings = vec![
filing("ACME", "2023-08-05T16:30:00 EDT", "10-Q"),
filing("ACME", "2023-11-05T16:30:00 EST", "10-Q"),
filing("ACME", "2024-02-20T16:30:00 EST", "10-Q"),
filing("ACME", "2024-05-29T16:30:00 EDT", "10-Q"),
];
let legacy = vec![
obs(
"ACME",
q2_23,
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 8, 5)),
fields_rev(90.0),
),
obs(
"ACME",
q3_23,
FiscalPeriod::Quarterly,
"USD",
Some(day(2023, 11, 5)),
fields_rev(100.0),
),
obs(
"ACME",
q4_23,
FiscalPeriod::Quarterly,
"USD",
Some(day(2024, 2, 20)),
fields_rev(110.0),
),
obs(
"ACME",
q1_24,
FiscalPeriod::Quarterly,
"USD",
None,
fields_rev(120.0),
),
];
let built = build_fundamentals_rows_with_legacy(Vec::new(), legacy, filings, &venues);
assert_reconciliation(&built);
assert_eq!(built.stats.observations_in, 4);
assert_eq!(built.stats.rows_out, 4);
assert_eq!(built.stats.rows_linked_to_filing, 3);
assert_eq!(built.stats.rows_statutory_lag_estimate, 1);
let q1_row = built
.rows
.iter()
.find(|r| r.period_end == q1_24)
.expect("Q1 row present");
let expected_late_filing_ts = utc_micros(2024, 5, 29, 20, 30, 0);
assert_eq!(q1_row.known_at_utc_micros, expected_late_filing_ts);
assert_eq!(q1_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG);
let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap();
// On May 20 (after the May 15 statutory deadline, before the May 29 late filing),
// Q1 must NOT be visible and 4-quarter TTM must not yet include Q1.
let at_may_20 = as_of(&snaps, "ACME", utc_micros(2024, 5, 20, 16, 0, 0))
.expect("May 20 snapshot exists from prior quarters");
assert_eq!(at_may_20.periods[0].period_end, q4_23);
assert!(at_may_20.periods.iter().all(|p| p.period_end != q1_24));
assert_eq!(at_may_20.ttm, None);
// At/after the May 29 late filing, Q1 and TTM become visible but remain marked estimated.
let at_may_30 = as_of(&snaps, "ACME", utc_micros(2024, 5, 30, 16, 0, 0))
.expect("May 30 snapshot");
assert_eq!(at_may_30.periods[0].period_end, q1_24);
assert_eq!(at_may_30.periods[0].fields.revenue, Some(120.0));
assert_eq!(
at_may_30.periods[0].known_at_source,
KNOWN_AT_SOURCE_STATUTORY_LAG
);
assert!(at_may_30.periods[0].has_estimated_lag);
let ttm = at_may_30.ttm.as_ref().expect("4-quarter TTM after late filing");
assert_eq!(ttm.flows.revenue, Some(420.0));
assert!(ttm.has_estimated_lag);
}

View file

@ -3,6 +3,7 @@
pub mod adj;
pub mod bars;
pub mod bars_1m;
pub(crate) mod bars_1m_sort;
pub mod bench;
pub mod bson_ceo_posts;
pub mod bson_ceo_shorts;

View file

@ -48,23 +48,22 @@
//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors
//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`].
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::ffi::OsStr;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use crate::bars_1m::EodIntradayBar;
use crate::bars_1m::BARS_1M_SOURCE_EOD;
use crate::bars_1m_sort::{
Bars1mExternalSortError, Bars1mExternalSorter, Bars1mSortConfig, ExternalSortMetrics,
};
use crate::bson_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecodeStats};
use crate::bson_qm_actions::BsonQmActionDecodeStats;
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
use crate::curate_bars_1m::{
curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError,
};
use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError};
use crate::ilp::{
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M,
};
@ -241,7 +240,6 @@ impl Error for RunCurateBars1mError {
struct LoadedReferenceInputs {
mapping: ProviderMappingTable,
eod_keys: HashSet<Arc<str>>,
splits: SplitTable<i32>,
splits_docs_framed: u64,
splits_bytes_read: u64,
@ -378,9 +376,7 @@ fn load_reference_inputs<RS: io::Read>(
let mapping_rows =
load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?;
let EodMappingIndex {
eod_keys,
eod_by_listing,
..
eod_by_listing, ..
} = build_eod_mapping_index(&mapping_rows, false);
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
@ -416,7 +412,6 @@ fn load_reference_inputs<RS: io::Read>(
Ok(LoadedReferenceInputs {
mapping,
eod_keys,
splits,
splits_docs_framed,
splits_bytes_read,
@ -425,17 +420,28 @@ fn load_reference_inputs<RS: io::Read>(
})
}
fn map_sort_error(err: Bars1mExternalSortError) -> RunCurateBars1mError {
match err {
Bars1mExternalSortError::Io { path, source } => RunCurateBars1mError::Io { path, source },
Bars1mExternalSortError::Ilp(err) => {
RunCurateBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(err))
}
}
}
fn stream_intraday_chunks_to_writer<RI, W>(
args: &CurateBars1mArgs,
reference: LoadedReferenceInputs,
intraday: RI,
mut writer: IlpShardedWriter<W>,
writer: IlpShardedWriter<W>,
sort_config: Bars1mSortConfig,
start: Instant,
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
) -> Result<(CurateBars1mRunReport, ExternalSortMetrics), RunCurateBars1mError>
where
RI: io::Read,
W: Write + Send,
{
let mut writer = writer;
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|source| RunCurateBars1mError::BsonStream {
label: "eod-intraday",
@ -448,10 +454,10 @@ where
let mut chunks: usize = 0;
let mut max_rows_per_chunk: usize = 0;
// Accumulate decoded bars across BSON chunks so global `(listing_id, ts)` ordering and
// duplicate/collision resolution are invariant to input document order and chunk boundaries.
let mut all_bars: Vec<EodIntradayBar<Arc<str>>> = Vec::new();
let mut unknown_keys: HashMap<String, Arc<str>> = HashMap::new();
// Bounded-memory external sort/merge resolves same-key duplicates and cross-source listing
// collisions globally across BSON chunks without retaining all rows in RAM.
let mut sorter =
Bars1mExternalSorter::new(&reference.mapping, &args.mapping_source, sort_config);
while let Some(chunk) =
reader
@ -462,63 +468,75 @@ where
source,
})?
{
let chunk_start = all_bars.len();
let mut chunk_rows = 0usize;
let mut spill_err: Option<Bars1mExternalSortError> = None;
let chunk_decode = decode_eod_intraday_buffer(
chunk.bytes,
|raw| {
let key = if let Some(existing) = reference.eod_keys.get(raw.eod_search_code) {
Arc::clone(existing)
} else if let Some(existing) = unknown_keys.get(raw.eod_search_code) {
Arc::clone(existing)
} else {
let arc: Arc<str> = Arc::from(raw.eod_search_code);
unknown_keys.insert(raw.eod_search_code.to_owned(), Arc::clone(&arc));
arc
};
all_bars.push(raw.into_eod_intraday_bar(|_, _| key));
if spill_err.is_some() {
return;
}
chunk_rows += 1;
if let Err(err) = sorter.push_raw(
raw.eod_search_code,
raw.ts,
raw.open,
raw.high,
raw.low,
raw.close,
raw.volume,
) {
spill_err = Some(err);
}
},
|_local_offset, _err| {},
);
if let Some(err) = spill_err {
return Err(map_sort_error(err));
}
intraday_decode += chunk_decode;
chunks += 1;
let chunk_len = all_bars.len() - chunk_start;
if chunk_len > max_rows_per_chunk {
max_rows_per_chunk = chunk_len;
if chunk_rows > max_rows_per_chunk {
max_rows_per_chunk = chunk_rows;
}
}
let write_report = curate_and_write_bars_1m_by_listing(
all_bars,
&reference.splits,
&reference.mapping,
&args.mapping_source,
&mut writer,
args.known_at_micros,
)
.map_err(RunCurateBars1mError::CurateWrite)?;
let intraday_docs_framed = reader.docs_framed();
let intraday_bytes_read = reader.bytes_read();
drop(reader);
let outcome = sorter
.finish_and_write(
Some(&reference.splits),
BARS_1M_SOURCE_EOD,
&mut writer,
args.known_at_micros,
)
.map_err(map_sort_error)?;
let write_report = outcome.write_report;
let ilp_stats = writer.finish().map_err(RunCurateBars1mError::Ilp)?;
Ok(CurateBars1mRunReport {
intraday_docs_framed,
intraday_bytes_read,
intraday_decode,
splits_docs_framed: reference.splits_docs_framed,
splits_bytes_read: reference.splits_bytes_read,
splits_decode: reference.splits_decode,
split_rekey: reference.split_rekey,
chunks,
max_rows_per_chunk,
curate_stats: write_report.curate_stats,
rows_written: write_report.rows_written,
ilp_stats,
shard_count: args.shard_count,
elapsed_secs: start.elapsed().as_secs_f64(),
})
Ok((
CurateBars1mRunReport {
intraday_docs_framed,
intraday_bytes_read,
intraday_decode,
splits_docs_framed: reference.splits_docs_framed,
splits_bytes_read: reference.splits_bytes_read,
splits_decode: reference.splits_decode,
split_rekey: reference.split_rekey,
chunks,
max_rows_per_chunk,
curate_stats: write_report.curate_stats,
rows_written: write_report.rows_written,
ilp_stats,
shard_count: args.shard_count,
elapsed_secs: start.elapsed().as_secs_f64(),
},
outcome.metrics,
))
}
/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary [`io::Read`] streams into a
@ -526,8 +544,8 @@ where
///
/// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits`
/// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] +
/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits,
/// and calls [`IlpShardedWriter::finish`] exactly once after EOF.
/// [`decode_eod_intraday_buffer`] into the bounded-memory external sorter/merger with listing-keyed
/// splits, and calls [`IlpShardedWriter::finish`] exactly once after EOF.
pub fn run_curate_bars_1m_with_readers<RI, RS, W>(
args: &CurateBars1mArgs,
intraday: RI,
@ -549,7 +567,10 @@ where
}
let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?;
stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)
let sort_config = Bars1mSortConfig::new(None, TABLE_BARS_1M);
let (report, _metrics) =
stream_intraday_chunks_to_writer(args, reference, intraday, writer, sort_config, start)?;
Ok(report)
}
/// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once
@ -720,12 +741,63 @@ where
}
let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?;
let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?;
let sort_config = Bars1mSortConfig::new(Some(args.out_dir.clone()), TABLE_BARS_1M);
let (report, _metrics) =
stream_intraday_chunks_to_writer(args, reference, intraday, writer, sort_config, start)?;
publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?;
Ok(report)
}
#[cfg(test)]
pub(crate) fn run_curate_bars_1m_from_readers_to_dir_with_sort_config<RI, RS>(
args: &CurateBars1mArgs,
intraday: RI,
splits: RS,
sort_config: Bars1mSortConfig,
) -> Result<(CurateBars1mRunReport, ExternalSortMetrics), RunCurateBars1mError>
where
RI: io::Read,
RS: io::Read,
{
let start = Instant::now();
validate_file_mode_args(args)?;
let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?;
fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateBars1mError::Io {
path: args.out_dir.clone(),
source,
})?;
let run_id = next_run_id();
let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count);
let mut sinks: Vec<SyncedBufFile> = Vec::with_capacity(args.shard_count);
for shard_idx in 0..args.shard_count {
let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table(
&args.out_dir,
TABLE_BARS_1M,
shard_idx,
&run_id,
)?;
let guard = StagingFileGuard::new(tmp_path.clone());
staged.push((tmp_path, guard));
sinks.push(SyncedBufFile::new(file));
}
let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?;
let (report, metrics) =
stream_intraday_chunks_to_writer(args, reference, intraday, writer, sort_config, start)?;
publish_staged_shards_for_table(
&args.out_dir,
TABLE_BARS_1M,
&mut staged,
|_shard_idx, _final_path| {},
)?;
Ok((report, metrics))
}
/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary raw-BSON [`io::Read`]
/// streams (such as read-only MongoDB cursors), running full directory preflight, exclusive `.tmp`
/// staging, atomic `hard_link` publication to `<out_dir>/bars_1m.shard-<NN>.ilp`, and rollback

View file

@ -1995,3 +1995,220 @@ fn qa_listing_split_applies_to_all_eod_aliases_of_the_listing() {
let oth = get(88, et_ts_sec(2025, 5, 20, 10, 0));
assert_eq!((oth.close, oth.volume), (20.5, 50.0));
}
#[test]
fn external_sort_multi_run_matches_single_run_byte_for_byte_across_reordered_collisions_and_splits()
{
let dir = TempDirGuard::new("bars1m-ext-sort-parity");
let mapping_path = write_mapping_tsv(
dir.path(),
&[
"eod\tA1.US\t2020-01-01\t\t10",
"eod\tA2.US\t2020-01-01\t\t10",
"qm\tAQ\t2020-01-01\t\t10",
"eod\tB.US\t2020-01-01\t\t20",
],
);
let splits_bytes = concat_docs(&[make_split_doc("AQ", "2024-06-10", 1.0, 2.0)]);
let t1 = et_ts_sec(2024, 6, 7, 9, 30);
let t2 = et_ts_sec(2024, 6, 7, 9, 31);
let t3 = et_ts_sec(2024, 6, 7, 9, 32);
let t4 = et_ts_sec(2024, 6, 7, 9, 33);
let docs = vec![
// Same-key identical duplicate (A1.US @ t1)
make_intraday_doc("A1.US", t1, 50.0, 51.0, 49.0, 50.5, 200.0),
make_intraday_doc("A1.US", t1, 50.0, 51.0, 49.0, 50.5, 200.0),
// Cross-source identical collision on listing 10 @ t1 (A2.US matches A1.US)
make_intraday_doc("A2.US", t1, 50.0, 51.0, 49.0, 50.5, 200.0),
// Cross-source conflicting collision on listing 10 @ t2 (both dropped)
make_intraday_doc("A1.US", t2, 51.0, 52.0, 50.0, 51.5, 100.0),
make_intraday_doc("A2.US", t2, 51.0, 52.0, 50.0, 51.75, 100.0),
// Same-key conflicting duplicate on B.US @ t3 (both dropped)
make_intraday_doc("B.US", t3, 20.0, 21.0, 19.0, 20.5, 50.0),
make_intraday_doc("B.US", t3, 20.0, 21.0, 19.0, 20.6, 50.0),
// Clean bar on B.US @ t4 + unmapped bar
make_intraday_doc("B.US", t4, 21.0, 22.0, 20.0, 21.5, 75.0),
make_intraday_doc("UNMAPPED.US", t1, 5.0, 6.0, 4.0, 5.5, 10.0),
make_intraday_doc("UNMAPPED.US", t1, 5.0, 6.0, 4.0, 5.5, 10.0),
];
let canonical_bytes = concat_docs(&docs);
let mut reversed_docs = docs.clone();
reversed_docs.reverse();
let reordered_bytes = concat_docs(&reversed_docs);
let out_ref = dir.path().join("out-ref");
let out_bounded = dir.path().join("out-bounded");
let ref_args = make_args(
mapping_path.clone(),
dir.path().join("qmSplits.bson"),
dir.path().join("eodIntraday1M.bson"),
out_ref.clone(),
2,
1_750_000_000_000_000,
BsonStreamOptions::default(),
);
let (ref_report, ref_metrics) = run_curate_bars_1m_from_readers_to_dir_with_sort_config(
&ref_args,
Cursor::new(&canonical_bytes),
Cursor::new(&splits_bytes),
Bars1mSortConfig {
spill_dir: Some(out_ref.clone()),
spill_prefix: TABLE_BARS_1M,
max_run_rows: 10_000,
max_merge_fan_in: 64,
},
)
.expect("single-run reference");
assert_report_conservation(&ref_report);
assert_eq!(ref_metrics.runs_spilled, 0);
let bounded_args = make_args(
mapping_path,
dir.path().join("qmSplits.bson"),
dir.path().join("eodIntraday1M.bson"),
out_bounded.clone(),
2,
1_750_000_000_000_000,
BsonStreamOptions {
chunk_capacity_bytes: 256,
max_doc_bytes: 1024 * 1024,
},
);
let (bounded_report, bounded_metrics) =
run_curate_bars_1m_from_readers_to_dir_with_sort_config(
&bounded_args,
Cursor::new(&reordered_bytes),
Cursor::new(&splits_bytes),
Bars1mSortConfig {
spill_dir: Some(out_bounded.clone()),
spill_prefix: TABLE_BARS_1M,
max_run_rows: 2,
max_merge_fan_in: 2,
},
)
.expect("bounded multi-run external sort");
assert_report_conservation(&bounded_report);
assert!(bounded_metrics.peak_buffer_rows <= 2);
assert!(bounded_metrics.runs_spilled >= 4);
assert!(bounded_metrics.merge_passes >= 2);
assert_eq!(bounded_report.curate_stats, ref_report.curate_stats);
assert_eq!(bounded_report.rows_written, ref_report.rows_written);
assert_eq!(bounded_report.ilp_stats, ref_report.ilp_stats);
assert_eq!(bounded_report.rows_written, 2);
assert_eq!(bounded_report.curate_stats.builder.duplicate_collapsed, 2);
assert_eq!(
bounded_report.curate_stats.builder.duplicate_conflict_dropped,
2
);
assert_eq!(bounded_report.curate_stats.listing_collision_collapsed, 1);
assert_eq!(bounded_report.curate_stats.listing_collision_dropped, 2);
assert_eq!(bounded_report.curate_stats.dropped_unmapped, 1);
let expected_names = vec![
"bars_1m.shard-00.ilp".to_string(),
"bars_1m.shard-01.ilp".to_string(),
];
assert_eq!(list_dir_names(&out_ref), expected_names);
assert_eq!(list_dir_names(&out_bounded), expected_names);
for name in &expected_names {
assert_eq!(
fs::read(out_bounded.join(name)).unwrap(),
fs::read(out_ref.join(name)).unwrap(),
"shard {name} must match byte-for-byte across external sort runs"
);
}
}
#[test]
fn external_sort_bounded_memory_on_representative_multi_symbol_backfill() {
let dir = TempDirGuard::new("bars1m-ext-sort-backfill");
let mut map_lines = Vec::new();
for sym in 0..10 {
map_lines.push(format!("eod\tSYM{sym}.US\t2020-01-01\t\t{}", 100 + sym));
}
let map_refs: Vec<&str> = map_lines.iter().map(String::as_str).collect();
let mapping_path = write_mapping_tsv(dir.path(), &map_refs);
let base_ts = et_ts_sec(2024, 6, 7, 9, 30);
let mut docs = Vec::with_capacity(4_000);
for minute in (0..400i64).rev() {
for sym in 0..10 {
let price = 10.0 + sym as f64 + (minute % 20) as f64 * 0.05;
docs.push(make_intraday_doc(
&format!("SYM{sym}.US"),
base_ts + minute * 60,
price,
price + 0.5,
price - 0.5,
price + 0.1,
100.0 + sym as f64,
));
}
}
let intraday_bytes = concat_docs(&docs);
let splits_bytes: Vec<u8> = Vec::new();
let out_ref = dir.path().join("out-ref");
let out_bounded = dir.path().join("out-bounded");
let (ref_report, _) = run_curate_bars_1m_from_readers_to_dir_with_sort_config(
&make_args(
mapping_path.clone(),
dir.path().join("qmSplits.bson"),
dir.path().join("eodIntraday1M.bson"),
out_ref.clone(),
2,
1_750_000_000_000_000,
BsonStreamOptions::default(),
),
Cursor::new(&intraday_bytes),
Cursor::new(&splits_bytes),
Bars1mSortConfig {
spill_dir: Some(out_ref.clone()),
spill_prefix: TABLE_BARS_1M,
max_run_rows: 100_000,
max_merge_fan_in: 64,
},
)
.expect("reference backfill");
let (bounded_report, metrics) = run_curate_bars_1m_from_readers_to_dir_with_sort_config(
&make_args(
mapping_path,
dir.path().join("qmSplits.bson"),
dir.path().join("eodIntraday1M.bson"),
out_bounded.clone(),
2,
1_750_000_000_000_000,
BsonStreamOptions::default(),
),
Cursor::new(&intraday_bytes),
Cursor::new(&splits_bytes),
Bars1mSortConfig {
spill_dir: Some(out_bounded.clone()),
spill_prefix: TABLE_BARS_1M,
max_run_rows: 250,
max_merge_fan_in: 4,
},
)
.expect("bounded backfill");
assert_report_conservation(&bounded_report);
assert_eq!(bounded_report.rows_written, 4_000);
assert!(metrics.peak_buffer_rows <= 250);
assert_eq!(metrics.runs_spilled, 16);
assert!(metrics.merge_passes >= 2);
assert_eq!(bounded_report.curate_stats, ref_report.curate_stats);
assert_eq!(bounded_report.ilp_stats, ref_report.ilp_stats);
for shard in 0..2 {
let name = format!("bars_1m.shard-{shard:02}.ilp");
assert_eq!(
fs::read(out_bounded.join(&name)).unwrap(),
fs::read(out_ref.join(&name)).unwrap(),
);
}
assert_eq!(list_dir_names(&out_bounded).len(), 2);
}

View file

@ -52,20 +52,20 @@
//! removes this run's staging files, and leaves pre-existing files untouched. Per-document
//! semantic decode errors stay counted-and-skipped in [`BsonQmIntradayDecodeStats`].
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use crate::bars_1m::EodIntradayBar;
use crate::bars_1m::BARS_1M_SOURCE_QM;
use crate::bars_1m_sort::{
Bars1mExternalSortError, Bars1mExternalSorter, Bars1mSortConfig, ExternalSortMetrics,
};
use crate::bson_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats};
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError};
use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m;
use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions};
use crate::parquet_bars::RollbackFailure;
use crate::parquet_publish::{next_run_id, StagingFileGuard};
@ -288,13 +288,23 @@ fn load_provider_mapping_table(
})
}
fn map_sort_error(err: Bars1mExternalSortError) -> RunCurateQmBars1mError {
match err {
Bars1mExternalSortError::Io { path, source } => RunCurateQmBars1mError::Io { path, source },
Bars1mExternalSortError::Ilp(err) => {
RunCurateQmBars1mError::CurateWrite(CurateBars1mWriteError::Ilp(err))
}
}
}
fn stream_qm_intraday_chunks_to_writer<R, W>(
args: &CurateQmBars1mArgs,
mapping: &ProviderMappingTable,
intraday: R,
mut writer: IlpShardedWriter<W>,
sort_config: Bars1mSortConfig,
start: Instant,
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
) -> Result<(CurateQmBars1mRunReport, ExternalSortMetrics), RunCurateQmBars1mError>
where
R: io::Read,
W: Write + Send,
@ -311,10 +321,9 @@ where
let mut chunks: usize = 0;
let mut max_rows_per_chunk: usize = 0;
// Accumulate decoded bars across BSON chunks so global `(listing_id, ts)` ordering and
// duplicate/collision resolution are invariant to input document order and chunk boundaries.
let mut all_bars: Vec<EodIntradayBar<Arc<str>>> = Vec::new();
let mut interned_keys: HashMap<String, Arc<str>> = HashMap::new();
// Bounded-memory external sort/merge resolves same-key duplicates and cross-source listing
// collisions globally across BSON chunks without retaining all rows in RAM.
let mut sorter = Bars1mExternalSorter::new(mapping, &args.mapping_source, sort_config);
while let Some(chunk) =
reader
@ -325,56 +334,66 @@ where
source,
})?
{
let chunk_start = all_bars.len();
let mut chunk_rows = 0usize;
let mut spill_err: Option<Bars1mExternalSortError> = None;
let chunk_decode = decode_qm_intraday_buffer(
chunk.bytes,
|raw| {
all_bars.push(raw.into_eod_intraday_bar(|key, _| {
if let Some(existing) = interned_keys.get(key) {
Arc::clone(existing)
} else {
let arc: Arc<str> = Arc::from(key);
interned_keys.insert(key.to_owned(), Arc::clone(&arc));
arc
}
}));
if spill_err.is_some() {
return;
}
chunk_rows += 1;
if let Err(err) = sorter.push_raw(
raw.qm_search_code,
raw.ts,
raw.open,
raw.high,
raw.low,
raw.close,
raw.volume,
) {
spill_err = Some(err);
}
},
|_local_offset, _err| {},
);
if let Some(err) = spill_err {
return Err(map_sort_error(err));
}
intraday_decode.merge(&chunk_decode);
chunks += 1;
let chunk_len = all_bars.len() - chunk_start;
if chunk_len > max_rows_per_chunk {
max_rows_per_chunk = chunk_len;
if chunk_rows > max_rows_per_chunk {
max_rows_per_chunk = chunk_rows;
}
}
let write_report = curate_and_write_qm_bars_1m(
all_bars,
mapping,
&args.mapping_source,
&mut writer,
args.known_at_micros,
)
.map_err(RunCurateQmBars1mError::CurateWrite)?;
let intraday_docs_framed = reader.docs_framed();
let intraday_bytes_read = reader.bytes_read();
drop(reader);
let outcome = sorter
.finish_and_write(None, BARS_1M_SOURCE_QM, &mut writer, args.known_at_micros)
.map_err(map_sort_error)?;
let write_report = outcome.write_report;
let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?;
Ok(CurateQmBars1mRunReport {
intraday_docs_framed,
intraday_bytes_read,
intraday_decode,
chunks,
max_rows_per_chunk,
curate_stats: write_report.curate_stats,
rows_written: write_report.rows_written,
ilp_stats,
shard_count: args.shard_count,
elapsed_secs: start.elapsed().as_secs_f64(),
})
Ok((
CurateQmBars1mRunReport {
intraday_docs_framed,
intraday_bytes_read,
intraday_decode,
chunks,
max_rows_per_chunk,
curate_stats: write_report.curate_stats,
rows_written: write_report.rows_written,
ilp_stats,
shard_count: args.shard_count,
elapsed_secs: start.elapsed().as_secs_f64(),
},
outcome.metrics,
))
}
/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary
@ -383,9 +402,9 @@ where
/// Validates `args` (rejecting blank `mapping_source` first, then `shard_count`, stream options,
/// and ILP options) and loads `provider_mapping.tsv` from `args.provider_mapping_path` before
/// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through
/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once
/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once
/// after clean EOF.
/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`] into the bounded-memory
/// external sorter/merger without split un-adjustment, and calls [`IlpShardedWriter::finish`]
/// exactly once after clean EOF.
pub fn run_curate_qm_bars_1m_with_readers<R, W, F>(
args: &CurateQmBars1mArgs,
intraday: R,
@ -408,7 +427,10 @@ where
let writer =
IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?;
stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
let sort_config = Bars1mSortConfig::new(None, QM_BARS_1M_SHARD_PREFIX);
let (report, _metrics) =
stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, sort_config, start)?;
Ok(report)
}
fn fail_with_staging_cleanup<RF>(
@ -503,9 +525,16 @@ where
));
}
};
let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
{
Ok(report) => report,
let sort_config = Bars1mSortConfig::new(Some(args.out_dir.clone()), QM_BARS_1M_SHARD_PREFIX);
let (report, _metrics) = match stream_qm_intraday_chunks_to_writer(
args,
&mapping,
intraday,
writer,
sort_config,
start,
) {
Ok(pair) => pair,
Err(err) => {
return Err(fail_with_staging_cleanup(
err,
@ -573,6 +602,93 @@ where
)
}
#[cfg(test)]
pub(crate) fn run_curate_qm_bars_1m_from_reader_to_dir_with_sort_config<R>(
args: &CurateQmBars1mArgs,
intraday: R,
sort_config: Bars1mSortConfig,
) -> Result<(CurateQmBars1mRunReport, ExternalSortMetrics), RunCurateQmBars1mError>
where
R: io::Read,
{
let start = Instant::now();
validate_file_mode_args(args)?;
let mapping = load_provider_mapping_table(&args.provider_mapping_path)?;
fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateQmBars1mError::Io {
path: args.out_dir.clone(),
source,
})?;
let run_id = next_run_id();
let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count);
let mut sinks: Vec<SyncedBufFile> = Vec::with_capacity(args.shard_count);
for shard_idx in 0..args.shard_count {
let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table(
&args.out_dir,
QM_BARS_1M_SHARD_PREFIX,
shard_idx,
&run_id,
) {
Ok(pair) => pair,
Err(err) => {
drop(sinks);
return Err(fail_with_staging_cleanup(
err.into(),
&mut staged,
&mut |path| fs::remove_file(path),
));
}
};
let guard = StagingFileGuard::new(tmp_path.clone());
staged.push((tmp_path, guard));
sinks.push(SyncedBufFile::new(file));
}
let writer = match IlpShardedWriter::new(sinks, args.ilp_options) {
Ok(writer) => writer,
Err(err) => {
return Err(fail_with_staging_cleanup(
RunCurateQmBars1mError::Ilp(err),
&mut staged,
&mut |path| fs::remove_file(path),
));
}
};
let (report, metrics) = match stream_qm_intraday_chunks_to_writer(
args,
&mapping,
intraday,
writer,
sort_config,
start,
) {
Ok(pair) => pair,
Err(err) => {
return Err(fail_with_staging_cleanup(
err,
&mut staged,
&mut |path| fs::remove_file(path),
));
}
};
if let Err(err) = publish_staged_shards_for_table(
&args.out_dir,
QM_BARS_1M_SHARD_PREFIX,
&mut staged,
|_shard_idx, _final_path| {},
) {
return Err(fail_with_staging_cleanup(
err.into(),
&mut staged,
&mut |path| fs::remove_file(path),
));
}
Ok((report, metrics))
}
/// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing
/// exactly `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`).
pub fn run_curate_qm_bars_1m(

View file

@ -1748,3 +1748,109 @@ fn doc_larger_than_chunk_capacity_succeeds_and_doc_over_max_doc_bytes_fails_clea
);
assert!(list_dir_names(&out_bad).is_empty());
}
#[test]
fn qm_external_sort_multi_run_matches_single_run_byte_for_byte_across_reordered_collisions() {
let dir = TempDirGuard::new("qmbars1m-ext-sort-parity");
let mapping_path = write_mapping_tsv(
dir.path(),
&[
"qm\tA1:US\t2020-01-01\t\t10",
"qm\tA2:US\t2020-01-01\t\t10",
"qm\tB:US\t2020-01-01\t\t20",
],
);
let t1 = et_ts_millis(2024, 6, 7, 9, 30);
let t2 = et_ts_millis(2024, 6, 7, 9, 31);
let t3 = et_ts_millis(2024, 6, 7, 9, 32);
let t4 = et_ts_millis(2024, 6, 7, 9, 33);
let docs = vec![
make_qm_intraday_doc("A1:US", t1, 50.0, 51.0, 49.0, 50.5, 200.0),
make_qm_intraday_doc("A1:US", t1, 50.0, 51.0, 49.0, 50.5, 200.0),
make_qm_intraday_doc("A2:US", t1, 50.0, 51.0, 49.0, 50.5, 200.0),
make_qm_intraday_doc("A1:US", t2, 51.0, 52.0, 50.0, 51.5, 100.0),
make_qm_intraday_doc("A2:US", t2, 51.0, 52.0, 50.0, 51.75, 100.0),
make_qm_intraday_doc("B:US", t3, 20.0, 21.0, 19.0, 20.5, 50.0),
make_qm_intraday_doc("B:US", t3, 20.0, 21.0, 19.0, 20.6, 50.0),
make_qm_intraday_doc("B:US", t4, 21.0, 22.0, 20.0, 21.5, 75.0),
make_qm_intraday_doc("UNMAPPED:US", t1, 5.0, 6.0, 4.0, 5.5, 10.0),
];
let canonical_bytes = concat_docs(&docs);
let mut reversed_docs = docs.clone();
reversed_docs.reverse();
let reordered_bytes = concat_docs(&reversed_docs);
let out_ref = dir.path().join("out-ref");
let out_bounded = dir.path().join("out-bounded");
let (ref_report, ref_metrics) = run_curate_qm_bars_1m_from_reader_to_dir_with_sort_config(
&make_args(
dir.path().join("qmIntraday.bson"),
mapping_path.clone(),
out_ref.clone(),
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
2,
1_750_000_000_000_000,
BsonStreamOptions::default(),
),
Cursor::new(&canonical_bytes),
Bars1mSortConfig {
spill_dir: Some(out_ref.clone()),
spill_prefix: QM_BARS_1M_SHARD_PREFIX,
max_run_rows: 10_000,
max_merge_fan_in: 64,
},
)
.expect("single-run QM reference");
assert_report_conservation(&ref_report);
assert_eq!(ref_metrics.runs_spilled, 0);
let (bounded_report, bounded_metrics) =
run_curate_qm_bars_1m_from_reader_to_dir_with_sort_config(
&make_args(
dir.path().join("qmIntraday.bson"),
mapping_path,
out_bounded.clone(),
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
2,
1_750_000_000_000_000,
BsonStreamOptions {
chunk_capacity_bytes: 256,
max_doc_bytes: 1024 * 1024,
},
),
Cursor::new(&reordered_bytes),
Bars1mSortConfig {
spill_dir: Some(out_bounded.clone()),
spill_prefix: QM_BARS_1M_SHARD_PREFIX,
max_run_rows: 2,
max_merge_fan_in: 2,
},
)
.expect("bounded multi-run QM external sort");
assert_report_conservation(&bounded_report);
assert!(bounded_metrics.peak_buffer_rows <= 2);
assert!(bounded_metrics.runs_spilled >= 4);
assert!(bounded_metrics.merge_passes >= 2);
assert_eq!(bounded_report.curate_stats, ref_report.curate_stats);
assert_eq!(bounded_report.rows_written, ref_report.rows_written);
assert_eq!(bounded_report.ilp_stats, ref_report.ilp_stats);
assert_eq!(bounded_report.rows_written, 2);
let expected_names = vec![
"bars_1m_qm.shard-00.ilp".to_string(),
"bars_1m_qm.shard-01.ilp".to_string(),
];
assert_eq!(list_dir_names(&out_ref), expected_names);
assert_eq!(list_dir_names(&out_bounded), expected_names);
for name in &expected_names {
assert_eq!(
fs::read(out_bounded.join(name)).unwrap(),
fs::read(out_ref.join(name)).unwrap(),
"QM shard {name} must match byte-for-byte across external sort runs"
);
}
}