T-185: M2.3m — tools/curate-etl: bounded-memory file-to-file qmIntraday → bars_1m runner (run_curate_qm_bars_1m.rs: raw qmIntraday BSON dump + provider_mapping.tsv → chunked curate_and_write_qm_bars_1m → per-shard bars_1m_qm.shard-<NN>.ilp ILP v2 files, fail-closed publish) with tests (no new crates, no CLI/bench changes, no live Mongo/QuestDB)
This commit is contained in:
parent
749323080a
commit
859453edd7
6 changed files with 2090 additions and 2 deletions
|
|
@ -1683,6 +1683,14 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m
|
|||
- **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files.
|
||||
- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-<digits>.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, 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 error. CLI wiring, `--from-mongo`, and live QuestDB load remain follow-ups.
|
||||
|
||||
## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`)
|
||||
|
||||
`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`):
|
||||
|
||||
- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`).
|
||||
- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-<NN>.ilp` prefix so QM and EOD (`bars_1m.shard-<NN>.ilp`) exports can share `out_dir` safely.
|
||||
- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-<digits>.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain 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).
|
||||
|
|
|
|||
|
|
@ -334,6 +334,13 @@ pub use run_curate_fx_1m::{
|
|||
CurateFx1mRunReport, RunCurateFx1mError,
|
||||
};
|
||||
|
||||
pub mod run_curate_qm_bars_1m;
|
||||
pub use run_curate_qm_bars_1m::{
|
||||
format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers,
|
||||
CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError,
|
||||
DEFAULT_QM_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,
|
||||
|
|
|
|||
|
|
@ -442,7 +442,7 @@ fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) {
|
||||
pub(crate) 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;
|
||||
|
|
|
|||
|
|
@ -311,7 +311,7 @@ where
|
|||
run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)
|
||||
}
|
||||
|
||||
fn cleanup_armed_staged_shards<RF>(
|
||||
pub(crate) fn cleanup_armed_staged_shards<RF>(
|
||||
staged: &mut [(PathBuf, StagingFileGuard)],
|
||||
remove_file: &mut RF,
|
||||
) -> Vec<RollbackFailure>
|
||||
|
|
|
|||
643
tools/curate-etl/src/run_curate_qm_bars_1m.rs
Normal file
643
tools/curate-etl/src/run_curate_qm_bars_1m.rs
Normal file
|
|
@ -0,0 +1,643 @@
|
|||
//! Bounded-memory file-to-file `qmIntraday` -> `bars_1m` runner (`M2.3m`).
|
||||
//!
|
||||
//! Streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column
|
||||
//! `provider_mapping.tsv` into per-shard QuestDB ILP v2 files
|
||||
//! (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`) via [`crate::curate_qm_bars_1m`].
|
||||
//!
|
||||
//! # Bounded-Memory Chunking & Zero Split Un-Adjustment
|
||||
//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and
|
||||
//! [`decode_qm_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by
|
||||
//! `crate::bson_stream::decode_qm_intraday_chunks`, whose callback API hides chunk boundaries.
|
||||
//! - Each framed chunk is decoded into a chunk-local `Vec<EodIntradayBar<&str>>` borrowing
|
||||
//! `qmSearchCode` directly from the chunk slice, then curated per chunk via
|
||||
//! [`curate_and_write_qm_bars_1m`] against one shared [`IlpShardedWriter`]. Borrows are
|
||||
//! consumed before advancing the chunk reader.
|
||||
//! - Takes no splits input: `qmIntraday` raw fields (`open..close`, `sharevolume`) are already
|
||||
//! un-adjusted (`design/DATA-CONTRACTS.md` §1) and pass through bit-identical (aside from
|
||||
//! `-0.0 -> +0.0` volume normalization).
|
||||
//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF.
|
||||
//! - Peak memory is bounded by the `provider_mapping` table, 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 `qmIntraday` input size.
|
||||
//!
|
||||
//! # Cross-Chunk Semantics, Output Naming & Reporting
|
||||
//! - Collision collapse/drop in `curate_qm_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)`.
|
||||
//! - `CurateQmBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its
|
||||
//! nested [`crate::bars_1m::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.
|
||||
//! - Output files use the distinct shard prefix `bars_1m_qm` (`bars_1m_qm.shard-<NN>.ilp`) so a
|
||||
//! QM run can share `out_dir` with `run_curate_bars_1m` (`bars_1m.shard-<NN>.ilp`) without
|
||||
//! tripping either preflight, while every emitted ILP v2 row still targets QuestDB table
|
||||
//! `bars_1m` (`TABLE_BARS_1M`) with `source=qm_raw` (`BARS_1M_SOURCE_QM`).
|
||||
//! - `mapping_source` is caller-supplied and forwarded verbatim to `curate_and_write_qm_bars_1m`
|
||||
//! after rejecting empty or whitespace-only values (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`).
|
||||
//! - `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
|
||||
//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m_qm.shard-<digits>.ilp` file
|
||||
//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards
|
||||
//! from a prior larger-shard-count run cannot survive alongside a new export.
|
||||
//! - Each shard writes into an exclusively created staging file in `out_dir`
|
||||
//! (`.bars_1m_qm.shard-<NN>.<run_id>.tmp`), flushes and `sync_all`s on `finish`, and publishes
|
||||
//! to `bars_1m_qm.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) drops open sinks, 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 [`BsonQmIntradayDecodeStats`].
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bars_1m::EodIntradayBar;
|
||||
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};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
||||
use crate::run_curate_bars_1m::{
|
||||
add_curate_bars_1m_stats, create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir,
|
||||
publish_staged_shards_for_table, ShardPublishError, SyncedBufFile,
|
||||
};
|
||||
use crate::run_curate_fx_1m::cleanup_armed_staged_shards;
|
||||
|
||||
/// Default `provider_mapping` source namespace for `qmSearchCode` rows in `qmIntraday`.
|
||||
pub const DEFAULT_QM_BARS_1M_MAPPING_SOURCE: &str = "qm";
|
||||
|
||||
/// Output filename prefix for QM intraday shard files (`bars_1m_qm.shard-<NN>.ilp`).
|
||||
///
|
||||
/// Distinct from `TABLE_BARS_1M` (`bars_1m`) so QM and EOD intraday exports can share `out_dir`
|
||||
/// without colliding in preflight or publication while both emit ILP v2 rows into `bars_1m`.
|
||||
const QM_BARS_1M_SHARD_PREFIX: &str = "bars_1m_qm";
|
||||
|
||||
/// Arguments for [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateQmBars1mArgs {
|
||||
pub intraday_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_qm_bars_1m`] and
|
||||
/// [`run_curate_qm_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 CurateQmBars1mRunReport {
|
||||
pub intraday_docs_framed: u64,
|
||||
pub intraday_bytes_read: u64,
|
||||
pub intraday_decode: BsonQmIntradayDecodeStats,
|
||||
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_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`].
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateQmBars1mError {
|
||||
/// `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
/// `shard_count` was `0`.
|
||||
ZeroShardCount,
|
||||
/// `out_dir` exists and is not a directory.
|
||||
InvalidOutDir { path: PathBuf, detail: String },
|
||||
/// A final shard output file (`bars_1m_qm.shard-<digits>.ilp`) already existed.
|
||||
OutputFileExists { path: PathBuf },
|
||||
/// Failed to open the input `qmIntraday` dump file.
|
||||
OpenInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Failed to load `provider_mapping.tsv` via the shared reference loader.
|
||||
LoadReference(RunCurateBarsError),
|
||||
/// Fatal BSON framing, option validation, or I/O error while reading `qmIntraday`.
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
/// Curation or per-row ILP write error inside the per-chunk `qmIntraday` curation stage.
|
||||
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 or failure cleanup failed and removing one or more final or staging files also
|
||||
/// failed.
|
||||
RollbackFailed {
|
||||
cause: Box<RunCurateQmBars1mError>,
|
||||
failures: Vec<RollbackFailure>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<ShardPublishError> for RunCurateQmBars1mError {
|
||||
fn from(err: ShardPublishError) -> Self {
|
||||
match err {
|
||||
ShardPublishError::InvalidOutDir { path, detail } => {
|
||||
Self::InvalidOutDir { path, detail }
|
||||
}
|
||||
ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path },
|
||||
ShardPublishError::Io { path, source } => Self::Io { path, source },
|
||||
ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed {
|
||||
cause: Box::new((*cause).into()),
|
||||
failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateQmBars1mError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"),
|
||||
Self::ZeroShardCount => write!(f, "shard_count must be >= 1"),
|
||||
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, "qm 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 RunCurateQmBars1mError {
|
||||
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::ZeroShardCount
|
||||
| Self::InvalidOutDir { .. }
|
||||
| Self::OutputFileExists { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_common_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> {
|
||||
if args.mapping_source.trim().is_empty() {
|
||||
return Err(RunCurateQmBars1mError::EmptyMappingSource);
|
||||
}
|
||||
if args.shard_count == 0 {
|
||||
return Err(RunCurateQmBars1mError::ZeroShardCount);
|
||||
}
|
||||
args.stream_options
|
||||
.validate()
|
||||
.map_err(|source| RunCurateQmBars1mError::BsonStream {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
if args.ilp_options.max_batch_bytes == 0 {
|
||||
return Err(RunCurateQmBars1mError::Ilp(
|
||||
IlpWriterError::ZeroMaxBatchBytes,
|
||||
));
|
||||
}
|
||||
if args.ilp_options.max_batch_rows == 0 {
|
||||
return Err(RunCurateQmBars1mError::Ilp(
|
||||
IlpWriterError::ZeroMaxBatchRows,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_file_mode_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> {
|
||||
validate_common_args(args)?;
|
||||
preflight_shard_out_dir(&args.out_dir, QM_BARS_1M_SHARD_PREFIX)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_provider_mapping_table(
|
||||
provider_mapping_path: &Path,
|
||||
) -> Result<ProviderMappingTable, RunCurateQmBars1mError> {
|
||||
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)
|
||||
.map_err(RunCurateQmBars1mError::LoadReference)?;
|
||||
ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateQmBars1mError::LoadReference(RunCurateBarsError::ProviderMapping {
|
||||
path: provider_mapping_path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn stream_qm_intraday_chunks_to_writer<R, W>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
mapping: &ProviderMappingTable,
|
||||
intraday: R,
|
||||
mut writer: IlpShardedWriter<W>,
|
||||
start: Instant,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|
||||
|source| RunCurateQmBars1mError::BsonStream {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
|
||||
let mut intraday_decode = BsonQmIntradayDecodeStats::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;
|
||||
|
||||
while let Some(chunk) =
|
||||
reader
|
||||
.next_chunk()
|
||||
.map_err(|source| RunCurateQmBars1mError::BsonStream {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?
|
||||
{
|
||||
let mut chunk_bars: Vec<EodIntradayBar<&str>> = Vec::new();
|
||||
let chunk_decode = decode_qm_intraday_buffer(
|
||||
chunk.bytes,
|
||||
|raw| {
|
||||
chunk_bars.push(raw.into_eod_intraday_bar(|key, _| key));
|
||||
},
|
||||
|_local_offset, _err| {},
|
||||
);
|
||||
intraday_decode.merge(&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_qm_bars_1m(
|
||||
chunk_bars,
|
||||
mapping,
|
||||
&args.mapping_source,
|
||||
&mut writer,
|
||||
args.known_at_micros,
|
||||
)
|
||||
.map_err(RunCurateQmBars1mError::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(RunCurateQmBars1mError::Ilp)?;
|
||||
|
||||
Ok(CurateQmBars1mRunReport {
|
||||
intraday_docs_framed,
|
||||
intraday_bytes_read,
|
||||
intraday_decode,
|
||||
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 `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary
|
||||
/// [`io::Read`] stream into per-shard sinks created by `make_sink`.
|
||||
///
|
||||
/// 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.
|
||||
pub fn run_curate_qm_bars_1m_with_readers<R, W, F>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
intraday: R,
|
||||
mut make_sink: F,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
F: FnMut(usize) -> W,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_common_args(args)?;
|
||||
|
||||
let mapping = load_provider_mapping_table(&args.provider_mapping_path)?;
|
||||
|
||||
let mut sinks = Vec::with_capacity(args.shard_count);
|
||||
for shard_idx in 0..args.shard_count {
|
||||
sinks.push(make_sink(shard_idx));
|
||||
}
|
||||
let writer =
|
||||
IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?;
|
||||
|
||||
stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
|
||||
}
|
||||
|
||||
fn fail_with_staging_cleanup<RF>(
|
||||
cause: RunCurateQmBars1mError,
|
||||
staged: &mut [(PathBuf, StagingFileGuard)],
|
||||
remove_file: &mut RF,
|
||||
) -> RunCurateQmBars1mError
|
||||
where
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
let staging_failures = cleanup_armed_staged_shards(staged, remove_file);
|
||||
if staging_failures.is_empty() {
|
||||
return cause;
|
||||
}
|
||||
match cause {
|
||||
RunCurateQmBars1mError::RollbackFailed {
|
||||
cause: inner_cause,
|
||||
mut failures,
|
||||
} => {
|
||||
failures.extend(staging_failures);
|
||||
RunCurateQmBars1mError::RollbackFailed {
|
||||
cause: inner_cause,
|
||||
failures,
|
||||
}
|
||||
}
|
||||
other => RunCurateQmBars1mError::RollbackFailed {
|
||||
cause: Box::new(other),
|
||||
failures: staging_failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging
|
||||
/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging
|
||||
/// unlink failure reporting deterministically.
|
||||
fn run_curate_qm_bars_1m_to_dir_with_cleanup_hook<R, W, SF, BL, RF>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
intraday: R,
|
||||
mut make_sink: SF,
|
||||
before_link: BL,
|
||||
mut remove_staged_file: RF,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
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<W> = 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 remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
let guard = StagingFileGuard::new(tmp_path.clone());
|
||||
staged.push((tmp_path, guard));
|
||||
sinks.push(make_sink(shard_idx, 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 remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
|
||||
{
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err,
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = publish_staged_shards_for_table(
|
||||
&args.out_dir,
|
||||
QM_BARS_1M_SHARD_PREFIX,
|
||||
&mut staged,
|
||||
before_link,
|
||||
) {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err.into(),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting an injected reader, 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_qm_bars_1m_to_dir_with_hooks<R, W, SF, BL>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
intraday: R,
|
||||
make_sink: SF,
|
||||
before_link: BL,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
{
|
||||
run_curate_qm_bars_1m_to_dir_with_cleanup_hook(
|
||||
args,
|
||||
intraday,
|
||||
make_sink,
|
||||
before_link,
|
||||
|path| fs::remove_file(path),
|
||||
)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
args: &CurateQmBars1mArgs,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError> {
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let intraday_file =
|
||||
File::open(&args.intraday_path).map_err(|source| RunCurateQmBars1mError::OpenInput {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
run_curate_qm_bars_1m_to_dir_with_hooks(
|
||||
args,
|
||||
intraday_file,
|
||||
|_shard_idx, file| SyncedBufFile::new(file),
|
||||
|_shard_idx, _final_path| {},
|
||||
)
|
||||
}
|
||||
|
||||
/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_qm_bars_1m_report(report: &CurateQmBars1mRunReport) -> 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;
|
||||
|
||||
format!(
|
||||
"curate-etl curate-qm-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 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.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_qm_bars_1m_tests.rs"]
|
||||
mod tests;
|
||||
1430
tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs
Normal file
1430
tools/curate-etl/src/run_curate_qm_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