stock-bot/tools/curate-etl/src/run_curate_fx_1m.rs

555 lines
20 KiB
Rust

//! 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 },
/// Caller-supplied `IlpShardedWriter` already had queued or flushed rows before the run.
NonEmptyWriter {
flushed_rows: usize,
pending_rows: 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 or failure cleanup failed and removing one or more final or staging files 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::NonEmptyWriter {
flushed_rows,
pending_rows,
} => write!(
f,
"ILP writer must be fresh before running fx_1m (found {flushed_rows} flushed and {pending_rows} pending rows)"
),
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::NonEmptyWriter { .. }
| 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`, writer shard-count agreement, and that `writer` is fresh (zero queued or
/// flushed rows) before reading `intraday`. 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(),
});
}
let (flushed_rows, pending_rows) = writer.row_counts();
if flushed_rows > 0 || pending_rows > 0 {
return Err(RunCurateFx1mError::NonEmptyWriter {
flushed_rows,
pending_rows,
});
}
run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)
}
pub(crate) fn cleanup_armed_staged_shards<RF>(
staged: &mut [(PathBuf, StagingFileGuard)],
remove_file: &mut RF,
) -> Vec<RollbackFailure>
where
RF: FnMut(&Path) -> io::Result<()>,
{
let mut failures = Vec::new();
for (tmp_path, guard) in staged.iter_mut() {
if !guard.is_armed() {
continue;
}
match remove_file(tmp_path) {
Ok(()) => guard.disarm(),
Err(err) if err.kind() == io::ErrorKind::NotFound => guard.disarm(),
Err(source) => {
guard.disarm();
failures.push(RollbackFailure {
final_path: tmp_path.clone(),
backup_path: None,
source,
});
}
}
}
failures
}
fn fail_with_staging_cleanup<RF>(
cause: RunCurateFx1mError,
staged: &mut [(PathBuf, StagingFileGuard)],
remove_file: &mut RF,
) -> RunCurateFx1mError
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 {
RunCurateFx1mError::RollbackFailed {
cause: inner_cause,
mut failures,
} => {
failures.extend(staging_failures);
RunCurateFx1mError::RollbackFailed {
cause: inner_cause,
failures,
}
}
other => RunCurateFx1mError::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_fx_1m_to_dir_with_cleanup_hook<R, W, SF, BL, RF>(
args: &CurateFx1mArgs,
intraday: R,
mut make_sink: SF,
before_link: BL,
mut remove_staged_file: RF,
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
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)?;
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) = match create_exclusive_shard_tmp_file_for_table(
&args.out_dir,
TABLE_FX_1M,
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(
RunCurateFx1mError::Ilp(err),
&mut staged,
&mut remove_staged_file,
));
}
};
let report = match run_curate_fx_1m_with_readers_inner(args, 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, TABLE_FX_1M, &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_fx_1m_to_dir_with_hooks<R, W, SF, BL>(
args: &CurateFx1mArgs,
intraday: R,
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),
{
run_curate_fx_1m_to_dir_with_cleanup_hook(
args,
intraday,
make_sink,
before_link,
|path| fs::remove_file(path),
)
}
/// 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;