708 lines
25 KiB
Rust
708 lines
25 KiB
Rust
//! File-to-file `curate-fx-1d` command runner (`M1.2ac`).
|
|
//!
|
|
//! Streams concatenated raw BSON `eodPrices` (`CAD.FOREX`) and `teMarketData` (`USDCAD`,
|
|
//! configurable via `--te-symbol`) dump files into an atomically published
|
|
//! `<out_dir>/fx_1d/part.parquet` dataset via [`curate_and_write_fx_1d`].
|
|
//!
|
|
//! # Source Filtering & Contract Rules
|
|
//! - `--eod-prices`: streams via [`RawBsonChunkReader`] + [`decode_eod_price_chunks`], keeping
|
|
//! only documents whose `eodSearchCode` is exactly [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`).
|
|
//! Other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when
|
|
//! mapping to [`FxDailyBar`].
|
|
//! - `--te-market-data`: streams via [`RawBsonChunkReader`] + [`decode_te_market_data_chunks`],
|
|
//! keeping only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive,
|
|
//! default [`DEFAULT_TE_SYMBOL`] = `"USDCAD"`). `monthly`, `pc`, `ac`, and unknown fields are
|
|
//! ignored.
|
|
//! - Delegates merge precedence (`CAD.FOREX` wins on overlap, `teMarketData` fills interior gaps
|
|
//! and post-EOD tail), read-only 1% overlap cross-check, conservative `23:59:59.999999 UTC`
|
|
//! `ts`/`known_at` stamping, and atomic Zstd Parquet publication unchanged to
|
|
//! [`curate_and_write_fx_1d`].
|
|
//! - **Fail-closed safety:** invalid `--out`, unsupported/blank `--te-symbol`, unreadable input
|
|
//! files, corrupt/truncated BSON framing or element bytes, zero decoded bars across both
|
|
//! sources, and zero publishable rows after FX curation each return a typed [`RunCurateFxError`]
|
|
//! without modifying any pre-existing `<out_dir>/fx_1d/part.parquet`.
|
|
//!
|
|
//! # Counter Conservation Invariants
|
|
//! Every successful [`CurateFx1dRunReport`] satisfies:
|
|
//! - EOD BSON:
|
|
//! `eod_docs_framed as usize == eod_decode.docs_in == eod_decode.decoded + eod_decode.rejected_total()`
|
|
//! `eod_decode.decoded == eod_cad_forex_kept + eod_other_symbol_skipped`
|
|
//! `eod_cad_forex_kept == curate_stats.builder.eod.rows_in`
|
|
//! - TE BSON:
|
|
//! `te_docs_framed as usize == te_decode.docs_in == te_decode.docs_matched + te_decode.docs_other_symbol + te_decode.docs_rejected_total()`
|
|
//! `te_decode.points_in == te_decode.points_decoded + te_decode.rejected_total()`
|
|
//! `te_decode.points_decoded == curate_stats.builder.te.rows_in`
|
|
//! - Stage & Write:
|
|
//! `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out == write_stats.rows_written`
|
|
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
use std::fs::File;
|
|
use std::io;
|
|
use std::path::{Path, PathBuf};
|
|
use std::time::Instant;
|
|
|
|
use crate::bson_eod_prices::{BsonEodDecodeStats, BsonEodPriceError};
|
|
use crate::bson_stream::{
|
|
decode_eod_price_chunks, decode_te_market_data_chunks, BsonStreamError, BsonStreamOptions,
|
|
RawBsonChunkReader,
|
|
};
|
|
use crate::bson_te_market_data::{BsonTeMarketDataDecodeStats, BsonTeMarketDataError};
|
|
use crate::curate_fx::{
|
|
curate_and_write_fx_1d, curate_fx_1d, CurateFx1dStats, CurateFxWriteError,
|
|
};
|
|
use crate::fx::FxDailyBar;
|
|
use crate::parquet_fx::{
|
|
write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats,
|
|
};
|
|
|
|
/// Exact `eodPrices.eodSearchCode` kept for USD/CAD FX curation.
|
|
pub const EOD_CAD_FOREX_CODE: &str = "CAD.FOREX";
|
|
/// Default `--te-symbol` matched (ASCII case-insensitive) against `teMarketData.teSymbol`.
|
|
pub const DEFAULT_TE_SYMBOL: &str = "USDCAD";
|
|
/// Verified USD/CAD `teMarketData.teSymbol` selectors accepted by `curate-fx-1d`
|
|
/// (matched ASCII case-insensitively).
|
|
pub const ALLOWED_TE_SYMBOLS: &[&str] = &[DEFAULT_TE_SYMBOL];
|
|
|
|
/// Returns `true` if `te_symbol` is an allowed USD/CAD `teMarketData` selector
|
|
/// (ASCII case-insensitive match against [`ALLOWED_TE_SYMBOLS`]).
|
|
#[inline]
|
|
pub fn is_supported_te_symbol(te_symbol: &str) -> bool {
|
|
ALLOWED_TE_SYMBOLS
|
|
.iter()
|
|
.any(|allowed| te_symbol.eq_ignore_ascii_case(allowed))
|
|
}
|
|
|
|
/// Parsed arguments for the `curate-fx-1d` CLI command.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct CurateFx1dArgs {
|
|
pub eod_prices: PathBuf,
|
|
pub te_market_data: PathBuf,
|
|
pub te_symbol: String,
|
|
pub out_dir: PathBuf,
|
|
}
|
|
|
|
/// Full run report produced by [`run_curate_fx_1d`].
|
|
///
|
|
/// Conservation invariants:
|
|
/// - `eod_docs_framed as usize == eod_decode.docs_in == eod_decode.decoded + eod_decode.rejected_total()`
|
|
/// - `eod_decode.decoded == eod_cad_forex_kept + eod_other_symbol_skipped`
|
|
/// - `eod_cad_forex_kept == curate_stats.builder.eod.rows_in`
|
|
/// - `te_docs_framed as usize == te_decode.docs_in == te_decode.docs_matched + te_decode.docs_other_symbol + te_decode.docs_rejected_total()`
|
|
/// - `te_decode.points_in == te_decode.points_decoded + te_decode.rejected_total()`
|
|
/// - `te_decode.points_decoded == curate_stats.builder.te.rows_in`
|
|
/// - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out == write_stats.rows_written`
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct CurateFx1dRunReport {
|
|
pub eod_docs_framed: u64,
|
|
pub eod_bytes_read: u64,
|
|
pub eod_decode: BsonEodDecodeStats,
|
|
pub eod_cad_forex_kept: usize,
|
|
pub eod_other_symbol_skipped: usize,
|
|
pub te_docs_framed: u64,
|
|
pub te_bytes_read: u64,
|
|
pub te_decode: BsonTeMarketDataDecodeStats,
|
|
pub curate_stats: CurateFx1dStats,
|
|
pub write_stats: Fx1dWriteStats,
|
|
pub elapsed_secs: f64,
|
|
}
|
|
|
|
/// Stage-timed run output used internally by `bench-curate-fx-cmd`.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub(crate) struct CurateFx1dTimedRun {
|
|
pub report: CurateFx1dRunReport,
|
|
pub decode_elapsed_secs: f64,
|
|
pub curate_elapsed_secs: f64,
|
|
pub write_elapsed_secs: f64,
|
|
pub checksum: u64,
|
|
}
|
|
|
|
/// Typed errors returned by [`run_curate_fx_1d`].
|
|
///
|
|
/// Every variant's `Display` output is a single line naming the offending path (and byte offset
|
|
/// for BSON framing/corruption errors).
|
|
#[derive(Debug)]
|
|
pub enum RunCurateFxError {
|
|
InvalidOutDir {
|
|
path: PathBuf,
|
|
detail: String,
|
|
},
|
|
InvalidTeSymbol {
|
|
value: String,
|
|
},
|
|
OpenInput {
|
|
label: &'static str,
|
|
path: PathBuf,
|
|
source: io::Error,
|
|
},
|
|
BsonStream {
|
|
label: &'static str,
|
|
path: PathBuf,
|
|
source: BsonStreamError,
|
|
},
|
|
CorruptEodBson {
|
|
path: PathBuf,
|
|
offset: u64,
|
|
source: BsonEodPriceError,
|
|
},
|
|
CorruptTeBson {
|
|
path: PathBuf,
|
|
offset: u64,
|
|
source: BsonTeMarketDataError,
|
|
},
|
|
NoDecodedBars {
|
|
eod_path: PathBuf,
|
|
te_path: PathBuf,
|
|
te_symbol: String,
|
|
},
|
|
NoCuratedRows {
|
|
eod_path: PathBuf,
|
|
te_path: PathBuf,
|
|
eod_bars_in: usize,
|
|
te_bars_in: usize,
|
|
},
|
|
CurateWrite {
|
|
out_dir: PathBuf,
|
|
source: CurateFxWriteError,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for RunCurateFxError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::InvalidOutDir { path, detail } => {
|
|
write!(f, "invalid --out '{}': {detail}", path.display())
|
|
}
|
|
Self::InvalidTeSymbol { value } => {
|
|
write!(
|
|
f,
|
|
"invalid --te-symbol '{value}': only USD/CAD selector '{DEFAULT_TE_SYMBOL}' (case-insensitive) is supported for fx_1d"
|
|
)
|
|
}
|
|
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::CorruptEodBson {
|
|
path,
|
|
offset,
|
|
source,
|
|
} => write!(
|
|
f,
|
|
"corrupt eod-prices BSON '{}' at byte offset {offset}: {source}",
|
|
path.display()
|
|
),
|
|
Self::CorruptTeBson {
|
|
path,
|
|
offset,
|
|
source,
|
|
} => write!(
|
|
f,
|
|
"corrupt te-market-data BSON '{}' at byte offset {offset}: {source}",
|
|
path.display()
|
|
),
|
|
Self::NoDecodedBars {
|
|
eod_path,
|
|
te_path,
|
|
te_symbol,
|
|
} => write!(
|
|
f,
|
|
"no FX bars decoded for '{EOD_CAD_FOREX_CODE}' in '{}' or '{te_symbol}' in '{}'",
|
|
eod_path.display(),
|
|
te_path.display()
|
|
),
|
|
Self::NoCuratedRows {
|
|
eod_path,
|
|
te_path,
|
|
eod_bars_in,
|
|
te_bars_in,
|
|
} => write!(
|
|
f,
|
|
"no publishable fx_1d rows survived curation (eod_bars_in={eod_bars_in} from '{}', te_bars_in={te_bars_in} from '{}')",
|
|
eod_path.display(),
|
|
te_path.display()
|
|
),
|
|
Self::CurateWrite { out_dir, source } => {
|
|
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for RunCurateFxError {
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
match self {
|
|
Self::OpenInput { source, .. } => Some(source),
|
|
Self::BsonStream { source, .. } => Some(source),
|
|
Self::CorruptEodBson { source, .. } => Some(source),
|
|
Self::CorruptTeBson { source, .. } => Some(source),
|
|
Self::CurateWrite { source, .. } => Some(source),
|
|
Self::InvalidOutDir { .. }
|
|
| Self::InvalidTeSymbol { .. }
|
|
| Self::NoDecodedBars { .. }
|
|
| Self::NoCuratedRows { .. } => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateFxError> {
|
|
if out_dir.exists() && !out_dir.is_dir() {
|
|
return Err(RunCurateFxError::InvalidOutDir {
|
|
path: out_dir.to_path_buf(),
|
|
detail: "path exists and is not a directory".to_string(),
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn validate_te_symbol(te_symbol: &str) -> Result<(), RunCurateFxError> {
|
|
if !is_supported_te_symbol(te_symbol) {
|
|
return Err(RunCurateFxError::InvalidTeSymbol {
|
|
value: te_symbol.to_string(),
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[inline]
|
|
fn is_structural_eod_bson_error(err: &BsonEodPriceError) -> bool {
|
|
matches!(
|
|
err,
|
|
BsonEodPriceError::TruncatedDocument { .. }
|
|
| BsonEodPriceError::CorruptDocumentLength { .. }
|
|
| BsonEodPriceError::CorruptBson { .. }
|
|
)
|
|
}
|
|
|
|
#[inline]
|
|
fn is_structural_te_bson_error(err: &BsonTeMarketDataError) -> bool {
|
|
matches!(
|
|
err,
|
|
BsonTeMarketDataError::TruncatedDocument { .. }
|
|
| BsonTeMarketDataError::CorruptDocumentLength { .. }
|
|
| BsonTeMarketDataError::CorruptBson { .. }
|
|
| BsonTeMarketDataError::CorruptPointBson { .. }
|
|
)
|
|
}
|
|
|
|
struct DecodedFxInputs {
|
|
eod_bars: Vec<FxDailyBar>,
|
|
te_bars: Vec<FxDailyBar>,
|
|
eod_docs_framed: u64,
|
|
eod_bytes_read: u64,
|
|
eod_decode: BsonEodDecodeStats,
|
|
eod_cad_forex_kept: usize,
|
|
eod_other_symbol_skipped: usize,
|
|
te_docs_framed: u64,
|
|
te_bytes_read: u64,
|
|
te_decode: BsonTeMarketDataDecodeStats,
|
|
}
|
|
|
|
fn decode_all_inputs(args: &CurateFx1dArgs) -> Result<DecodedFxInputs, RunCurateFxError> {
|
|
decode_inputs_from_openers(
|
|
&args.eod_prices,
|
|
|| {
|
|
File::open(&args.eod_prices).map_err(|source| RunCurateFxError::OpenInput {
|
|
label: "eod-prices",
|
|
path: args.eod_prices.clone(),
|
|
source,
|
|
})
|
|
},
|
|
&args.te_market_data,
|
|
|| {
|
|
File::open(&args.te_market_data).map_err(|source| RunCurateFxError::OpenInput {
|
|
label: "te-market-data",
|
|
path: args.te_market_data.clone(),
|
|
source,
|
|
})
|
|
},
|
|
&args.te_symbol,
|
|
)
|
|
}
|
|
|
|
fn decode_inputs_from_openers<RE, FE, RT, FT>(
|
|
eod_prices_path: &Path,
|
|
open_eod: FE,
|
|
te_market_data_path: &Path,
|
|
open_te: FT,
|
|
te_symbol: &str,
|
|
) -> Result<DecodedFxInputs, RunCurateFxError>
|
|
where
|
|
RE: io::Read,
|
|
FE: FnOnce() -> Result<RE, RunCurateFxError>,
|
|
RT: io::Read,
|
|
FT: FnOnce() -> Result<RT, RunCurateFxError>,
|
|
{
|
|
// 1. Stream `eodPrices` and retain exact `CAD.FOREX` bars.
|
|
let eod_stream = open_eod()?;
|
|
let mut eod_reader =
|
|
RawBsonChunkReader::with_options(eod_stream, BsonStreamOptions::default()).map_err(
|
|
|source| RunCurateFxError::BsonStream {
|
|
label: "eod-prices",
|
|
path: eod_prices_path.to_path_buf(),
|
|
source,
|
|
},
|
|
)?;
|
|
let mut eod_bars: Vec<FxDailyBar> = Vec::new();
|
|
let mut eod_cad_forex_kept = 0usize;
|
|
let mut eod_other_symbol_skipped = 0usize;
|
|
let mut eod_corrupt_err: Option<(u64, BsonEodPriceError)> = None;
|
|
|
|
let eod_decode_res = decode_eod_price_chunks(
|
|
&mut eod_reader,
|
|
|raw| {
|
|
if raw.eod_search_code == EOD_CAD_FOREX_CODE {
|
|
eod_cad_forex_kept += 1;
|
|
eod_bars.push(FxDailyBar {
|
|
session_date: raw.session_date,
|
|
open: raw.open,
|
|
high: raw.high,
|
|
low: raw.low,
|
|
close: raw.close,
|
|
});
|
|
} else {
|
|
eod_other_symbol_skipped += 1;
|
|
}
|
|
},
|
|
|offset, err| {
|
|
if eod_corrupt_err.is_none() && is_structural_eod_bson_error(&err) {
|
|
eod_corrupt_err = Some((offset, err));
|
|
}
|
|
},
|
|
);
|
|
if let Some((offset, source)) = eod_corrupt_err {
|
|
return Err(RunCurateFxError::CorruptEodBson {
|
|
path: eod_prices_path.to_path_buf(),
|
|
offset,
|
|
source,
|
|
});
|
|
}
|
|
let eod_decode = eod_decode_res.map_err(|source| RunCurateFxError::BsonStream {
|
|
label: "eod-prices",
|
|
path: eod_prices_path.to_path_buf(),
|
|
source,
|
|
})?;
|
|
let eod_docs_framed = eod_reader.docs_framed();
|
|
let eod_bytes_read = eod_reader.bytes_read();
|
|
|
|
// 2. Stream `teMarketData` and retain points for `te_symbol` (ASCII case-insensitive).
|
|
let te_stream = open_te()?;
|
|
let mut te_reader =
|
|
RawBsonChunkReader::with_options(te_stream, BsonStreamOptions::default()).map_err(
|
|
|source| RunCurateFxError::BsonStream {
|
|
label: "te-market-data",
|
|
path: te_market_data_path.to_path_buf(),
|
|
source,
|
|
},
|
|
)?;
|
|
let mut te_bars: Vec<FxDailyBar> = Vec::new();
|
|
let mut te_corrupt_err: Option<(u64, BsonTeMarketDataError)> = None;
|
|
|
|
let te_decode_res = decode_te_market_data_chunks(
|
|
&mut te_reader,
|
|
te_symbol,
|
|
|bar| {
|
|
te_bars.push(bar);
|
|
},
|
|
|offset, err| {
|
|
if te_corrupt_err.is_none() && is_structural_te_bson_error(&err) {
|
|
te_corrupt_err = Some((offset, err));
|
|
}
|
|
},
|
|
);
|
|
if let Some((offset, source)) = te_corrupt_err {
|
|
return Err(RunCurateFxError::CorruptTeBson {
|
|
path: te_market_data_path.to_path_buf(),
|
|
offset,
|
|
source,
|
|
});
|
|
}
|
|
let te_decode = te_decode_res.map_err(|source| RunCurateFxError::BsonStream {
|
|
label: "te-market-data",
|
|
path: te_market_data_path.to_path_buf(),
|
|
source,
|
|
})?;
|
|
let te_docs_framed = te_reader.docs_framed();
|
|
let te_bytes_read = te_reader.bytes_read();
|
|
|
|
if eod_bars.is_empty() && te_bars.is_empty() {
|
|
return Err(RunCurateFxError::NoDecodedBars {
|
|
eod_path: eod_prices_path.to_path_buf(),
|
|
te_path: te_market_data_path.to_path_buf(),
|
|
te_symbol: te_symbol.to_owned(),
|
|
});
|
|
}
|
|
|
|
Ok(DecodedFxInputs {
|
|
eod_bars,
|
|
te_bars,
|
|
eod_docs_framed,
|
|
eod_bytes_read,
|
|
eod_decode,
|
|
eod_cad_forex_kept,
|
|
eod_other_symbol_skipped,
|
|
te_docs_framed,
|
|
te_bytes_read,
|
|
te_decode,
|
|
})
|
|
}
|
|
|
|
/// Runs the end-to-end `curate-fx-1d` file-to-Parquet pipeline via [`curate_and_write_fx_1d`].
|
|
///
|
|
/// Any validation, I/O, BSON framing/corruption, zero-bar, or curation error returns before
|
|
/// touching `args.out_dir`, leaving any pre-existing `<out_dir>/fx_1d/part.parquet`
|
|
/// byte-identical.
|
|
pub fn run_curate_fx_1d(args: &CurateFx1dArgs) -> Result<CurateFx1dRunReport, RunCurateFxError> {
|
|
let start = Instant::now();
|
|
validate_out_dir(&args.out_dir)?;
|
|
validate_te_symbol(&args.te_symbol)?;
|
|
|
|
let decoded = decode_all_inputs(args)?;
|
|
finish_curate_fx_1d(
|
|
decoded,
|
|
&args.eod_prices,
|
|
&args.te_market_data,
|
|
&args.out_dir,
|
|
start,
|
|
)
|
|
}
|
|
|
|
/// Runs `curate-fx-1d` from arbitrary raw-BSON [`io::Read`] streams.
|
|
pub fn run_curate_fx_1d_with_readers<RE: io::Read, RT: io::Read>(
|
|
eod_prices_input: (&Path, RE),
|
|
te_market_data_input: (&Path, RT),
|
|
te_symbol: &str,
|
|
out_dir: &Path,
|
|
) -> Result<CurateFx1dRunReport, RunCurateFxError> {
|
|
let start = Instant::now();
|
|
validate_out_dir(out_dir)?;
|
|
validate_te_symbol(te_symbol)?;
|
|
|
|
let (eod_path, eod_stream) = eod_prices_input;
|
|
let (te_path, te_stream) = te_market_data_input;
|
|
let decoded = decode_inputs_from_openers(
|
|
eod_path,
|
|
|| Ok(eod_stream),
|
|
te_path,
|
|
|| Ok(te_stream),
|
|
te_symbol,
|
|
)?;
|
|
finish_curate_fx_1d(decoded, eod_path, te_path, out_dir, start)
|
|
}
|
|
|
|
fn finish_curate_fx_1d(
|
|
decoded: DecodedFxInputs,
|
|
eod_path: &Path,
|
|
te_path: &Path,
|
|
out_dir: &Path,
|
|
start: Instant,
|
|
) -> Result<CurateFx1dRunReport, RunCurateFxError> {
|
|
let write_report = curate_and_write_fx_1d(
|
|
out_dir,
|
|
&decoded.eod_bars,
|
|
&decoded.te_bars,
|
|
Fx1dWriteOptions::default(),
|
|
)
|
|
.map_err(|source| RunCurateFxError::CurateWrite {
|
|
out_dir: out_dir.to_path_buf(),
|
|
source,
|
|
})?;
|
|
if write_report.curate_stats.rows_out == 0 {
|
|
return Err(RunCurateFxError::NoCuratedRows {
|
|
eod_path: eod_path.to_path_buf(),
|
|
te_path: te_path.to_path_buf(),
|
|
eod_bars_in: decoded.eod_cad_forex_kept,
|
|
te_bars_in: decoded.te_decode.points_decoded,
|
|
});
|
|
}
|
|
|
|
Ok(CurateFx1dRunReport {
|
|
eod_docs_framed: decoded.eod_docs_framed,
|
|
eod_bytes_read: decoded.eod_bytes_read,
|
|
eod_decode: decoded.eod_decode,
|
|
eod_cad_forex_kept: decoded.eod_cad_forex_kept,
|
|
eod_other_symbol_skipped: decoded.eod_other_symbol_skipped,
|
|
te_docs_framed: decoded.te_docs_framed,
|
|
te_bytes_read: decoded.te_bytes_read,
|
|
te_decode: decoded.te_decode,
|
|
curate_stats: write_report.curate_stats,
|
|
write_stats: write_report.write_stats,
|
|
elapsed_secs: start.elapsed().as_secs_f64(),
|
|
})
|
|
}
|
|
|
|
fn compute_rows_checksum(rows: &[Fx1dParquetRow]) -> u64 {
|
|
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
|
|
let mix = |mut h: u64, v: u64| -> u64 {
|
|
h ^= v;
|
|
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
|
h
|
|
};
|
|
let mix_str = |mut h: u64, s: &str| -> u64 {
|
|
h = mix(h, s.len() as u64);
|
|
for &b in s.as_bytes() {
|
|
h = mix(h, u64::from(b));
|
|
}
|
|
h
|
|
};
|
|
for row in rows {
|
|
hash = mix_str(hash, row.pair.as_ref());
|
|
hash = mix(hash, row.session_date as u64);
|
|
hash = mix(hash, row.ts_micros as u64);
|
|
hash = mix(hash, row.open.to_bits());
|
|
hash = mix(hash, row.high.to_bits());
|
|
hash = mix(hash, row.low.to_bits());
|
|
hash = mix(hash, row.close.to_bits());
|
|
hash = mix_str(hash, row.source.as_ref());
|
|
hash = mix(hash, row.known_at_micros as u64);
|
|
}
|
|
hash
|
|
}
|
|
|
|
/// Stage-timed variant of [`run_curate_fx_1d`] used internally by `bench-curate-fx-cmd`.
|
|
///
|
|
/// Separately times `decode` (both BSON streams), `curate` (`curate_fx_1d`), and `write`
|
|
/// (`write_fx_1d_dataset`), and computes a deterministic FNV-1a checksum over all 9 columns of
|
|
/// the curated rows.
|
|
pub(crate) fn run_curate_fx_1d_timed(
|
|
args: &CurateFx1dArgs,
|
|
) -> Result<CurateFx1dTimedRun, RunCurateFxError> {
|
|
let total_start = Instant::now();
|
|
validate_out_dir(&args.out_dir)?;
|
|
validate_te_symbol(&args.te_symbol)?;
|
|
|
|
let decode_start = Instant::now();
|
|
let decoded = decode_all_inputs(args)?;
|
|
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
|
|
|
|
let curate_start = Instant::now();
|
|
let curated = curate_fx_1d(&decoded.eod_bars, &decoded.te_bars).map_err(|source| {
|
|
RunCurateFxError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateFxWriteError::Curate(source),
|
|
}
|
|
})?;
|
|
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
|
if curated.rows.is_empty() {
|
|
return Err(RunCurateFxError::NoCuratedRows {
|
|
eod_path: args.eod_prices.clone(),
|
|
te_path: args.te_market_data.clone(),
|
|
eod_bars_in: decoded.eod_cad_forex_kept,
|
|
te_bars_in: decoded.te_decode.points_decoded,
|
|
});
|
|
}
|
|
|
|
let checksum = compute_rows_checksum(&curated.rows);
|
|
|
|
let write_start = Instant::now();
|
|
let write_stats =
|
|
write_fx_1d_dataset(&args.out_dir, &curated.rows, Fx1dWriteOptions::default()).map_err(
|
|
|source| RunCurateFxError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateFxWriteError::Parquet(source),
|
|
},
|
|
)?;
|
|
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
|
|
|
|
let report = CurateFx1dRunReport {
|
|
eod_docs_framed: decoded.eod_docs_framed,
|
|
eod_bytes_read: decoded.eod_bytes_read,
|
|
eod_decode: decoded.eod_decode,
|
|
eod_cad_forex_kept: decoded.eod_cad_forex_kept,
|
|
eod_other_symbol_skipped: decoded.eod_other_symbol_skipped,
|
|
te_docs_framed: decoded.te_docs_framed,
|
|
te_bytes_read: decoded.te_bytes_read,
|
|
te_decode: decoded.te_decode,
|
|
curate_stats: curated.stats,
|
|
write_stats,
|
|
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
|
};
|
|
|
|
Ok(CurateFx1dTimedRun {
|
|
report,
|
|
decode_elapsed_secs,
|
|
curate_elapsed_secs,
|
|
write_elapsed_secs,
|
|
checksum,
|
|
})
|
|
}
|
|
|
|
/// Formats [`CurateFx1dRunReport`] into a deterministic machine-readable `key=value` summary.
|
|
///
|
|
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
|
pub fn format_curate_fx_report(report: &CurateFx1dRunReport) -> String {
|
|
let b = &report.curate_stats.builder;
|
|
format!(
|
|
"curate-etl curate-fx-1d\n\
|
|
\x20 eod_bson: docs_framed={} bytes_read={} docs_in={} decoded={} cad_forex_kept={} other_symbol_skipped={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
|
\x20 te_bson: docs_framed={} bytes_read={} docs_in={} matched={} other_symbol={} docs_rejected={} points_in={} points_decoded={} points_rejected={} (not_doc={} missing={} wrong_type={} non_finite={} date_oor={} corrupt={})\n\
|
|
\x20 builder: eod_in={} eod_kept={} eod_invalid={} eod_inconsistent={} eod_dup_collapsed={} eod_dup_conflict={} te_in={} te_kept={} te_invalid={} te_inconsistent={} te_dup_collapsed={} te_dup_conflict={}\n\
|
|
\x20 curate: rows_in={} rows_out={} eod_rows_out={} te_rows_out={} te_superseded={} overlap_checked={} within_tol={} mismatched={} max_overlap_rel={:.6}\n\
|
|
\x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\
|
|
\x20 timing: elapsed_secs={:.6}",
|
|
report.eod_docs_framed,
|
|
report.eod_bytes_read,
|
|
report.eod_decode.docs_in,
|
|
report.eod_decode.decoded,
|
|
report.eod_cad_forex_kept,
|
|
report.eod_other_symbol_skipped,
|
|
report.eod_decode.rejected_total(),
|
|
report.eod_decode.rejected_missing_field,
|
|
report.eod_decode.rejected_empty_field,
|
|
report.eod_decode.rejected_wrong_type,
|
|
report.eod_decode.rejected_malformed_date,
|
|
report.eod_decode.rejected_invalid_number,
|
|
report.eod_decode.rejected_corrupt_document,
|
|
report.te_docs_framed,
|
|
report.te_bytes_read,
|
|
report.te_decode.docs_in,
|
|
report.te_decode.docs_matched,
|
|
report.te_decode.docs_other_symbol,
|
|
report.te_decode.docs_rejected_total(),
|
|
report.te_decode.points_in,
|
|
report.te_decode.points_decoded,
|
|
report.te_decode.rejected_total(),
|
|
report.te_decode.rejected_point_not_document,
|
|
report.te_decode.rejected_missing_field,
|
|
report.te_decode.rejected_wrong_type,
|
|
report.te_decode.rejected_non_finite,
|
|
report.te_decode.rejected_date_out_of_range,
|
|
report.te_decode.rejected_corrupt_point,
|
|
b.eod.rows_in,
|
|
b.eod.rows_kept,
|
|
b.eod.dropped_invalid_ohlc,
|
|
b.eod.dropped_inconsistent_ohlc,
|
|
b.eod.duplicate_collapsed,
|
|
b.eod.duplicate_conflict_dropped,
|
|
b.te.rows_in,
|
|
b.te.rows_kept,
|
|
b.te.dropped_invalid_ohlc,
|
|
b.te.dropped_inconsistent_ohlc,
|
|
b.te.duplicate_collapsed,
|
|
b.te.duplicate_conflict_dropped,
|
|
report.curate_stats.rows_in,
|
|
report.curate_stats.rows_out,
|
|
b.eod_rows_out,
|
|
b.te_rows_out,
|
|
b.te_superseded_by_eod,
|
|
b.overlap_checked,
|
|
b.overlap_within_tolerance,
|
|
b.overlap_mismatched,
|
|
b.max_overlap_rel,
|
|
report.write_stats.files_written,
|
|
report.write_stats.row_groups_written,
|
|
report.write_stats.rows_written,
|
|
report.write_stats.bytes_written,
|
|
report.elapsed_secs,
|
|
)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "run_curate_fx_tests.rs"]
|
|
mod tests;
|