T-183: M2.3l — tools/curate-etl: file-to-file fx_1m runner (run_curate_fx_1m.rs: raw eodIntraday1M BSON dump → curate_and_write_fx_1m_from_bson → per-shard fx_1m.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:
Studio 2026-12-02 18:41:38 -05:00
parent 02cc44e70b
commit e45889c525
6 changed files with 1620 additions and 38 deletions

View file

@ -1675,6 +1675,14 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m
- **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:** Preflight scans `out_dir` for any pre-existing `bars_1m.shard-<digits>.ilp` file (regardless of `shard_count`) and rejects 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.
## `run_curate_fx_1m` File-to-File Runner (`M2.3l`)
`run_curate_fx_1m` / `run_curate_fx_1m_with_readers` (`src/run_curate_fx_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`) via `curate_and_write_fx_1m_from_bson` (`src/curate_fx_1m.rs`):
- **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers.
- **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.
## 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).

View file

@ -328,6 +328,12 @@ pub use run_curate_bars_1m::{
DEFAULT_BARS_1M_MAPPING_SOURCE,
};
pub mod run_curate_fx_1m;
pub use run_curate_fx_1m::{
format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs,
CurateFx1mRunReport, RunCurateFx1mError,
};
pub mod run_curate_adj;
pub use run_curate_adj::{
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,

View file

@ -65,7 +65,9 @@ use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader}
use crate::curate_bars_1m::{
curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError,
};
use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions};
use crate::ilp::{
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M,
};
use crate::parquet_bars::RollbackFailure;
use crate::parquet_publish::{
next_run_id, rollback_published, PublishedPartition, StagingFileGuard, FILE_BUF_CAPACITY_BYTES,
@ -269,6 +271,32 @@ fn validate_common_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mEr
Ok(())
}
pub(crate) enum ShardPublishError {
InvalidOutDir { path: PathBuf, detail: String },
OutputFileExists { path: PathBuf },
Io { path: PathBuf, source: io::Error },
RollbackFailed {
cause: Box<ShardPublishError>,
failures: Vec<RollbackFailure>,
},
}
impl From<ShardPublishError> for RunCurateBars1mError {
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,
},
}
}
}
fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> {
validate_common_args(args)?;
if args.ilp_options.max_batch_bytes == 0 {
@ -277,30 +305,38 @@ fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1
if args.ilp_options.max_batch_rows == 0 {
return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchRows));
}
if args.out_dir.exists() {
if !args.out_dir.is_dir() {
return Err(RunCurateBars1mError::InvalidOutDir {
path: args.out_dir.clone(),
preflight_shard_out_dir(&args.out_dir, TABLE_BARS_1M)?;
Ok(())
}
pub(crate) fn preflight_shard_out_dir(
out_dir: &Path,
table: &str,
) -> Result<(), ShardPublishError> {
if out_dir.exists() {
if !out_dir.is_dir() {
return Err(ShardPublishError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
let entries = fs::read_dir(&args.out_dir).map_err(|source| RunCurateBars1mError::Io {
path: args.out_dir.clone(),
let entries = fs::read_dir(out_dir).map_err(|source| ShardPublishError::Io {
path: out_dir.to_path_buf(),
source,
})?;
let mut existing_shards: Vec<PathBuf> = Vec::new();
for entry in entries {
let entry = entry.map_err(|source| RunCurateBars1mError::Io {
path: args.out_dir.clone(),
let entry = entry.map_err(|source| ShardPublishError::Io {
path: out_dir.to_path_buf(),
source,
})?;
if is_final_shard_file_name(&entry.file_name()) {
if is_final_shard_file_name_for_table(table, &entry.file_name()) {
existing_shards.push(entry.path());
}
}
if !existing_shards.is_empty() {
existing_shards.sort();
return Err(RunCurateBars1mError::OutputFileExists {
return Err(ShardPublishError::OutputFileExists {
path: existing_shards.remove(0),
});
}
@ -309,11 +345,14 @@ fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1
}
#[inline]
fn is_final_shard_file_name(name: &OsStr) -> bool {
pub(crate) fn is_final_shard_file_name_for_table(table: &str, name: &OsStr) -> bool {
let Some(s) = name.to_str() else {
return false;
};
let Some(rest) = s.strip_prefix("bars_1m.shard-") else {
let Some(after_table) = s.strip_prefix(table) else {
return false;
};
let Some(rest) = after_table.strip_prefix(".shard-") else {
return false;
};
let Some(digits) = rest.strip_suffix(".ilp") else {
@ -323,8 +362,12 @@ fn is_final_shard_file_name(name: &OsStr) -> bool {
}
#[inline]
fn final_shard_path(out_dir: &Path, shard_idx: usize) -> PathBuf {
out_dir.join(format!("bars_1m.shard-{shard_idx:02}.ilp"))
pub(crate) fn final_shard_path_for_table(
out_dir: &Path,
table: &str,
shard_idx: usize,
) -> PathBuf {
out_dir.join(format!("{table}.shard-{shard_idx:02}.ilp"))
}
fn load_reference_inputs<RS: io::Read>(
@ -546,12 +589,12 @@ where
/// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once
/// per shard by [`IlpShardedWriter::finish`]).
struct SyncedBufFile {
pub(crate) struct SyncedBufFile {
inner: BufWriter<File>,
}
impl SyncedBufFile {
fn new(file: File) -> Self {
pub(crate) fn new(file: File) -> Self {
Self {
inner: BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file),
}
@ -573,16 +616,17 @@ impl Write for SyncedBufFile {
}
}
fn create_exclusive_shard_tmp_file(
pub(crate) fn create_exclusive_shard_tmp_file_for_table(
out_dir: &Path,
table: &str,
shard_idx: usize,
run_id: &str,
) -> Result<(PathBuf, File), RunCurateBars1mError> {
) -> Result<(PathBuf, File), ShardPublishError> {
for attempt in 0..1024u32 {
let file_name = if attempt == 0 {
format!(".bars_1m.shard-{shard_idx:02}.{run_id}.tmp")
format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")
} else {
format!(".bars_1m.shard-{shard_idx:02}.{run_id}.{attempt}.tmp")
format!(".{table}.shard-{shard_idx:02}.{run_id}.{attempt}.tmp")
};
let tmp_path = out_dir.join(file_name);
match OpenOptions::new()
@ -593,15 +637,15 @@ fn create_exclusive_shard_tmp_file(
Ok(file) => return Ok((tmp_path, file)),
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
Err(source) => {
return Err(RunCurateBars1mError::Io {
return Err(ShardPublishError::Io {
path: tmp_path,
source,
});
}
}
}
Err(RunCurateBars1mError::Io {
path: out_dir.join(format!(".bars_1m.shard-{shard_idx:02}.{run_id}.tmp")),
Err(ShardPublishError::Io {
path: out_dir.join(format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")),
source: io::Error::new(
io::ErrorKind::AlreadyExists,
"exhausted unique staging file names",
@ -609,32 +653,33 @@ fn create_exclusive_shard_tmp_file(
})
}
fn publish_staged_shards<F>(
pub(crate) fn publish_staged_shards_for_table<F>(
out_dir: &Path,
table: &str,
mut staged: Vec<(PathBuf, StagingFileGuard)>,
mut before_link: F,
) -> Result<(), RunCurateBars1mError>
) -> Result<(), ShardPublishError>
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);
let final_path = final_shard_path_for_table(out_dir, table, 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 }
ShardPublishError::OutputFileExists { path: final_path }
} else {
RunCurateBars1mError::Io {
ShardPublishError::Io {
path: final_path,
source,
}
};
let rollback_failures = rollback_published(&published);
if !rollback_failures.is_empty() {
return Err(RunCurateBars1mError::RollbackFailed {
return Err(ShardPublishError::RollbackFailed {
cause: Box::new(cause),
failures: rollback_failures,
});
@ -648,13 +693,13 @@ where
});
if let Err(source) = fs::remove_file(&tmp_path) {
let cause = RunCurateBars1mError::Io {
let cause = ShardPublishError::Io {
path: tmp_path.clone(),
source,
};
let rollback_failures = rollback_published(&published);
if !rollback_failures.is_empty() {
return Err(RunCurateBars1mError::RollbackFailed {
return Err(ShardPublishError::RollbackFailed {
cause: Box::new(cause),
failures: rollback_failures,
});
@ -698,7 +743,12 @@ where
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 (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(make_sink(shard_idx, file));
@ -707,7 +757,7 @@ 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)?;
publish_staged_shards(&args.out_dir, staged, before_link)?;
publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, staged, before_link)?;
Ok(report)
}
@ -839,4 +889,4 @@ pub fn format_curate_bars_1m_report(report: &CurateBars1mRunReport) -> String {
#[cfg(test)]
#[path = "run_curate_bars_1m_tests.rs"]
mod tests;
pub(crate) mod tests;

View file

@ -20,12 +20,12 @@ use crate::split::ymd_to_epoch_days;
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDirGuard {
pub(crate) struct TempDirGuard {
path: PathBuf,
}
impl TempDirGuard {
fn new(prefix: &str) -> Self {
pub(crate) fn new(prefix: &str) -> Self {
let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"curate-etl-{prefix}-{}-{seq}",
@ -35,7 +35,7 @@ impl TempDirGuard {
Self { path }
}
fn path(&self) -> &Path {
pub(crate) fn path(&self) -> &Path {
&self.path
}
}

View file

@ -0,0 +1,414 @@
//! File-to-file `fx_1m` runner (`M2.3l`).
//!
//! Streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files
//! (`<out_dir>/fx_1m.shard-<NN>.ilp`) via [`crate::curate_fx_1m::curate_and_write_fx_1m_from_bson`].
//!
//! # Global Sort, Deduplication & Memory Bound
//! - Calls [`curate_and_write_fx_1m_from_bson`] **once** over the entire input stream so timestamp
//! sorting and `ts` deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop)
//! are global across all BSON stream chunks, then calls [`IlpShardedWriter::finish`] exactly
//! once after clean EOF.
//! - **Memory bound:** `Fx1mAccumulator::push` in `src/curate_fx_1m.rs` counts non-`CAD.FOREX`
//! rows in `dropped_wrong_code` and returns immediately without appending or allocating. Peak
//! memory is therefore bounded by:
//! - accepted `CAD.FOREX` rows (`Vec<Fx1mRow<'static>>`),
//! - the configured BSON stream chunk buffer (`BsonStreamOptions::chunk_capacity_bytes`,
//! growing only for a single document up to `max_doc_bytes`), and
//! - bounded ILP output batch buffers per shard (`IlpWriterOptions`) plus per-shard file
//! buffering in file mode.
//!
//! Non-`CAD.FOREX` rows from the full `eodIntraday1M` dump are never buffered.
//! - **Single-pair sharding:** every curated row carries `pair = "USDCAD"` and `source = "eod"`,
//! so [`IlpShardedWriter`] routes all rows deterministically to
//! `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files.
//! - **Timestamp provenance:** preserves EODHD's UTC microsecond bar-start `ts` and CAD-per-USD
//! OHLC bits verbatim; bar-start `ts` alone does not establish when the bar's close was
//! observable.
//! - **Omitted framing counters:** [`CurateFx1mRunReport`] omits `intraday_docs_framed` and
//! `intraday_bytes_read` because [`curate_and_write_fx_1m_from_bson`] owns the underlying
//! `RawBsonChunkReader` internally and returns [`BsonEodIntradayDecodeStats`] only.
//!
//! # File Publication & Fail-Closed Guarantees
//! - Preflight scans `out_dir` for **any** pre-existing `fx_1m.shard-<digits>.ilp` file
//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards
//! from a prior run cannot survive alongside a new export.
//! - Each shard writes into an exclusively created staging file in `out_dir`
//! (`.fx_1m.shard-<NN>.<run_id>.tmp`), flushes and `sync_all`s on `finish`, and publishes to
//! `fx_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 input, 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::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::bson_eod_intraday::BsonEodIntradayDecodeStats;
use crate::bson_stream::{BsonStreamError, BsonStreamOptions};
use crate::curate_fx_1m::{
curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, CurateFx1mStats,
};
use crate::ilp::{
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_FX_1M,
};
use crate::parquet_bars::RollbackFailure;
use crate::parquet_publish::{next_run_id, StagingFileGuard};
use crate::run_curate_bars_1m::{
create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir,
publish_staged_shards_for_table, ShardPublishError, SyncedBufFile,
};
/// Arguments for [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateFx1mArgs {
pub intraday_path: PathBuf,
pub out_dir: PathBuf,
pub shard_count: usize,
pub stream_options: BsonStreamOptions,
pub ilp_options: IlpWriterOptions,
}
/// Full run report produced by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`].
///
/// `intraday_docs_framed` and `intraday_bytes_read` are intentionally omitted because
/// [`curate_and_write_fx_1m_from_bson`] owns the underlying `RawBsonChunkReader` and returns
/// [`BsonEodIntradayDecodeStats`] only.
///
/// Conservation invariants:
/// - `decode.docs_seen == decode.rows_decoded + decode.rejected_total()`
/// - `decode.rows_decoded == curate_stats.bars_in`
/// - `curate_stats.bars_in == curate_stats.rows_out + curate_stats.dropped_wrong_code + curate_stats.dropped_negative_ts + curate_stats.dropped_invalid_ohlc + curate_stats.dropped_high_below_bound + curate_stats.dropped_low_above_bound + curate_stats.duplicate_collapsed + curate_stats.duplicate_conflict_dropped`
/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::<usize>()`
#[derive(Debug, Clone, PartialEq)]
pub struct CurateFx1mRunReport {
pub decode: BsonEodIntradayDecodeStats,
pub curate_stats: CurateFx1mStats,
pub rows_written: usize,
pub ilp_stats: IlpWriteStats,
pub shard_count: usize,
pub elapsed_secs: f64,
}
/// Typed errors returned by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`].
#[derive(Debug)]
pub enum RunCurateFx1mError {
/// `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 (`fx_1m.shard-<digits>.ilp`) already existed.
OutputFileExists { path: PathBuf },
/// Failed to open the input `eodIntraday1M` dump file.
OpenInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
/// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`.
BsonStream {
label: &'static str,
path: PathBuf,
source: BsonStreamError,
},
/// ILP writer initialization, per-row write, 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<RunCurateFx1mError>,
failures: Vec<RollbackFailure>,
},
}
impl From<ShardPublishError> for RunCurateFx1mError {
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 RunCurateFx1mError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
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::BsonStream {
label,
path,
source,
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
Self::Ilp(err) => write!(f, "fx_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 RunCurateFx1mError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source),
Self::BsonStream { source, .. } => Some(source),
Self::Ilp(err) => Some(err),
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
Self::ZeroShardCount
| Self::ShardCountMismatch { .. }
| Self::InvalidOutDir { .. }
| Self::OutputFileExists { .. } => None,
}
}
}
fn validate_common_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> {
if args.shard_count == 0 {
return Err(RunCurateFx1mError::ZeroShardCount);
}
args.stream_options
.validate()
.map_err(|source| RunCurateFx1mError::BsonStream {
label: "eod-intraday",
path: args.intraday_path.clone(),
source,
})?;
Ok(())
}
fn validate_file_mode_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> {
validate_common_args(args)?;
if args.ilp_options.max_batch_bytes == 0 {
return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes));
}
if args.ilp_options.max_batch_rows == 0 {
return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows));
}
preflight_shard_out_dir(&args.out_dir, TABLE_FX_1M)?;
Ok(())
}
fn run_curate_fx_1m_with_readers_inner<R, W>(
args: &CurateFx1mArgs,
intraday: R,
mut writer: IlpShardedWriter<W>,
start: Instant,
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
where
R: io::Read,
W: Write + Send,
{
let bson_report =
curate_and_write_fx_1m_from_bson(intraday, args.stream_options, &mut writer).map_err(
|err| match err {
CurateFx1mBsonError::Stream(source) => RunCurateFx1mError::BsonStream {
label: "eod-intraday",
path: args.intraday_path.clone(),
source,
},
CurateFx1mBsonError::Write(err) => RunCurateFx1mError::Ilp(err),
},
)?;
let ilp_stats = writer.finish().map_err(RunCurateFx1mError::Ilp)?;
Ok(CurateFx1mRunReport {
decode: bson_report.decode_stats,
curate_stats: bson_report.write_report.curate_stats,
rows_written: bson_report.write_report.rows_written,
ilp_stats,
shard_count: args.shard_count,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
/// Runs the `fx_1m` curation pipeline from an arbitrary [`io::Read`] stream into a caller-owned
/// [`IlpShardedWriter`].
///
/// Validates `args` and writer shard-count agreement, calls [`curate_and_write_fx_1m_from_bson`]
/// once over the entire stream for global sort and `ts` deduplication, and calls
/// [`IlpShardedWriter::finish`] exactly once after clean EOF.
pub fn run_curate_fx_1m_with_readers<R, W>(
args: &CurateFx1mArgs,
intraday: R,
writer: IlpShardedWriter<W>,
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
where
R: io::Read,
W: Write + Send,
{
let start = Instant::now();
validate_common_args(args)?;
if writer.shard_count() != args.shard_count {
return Err(RunCurateFx1mError::ShardCountMismatch {
expected: args.shard_count,
actual: writer.shard_count(),
});
}
run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)
}
/// 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_fx_1m_to_dir_with_hooks<R, W, SF, BL>(
args: &CurateFx1mArgs,
intraday: R,
mut make_sink: SF,
before_link: BL,
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
where
R: io::Read,
W: Write + Send,
SF: FnMut(usize, File) -> W,
BL: FnMut(usize, &Path),
{
let start = Instant::now();
validate_file_mode_args(args)?;
fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateFx1mError::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_for_table(
&args.out_dir,
TABLE_FX_1M,
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(RunCurateFx1mError::Ilp)?;
let report = run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)?;
publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, staged, before_link)?;
Ok(report)
}
/// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB
/// ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`).
pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result<CurateFx1mRunReport, RunCurateFx1mError> {
validate_file_mode_args(args)?;
let intraday_file = File::open(&args.intraday_path).map_err(|source| {
RunCurateFx1mError::OpenInput {
label: "eod-intraday",
path: args.intraday_path.clone(),
source,
}
})?;
run_curate_fx_1m_to_dir_with_hooks(
args,
intraday_file,
|_shard_idx, file| SyncedBufFile::new(file),
|_shard_idx, _final_path| {},
)
}
/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary.
///
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
pub fn format_curate_fx_1m_report(report: &CurateFx1mRunReport) -> 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 d = &report.decode;
let c = &report.curate_stats;
format!(
"curate-etl curate-fx-1m\n\
\x20 intraday_bson: docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\
\x20 curate: bars_in={} rows_out={} wrong_code={} negative_ts={} invalid_ohlc={} high_below_bound={} low_above_bound={} dup_collapsed={} dup_conflict_dropped={}\n\
\x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\
\x20 timing: elapsed_secs={:.6}",
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,
c.bars_in,
c.rows_out,
c.dropped_wrong_code,
c.dropped_negative_ts,
c.dropped_invalid_ohlc,
c.dropped_high_below_bound,
c.dropped_low_above_bound,
c.duplicate_collapsed,
c.duplicate_conflict_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_fx_1m_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff