T-179: M2.3k — tools/curate-etl: bounded-memory file-to-file bars_1m runner (run_curate_bars_1m.rs: raw eodIntraday1M BSON dump + qmSplits dump + provider_mapping.tsv → chunked curate_and_write_bars_1m → per-shard ILP v2 output files) with tests (no new crates, no CLI/bench changes, no live Mongo/QuestDB)
This commit is contained in:
parent
5bed33e084
commit
8aab31b9c2
5 changed files with 2290 additions and 105 deletions
|
|
@ -1667,6 +1667,14 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m
|
|||
- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number.
|
||||
- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up.
|
||||
|
||||
## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`)
|
||||
|
||||
`run_curate_bars_1m` / `run_curate_bars_1m_with_readers` (`src/run_curate_bars_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a headerless 5-column `provider_mapping.tsv` (reusing `load_provider_mapping_tsv` and the shared `qmSplits` loader from `src/run_curate_bars.rs`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`):
|
||||
|
||||
- **Bounded-memory chunking:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), calling `curate_and_write_bars_1m` once per framed chunk into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard.
|
||||
- **Cross-chunk semantics & reporting:** `mapping_source` must be `"eod"`. Collision collapse/drop and `(listing_id, ts)` ordering apply per chunk; the same `(listing_id, ts)` appearing in two chunks is emitted twice and relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. Aggregated `curate_stats.listings_out` and `curate_stats.builder.keys_out` are sums of per-chunk counts (not global distinct counts). `known_at_micros` is caller-supplied and supplies no evidence of earlier market availability.
|
||||
- **Fail-closed publication:** Rejects pre-existing `bars_1m.shard-<NN>.ilp` files before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. CLI wiring, `--from-mongo`, and live QuestDB ingestion are separate follow-ups.
|
||||
|
||||
## Lagged Macro Regime Series Builder (`M2.2n`)
|
||||
|
||||
`build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation<K>` inputs and a caller-supplied `(country_iso, indicator) -> Option<MacroLagClass>` lookup into sorted, unique `MacroRow<K>` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A).
|
||||
|
|
|
|||
|
|
@ -321,6 +321,13 @@ pub use run_curate_bars::{
|
|||
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_bars_1m;
|
||||
pub use run_curate_bars_1m::{
|
||||
format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_with_readers,
|
||||
CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError,
|
||||
DEFAULT_BARS_1M_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_adj;
|
||||
pub use run_curate_adj::{
|
||||
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
|
||||
|
|
|
|||
|
|
@ -516,12 +516,26 @@ struct LoadedCurateBarsInputs {
|
|||
buffered_bar_bytes: usize,
|
||||
}
|
||||
|
||||
struct EodListingRange {
|
||||
pub(crate) struct EodListingRange {
|
||||
valid_from: i32,
|
||||
valid_to: Option<i32>,
|
||||
key: Arc<str>,
|
||||
}
|
||||
|
||||
pub(crate) struct EodMappingIndex {
|
||||
pub(crate) eod_keys: HashSet<Arc<str>>,
|
||||
pub(crate) eod_by_listing: HashMap<i32, Vec<Arc<str>>>,
|
||||
pub(crate) eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>>,
|
||||
}
|
||||
|
||||
pub(crate) struct LoadedQmSplits {
|
||||
pub(crate) splits: SplitTable<Arc<str>>,
|
||||
pub(crate) splits_docs_framed: u64,
|
||||
pub(crate) splits_bytes_read: u64,
|
||||
pub(crate) splits_decode: BsonQmActionDecodeStats,
|
||||
pub(crate) split_rekey: SplitRekeyStats,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn valid_to_sort_key(valid_to: Option<i32>) -> (u8, i32) {
|
||||
match valid_to {
|
||||
|
|
@ -530,6 +544,139 @@ fn valid_to_sort_key(valid_to: Option<i32>) -> (u8, i32) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Builds the interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
||||
/// When `track_eod_ranges` is true, also builds a date-aware reverse index
|
||||
/// `listing_id -> [(valid_from, valid_to, Arc<str>)]` so reused EOD tickers never receive
|
||||
/// cross-check observations outside their mapping range.
|
||||
pub(crate) fn build_eod_mapping_index(
|
||||
mapping_rows: &[ProviderMappingRow],
|
||||
track_eod_ranges: bool,
|
||||
) -> EodMappingIndex {
|
||||
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
||||
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
|
||||
for row in mapping_rows {
|
||||
if row.source == "eod" {
|
||||
let key = match eod_keys.get(row.source_id.as_str()) {
|
||||
Some(existing) => Arc::clone(existing),
|
||||
None => {
|
||||
let arc: Arc<str> = Arc::from(row.source_id.as_str());
|
||||
eod_keys.insert(Arc::clone(&arc));
|
||||
arc
|
||||
}
|
||||
};
|
||||
if track_eod_ranges {
|
||||
eod_ranges_by_listing
|
||||
.entry(row.listing_id)
|
||||
.or_default()
|
||||
.push(EodListingRange {
|
||||
valid_from: row.valid_from,
|
||||
valid_to: row.valid_to,
|
||||
key: Arc::clone(&key),
|
||||
});
|
||||
}
|
||||
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
||||
}
|
||||
}
|
||||
for partners in eod_by_listing.values_mut() {
|
||||
partners.sort_unstable();
|
||||
partners.dedup();
|
||||
}
|
||||
for ranges in eod_ranges_by_listing.values_mut() {
|
||||
ranges.sort_unstable_by(|a, b| {
|
||||
a.valid_from
|
||||
.cmp(&b.valid_from)
|
||||
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
}
|
||||
EodMappingIndex {
|
||||
eod_keys,
|
||||
eod_by_listing,
|
||||
eod_ranges_by_listing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, compacts
|
||||
/// cross-key QM aliases per `(listing_id, ex_date)`, fans out to `"eod"` partners, and builds
|
||||
/// [`SplitTable<Arc<str>>`].
|
||||
pub(crate) fn load_qm_splits_from_reader<R: io::Read>(
|
||||
splits_stream: R,
|
||||
qm_splits_path: &Path,
|
||||
mapping: &ProviderMappingTable,
|
||||
eod_by_listing: &HashMap<i32, Vec<Arc<str>>>,
|
||||
) -> Result<LoadedQmSplits, RunCurateBarsError> {
|
||||
let mut splits_reader = RawBsonChunkReader::new(splits_stream);
|
||||
let mut split_rekey = SplitRekeyStats::default();
|
||||
let mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
if split.ratio == 1.0 {
|
||||
split_rekey.splits_noop_dropped += 1;
|
||||
return;
|
||||
}
|
||||
let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date)
|
||||
else {
|
||||
split_rekey.splits_unmapped_qm += 1;
|
||||
return;
|
||||
};
|
||||
let has_eod_partner = eod_by_listing
|
||||
.get(&listing_id)
|
||||
.is_some_and(|partners| !partners.is_empty());
|
||||
if !has_eod_partner {
|
||||
split_rekey.splits_no_eod_partner += 1;
|
||||
return;
|
||||
}
|
||||
mapped_splits.push(MappedQmSplit {
|
||||
listing_id,
|
||||
ex_date: split.ex_date,
|
||||
qm_key: split.qm_search_code.to_owned(),
|
||||
ratio: split.ratio,
|
||||
});
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::BsonStream {
|
||||
label: "qm-splits",
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let splits_docs_framed = splits_reader.docs_framed();
|
||||
let splits_bytes_read = splits_reader.bytes_read();
|
||||
split_rekey.splits_in = splits_decode.docs_in;
|
||||
|
||||
// Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys.
|
||||
let (compacted_splits, splits_collision_collapsed) =
|
||||
compact_mapped_qm_splits(qm_splits_path, mapped_splits)?;
|
||||
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
|
||||
|
||||
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
|
||||
for (listing_id, event) in compacted_splits {
|
||||
let partners = &eod_by_listing[&listing_id];
|
||||
split_rekey.splits_applied += 1;
|
||||
for eod_key in partners {
|
||||
split_events.push((Arc::clone(eod_key), event));
|
||||
}
|
||||
split_rekey.split_events_attached += partners.len();
|
||||
}
|
||||
|
||||
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
||||
RunCurateBarsError::SplitTable {
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(LoadedQmSplits {
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> {
|
||||
if out_dir.exists() && !out_dir.is_dir() {
|
||||
return Err(RunCurateBarsError::InvalidOutDir {
|
||||
|
|
@ -718,49 +865,11 @@ where
|
|||
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)?;
|
||||
let currencies = load_listing_currencies_tsv(listing_currencies_path)?;
|
||||
|
||||
// Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
||||
// When `--qm-prices` is provided, also build a date-aware reverse index
|
||||
// `listing_id -> [(valid_from, valid_to, Arc<str>)]` so reused EOD tickers never receive
|
||||
// cross-check observations outside their mapping range.
|
||||
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
||||
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
|
||||
let track_eod_ranges = qm_prices_path.is_some();
|
||||
for row in &mapping_rows {
|
||||
if row.source == "eod" {
|
||||
let key = match eod_keys.get(row.source_id.as_str()) {
|
||||
Some(existing) => Arc::clone(existing),
|
||||
None => {
|
||||
let arc: Arc<str> = Arc::from(row.source_id.as_str());
|
||||
eod_keys.insert(Arc::clone(&arc));
|
||||
arc
|
||||
}
|
||||
};
|
||||
if track_eod_ranges {
|
||||
eod_ranges_by_listing
|
||||
.entry(row.listing_id)
|
||||
.or_default()
|
||||
.push(EodListingRange {
|
||||
valid_from: row.valid_from,
|
||||
valid_to: row.valid_to,
|
||||
key: Arc::clone(&key),
|
||||
});
|
||||
}
|
||||
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
||||
}
|
||||
}
|
||||
for partners in eod_by_listing.values_mut() {
|
||||
partners.sort_unstable();
|
||||
partners.dedup();
|
||||
}
|
||||
for ranges in eod_ranges_by_listing.values_mut() {
|
||||
ranges.sort_unstable_by(|a, b| {
|
||||
a.valid_from
|
||||
.cmp(&b.valid_from)
|
||||
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
}
|
||||
let EodMappingIndex {
|
||||
eod_keys,
|
||||
eod_by_listing,
|
||||
eod_ranges_by_listing,
|
||||
} = build_eod_mapping_index(&mapping_rows, qm_prices_path.is_some());
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateBarsError::ProviderMapping {
|
||||
|
|
@ -771,67 +880,13 @@ where
|
|||
|
||||
// Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`.
|
||||
let splits_stream = open_splits()?;
|
||||
let mut splits_reader = RawBsonChunkReader::new(splits_stream);
|
||||
let mut split_rekey = SplitRekeyStats::default();
|
||||
let mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
if split.ratio == 1.0 {
|
||||
split_rekey.splits_noop_dropped += 1;
|
||||
return;
|
||||
}
|
||||
let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date)
|
||||
else {
|
||||
split_rekey.splits_unmapped_qm += 1;
|
||||
return;
|
||||
};
|
||||
let has_eod_partner = eod_by_listing
|
||||
.get(&listing_id)
|
||||
.is_some_and(|partners| !partners.is_empty());
|
||||
if !has_eod_partner {
|
||||
split_rekey.splits_no_eod_partner += 1;
|
||||
return;
|
||||
}
|
||||
mapped_splits.push(MappedQmSplit {
|
||||
listing_id,
|
||||
ex_date: split.ex_date,
|
||||
qm_key: split.qm_search_code.to_owned(),
|
||||
ratio: split.ratio,
|
||||
});
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::BsonStream {
|
||||
label: "qm-splits",
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let splits_docs_framed = splits_reader.docs_framed();
|
||||
let splits_bytes_read = splits_reader.bytes_read();
|
||||
split_rekey.splits_in = splits_decode.docs_in;
|
||||
|
||||
// Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys.
|
||||
let (compacted_splits, splits_collision_collapsed) =
|
||||
compact_mapped_qm_splits(qm_splits_path, mapped_splits)?;
|
||||
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
|
||||
|
||||
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
|
||||
for (listing_id, event) in compacted_splits {
|
||||
let partners = &eod_by_listing[&listing_id];
|
||||
split_rekey.splits_applied += 1;
|
||||
for eod_key in partners {
|
||||
split_events.push((Arc::clone(eod_key), event));
|
||||
}
|
||||
split_rekey.split_events_attached += partners.len();
|
||||
}
|
||||
|
||||
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
||||
RunCurateBarsError::SplitTable {
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let LoadedQmSplits {
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
} = load_qm_splits_from_reader(splits_stream, qm_splits_path, &mapping, &eod_by_listing)?;
|
||||
|
||||
// Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys.
|
||||
let eod_stream = open_eod()?;
|
||||
|
|
|
|||
791
tools/curate-etl/src/run_curate_bars_1m.rs
Normal file
791
tools/curate-etl/src/run_curate_bars_1m.rs
Normal file
|
|
@ -0,0 +1,791 @@
|
|||
//! Bounded-memory file-to-file `bars_1m` runner (`M2.3k`).
|
||||
//!
|
||||
//! Streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a
|
||||
//! headerless 5-column `provider_mapping.tsv` into per-shard QuestDB ILP v2 files
|
||||
//! (`<out_dir>/bars_1m.shard-<NN>.ilp`) via [`curate_and_write_bars_1m`].
|
||||
//!
|
||||
//! # Bounded-Memory Chunking
|
||||
//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and
|
||||
//! [`decode_eod_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by
|
||||
//! `crate::bson_stream::decode_eod_intraday_chunks`, whose callback API hides chunk boundaries.
|
||||
//! - Each framed chunk is decoded into a chunk-local `Vec<EodIntradayBar<Arc<str>>>` (reusing
|
||||
//! interned `"eod"` keys from `provider_mapping.tsv` and retaining unknown codes so
|
||||
//! `curate_bars_1m` counts them in `dropped_unmapped`) and passed to
|
||||
//! [`curate_and_write_bars_1m`] against one shared [`IlpShardedWriter`].
|
||||
//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF.
|
||||
//! - Peak memory is bounded by the reference tables (`provider_mapping` + `SplitTable`), the
|
||||
//! current BSON chunk (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single
|
||||
//! document up to `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per
|
||||
//! shard—independent of the total `eodIntraday1M` input size.
|
||||
//!
|
||||
//! # Cross-Chunk Semantics & Reporting
|
||||
//! - Collision collapse/drop in `curate_bars_1m` and row ordering apply **per chunk**: output is
|
||||
//! sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing in
|
||||
//! two different chunks is emitted twice (with zero within-chunk collapse between them) and
|
||||
//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`.
|
||||
//! - `CurateBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its
|
||||
//! nested [`Bars1mStats`] across chunks. In particular, `curate_stats.listings_out` and
|
||||
//! `curate_stats.builder.keys_out` are **sums of per-chunk counts**, not global distinct counts.
|
||||
//! - `mapping_source` must be `"eod"` because the shared `qmSplits` re-keying helper
|
||||
//! (`run_curate_bars::load_qm_splits_from_reader`) builds `SplitTable<Arc<str>>` keyed for
|
||||
//! `"eod"` `source_id`s.
|
||||
//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's
|
||||
//! `known_at` column; it supplies no evidence of earlier market availability.
|
||||
//!
|
||||
//! # File Publication & Fail-Closed Guarantees
|
||||
//! - Pre-existing `bars_1m.shard-<NN>.ilp` files in `out_dir` are rejected before staging.
|
||||
//! - Each shard writes into an exclusively created staging file in `out_dir`
|
||||
//! (`.bars_1m.shard-<NN>.<run_id>.tmp`), flushes and `sync_all`s on `finish`, and publishes to
|
||||
//! `bars_1m.shard-<NN>.ilp` via same-directory `hard_link` followed by removing the staged name
|
||||
//! (preserving no-overwrite semantics even if a final file appears after preflight).
|
||||
//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or
|
||||
//! publication collision) rolls back only final files created by this run, removes this run's
|
||||
//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors
|
||||
//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`].
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
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::{Bars1mStats, EodIntradayBar};
|
||||
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, CurateBars1mStats, CurateBars1mWriteError,
|
||||
};
|
||||
use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions};
|
||||
use crate::parquet_bars::RollbackFailure;
|
||||
use crate::parquet_publish::{
|
||||
next_run_id, rollback_published, PublishedPartition, StagingFileGuard, FILE_BUF_CAPACITY_BYTES,
|
||||
};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::run_curate_bars::{
|
||||
build_eod_mapping_index, load_provider_mapping_tsv, load_qm_splits_from_reader,
|
||||
EodMappingIndex, LoadedQmSplits, RunCurateBarsError, SplitRekeyStats,
|
||||
};
|
||||
use crate::split::SplitTable;
|
||||
|
||||
/// Required `provider_mapping` source namespace for `eodIntraday1M` bars.
|
||||
pub const DEFAULT_BARS_1M_MAPPING_SOURCE: &str = "eod";
|
||||
|
||||
/// Arguments for [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateBars1mArgs {
|
||||
pub intraday_path: PathBuf,
|
||||
pub splits_path: PathBuf,
|
||||
pub provider_mapping_path: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
pub mapping_source: String,
|
||||
pub shard_count: usize,
|
||||
pub known_at_micros: i64,
|
||||
pub stream_options: BsonStreamOptions,
|
||||
pub ilp_options: IlpWriterOptions,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `intraday_docs_framed as usize == intraday_decode.docs_seen`
|
||||
/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()`
|
||||
/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in`
|
||||
/// - `curate_stats.rows_in == curate_stats.builder.rows_out`
|
||||
/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped`
|
||||
/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out`
|
||||
/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::<usize>()`
|
||||
///
|
||||
/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks
|
||||
/// (not global distinct counts).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateBars1mRunReport {
|
||||
pub intraday_docs_framed: u64,
|
||||
pub intraday_bytes_read: u64,
|
||||
pub intraday_decode: BsonEodIntradayDecodeStats,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub split_rekey: SplitRekeyStats,
|
||||
pub chunks: usize,
|
||||
pub max_rows_per_chunk: usize,
|
||||
pub curate_stats: CurateBars1mStats,
|
||||
pub rows_written: usize,
|
||||
pub ilp_stats: IlpWriteStats,
|
||||
pub shard_count: usize,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`].
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateBars1mError {
|
||||
/// `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
/// `mapping_source` was non-blank but not `"eod"`.
|
||||
UnsupportedMappingSource { mapping_source: String },
|
||||
/// `shard_count` was `0`.
|
||||
ZeroShardCount,
|
||||
/// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`.
|
||||
ShardCountMismatch { expected: usize, actual: usize },
|
||||
/// `out_dir` exists and is not a directory.
|
||||
InvalidOutDir { path: PathBuf, detail: String },
|
||||
/// A final shard output file (`bars_1m.shard-<NN>.ilp`) already existed.
|
||||
OutputFileExists { path: PathBuf },
|
||||
/// Failed to open an input dump file.
|
||||
OpenInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Failed to load `provider_mapping.tsv` or `qmSplits` via the shared reference loader.
|
||||
LoadReference(RunCurateBarsError),
|
||||
/// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`.
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
/// Curation or per-row ILP write error inside [`curate_and_write_bars_1m`].
|
||||
CurateWrite(CurateBars1mWriteError),
|
||||
/// ILP writer initialization or final flush error.
|
||||
Ilp(IlpWriterError),
|
||||
/// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files.
|
||||
Io { path: PathBuf, source: io::Error },
|
||||
/// Publication failed and rolling back one or more already-published shards also failed.
|
||||
RollbackFailed {
|
||||
cause: Box<RunCurateBars1mError>,
|
||||
failures: Vec<RollbackFailure>,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateBars1mError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"),
|
||||
Self::UnsupportedMappingSource { mapping_source } => write!(
|
||||
f,
|
||||
"unsupported mapping_source '{mapping_source}': only '{DEFAULT_BARS_1M_MAPPING_SOURCE}' is supported"
|
||||
),
|
||||
Self::ZeroShardCount => write!(f, "shard_count must be >= 1"),
|
||||
Self::ShardCountMismatch { expected, actual } => write!(
|
||||
f,
|
||||
"ILP writer shard count mismatch: expected {expected}, got {actual}"
|
||||
),
|
||||
Self::InvalidOutDir { path, detail } => {
|
||||
write!(f, "invalid out_dir '{}': {detail}", path.display())
|
||||
}
|
||||
Self::OutputFileExists { path } => write!(
|
||||
f,
|
||||
"refusing to overwrite existing output file '{}'",
|
||||
path.display()
|
||||
),
|
||||
Self::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
|
||||
Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"),
|
||||
Self::BsonStream {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
||||
Self::CurateWrite(err) => write!(f, "{err}"),
|
||||
Self::Ilp(err) => write!(f, "bars_1m ILP writer failed: {err}"),
|
||||
Self::Io { path, source } => {
|
||||
write!(f, "I/O error on '{}': {source}", path.display())
|
||||
}
|
||||
Self::RollbackFailed { cause, failures } => {
|
||||
write!(f, "{cause}; rollback also failed for: ")?;
|
||||
for (i, failure) in failures.iter().enumerate() {
|
||||
if i > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{failure}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateBars1mError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source),
|
||||
Self::LoadReference(err) => Some(err),
|
||||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::CurateWrite(err) => Some(err),
|
||||
Self::Ilp(err) => Some(err),
|
||||
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
|
||||
Self::EmptyMappingSource
|
||||
| Self::UnsupportedMappingSource { .. }
|
||||
| Self::ZeroShardCount
|
||||
| Self::ShardCountMismatch { .. }
|
||||
| Self::InvalidOutDir { .. }
|
||||
| Self::OutputFileExists { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadedReferenceInputs {
|
||||
mapping: ProviderMappingTable,
|
||||
eod_keys: HashSet<Arc<str>>,
|
||||
splits: SplitTable<Arc<str>>,
|
||||
splits_docs_framed: u64,
|
||||
splits_bytes_read: u64,
|
||||
splits_decode: BsonQmActionDecodeStats,
|
||||
split_rekey: SplitRekeyStats,
|
||||
}
|
||||
|
||||
fn validate_common_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> {
|
||||
if args.mapping_source.trim().is_empty() {
|
||||
return Err(RunCurateBars1mError::EmptyMappingSource);
|
||||
}
|
||||
if args.mapping_source != DEFAULT_BARS_1M_MAPPING_SOURCE {
|
||||
return Err(RunCurateBars1mError::UnsupportedMappingSource {
|
||||
mapping_source: args.mapping_source.clone(),
|
||||
});
|
||||
}
|
||||
if args.shard_count == 0 {
|
||||
return Err(RunCurateBars1mError::ZeroShardCount);
|
||||
}
|
||||
args.stream_options
|
||||
.validate()
|
||||
.map_err(|source| RunCurateBars1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> {
|
||||
validate_common_args(args)?;
|
||||
if args.ilp_options.max_batch_bytes == 0 {
|
||||
return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes));
|
||||
}
|
||||
if args.ilp_options.max_batch_rows == 0 {
|
||||
return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchRows));
|
||||
}
|
||||
if args.out_dir.exists() && !args.out_dir.is_dir() {
|
||||
return Err(RunCurateBars1mError::InvalidOutDir {
|
||||
path: args.out_dir.clone(),
|
||||
detail: "path exists and is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
for shard_idx in 0..args.shard_count {
|
||||
let final_path = final_shard_path(&args.out_dir, shard_idx);
|
||||
if final_path.exists() {
|
||||
return Err(RunCurateBars1mError::OutputFileExists { path: final_path });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn final_shard_path(out_dir: &Path, shard_idx: usize) -> PathBuf {
|
||||
out_dir.join(format!("bars_1m.shard-{shard_idx:02}.ilp"))
|
||||
}
|
||||
|
||||
fn load_reference_inputs<RS: io::Read>(
|
||||
provider_mapping_path: &Path,
|
||||
splits_path: &Path,
|
||||
splits_reader: RS,
|
||||
) -> Result<LoadedReferenceInputs, RunCurateBars1mError> {
|
||||
let mapping_rows =
|
||||
load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?;
|
||||
let EodMappingIndex {
|
||||
eod_keys,
|
||||
eod_by_listing,
|
||||
..
|
||||
} = build_eod_mapping_index(&mapping_rows, false);
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateBars1mError::LoadReference(RunCurateBarsError::ProviderMapping {
|
||||
path: provider_mapping_path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
|
||||
let LoadedQmSplits {
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
} = load_qm_splits_from_reader(splits_reader, splits_path, &mapping, &eod_by_listing)
|
||||
.map_err(RunCurateBars1mError::LoadReference)?;
|
||||
|
||||
Ok(LoadedReferenceInputs {
|
||||
mapping,
|
||||
eod_keys,
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) {
|
||||
total.bars_in += chunk.bars_in;
|
||||
total.rows_out += chunk.rows_out;
|
||||
total.keys_out += chunk.keys_out;
|
||||
total.pre_rows_out += chunk.pre_rows_out;
|
||||
total.rth_rows_out += chunk.rth_rows_out;
|
||||
total.post_rows_out += chunk.post_rows_out;
|
||||
total.dropped_invalid_ohlc += chunk.dropped_invalid_ohlc;
|
||||
total.dropped_inconsistent_ohlc += chunk.dropped_inconsistent_ohlc;
|
||||
total.dropped_invalid_volume += chunk.dropped_invalid_volume;
|
||||
total.dropped_ts_out_of_range += chunk.dropped_ts_out_of_range;
|
||||
total.duplicate_collapsed += chunk.duplicate_collapsed;
|
||||
total.duplicate_conflict_dropped += chunk.duplicate_conflict_dropped;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) {
|
||||
add_bars_1m_stats(&mut total.builder, &chunk.builder);
|
||||
total.rows_in += chunk.rows_in;
|
||||
total.rows_out += chunk.rows_out;
|
||||
total.listings_out += chunk.listings_out;
|
||||
total.pre_rows_out += chunk.pre_rows_out;
|
||||
total.rth_rows_out += chunk.rth_rows_out;
|
||||
total.post_rows_out += chunk.post_rows_out;
|
||||
total.dropped_unmapped += chunk.dropped_unmapped;
|
||||
total.listing_collision_collapsed += chunk.listing_collision_collapsed;
|
||||
total.listing_collision_dropped += chunk.listing_collision_dropped;
|
||||
}
|
||||
|
||||
fn stream_intraday_chunks_to_writer<RI, W>(
|
||||
args: &CurateBars1mArgs,
|
||||
reference: LoadedReferenceInputs,
|
||||
intraday: RI,
|
||||
mut writer: IlpShardedWriter<W>,
|
||||
start: Instant,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||
where
|
||||
RI: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|
||||
|source| RunCurateBars1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
|
||||
let mut intraday_decode = BsonEodIntradayDecodeStats::default();
|
||||
let mut curate_stats = CurateBars1mStats::default();
|
||||
let mut chunks: usize = 0;
|
||||
let mut max_rows_per_chunk: usize = 0;
|
||||
let mut rows_written: usize = 0;
|
||||
|
||||
// Reusable per-chunk buffers; cleared before each chunk so peak RAM stays bounded by chunk size.
|
||||
let mut chunk_bars: Vec<EodIntradayBar<Arc<str>>> = Vec::new();
|
||||
let mut unknown_keys: HashMap<String, Arc<str>> = HashMap::new();
|
||||
|
||||
while let Some(chunk) =
|
||||
reader
|
||||
.next_chunk()
|
||||
.map_err(|source| RunCurateBars1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?
|
||||
{
|
||||
chunk_bars.clear();
|
||||
unknown_keys.clear();
|
||||
|
||||
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
|
||||
};
|
||||
chunk_bars.push(raw.into_eod_intraday_bar(|_, _| key));
|
||||
},
|
||||
|_local_offset, _err| {},
|
||||
);
|
||||
intraday_decode += chunk_decode;
|
||||
|
||||
chunks += 1;
|
||||
let chunk_len = chunk_bars.len();
|
||||
if chunk_len > max_rows_per_chunk {
|
||||
max_rows_per_chunk = chunk_len;
|
||||
}
|
||||
|
||||
let write_report = curate_and_write_bars_1m(
|
||||
chunk_bars.drain(..),
|
||||
&reference.splits,
|
||||
&reference.mapping,
|
||||
&args.mapping_source,
|
||||
&mut writer,
|
||||
args.known_at_micros,
|
||||
)
|
||||
.map_err(RunCurateBars1mError::CurateWrite)?;
|
||||
|
||||
add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats);
|
||||
rows_written += write_report.rows_written;
|
||||
}
|
||||
|
||||
let intraday_docs_framed = reader.docs_framed();
|
||||
let intraday_bytes_read = reader.bytes_read();
|
||||
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,
|
||||
rows_written,
|
||||
ilp_stats,
|
||||
shard_count: args.shard_count,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary [`io::Read`] streams into a
|
||||
/// caller-owned [`IlpShardedWriter`].
|
||||
///
|
||||
/// 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`] calling [`curate_and_write_bars_1m`] once per chunk, and calls
|
||||
/// [`IlpShardedWriter::finish`] exactly once after EOF.
|
||||
pub fn run_curate_bars_1m_with_readers<RI, RS, W>(
|
||||
args: &CurateBars1mArgs,
|
||||
intraday: RI,
|
||||
splits: RS,
|
||||
writer: IlpShardedWriter<W>,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||
where
|
||||
RI: io::Read,
|
||||
RS: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_common_args(args)?;
|
||||
if writer.shard_count() != args.shard_count {
|
||||
return Err(RunCurateBars1mError::ShardCountMismatch {
|
||||
expected: args.shard_count,
|
||||
actual: writer.shard_count(),
|
||||
});
|
||||
}
|
||||
|
||||
let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?;
|
||||
stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)
|
||||
}
|
||||
|
||||
/// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once
|
||||
/// per shard by [`IlpShardedWriter::finish`]).
|
||||
struct SyncedBufFile {
|
||||
inner: BufWriter<File>,
|
||||
}
|
||||
|
||||
impl SyncedBufFile {
|
||||
fn new(file: File) -> Self {
|
||||
Self {
|
||||
inner: BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for SyncedBufFile {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.inner.write(buf)
|
||||
}
|
||||
|
||||
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
|
||||
self.inner.write_all(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()?;
|
||||
self.inner.get_ref().sync_all()
|
||||
}
|
||||
}
|
||||
|
||||
fn create_exclusive_shard_tmp_file(
|
||||
out_dir: &Path,
|
||||
shard_idx: usize,
|
||||
run_id: &str,
|
||||
) -> Result<(PathBuf, File), RunCurateBars1mError> {
|
||||
for attempt in 0..1024u32 {
|
||||
let file_name = if attempt == 0 {
|
||||
format!(".bars_1m.shard-{shard_idx:02}.{run_id}.tmp")
|
||||
} else {
|
||||
format!(".bars_1m.shard-{shard_idx:02}.{run_id}.{attempt}.tmp")
|
||||
};
|
||||
let tmp_path = out_dir.join(file_name);
|
||||
match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp_path)
|
||||
{
|
||||
Ok(file) => return Ok((tmp_path, file)),
|
||||
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(source) => {
|
||||
return Err(RunCurateBars1mError::Io {
|
||||
path: tmp_path,
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(RunCurateBars1mError::Io {
|
||||
path: out_dir.join(format!(".bars_1m.shard-{shard_idx:02}.{run_id}.tmp")),
|
||||
source: io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"exhausted unique staging file names",
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn publish_staged_shards<F>(
|
||||
out_dir: &Path,
|
||||
mut staged: Vec<(PathBuf, StagingFileGuard)>,
|
||||
mut before_link: F,
|
||||
) -> Result<(), RunCurateBars1mError>
|
||||
where
|
||||
F: FnMut(usize, &Path),
|
||||
{
|
||||
let mut published: Vec<PublishedPartition> = Vec::with_capacity(staged.len());
|
||||
|
||||
for (shard_idx, (tmp_path, guard)) in staged.iter_mut().enumerate() {
|
||||
let final_path = final_shard_path(out_dir, shard_idx);
|
||||
before_link(shard_idx, &final_path);
|
||||
|
||||
if let Err(source) = fs::hard_link(&tmp_path, &final_path) {
|
||||
let cause = if source.kind() == io::ErrorKind::AlreadyExists {
|
||||
RunCurateBars1mError::OutputFileExists { path: final_path }
|
||||
} else {
|
||||
RunCurateBars1mError::Io {
|
||||
path: final_path,
|
||||
source,
|
||||
}
|
||||
};
|
||||
let rollback_failures = rollback_published(&published);
|
||||
if !rollback_failures.is_empty() {
|
||||
return Err(RunCurateBars1mError::RollbackFailed {
|
||||
cause: Box::new(cause),
|
||||
failures: rollback_failures,
|
||||
});
|
||||
}
|
||||
return Err(cause);
|
||||
}
|
||||
|
||||
published.push(PublishedPartition {
|
||||
final_path,
|
||||
backup_path: None,
|
||||
});
|
||||
|
||||
if let Err(source) = fs::remove_file(&tmp_path) {
|
||||
let cause = RunCurateBars1mError::Io {
|
||||
path: tmp_path.clone(),
|
||||
source,
|
||||
};
|
||||
let rollback_failures = rollback_published(&published);
|
||||
if !rollback_failures.is_empty() {
|
||||
return Err(RunCurateBars1mError::RollbackFailed {
|
||||
cause: Box::new(cause),
|
||||
failures: rollback_failures,
|
||||
});
|
||||
}
|
||||
return Err(cause);
|
||||
}
|
||||
guard.disarm();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting injected readers, sink factory, and pre-link hook so tests can
|
||||
/// exercise staging, writer failure, and post-preflight publication rollback through the exact
|
||||
/// file publication path.
|
||||
fn run_curate_bars_1m_to_dir_with_hooks<RI, RS, W, SF, BL>(
|
||||
args: &CurateBars1mArgs,
|
||||
intraday: RI,
|
||||
splits: RS,
|
||||
mut make_sink: SF,
|
||||
before_link: BL,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||
where
|
||||
RI: io::Read,
|
||||
RS: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
{
|
||||
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<W> = Vec::with_capacity(args.shard_count);
|
||||
for shard_idx in 0..args.shard_count {
|
||||
let (tmp_path, file) = create_exclusive_shard_tmp_file(&args.out_dir, shard_idx, &run_id)?;
|
||||
let guard = StagingFileGuard::new(tmp_path.clone());
|
||||
staged.push((tmp_path, guard));
|
||||
sinks.push(make_sink(shard_idx, file));
|
||||
}
|
||||
|
||||
let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?;
|
||||
let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?;
|
||||
|
||||
publish_staged_shards(&args.out_dir, staged, before_link)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly
|
||||
/// `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`).
|
||||
pub fn run_curate_bars_1m(
|
||||
args: &CurateBars1mArgs,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError> {
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let splits_file = File::open(&args.splits_path).map_err(|source| {
|
||||
RunCurateBars1mError::OpenInput {
|
||||
label: "qm-splits",
|
||||
path: args.splits_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let intraday_file = File::open(&args.intraday_path).map_err(|source| {
|
||||
RunCurateBars1mError::OpenInput {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
run_curate_bars_1m_to_dir_with_hooks(
|
||||
args,
|
||||
intraday_file,
|
||||
splits_file,
|
||||
|_shard_idx, file| SyncedBufFile::new(file),
|
||||
|_shard_idx, _final_path| {},
|
||||
)
|
||||
}
|
||||
|
||||
/// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_bars_1m_report(report: &CurateBars1mRunReport) -> String {
|
||||
let per_shard = if report.ilp_stats.per_shard_rows.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
report
|
||||
.ilp_stats
|
||||
.per_shard_rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, count)| format!("{idx:02}={count}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
};
|
||||
|
||||
let b = &report.curate_stats.builder;
|
||||
let c = &report.curate_stats;
|
||||
let d = &report.intraday_decode;
|
||||
let sd = &report.splits_decode;
|
||||
let sr = &report.split_rekey;
|
||||
|
||||
format!(
|
||||
"curate-etl curate-bars-1m\n\
|
||||
\x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\
|
||||
\x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
\x20 splits: splits_in={} splits_applied={} splits_collision_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\
|
||||
\x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\
|
||||
\x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\
|
||||
\x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\
|
||||
\x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\
|
||||
\x20 timing: elapsed_secs={:.6}",
|
||||
report.intraday_docs_framed,
|
||||
report.intraday_bytes_read,
|
||||
d.docs_seen,
|
||||
d.rows_decoded,
|
||||
d.rejected_total(),
|
||||
d.rejected_missing_field,
|
||||
d.rejected_empty_field,
|
||||
d.rejected_wrong_type,
|
||||
d.rejected_invalid_timestamp,
|
||||
d.rejected_invalid_number,
|
||||
d.rejected_corrupt_document,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
sd.docs_in,
|
||||
sd.decoded,
|
||||
sd.split_noop_ratio_one,
|
||||
sd.rejected_total(),
|
||||
sd.rejected_missing_field,
|
||||
sd.rejected_empty_field,
|
||||
sd.rejected_wrong_type,
|
||||
sd.rejected_malformed_date,
|
||||
sd.rejected_invalid_number,
|
||||
sd.rejected_corrupt_document,
|
||||
sr.splits_in,
|
||||
sr.splits_applied,
|
||||
sr.splits_collision_collapsed,
|
||||
sr.splits_unmapped_qm,
|
||||
sr.splits_no_eod_partner,
|
||||
sr.splits_noop_dropped,
|
||||
sr.split_events_attached,
|
||||
report.chunks,
|
||||
report.max_rows_per_chunk,
|
||||
b.bars_in,
|
||||
b.rows_out,
|
||||
b.keys_out,
|
||||
b.pre_rows_out,
|
||||
b.rth_rows_out,
|
||||
b.post_rows_out,
|
||||
b.dropped_invalid_ohlc,
|
||||
b.dropped_inconsistent_ohlc,
|
||||
b.dropped_invalid_volume,
|
||||
b.dropped_ts_out_of_range,
|
||||
b.duplicate_collapsed,
|
||||
b.duplicate_conflict_dropped,
|
||||
c.rows_in,
|
||||
c.rows_out,
|
||||
c.listings_out,
|
||||
c.pre_rows_out,
|
||||
c.rth_rows_out,
|
||||
c.post_rows_out,
|
||||
c.dropped_unmapped,
|
||||
c.listing_collision_collapsed,
|
||||
c.listing_collision_dropped,
|
||||
report.shard_count,
|
||||
report.rows_written,
|
||||
report.ilp_stats.rows,
|
||||
report.ilp_stats.bytes,
|
||||
report.ilp_stats.flushes,
|
||||
report.elapsed_secs,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "run_curate_bars_1m_tests.rs"]
|
||||
mod tests;
|
||||
1324
tools/curate-etl/src/run_curate_bars_1m_tests.rs
Normal file
1324
tools/curate-etl/src/run_curate_bars_1m_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue