T-113: M1.2ac — tools/curate-etl: fourth runnable command curate-fx-1d (concatenated-BSON eodPrices CAD.FOREX + teMarketData USDCAD files → fx_1d/part.parquet) with a zero-copy teMarketData decoder, end-to-end tests and local benchmark (no new crates, no MongoDB connection)
This commit is contained in:
parent
234573a19e
commit
cffcbe23a6
11 changed files with 3636 additions and 5 deletions
|
|
@ -1240,3 +1240,75 @@ Measured locally (`2026-11-29`):
|
|||
- **Unverified MongoDB `qmDividends` field names:** `bson_qm_actions::FIELD_DIVIDEND_CASH` (`"amount"`) and `FIELD_DIVIDEND_CURRENCY` (`"currency"`) remain isolated constants pending verification against live `mongodump` `qmDividends` exports.
|
||||
- **In-RAM buffering of decoded events:** the single-threaded runner buffers decoded splits, dividends, and delistings in RAM (with `Arc<str>` key interning) before curation — small for real `qmSplits` (~19k) + `qmDividends` (~500k) + Pass 6 delistings, unlike `eodPrices`.
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connections, and no TypeScript Pass 6 `delistings.tsv` exporter yet.
|
||||
|
||||
## `curate-fx-1d` Command (`M1.2ac`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_fx.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, the zero-copy `teMarketData` decoder (`src/bson_te_market_data.rs`, `decode_te_market_data_chunks`), and `curate_and_write_fx_1d` into an atomically published `<out>/fx_1d/part.parquet` dataset with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-fx-1d \
|
||||
--eod-prices eodPrices.bson \
|
||||
--te-market-data teMarketData.bson \
|
||||
[--te-symbol USDCAD] \
|
||||
--out ./out
|
||||
```
|
||||
|
||||
Inputs and output:
|
||||
- `--eod-prices <path>`: concatenated raw BSON (`mongodump` `eodPrices.bson`). Streams through `decode_eod_price_chunks` and keeps only documents whose `eodSearchCode` is **exact** `"CAD.FOREX"` (other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when mapping to `FxDailyBar`).
|
||||
- `--te-market-data <path>`: concatenated raw BSON (`mongodump` `teMarketData.bson`). Streams through `decode_te_market_data_chunks` and keeps only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive, default `USDCAD`).
|
||||
- `--te-symbol <sym>` *(optional)*: target `teMarketData.teSymbol` to match (default: `USDCAD`; must not be empty or whitespace-only).
|
||||
- `--out <dir>`: dataset root where `fx_1d/part.parquet` is atomically published.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--te-symbol`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, invalid `--out`, blank `--te-symbol`, truncated/corrupt/oversized BSON framing or element bytes in either input, or zero decoded bars across both inputs) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/fx_1d/part.parquet` byte-identical).
|
||||
|
||||
### `teMarketData` Input Contract & `t` Epoch Unit Rule
|
||||
|
||||
- Document shape (derived from `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`; field names isolated as `pub const FIELD_*` in `src/bson_te_market_data.rs`):
|
||||
- Top-level `teSymbol: string` and `daily: [{ t, o, h, l, c, pc, ac }]`.
|
||||
- `monthly`, `pc`, `ac`, and all unknown fields are skipped without decoding their values.
|
||||
- `daily` is captured lazily as a raw element and only decoded after `teSymbol` matches `--te-symbol`, so field ordering (`daily` before `teSymbol`) never causes false rejects on non-target symbols.
|
||||
- Numeric fields `t`, `o`, `h`, `l`, `c` accept BSON `Int32`, `Int64`, or `Double`. Malformed points (non-document element, missing field, wrong type, `NaN`/`±Inf`, out-of-`i32`-range date) are counted under per-reason reject counters and skipped without panicking.
|
||||
- **`t` epoch unit rule** (`TE_EPOCH_MILLIS_THRESHOLD = 100_000_000_000`):
|
||||
- `|t| >= 100_000_000_000` → treated as Unix **milliseconds** (`session_date = floor(t / 86_400_000)` UTC).
|
||||
- `|t| < 100_000_000_000` → treated as Unix **seconds** (`session_date = floor(t / 86_400)` UTC).
|
||||
- Uses `unsigned_abs()` + `div_euclid` (flooring pre-1970 negative timestamps to the earlier UTC day) and checked `i32::try_from` bounds checking.
|
||||
- Merge precedence (`CAD.FOREX` wins on overlap, `teMarketData` fills interior gaps and post-EOD tail), read-only 1% overlap cross-check, and conservative `23:59:59.999999 UTC` `ts`/`known_at` stamping stay delegated unchanged to `curate_and_write_fx_1d`.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-fx-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `te_bson`, `builder`, `curate`, `write`, and `timing`):
|
||||
|
||||
- **EOD BSON:**
|
||||
`eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
|
||||
`eod_bson.decoded == eod_bson.cad_forex_kept + eod_bson.other_symbol_skipped`
|
||||
`eod_bson.cad_forex_kept == builder.eod_in`
|
||||
- **TE BSON:**
|
||||
`te_bson.docs_framed == te_bson.docs_in == te_bson.matched + te_bson.other_symbol + te_bson.docs_rejected`
|
||||
`te_bson.points_in == te_bson.points_decoded + te_bson.points_rejected`
|
||||
`te_bson.points_decoded == builder.te_in`
|
||||
- **Stage & Write:**
|
||||
`curate.rows_in == curate.rows_out == write.rows_written`
|
||||
|
||||
### `bench-curate-fx-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson` (`CAD.FOREX` with interior gaps, invalid/inconsistent/duplicate bars, skipped other symbols, and malformed docs) and `teMarketData.bson` (`USDCAD` with overlap including >1% cross-check mismatches, interior gap fills, post-EOD tail, mixed seconds/ms `t` across `Int32`/`Int64`/`Double`, malformed points, ignored `monthly`, and skipped other symbols) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd [rows]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`, default `20,000` rows; two back-to-back runs with identical checksum `0x45ac34f4ddf4407c`):
|
||||
|
||||
- Input: `rows=20000`, `eod_docs=18936` (`2,706,485 B`), `te_docs=3`, `te_points=5000` (`443,498 B`)
|
||||
- Decode counts: `eod_kept=14918`, `eod_other=3936`, `eod_rejected=82`, `te_matched=1`, `te_other=2`, `te_decoded=4925`, `te_rejected=75`
|
||||
- Output: `rows_out=17524` (`eod_out=14569`, `te_out=2955`, `te_superseded=1970`), `files=1`, `row_groups=1`, `bytes=733752`, `read_back_rows=17524`, `overlap: checked=1970 within_tol=1870 mismatched=100 max_rel=0.025000`
|
||||
- Run 1: `decode=4.53 ms` (`4,413,780 rows/s`, `662.96 MB/s`), `curate=0.62 ms` (`31,847,808 rows/s`), `write=15.31 ms` (`1,144,502 rows/s`, `45.70 MB/s`), `total=20.47 ms` (`977,241 rows/s`), `checksum=0x45ac34f4ddf4407c`
|
||||
- Run 2: `decode=4.73 ms` (`4,226,871 rows/s`, `634.89 MB/s`), `curate=0.76 ms` (`26,093,863 rows/s`), `write=15.22 ms` (`1,151,389 rows/s`, `45.98 MB/s`), `total=20.71 ms` (`965,626 rows/s`), `checksum=0x45ac34f4ddf4407c`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Unverified live `teMarketData` schema & `t` unit:** `bson_te_market_data::FIELD_*` constants and the `|t| >= 100_000_000_000` ms/s threshold are derived from `market-data-fetch.action.ts` and have not yet been verified against a live `mongodump` export.
|
||||
- **`eodPrices` `volume` field:** `decode_eod_price_chunks` still requires a non-negative `volume` field on `CAD.FOREX` documents (ignored when mapping to `FxDailyBar`); if a live `CAD.FOREX` dump omits `volume`, those docs will surface in `eod_bson.rejected (missing=...)`.
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB connection, and `fx_1m` is out of scope.
|
||||
|
|
|
|||
|
|
@ -8587,6 +8587,505 @@ pub fn run_curate_corporate_actions_cmd_benchmark(
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_FX_CMD_BENCH_ROWS: usize = 20_000;
|
||||
const CURATE_FX_CMD_BENCH_SEED: u64 = 0x570C_4B07_C04A_F01D;
|
||||
|
||||
/// Errors returned by [`run_curate_fx_cmd_benchmark`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateFxCmdBenchError {
|
||||
FixtureIo {
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
Run(crate::run_curate_fx::RunCurateFxError),
|
||||
Verify(ParquetFxError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CurateFxCmdBenchError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::FixtureIo { path, source } => {
|
||||
write!(f, "benchmark fixture I/O '{}': {source}", path.display())
|
||||
}
|
||||
Self::Run(err) => write!(f, "{err}"),
|
||||
Self::Verify(err) => write!(f, "Parquet verify failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CurateFxCmdBenchError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::FixtureIo { source, .. } => Some(source),
|
||||
Self::Run(err) => Some(err),
|
||||
Self::Verify(err) => Some(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_curate_fx_cmd_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CurateFxCmdBenchReport {
|
||||
pub rows: usize,
|
||||
pub eod_docs_framed: u64,
|
||||
pub eod_bytes_read: u64,
|
||||
pub eod_cad_forex_kept: usize,
|
||||
pub eod_other_symbol_skipped: usize,
|
||||
pub te_docs_framed: u64,
|
||||
pub te_bytes_read: u64,
|
||||
pub rows_out: usize,
|
||||
pub files_written: usize,
|
||||
pub row_groups_written: usize,
|
||||
pub bytes_written: u64,
|
||||
pub read_back_rows: usize,
|
||||
pub decode_elapsed_ms: f64,
|
||||
pub decode_rows_per_sec: f64,
|
||||
pub input_mb_per_sec: f64,
|
||||
pub curate_elapsed_ms: f64,
|
||||
pub curate_rows_per_sec: f64,
|
||||
pub write_elapsed_ms: f64,
|
||||
pub write_rows_per_sec: f64,
|
||||
pub write_mb_per_sec: f64,
|
||||
pub total_elapsed_ms: f64,
|
||||
pub total_rows_per_sec: f64,
|
||||
pub checksum: u64,
|
||||
pub eod_decode: BsonEodDecodeStats,
|
||||
pub te_decode: crate::bson_te_market_data::BsonTeMarketDataDecodeStats,
|
||||
pub curate_stats: crate::curate_fx::CurateFx1dStats,
|
||||
}
|
||||
|
||||
fn run_curate_fx_cmd_benchmark_tracked(
|
||||
rows: usize,
|
||||
) -> Result<(CurateFxCmdBenchReport, PathBuf), CurateFxCmdBenchError> {
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use bson::raw::RawArrayBuf;
|
||||
|
||||
use crate::bson_te_market_data::{
|
||||
BsonTeMarketDataDecodeStats, MILLIS_PER_DAY as TE_MILLIS_PER_DAY,
|
||||
SECONDS_PER_DAY as TE_SECONDS_PER_DAY,
|
||||
};
|
||||
use crate::curate_fx::CurateFx1dStats;
|
||||
use crate::run_curate_fx::{
|
||||
run_curate_fx_1d_timed, CurateFx1dArgs, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE,
|
||||
};
|
||||
|
||||
const MIB: f64 = 1024.0 * 1024.0;
|
||||
const OTHER_EOD_CODES: [&str; 4] = ["EUR.FOREX", "AAPL.US", "RY.TO", "cad.forex"];
|
||||
const MAX_TE_POINTS_PER_DOC: usize = 50_000;
|
||||
|
||||
let temp =
|
||||
BenchTempDir::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-curate-fx-cmd")
|
||||
.map_err(|(path, source)| CurateFxCmdBenchError::FixtureIo { path, source })?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
if rows == 0 {
|
||||
drop(temp);
|
||||
return Ok((
|
||||
CurateFxCmdBenchReport {
|
||||
rows: 0,
|
||||
eod_docs_framed: 0,
|
||||
eod_bytes_read: 0,
|
||||
eod_cad_forex_kept: 0,
|
||||
eod_other_symbol_skipped: 0,
|
||||
te_docs_framed: 0,
|
||||
te_bytes_read: 0,
|
||||
rows_out: 0,
|
||||
files_written: 0,
|
||||
row_groups_written: 0,
|
||||
bytes_written: 0,
|
||||
read_back_rows: 0,
|
||||
decode_elapsed_ms: 0.0,
|
||||
decode_rows_per_sec: 0.0,
|
||||
input_mb_per_sec: 0.0,
|
||||
curate_elapsed_ms: 0.0,
|
||||
curate_rows_per_sec: 0.0,
|
||||
write_elapsed_ms: 0.0,
|
||||
write_rows_per_sec: 0.0,
|
||||
write_mb_per_sec: 0.0,
|
||||
total_elapsed_ms: 0.0,
|
||||
total_rows_per_sec: 0.0,
|
||||
checksum: 0,
|
||||
eod_decode: BsonEodDecodeStats::default(),
|
||||
te_decode: BsonTeMarketDataDecodeStats::default(),
|
||||
curate_stats: CurateFx1dStats::default(),
|
||||
},
|
||||
temp_path,
|
||||
));
|
||||
}
|
||||
|
||||
let eod_path = temp.path.join("eodPrices.bson");
|
||||
let te_path = temp.path.join("teMarketData.bson");
|
||||
let out_dir = temp.path.join("out");
|
||||
|
||||
let mut rng = SplitMix64::new(CURATE_FX_CMD_BENCH_SEED);
|
||||
// Start in 1975 so every date's millisecond epoch exceeds TE_EPOCH_MILLIS_THRESHOLD (1e11).
|
||||
let start_day = ymd_to_epoch_days(1975, 1, 2).expect("valid start_day");
|
||||
|
||||
let eod_target = (rows * 75 / 100).max(1);
|
||||
let te_target = rows.saturating_sub(eod_target);
|
||||
|
||||
// Track EOD valid dates, closes, and interior gap dates so TE points can overlap and fill gaps.
|
||||
let mut eod_valid_dates: Vec<(i32, f64)> = Vec::with_capacity(eod_target);
|
||||
let mut gap_dates: Vec<i32> = Vec::new();
|
||||
let mut last_eod_day = start_day;
|
||||
|
||||
// 1. Write `eodPrices.bson` (`CAD.FOREX` + skipped other symbols + malformed docs).
|
||||
{
|
||||
let mut eod_w = BufWriter::new(File::create(&eod_path).map_err(|source| {
|
||||
CurateFxCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?);
|
||||
|
||||
let mut eod_seq = 0u64;
|
||||
let mut write_eod_doc =
|
||||
|code: &str,
|
||||
day: i32,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
omit_close: bool|
|
||||
-> Result<(), CurateFxCmdBenchError> {
|
||||
let mut oid = [0u8; 12];
|
||||
oid[0] = 1;
|
||||
oid[4..12].copy_from_slice(&eod_seq.to_be_bytes());
|
||||
eod_seq += 1;
|
||||
let date_str = format_ymd_string(day);
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), ObjectId::from_bytes(oid));
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
if eod_seq % 10 == 0 {
|
||||
doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day) * TE_MILLIS_PER_DAY),
|
||||
);
|
||||
} else {
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
}
|
||||
doc.append(cstr!("open"), open);
|
||||
doc.append(cstr!("high"), high);
|
||||
doc.append(cstr!("low"), low);
|
||||
if !omit_close {
|
||||
doc.append(cstr!("close"), close);
|
||||
}
|
||||
doc.append(cstr!("volume"), 0.0_f64);
|
||||
eod_w.write_all(doc.as_bytes()).map_err(|source| {
|
||||
CurateFxCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
let mut day_cursor = start_day;
|
||||
let mut generated_eod = 0usize;
|
||||
let mut rate = 1.32_f64;
|
||||
|
||||
while generated_eod < eod_target {
|
||||
// Interleave an other-symbol doc every 4th iteration so `eod_other_symbol_skipped > 0`.
|
||||
if generated_eod % 4 == 0 {
|
||||
let other_code = OTHER_EOD_CODES[(rng.next_u64() as usize) % OTHER_EOD_CODES.len()];
|
||||
write_eod_doc(other_code, day_cursor, 10.0, 10.5, 9.8, 10.2, false)?;
|
||||
}
|
||||
|
||||
// Leave every 25th calendar day as an interior gap for TE to fill.
|
||||
if (day_cursor - start_day) % 25 == 12 {
|
||||
gap_dates.push(day_cursor);
|
||||
day_cursor += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0002;
|
||||
rate = (rate + step).clamp(0.95, 1.65);
|
||||
let spread = 0.003 + ((rng.next_u64() % 40) as f64) * 0.0002;
|
||||
let low = rate - spread * 0.5;
|
||||
let high = rate + spread * 0.5;
|
||||
let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
|
||||
let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01);
|
||||
|
||||
let roll = rng.next_u64() % 200;
|
||||
if roll == 0 {
|
||||
// Malformed EOD doc (missing `close`) -> decoder reject.
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, true)?;
|
||||
generated_eod += 1;
|
||||
} else if roll == 1 {
|
||||
// Invalid OHLC (`close == 0.0`) -> builder drop.
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, 0.0, false)?;
|
||||
generated_eod += 1;
|
||||
} else if roll == 2 {
|
||||
// Inconsistent OHLC (`high < low`) -> builder drop.
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, low - 0.01, high, close, false)?;
|
||||
generated_eod += 1;
|
||||
} else if roll == 3 && generated_eod + 1 < eod_target {
|
||||
// Identical duplicate pair -> collapsed in builder.
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?;
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?;
|
||||
eod_valid_dates.push((day_cursor, close));
|
||||
generated_eod += 2;
|
||||
} else if roll == 4 && generated_eod + 1 < eod_target {
|
||||
// Conflicting duplicate pair -> dropped in builder.
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?;
|
||||
write_eod_doc(
|
||||
EOD_CAD_FOREX_CODE,
|
||||
day_cursor,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
(close + 0.001).min(high),
|
||||
false,
|
||||
)?;
|
||||
generated_eod += 2;
|
||||
} else {
|
||||
write_eod_doc(EOD_CAD_FOREX_CODE, day_cursor, open, high, low, close, false)?;
|
||||
eod_valid_dates.push((day_cursor, close));
|
||||
generated_eod += 1;
|
||||
}
|
||||
|
||||
last_eod_day = day_cursor;
|
||||
day_cursor += 1;
|
||||
}
|
||||
|
||||
eod_w.flush().map_err(|source| CurateFxCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 2. Write `teMarketData.bson` (other symbols + `USDCAD` with overlap, gap fill, tail,
|
||||
// mixed seconds/ms `t`, malformed points, and ignored `monthly`).
|
||||
{
|
||||
let mut te_w = BufWriter::new(File::create(&te_path).map_err(|source| {
|
||||
CurateFxCmdBenchError::FixtureIo {
|
||||
path: te_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?);
|
||||
|
||||
// Two non-target symbol documents to exercise `docs_other_symbol`.
|
||||
for other_sym in ["EURUSD", "GBPUSD"] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("teSymbol"), other_sym);
|
||||
let mut arr = RawArrayBuf::new();
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(start_day) * TE_MILLIS_PER_DAY);
|
||||
pt.append(cstr!("o"), 1.10_f64);
|
||||
pt.append(cstr!("h"), 1.12_f64);
|
||||
pt.append(cstr!("l"), 1.09_f64);
|
||||
pt.append(cstr!("c"), 1.11_f64);
|
||||
arr.push(pt);
|
||||
doc.append(cstr!("daily"), arr);
|
||||
te_w.write_all(doc.as_bytes()).map_err(|source| {
|
||||
CurateFxCmdBenchError::FixtureIo {
|
||||
path: te_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
// Build `USDCAD` points across one or more docs (<= MAX_TE_POINTS_PER_DOC each).
|
||||
let overlap_quota = (te_target * 40 / 100).min(eod_valid_dates.len());
|
||||
let gap_quota = (te_target * 20 / 100).min(gap_dates.len());
|
||||
let mut te_points_written = 0usize;
|
||||
let mut tail_day = last_eod_day + 1;
|
||||
let mut doc_idx = 0usize;
|
||||
|
||||
while te_points_written < te_target || doc_idx == 0 {
|
||||
let batch_count = (te_target - te_points_written).min(MAX_TE_POINTS_PER_DOC);
|
||||
let mut daily = RawArrayBuf::new();
|
||||
|
||||
for _ in 0..batch_count {
|
||||
let idx = te_points_written;
|
||||
te_points_written += 1;
|
||||
|
||||
// ~1.5% malformed points (missing field, wrong type, non-finite)
|
||||
let bad_roll = idx % 200;
|
||||
if bad_roll == 197 {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(tail_day) * TE_SECONDS_PER_DAY);
|
||||
pt.append(cstr!("o"), 1.35_f64);
|
||||
pt.append(cstr!("h"), 1.36_f64);
|
||||
pt.append(cstr!("l"), 1.34_f64);
|
||||
// Missing `c`
|
||||
daily.push(pt);
|
||||
continue;
|
||||
} else if bad_roll == 198 {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), "not-a-timestamp");
|
||||
pt.append(cstr!("o"), 1.35_f64);
|
||||
pt.append(cstr!("h"), 1.36_f64);
|
||||
pt.append(cstr!("l"), 1.34_f64);
|
||||
pt.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(pt);
|
||||
continue;
|
||||
} else if bad_roll == 199 {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(tail_day) * TE_MILLIS_PER_DAY);
|
||||
pt.append(cstr!("o"), f64::NAN);
|
||||
pt.append(cstr!("h"), 1.36_f64);
|
||||
pt.append(cstr!("l"), 1.34_f64);
|
||||
pt.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(pt);
|
||||
continue;
|
||||
}
|
||||
|
||||
let (day, base_close) = if idx < overlap_quota {
|
||||
let (d, eod_c) = eod_valid_dates[idx];
|
||||
// ~5% overlap mismatch (> 1%) to exercise read-only overlap cross-check.
|
||||
let c = if idx % 20 == 0 {
|
||||
eod_c * 1.025
|
||||
} else {
|
||||
eod_c * 1.001
|
||||
};
|
||||
(d, c)
|
||||
} else if idx < overlap_quota + gap_quota {
|
||||
let d = gap_dates[idx - overlap_quota];
|
||||
(d, 1.34 + ((rng.next_u64() % 100) as f64) * 0.0005)
|
||||
} else {
|
||||
let d = tail_day;
|
||||
tail_day += 1;
|
||||
(d, 1.36 + ((rng.next_u64() % 100) as f64) * 0.0005)
|
||||
};
|
||||
|
||||
let low = base_close - 0.004;
|
||||
let high = base_close + 0.004;
|
||||
let open = base_close - 0.001;
|
||||
let close = base_close;
|
||||
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
// Mix seconds (i32/i64/f64) and milliseconds (i64/f64).
|
||||
match idx % 5 {
|
||||
0 => pt.append(cstr!("t"), i64::from(day) * TE_MILLIS_PER_DAY + 43_200_000),
|
||||
1 => pt.append(cstr!("t"), (i64::from(day) * TE_MILLIS_PER_DAY) as f64),
|
||||
2 => {
|
||||
let secs = i64::from(day) * TE_SECONDS_PER_DAY + 3_600;
|
||||
if let Ok(s32) = i32::try_from(secs) {
|
||||
pt.append(cstr!("t"), s32);
|
||||
} else {
|
||||
pt.append(cstr!("t"), secs);
|
||||
}
|
||||
}
|
||||
3 => pt.append(cstr!("t"), i64::from(day) * TE_SECONDS_PER_DAY),
|
||||
_ => pt.append(cstr!("t"), (i64::from(day) * TE_SECONDS_PER_DAY) as f64),
|
||||
}
|
||||
pt.append(cstr!("o"), open);
|
||||
pt.append(cstr!("h"), high);
|
||||
pt.append(cstr!("l"), low);
|
||||
pt.append(cstr!("c"), close);
|
||||
pt.append(cstr!("pc"), 0.01_f64);
|
||||
pt.append(cstr!("ac"), 0.0001_f64);
|
||||
daily.push(pt);
|
||||
}
|
||||
|
||||
let mut monthly = RawArrayBuf::new();
|
||||
monthly.push("ignored-monthly-entry");
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("teSymbol"), DEFAULT_TE_SYMBOL);
|
||||
doc.append(cstr!("monthly"), monthly);
|
||||
doc.append(cstr!("daily"), daily);
|
||||
te_w.write_all(doc.as_bytes()).map_err(|source| {
|
||||
CurateFxCmdBenchError::FixtureIo {
|
||||
path: te_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
doc_idx += 1;
|
||||
if te_points_written >= te_target {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
te_w.flush().map_err(|source| CurateFxCmdBenchError::FixtureIo {
|
||||
path: te_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
let args = CurateFx1dArgs {
|
||||
eod_prices: eod_path,
|
||||
te_market_data: te_path,
|
||||
te_symbol: DEFAULT_TE_SYMBOL.to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
};
|
||||
let timed = run_curate_fx_1d_timed(&args).map_err(CurateFxCmdBenchError::Run)?;
|
||||
let read_back_rows =
|
||||
verify_parquet_fx_row_count(&out_dir, timed.report.write_stats.rows_written)
|
||||
.map_err(CurateFxCmdBenchError::Verify)?;
|
||||
|
||||
let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0;
|
||||
let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0;
|
||||
let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0;
|
||||
let total_elapsed_secs =
|
||||
timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs;
|
||||
let total_elapsed_ms = total_elapsed_secs * 1_000.0;
|
||||
|
||||
let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs);
|
||||
let decoded_rows =
|
||||
timed.report.eod_cad_forex_kept + timed.report.te_decode.points_decoded;
|
||||
let (curate_rows_per_sec, _) = compute_rates(decoded_rows, timed.curate_elapsed_secs);
|
||||
let (write_rows_per_sec, _) =
|
||||
compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs);
|
||||
let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs);
|
||||
|
||||
let total_input_bytes = timed.report.eod_bytes_read + timed.report.te_bytes_read;
|
||||
let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 {
|
||||
(total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 {
|
||||
(timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let report = CurateFxCmdBenchReport {
|
||||
rows,
|
||||
eod_docs_framed: timed.report.eod_docs_framed,
|
||||
eod_bytes_read: timed.report.eod_bytes_read,
|
||||
eod_cad_forex_kept: timed.report.eod_cad_forex_kept,
|
||||
eod_other_symbol_skipped: timed.report.eod_other_symbol_skipped,
|
||||
te_docs_framed: timed.report.te_docs_framed,
|
||||
te_bytes_read: timed.report.te_bytes_read,
|
||||
rows_out: timed.report.curate_stats.rows_out,
|
||||
files_written: timed.report.write_stats.files_written,
|
||||
row_groups_written: timed.report.write_stats.row_groups_written,
|
||||
bytes_written: timed.report.write_stats.bytes_written,
|
||||
read_back_rows,
|
||||
decode_elapsed_ms,
|
||||
decode_rows_per_sec,
|
||||
input_mb_per_sec,
|
||||
curate_elapsed_ms,
|
||||
curate_rows_per_sec,
|
||||
write_elapsed_ms,
|
||||
write_rows_per_sec,
|
||||
write_mb_per_sec,
|
||||
total_elapsed_ms,
|
||||
total_rows_per_sec,
|
||||
checksum: timed.checksum,
|
||||
eod_decode: timed.report.eod_decode,
|
||||
te_decode: timed.report.te_decode,
|
||||
curate_stats: timed.report.curate_stats,
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
Ok((report, temp_path))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed end-to-end `curate-fx-1d` file -> Parquet benchmark for `rows` synthetic
|
||||
/// `eodPrices` (`CAD.FOREX` + skipped other symbols + malformed docs) and `teMarketData`
|
||||
/// (`USDCAD` + skipped other symbols + overlap + interior gap fills + post-EOD tail + mixed
|
||||
/// seconds/ms `t` + malformed points) inputs.
|
||||
pub fn run_curate_fx_cmd_benchmark(
|
||||
rows: usize,
|
||||
) -> Result<CurateFxCmdBenchReport, CurateFxCmdBenchError> {
|
||||
let (report, _) = run_curate_fx_cmd_benchmark_tracked(rows)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -10383,4 +10882,82 @@ mod tests {
|
|||
assert_eq!(report.dividends_docs_framed, 0);
|
||||
assert_eq!(report.delistings_rows_loaded, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_fx_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() {
|
||||
let (a, dir_a) = run_curate_fx_cmd_benchmark_tracked(2_000).unwrap();
|
||||
let (b, dir_b) = run_curate_fx_cmd_benchmark_tracked(2_000).unwrap();
|
||||
|
||||
assert!(
|
||||
!dir_a.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_a.display()
|
||||
);
|
||||
assert!(
|
||||
!dir_b.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_b.display()
|
||||
);
|
||||
assert_eq!(a.rows, 2_000);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert!(a.rows_out > 0);
|
||||
assert_eq!(a.read_back_rows, a.rows_out);
|
||||
assert_eq!(a.files_written, 1);
|
||||
assert_eq!(a.bytes_written, b.bytes_written);
|
||||
assert!(a.bytes_written > 0);
|
||||
assert!(a.eod_cad_forex_kept > 0);
|
||||
assert!(a.eod_other_symbol_skipped > 0);
|
||||
assert!(a.eod_decode.rejected_total() > 0);
|
||||
assert!(a.te_decode.docs_matched > 0);
|
||||
assert!(a.te_decode.docs_other_symbol > 0);
|
||||
assert!(a.te_decode.points_decoded > 0);
|
||||
assert!(a.te_decode.rejected_total() > 0);
|
||||
assert!(a.curate_stats.builder.eod_rows_out > 0);
|
||||
assert!(a.curate_stats.builder.te_rows_out > 0);
|
||||
assert!(a.curate_stats.builder.te_superseded_by_eod > 0);
|
||||
assert!(a.curate_stats.builder.overlap_within_tolerance > 0);
|
||||
assert!(a.curate_stats.builder.overlap_mismatched > 0);
|
||||
|
||||
// Conservation invariants
|
||||
assert_eq!(a.eod_docs_framed as usize, a.eod_decode.docs_in);
|
||||
assert_eq!(
|
||||
a.eod_decode.docs_in,
|
||||
a.eod_decode.decoded + a.eod_decode.rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
a.eod_decode.decoded,
|
||||
a.eod_cad_forex_kept + a.eod_other_symbol_skipped
|
||||
);
|
||||
assert_eq!(a.eod_cad_forex_kept, a.curate_stats.builder.eod.rows_in);
|
||||
assert_eq!(a.te_docs_framed as usize, a.te_decode.docs_in);
|
||||
assert_eq!(
|
||||
a.te_decode.docs_in,
|
||||
a.te_decode.docs_matched
|
||||
+ a.te_decode.docs_other_symbol
|
||||
+ a.te_decode.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
a.te_decode.points_in,
|
||||
a.te_decode.points_decoded + a.te_decode.rejected_total()
|
||||
);
|
||||
assert_eq!(a.te_decode.points_decoded, a.curate_stats.builder.te.rows_in);
|
||||
assert_eq!(a.curate_stats.rows_in, a.curate_stats.builder.rows_out);
|
||||
assert_eq!(a.curate_stats.rows_out, a.rows_out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_fx_cmd_benchmark_zero_rows_handles_cleanly() {
|
||||
let (report, dir) = run_curate_fx_cmd_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.eod_docs_framed, 0);
|
||||
assert_eq!(report.te_docs_framed, 0);
|
||||
assert_eq!(report.rows_out, 0);
|
||||
assert_eq!(report.files_written, 0);
|
||||
assert_eq!(report.bytes_written, 0);
|
||||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,10 @@ use crate::bson_qm_actions::{
|
|||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError,
|
||||
RawQmDividend, RawQmSplit,
|
||||
};
|
||||
use crate::bson_te_market_data::{
|
||||
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
|
||||
};
|
||||
use crate::fx::FxDailyBar;
|
||||
|
||||
/// Default chunk buffer capacity: 8 MiB.
|
||||
pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
|
@ -656,6 +660,93 @@ where
|
|||
decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_te_error(base: u64, err: BsonTeMarketDataError) -> BsonTeMarketDataError {
|
||||
match err {
|
||||
BsonTeMarketDataError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonTeMarketDataError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonTeMarketDataError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonTeMarketDataError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonTeMarketDataError::CorruptBson { offset, detail } => {
|
||||
BsonTeMarketDataError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
}
|
||||
}
|
||||
BsonTeMarketDataError::CorruptPointBson {
|
||||
offset,
|
||||
point_index,
|
||||
detail,
|
||||
} => BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
point_index,
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_te_market_data_buffer`],
|
||||
/// accumulating [`BsonTeMarketDataDecodeStats`] and rebasing per-document and per-point error
|
||||
/// offsets to absolute stream byte offsets.
|
||||
pub fn decode_te_market_data_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
target_symbol: &str,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonTeMarketDataDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(u64, BsonTeMarketDataError),
|
||||
{
|
||||
let mut total = BsonTeMarketDataDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_te_market_data_buffer(
|
||||
chunk.bytes,
|
||||
target_symbol,
|
||||
&mut on_bar,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_te_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `teMarketData` [`std::io::Read`] source through
|
||||
/// [`decode_te_market_data_buffer`] with bounded memory.
|
||||
pub fn decode_te_market_data_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
target_symbol: &str,
|
||||
on_bar: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonTeMarketDataDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(u64, BsonTeMarketDataError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_stream_tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
787
tools/curate-etl/src/bson_te_market_data.rs
Normal file
787
tools/curate-etl/src/bson_te_market_data.rs
Normal file
|
|
@ -0,0 +1,787 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `teMarketData` documents (`M1.2ac`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
|
||||
//! allocating a `bson::Document` or per-point heap memory, emitting [`FxDailyBar`] values via a
|
||||
//! caller-supplied callback.
|
||||
//!
|
||||
//! # Empirical Field Contract & Unverified Assumptions
|
||||
//!
|
||||
//! - Field names are derived from the ingestion writer in
|
||||
//! `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`
|
||||
//! (`teSymbol`, `daily: [{ t, o, h, l, c, pc, ac }]`, `monthly`), and isolated in the
|
||||
//! `pub const FIELD_*` constants below. They have **not** yet been verified against a live
|
||||
//! `mongodump` of `teMarketData`.
|
||||
//! - **`t` epoch unit rule (unverified in repo):** TradingEconomics CDN series timestamps may be
|
||||
//! stored in either Unix seconds or Unix milliseconds. This decoder converts numeric `t` via
|
||||
//! [`TE_EPOCH_MILLIS_THRESHOLD`] (`100_000_000_000`):
|
||||
//! - `|t| >= 100_000_000_000` → treated as Unix **milliseconds**
|
||||
//! (`session_date = floor(t / 86_400_000)` UTC).
|
||||
//! - `|t| < 100_000_000_000` → treated as Unix **seconds**
|
||||
//! (`session_date = floor(t / 86_400)` UTC).
|
||||
//! - Floor division (`div_euclid`) ensures pre-1970 negative timestamps round down to the
|
||||
//! earlier UTC calendar day rather than truncating toward zero.
|
||||
//! - `monthly`, `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
||||
//! - `daily` is captured lazily as a raw [`RawElement`] during the top-level scan and only decoded
|
||||
//! after `teSymbol` matches `target_symbol` (ASCII case-insensitive), so non-target symbols pay
|
||||
//! zero array-scan cost and never emit false `daily` errors even when `daily` precedes `teSymbol`
|
||||
//! in raw BSON field order.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
|
||||
use crate::fx::FxDailyBar;
|
||||
|
||||
/// MongoDB field name for the TradingEconomics symbol key (`market-data-fetch.action.ts:133`).
|
||||
pub const FIELD_TE_SYMBOL: &str = "teSymbol";
|
||||
/// MongoDB field name for the daily OHLC array (`market-data-fetch.action.ts:144`).
|
||||
pub const FIELD_DAILY: &str = "daily";
|
||||
/// MongoDB field name for the monthly OHLC array, explicitly ignored (`market-data-fetch.action.ts:145`).
|
||||
pub const FIELD_MONTHLY: &str = "monthly";
|
||||
/// Point field name for the Unix epoch timestamp (`market-data-fetch.action.ts:15`).
|
||||
pub const FIELD_POINT_T: &str = "t";
|
||||
/// Point field name for open price (`market-data-fetch.action.ts:16`).
|
||||
pub const FIELD_POINT_O: &str = "o";
|
||||
/// Point field name for high price (`market-data-fetch.action.ts:17`).
|
||||
pub const FIELD_POINT_H: &str = "h";
|
||||
/// Point field name for low price (`market-data-fetch.action.ts:18`).
|
||||
pub const FIELD_POINT_L: &str = "l";
|
||||
/// Point field name for close price (`market-data-fetch.action.ts:19`).
|
||||
pub const FIELD_POINT_C: &str = "c";
|
||||
|
||||
/// Magnitude threshold distinguishing Unix milliseconds (`|t| >= 100_000_000_000`) from Unix
|
||||
/// seconds (`|t| < 100_000_000_000`).
|
||||
pub const TE_EPOCH_MILLIS_THRESHOLD: i64 = 100_000_000_000;
|
||||
/// Number of seconds in one UTC calendar day.
|
||||
pub const SECONDS_PER_DAY: i64 = 86_400;
|
||||
/// Number of milliseconds in one UTC calendar day.
|
||||
pub const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
|
||||
/// Converts an integer Unix epoch timestamp `t` (seconds or milliseconds per
|
||||
/// [`TE_EPOCH_MILLIS_THRESHOLD`]) into UTC `session_date` (days since `1970-01-01`).
|
||||
///
|
||||
/// Uses `unsigned_abs()` (avoiding `i64::MIN.abs()` overflow), `div_euclid` (flooring negative
|
||||
/// pre-1970 timestamps to the earlier UTC calendar day), and checked `i32::try_from`.
|
||||
#[inline]
|
||||
pub fn te_epoch_i64_to_session_date(t: i64) -> Option<i32> {
|
||||
let days = if t.unsigned_abs() >= TE_EPOCH_MILLIS_THRESHOLD as u64 {
|
||||
t.div_euclid(MILLIS_PER_DAY)
|
||||
} else {
|
||||
t.div_euclid(SECONDS_PER_DAY)
|
||||
};
|
||||
i32::try_from(days).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn te_epoch_f64_to_session_date(point_index: usize, v: f64) -> Result<i32, BsonTeMarketDataError> {
|
||||
if !v.is_finite() {
|
||||
return Err(BsonTeMarketDataError::NonFiniteValue {
|
||||
point_index,
|
||||
field: FIELD_POINT_T,
|
||||
value: v,
|
||||
});
|
||||
}
|
||||
let is_millis = v.abs() >= TE_EPOCH_MILLIS_THRESHOLD as f64;
|
||||
let t_floor = v.floor();
|
||||
// Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`).
|
||||
if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&t_floor) {
|
||||
return Err(BsonTeMarketDataError::DateOutOfRange { point_index });
|
||||
}
|
||||
let t_i64 = t_floor as i64;
|
||||
let days = if is_millis {
|
||||
t_i64.div_euclid(MILLIS_PER_DAY)
|
||||
} else {
|
||||
t_i64.div_euclid(SECONDS_PER_DAY)
|
||||
};
|
||||
i32::try_from(days).map_err(|_| BsonTeMarketDataError::DateOutOfRange { point_index })
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `teMarketData` BSON documents or length-prefixed
|
||||
/// buffers.
|
||||
///
|
||||
/// Every variant's `Display` output is a single line; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonTeMarketDataError {
|
||||
/// Required top-level `teSymbol` field was absent.
|
||||
MissingSymbol,
|
||||
/// Top-level `teSymbol` string was empty or whitespace-only.
|
||||
EmptySymbol,
|
||||
/// Top-level `teSymbol` had an unexpected BSON element type.
|
||||
WrongSymbolType { actual: ElementType },
|
||||
/// Required `daily` field was absent on a matched `teSymbol` document.
|
||||
MissingDaily,
|
||||
/// `daily` field on a matched `teSymbol` document was not a BSON array.
|
||||
DailyNotArray { actual: ElementType },
|
||||
/// An element inside `daily` was not an embedded BSON document.
|
||||
PointNotDocument {
|
||||
point_index: usize,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A required field (`t`, `o`, `h`, `l`, or `c`) was absent from a `daily` point document.
|
||||
MissingPointField {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
},
|
||||
/// A required field in a `daily` point document had an unexpected BSON type.
|
||||
WrongPointFieldType {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A numeric field (`t`, `o`, `h`, `l`, or `c`) in a `daily` point was `NaN` or `±inf`.
|
||||
NonFiniteValue {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
value: f64,
|
||||
},
|
||||
/// Point timestamp `t` mapped outside the `i32` UTC epoch-day range.
|
||||
DateOutOfRange { point_index: usize },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying top-level BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
/// Underlying BSON bytes inside a `daily` array or point document were malformed.
|
||||
CorruptPointBson {
|
||||
offset: usize,
|
||||
point_index: usize,
|
||||
detail: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonTeMarketDataError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingSymbol => {
|
||||
write!(f, "teMarketData BSON missing required field '{FIELD_TE_SYMBOL}'")
|
||||
}
|
||||
Self::EmptySymbol => {
|
||||
write!(
|
||||
f,
|
||||
"teMarketData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongSymbolType { actual } => write!(
|
||||
f,
|
||||
"teMarketData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::MissingDaily => {
|
||||
write!(f, "teMarketData BSON missing required field '{FIELD_DAILY}'")
|
||||
}
|
||||
Self::DailyNotArray { actual } => write!(
|
||||
f,
|
||||
"teMarketData BSON field '{FIELD_DAILY}' has unexpected BSON type {actual:?} (expected Array)"
|
||||
),
|
||||
Self::PointNotDocument {
|
||||
point_index,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)"
|
||||
),
|
||||
Self::MissingPointField { point_index, field } => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}]' missing required field '{field}'"
|
||||
),
|
||||
Self::WrongPointFieldType {
|
||||
point_index,
|
||||
field,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::NonFiniteValue {
|
||||
point_index,
|
||||
field,
|
||||
value,
|
||||
} => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has non-finite value {value}"
|
||||
),
|
||||
Self::DateOutOfRange { point_index } => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{FIELD_POINT_T}' overflows i32 UTC session_date"
|
||||
),
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
Self::CorruptPointBson {
|
||||
offset,
|
||||
point_index,
|
||||
detail,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON bytes in '{FIELD_DAILY}[{point_index}]' at byte offset {offset}: {detail}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonTeMarketDataError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonTeMarketDataError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonTeMarketDataError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonTeMarketDataError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonTeMarketDataError::CorruptBson { offset, detail }
|
||||
}
|
||||
other => BsonTeMarketDataError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: other.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch document and point decode accounting for `teMarketData`.
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `docs_in == docs_matched + docs_other_symbol + docs_rejected_total()`
|
||||
/// - `points_in == points_decoded + rejected_total()`
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonTeMarketDataDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub docs_matched: usize,
|
||||
pub docs_other_symbol: usize,
|
||||
pub rejected_missing_symbol: usize,
|
||||
pub rejected_empty_symbol: usize,
|
||||
pub rejected_wrong_symbol_type: usize,
|
||||
pub rejected_daily_missing: usize,
|
||||
pub rejected_daily_not_array: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
pub points_in: usize,
|
||||
pub points_decoded: usize,
|
||||
pub rejected_point_not_document: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_non_finite: usize,
|
||||
pub rejected_date_out_of_range: usize,
|
||||
pub rejected_corrupt_point: usize,
|
||||
}
|
||||
|
||||
impl BsonTeMarketDataDecodeStats {
|
||||
/// Total number of document-level rejects across all document error categories.
|
||||
#[inline]
|
||||
pub fn docs_rejected_total(&self) -> usize {
|
||||
self.rejected_missing_symbol
|
||||
+ self.rejected_empty_symbol
|
||||
+ self.rejected_wrong_symbol_type
|
||||
+ self.rejected_daily_missing
|
||||
+ self.rejected_daily_not_array
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Total number of point-level rejects across all point error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_point_not_document
|
||||
+ self.rejected_missing_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_non_finite
|
||||
+ self.rejected_date_out_of_range
|
||||
+ self.rejected_corrupt_point
|
||||
}
|
||||
|
||||
/// Increments the point-level rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
fn record_point_error(&mut self, err: &BsonTeMarketDataError) {
|
||||
match err {
|
||||
BsonTeMarketDataError::PointNotDocument { .. } => {
|
||||
self.rejected_point_not_document += 1;
|
||||
}
|
||||
BsonTeMarketDataError::MissingPointField { .. } => {
|
||||
self.rejected_missing_field += 1;
|
||||
}
|
||||
BsonTeMarketDataError::WrongPointFieldType { .. } => {
|
||||
self.rejected_wrong_type += 1;
|
||||
}
|
||||
BsonTeMarketDataError::NonFiniteValue { .. } => {
|
||||
self.rejected_non_finite += 1;
|
||||
}
|
||||
BsonTeMarketDataError::DateOutOfRange { .. } => {
|
||||
self.rejected_date_out_of_range += 1;
|
||||
}
|
||||
BsonTeMarketDataError::CorruptPointBson { .. } => {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
_ => {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.docs_matched += other.docs_matched;
|
||||
self.docs_other_symbol += other.docs_other_symbol;
|
||||
self.rejected_missing_symbol += other.rejected_missing_symbol;
|
||||
self.rejected_empty_symbol += other.rejected_empty_symbol;
|
||||
self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type;
|
||||
self.rejected_daily_missing += other.rejected_daily_missing;
|
||||
self.rejected_daily_not_array += other.rejected_daily_not_array;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
self.points_in += other.points_in;
|
||||
self.points_decoded += other.points_decoded;
|
||||
self.rejected_point_not_document += other.rejected_point_not_document;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_non_finite += other.rejected_non_finite;
|
||||
self.rejected_date_out_of_range += other.rejected_date_out_of_range;
|
||||
self.rejected_corrupt_point += other.rejected_corrupt_point;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonTeMarketDataDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_point_t(
|
||||
point_index: usize,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<i32, BsonTeMarketDataError> {
|
||||
match val {
|
||||
RawBsonRef::Int32(v) => te_epoch_i64_to_session_date(i64::from(v))
|
||||
.ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }),
|
||||
RawBsonRef::Int64(v) => te_epoch_i64_to_session_date(v)
|
||||
.ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }),
|
||||
RawBsonRef::Double(v) => te_epoch_f64_to_session_date(point_index, v),
|
||||
other => Err(BsonTeMarketDataError::WrongPointFieldType {
|
||||
point_index,
|
||||
field: FIELD_POINT_T,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_point_price(
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonTeMarketDataError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() {
|
||||
return Err(BsonTeMarketDataError::NonFiniteValue {
|
||||
point_index,
|
||||
field,
|
||||
value: v,
|
||||
});
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => Ok(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => Ok(v as f64),
|
||||
other => Err(BsonTeMarketDataError::WrongPointFieldType {
|
||||
point_index,
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_point_doc(
|
||||
point_doc: &RawDocument,
|
||||
doc_offset: usize,
|
||||
point_index: usize,
|
||||
) -> Result<FxDailyBar, BsonTeMarketDataError> {
|
||||
let mut session_date: Option<i32> = None;
|
||||
let mut open: Option<f64> = None;
|
||||
let mut high: Option<f64> = None;
|
||||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
|
||||
for elem_res in point_doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_POINT_T {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_T}': {err}"),
|
||||
})?;
|
||||
session_date = Some(decode_point_t(point_index, val)?);
|
||||
} else if key == FIELD_POINT_O {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_O}': {err}"),
|
||||
})?;
|
||||
open = Some(decode_point_price(point_index, FIELD_POINT_O, val)?);
|
||||
} else if key == FIELD_POINT_H {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_H}': {err}"),
|
||||
})?;
|
||||
high = Some(decode_point_price(point_index, FIELD_POINT_H, val)?);
|
||||
} else if key == FIELD_POINT_L {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_L}': {err}"),
|
||||
})?;
|
||||
low = Some(decode_point_price(point_index, FIELD_POINT_L, val)?);
|
||||
} else if key == FIELD_POINT_C {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_C}': {err}"),
|
||||
})?;
|
||||
close = Some(decode_point_price(point_index, FIELD_POINT_C, val)?);
|
||||
}
|
||||
// `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(session_date) = session_date else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_T,
|
||||
});
|
||||
};
|
||||
let Some(open) = open else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_O,
|
||||
});
|
||||
};
|
||||
let Some(high) = high else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_H,
|
||||
});
|
||||
};
|
||||
let Some(low) = low else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_L,
|
||||
});
|
||||
};
|
||||
let Some(close) = close else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_C,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(FxDailyBar {
|
||||
session_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_te_market_data_doc_at<F, E>(
|
||||
doc: &RawDocument,
|
||||
doc_offset: usize,
|
||||
target_symbol: &str,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(BsonTeMarketDataError),
|
||||
{
|
||||
let mut stats = BsonTeMarketDataDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonTeMarketDataDecodeStats::default()
|
||||
};
|
||||
|
||||
let mut te_symbol: Option<&str> = None;
|
||||
let mut daily_elem: Option<RawElement<'_>> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = match elem_res {
|
||||
Ok(elem) => elem,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeMarketDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: err.to_string(),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
let key = elem.key().as_str();
|
||||
if key == FIELD_TE_SYMBOL {
|
||||
let val = match elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeMarketDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_TE_SYMBOL}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
stats.rejected_empty_symbol += 1;
|
||||
on_error(BsonTeMarketDataError::EmptySymbol);
|
||||
return stats;
|
||||
}
|
||||
te_symbol = Some(s);
|
||||
}
|
||||
other => {
|
||||
stats.rejected_wrong_symbol_type += 1;
|
||||
on_error(BsonTeMarketDataError::WrongSymbolType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_DAILY {
|
||||
daily_elem = Some(elem);
|
||||
}
|
||||
// `FIELD_MONTHLY` and all other top-level fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(symbol) = te_symbol else {
|
||||
stats.rejected_missing_symbol += 1;
|
||||
on_error(BsonTeMarketDataError::MissingSymbol);
|
||||
return stats;
|
||||
};
|
||||
|
||||
if !symbol.eq_ignore_ascii_case(target_symbol) {
|
||||
stats.docs_other_symbol += 1;
|
||||
return stats;
|
||||
}
|
||||
|
||||
let Some(daily_elem) = daily_elem else {
|
||||
stats.rejected_daily_missing += 1;
|
||||
on_error(BsonTeMarketDataError::MissingDaily);
|
||||
return stats;
|
||||
};
|
||||
|
||||
let daily_val = match daily_elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeMarketDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_DAILY}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
|
||||
let daily_arr = match daily_val {
|
||||
RawBsonRef::Array(arr) => arr,
|
||||
other => {
|
||||
stats.rejected_daily_not_array += 1;
|
||||
on_error(BsonTeMarketDataError::DailyNotArray {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
|
||||
stats.docs_matched += 1;
|
||||
|
||||
for (point_index, item_res) in daily_arr.into_iter().enumerate() {
|
||||
stats.points_in += 1;
|
||||
let item = match item_res {
|
||||
Ok(item) => item,
|
||||
Err(err) => {
|
||||
let err = BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: err.to_string(),
|
||||
};
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
let point_doc = match item {
|
||||
RawBsonRef::Document(point_doc) => point_doc,
|
||||
other => {
|
||||
let err = BsonTeMarketDataError::PointNotDocument {
|
||||
point_index,
|
||||
actual: other.element_type(),
|
||||
};
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
match decode_point_doc(point_doc, doc_offset, point_index) {
|
||||
Ok(bar) => {
|
||||
stats.points_decoded += 1;
|
||||
on_bar(bar);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `teMarketData` MongoDB document in one forward
|
||||
/// pass without allocating a `bson::Document` or per-point heap memory.
|
||||
///
|
||||
/// Matches `teSymbol` against `target_symbol` using ASCII case-insensitive comparison. For matched
|
||||
/// documents, emits each valid `daily` point as an [`FxDailyBar`] via `on_bar` and reports
|
||||
/// document- or point-level errors to `on_error` without panicking.
|
||||
#[inline]
|
||||
pub fn decode_te_market_data_doc<F, E>(
|
||||
doc: &RawDocument,
|
||||
target_symbol: &str,
|
||||
on_bar: F,
|
||||
on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(BsonTeMarketDataError),
|
||||
{
|
||||
decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice representing a `teMarketData`
|
||||
/// document.
|
||||
pub fn decode_te_market_data_bytes<F, E>(
|
||||
bytes: &[u8],
|
||||
target_symbol: &str,
|
||||
on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(BsonTeMarketDataError),
|
||||
{
|
||||
match parse_single_raw_doc(bytes) {
|
||||
Ok(doc) => decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error),
|
||||
Err(err) => {
|
||||
let mut stats = BsonTeMarketDataDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonTeMarketDataDecodeStats::default()
|
||||
};
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(map_framing_error(err));
|
||||
stats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_market_data_doc`],
|
||||
/// emitting every valid [`FxDailyBar`] for `target_symbol` (ASCII case-insensitive) to `on_bar`
|
||||
/// and reporting document- or point-level errors to `on_error(byte_offset, err)` without aborting.
|
||||
///
|
||||
/// Always maintains:
|
||||
/// - `stats.docs_in == stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total()`
|
||||
/// - `stats.points_in == stats.points_decoded + stats.rejected_total()`
|
||||
pub fn decode_te_market_data_buffer<F, E>(
|
||||
buf: &[u8],
|
||||
target_symbol: &str,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(usize, BsonTeMarketDataError),
|
||||
{
|
||||
let mut stats = BsonTeMarketDataDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => {
|
||||
let doc_stats = decode_te_market_data_doc_at(
|
||||
doc,
|
||||
doc_offset,
|
||||
target_symbol,
|
||||
&mut on_bar,
|
||||
|err| on_error(doc_offset, err),
|
||||
);
|
||||
stats += doc_stats;
|
||||
}
|
||||
Err((doc_offset, err)) => {
|
||||
stats.docs_in += 1;
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(doc_offset, map_framing_error(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_te_market_data_tests.rs"]
|
||||
mod tests;
|
||||
462
tools/curate-etl/src/bson_te_market_data_tests.rs
Normal file
462
tools/curate-etl/src/bson_te_market_data_tests.rs
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use super::*;
|
||||
use crate::bson_stream::{decode_te_market_data_stream, BsonStreamOptions};
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn assert_stats_conserved(stats: &BsonTeMarketDataDecodeStats) {
|
||||
assert_eq!(
|
||||
stats.docs_in,
|
||||
stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total(),
|
||||
"doc conservation failed: {stats:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stats.points_in,
|
||||
stats.points_decoded + stats.rejected_total(),
|
||||
"point conservation failed: {stats:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn make_te_doc(symbol: &str, daily: RawArrayBuf) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("teSymbol"), symbol);
|
||||
doc.append(cstr!("daily"), daily);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_int32_int64_double_and_seconds_vs_millis_to_same_session_date() {
|
||||
let d_2025 = day(2025, 1, 2);
|
||||
let secs_2025 = i64::from(d_2025) * SECONDS_PER_DAY;
|
||||
let ms_2025 = i64::from(d_2025) * MILLIS_PER_DAY;
|
||||
|
||||
let mut daily = RawArrayBuf::new();
|
||||
|
||||
// Point 0: Int32 seconds + Int32 OHLC
|
||||
let mut p0 = RawDocumentBuf::new();
|
||||
p0.append(cstr!("t"), i32::try_from(secs_2025 + 43_200).unwrap());
|
||||
p0.append(cstr!("o"), 1_i32);
|
||||
p0.append(cstr!("h"), 2_i32);
|
||||
p0.append(cstr!("l"), 1_i32);
|
||||
p0.append(cstr!("c"), 2_i32);
|
||||
p0.append(cstr!("pc"), 0.5_f64);
|
||||
p0.append(cstr!("ac"), 0.01_f64);
|
||||
daily.push(p0);
|
||||
|
||||
// Point 1: Int64 milliseconds + Int64 OHLC
|
||||
let mut p1 = RawDocumentBuf::new();
|
||||
p1.append(cstr!("t"), ms_2025 + 86_399_999);
|
||||
p1.append(cstr!("o"), 1_i64);
|
||||
p1.append(cstr!("h"), 3_i64);
|
||||
p1.append(cstr!("l"), 1_i64);
|
||||
p1.append(cstr!("c"), 2_i64);
|
||||
daily.push(p1);
|
||||
|
||||
// Point 2: Double seconds + Double OHLC
|
||||
let mut p2 = RawDocumentBuf::new();
|
||||
p2.append(cstr!("t"), (secs_2025 as f64) + 123.75);
|
||||
p2.append(cstr!("o"), 1.430_f64);
|
||||
p2.append(cstr!("h"), 1.445_f64);
|
||||
p2.append(cstr!("l"), 1.425_f64);
|
||||
p2.append(cstr!("c"), 1.438_f64);
|
||||
daily.push(p2);
|
||||
|
||||
// Point 3: Double milliseconds + Double OHLC
|
||||
let mut p3 = RawDocumentBuf::new();
|
||||
p3.append(cstr!("t"), (ms_2025 as f64) + 500.5);
|
||||
p3.append(cstr!("o"), 1.431_f64);
|
||||
p3.append(cstr!("h"), 1.446_f64);
|
||||
p3.append(cstr!("l"), 1.426_f64);
|
||||
p3.append(cstr!("c"), 1.439_f64);
|
||||
daily.push(p3);
|
||||
|
||||
let doc = make_te_doc("USDCAD", daily);
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_doc(&doc, "USDCAD", |b| bars.push(b), |e| errors.push(e));
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errors.is_empty(), "unexpected errors: {errors:?}");
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.docs_matched, 1);
|
||||
assert_eq!(stats.points_in, 4);
|
||||
assert_eq!(stats.points_decoded, 4);
|
||||
assert_eq!(bars.len(), 4);
|
||||
for bar in &bars {
|
||||
assert_eq!(bar.session_date, d_2025);
|
||||
}
|
||||
assert_eq!(bars[0].open, 1.0);
|
||||
assert_eq!(bars[0].high, 2.0);
|
||||
assert_eq!(bars[1].high, 3.0);
|
||||
assert_eq!(bars[2].close.to_bits(), 1.438_f64.to_bits());
|
||||
assert_eq!(bars[3].close.to_bits(), 1.439_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn epoch_threshold_boundaries_and_negative_pre_1970_floor_correctly() {
|
||||
// Exact threshold boundaries
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(TE_EPOCH_MILLIS_THRESHOLD - 1),
|
||||
Some((TE_EPOCH_MILLIS_THRESHOLD - 1).div_euclid(SECONDS_PER_DAY) as i32)
|
||||
);
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(TE_EPOCH_MILLIS_THRESHOLD),
|
||||
Some(TE_EPOCH_MILLIS_THRESHOLD.div_euclid(MILLIS_PER_DAY) as i32)
|
||||
);
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(-(TE_EPOCH_MILLIS_THRESHOLD - 1)),
|
||||
Some((-(TE_EPOCH_MILLIS_THRESHOLD - 1)).div_euclid(SECONDS_PER_DAY) as i32)
|
||||
);
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(-TE_EPOCH_MILLIS_THRESHOLD),
|
||||
Some((-TE_EPOCH_MILLIS_THRESHOLD).div_euclid(MILLIS_PER_DAY) as i32)
|
||||
);
|
||||
|
||||
// Pre-1970 negative timestamps floor to earlier UTC day
|
||||
assert_eq!(te_epoch_i64_to_session_date(0), Some(0)); // 1970-01-01
|
||||
assert_eq!(te_epoch_i64_to_session_date(-1), Some(-1)); // 1969-12-31 23:59:59 UTC
|
||||
assert_eq!(te_epoch_i64_to_session_date(-SECONDS_PER_DAY), Some(-1)); // 1969-12-31 00:00:00 UTC
|
||||
assert_eq!(te_epoch_i64_to_session_date(-SECONDS_PER_DAY - 1), Some(-2)); // 1969-12-30
|
||||
|
||||
// Pre-1970 negative milliseconds (1966-10-31 is past -100_000_000_000 ms)
|
||||
let neg_ms = -100_000_000_001_i64;
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(neg_ms),
|
||||
Some(neg_ms.div_euclid(MILLIS_PER_DAY) as i32)
|
||||
);
|
||||
|
||||
// Overflow boundaries: i64::MIN and i64::MAX must never panic, return None
|
||||
assert_eq!(te_epoch_i64_to_session_date(i64::MIN), None);
|
||||
assert_eq!(te_epoch_i64_to_session_date(i64::MAX), None);
|
||||
|
||||
// Fractional negative Double values in BSON
|
||||
let mut daily = RawArrayBuf::new();
|
||||
for t_val in [-1.5_f64, -86_400.5_f64, -100_000_000_000.5_f64] {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), t_val);
|
||||
pt.append(cstr!("o"), 1.05_f64);
|
||||
pt.append(cstr!("h"), 1.06_f64);
|
||||
pt.append(cstr!("l"), 1.04_f64);
|
||||
pt.append(cstr!("c"), 1.05_f64);
|
||||
daily.push(pt);
|
||||
}
|
||||
let doc = make_te_doc("USDCAD", daily);
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_doc(&doc, "USDCAD", |b| bars.push(b), |e| errors.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
assert_eq!(bars[0].session_date, -1); // -1.5 -> floor -2s -> day -1
|
||||
assert_eq!(bars[1].session_date, -2); // -86400.5 -> floor -86401s -> day -2
|
||||
assert_eq!(
|
||||
bars[2].session_date,
|
||||
(-100_000_000_001_i64).div_euclid(MILLIS_PER_DAY) as i32
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_before_symbol_case_insensitive_match_and_monthly_ignored() {
|
||||
let d1 = day(2025, 3, 10);
|
||||
|
||||
// 1. Matched doc (lowercase "usdcad") with `daily` BEFORE `teSymbol` and broken `monthly`
|
||||
let mut daily = RawArrayBuf::new();
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(d1) * SECONDS_PER_DAY);
|
||||
pt.append(cstr!("o"), 1.44_f64);
|
||||
pt.append(cstr!("h"), 1.45_f64);
|
||||
pt.append(cstr!("l"), 1.43_f64);
|
||||
pt.append(cstr!("c"), 1.445_f64);
|
||||
pt.append(cstr!("pc"), bson::raw::RawBson::Null);
|
||||
pt.append(cstr!("ac"), bson::raw::RawBson::Null);
|
||||
pt.append(cstr!("extra"), "ignored");
|
||||
daily.push(pt);
|
||||
|
||||
let mut bad_monthly = RawArrayBuf::new();
|
||||
bad_monthly.push("not-a-doc");
|
||||
bad_monthly.push(f64::NAN);
|
||||
|
||||
let mut doc1 = RawDocumentBuf::new();
|
||||
doc1.append(cstr!("monthly"), bad_monthly);
|
||||
doc1.append(cstr!("daily"), daily);
|
||||
doc1.append(cstr!("teSymbol"), "usdcad");
|
||||
|
||||
// 2. Non-target symbol with invalid `daily` (not an array) placed BEFORE `teSymbol`:
|
||||
// must be counted as `docs_other_symbol` with zero errors!
|
||||
let mut doc2 = RawDocumentBuf::new();
|
||||
doc2.append(cstr!("daily"), "not-an-array");
|
||||
doc2.append(cstr!("teSymbol"), "EURUSD");
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(doc1.as_bytes());
|
||||
buf.extend_from_slice(doc2.as_bytes());
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_buffer(
|
||||
&buf,
|
||||
"USDCAD",
|
||||
|b| bars.push(b),
|
||||
|off, e| errors.push((off, e)),
|
||||
);
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errors.is_empty(), "unexpected errors: {errors:?}");
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.docs_matched, 1);
|
||||
assert_eq!(stats.docs_other_symbol, 1);
|
||||
assert_eq!(stats.points_in, 1);
|
||||
assert_eq!(stats.points_decoded, 1);
|
||||
assert_eq!(bars.len(), 1);
|
||||
assert_eq!(bars[0].session_date, d1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_every_doc_and_point_reject_reason_without_panicking() {
|
||||
let mut buf = Vec::new();
|
||||
|
||||
// Doc 0: MissingSymbol
|
||||
let mut d_missing_sym = RawDocumentBuf::new();
|
||||
d_missing_sym.append(cstr!("daily"), RawArrayBuf::new());
|
||||
buf.extend_from_slice(d_missing_sym.as_bytes());
|
||||
|
||||
// Doc 1: EmptySymbol
|
||||
let mut d_empty_sym = RawDocumentBuf::new();
|
||||
d_empty_sym.append(cstr!("teSymbol"), " ");
|
||||
d_empty_sym.append(cstr!("daily"), RawArrayBuf::new());
|
||||
buf.extend_from_slice(d_empty_sym.as_bytes());
|
||||
|
||||
// Doc 2: WrongSymbolType
|
||||
let mut d_wrong_sym = RawDocumentBuf::new();
|
||||
d_wrong_sym.append(cstr!("teSymbol"), 42_i32);
|
||||
buf.extend_from_slice(d_wrong_sym.as_bytes());
|
||||
|
||||
// Doc 3: MissingDaily
|
||||
let mut d_missing_daily = RawDocumentBuf::new();
|
||||
d_missing_daily.append(cstr!("teSymbol"), "USDCAD");
|
||||
buf.extend_from_slice(d_missing_daily.as_bytes());
|
||||
|
||||
// Doc 4: DailyNotArray
|
||||
let mut d_not_array = RawDocumentBuf::new();
|
||||
d_not_array.append(cstr!("teSymbol"), "USDCAD");
|
||||
d_not_array.append(cstr!("daily"), 123_i32);
|
||||
buf.extend_from_slice(d_not_array.as_bytes());
|
||||
|
||||
// Doc 5: Matched doc containing every point-level reject + 1 valid point
|
||||
let mut daily = RawArrayBuf::new();
|
||||
// [0] PointNotDocument
|
||||
daily.push("not-a-doc");
|
||||
// [1] MissingPointField (`t`)
|
||||
let mut p_no_t = RawDocumentBuf::new();
|
||||
p_no_t.append(cstr!("o"), 1.3_f64);
|
||||
p_no_t.append(cstr!("h"), 1.4_f64);
|
||||
p_no_t.append(cstr!("l"), 1.2_f64);
|
||||
p_no_t.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_no_t);
|
||||
// [2] MissingPointField (`o`)
|
||||
let mut p_no_o = RawDocumentBuf::new();
|
||||
p_no_o.append(cstr!("t"), 0_i32);
|
||||
p_no_o.append(cstr!("h"), 1.4_f64);
|
||||
p_no_o.append(cstr!("l"), 1.2_f64);
|
||||
p_no_o.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_no_o);
|
||||
// [3] WrongPointFieldType (`t` as String)
|
||||
let mut p_bad_t = RawDocumentBuf::new();
|
||||
p_bad_t.append(cstr!("t"), "2025-01-01");
|
||||
p_bad_t.append(cstr!("o"), 1.3_f64);
|
||||
p_bad_t.append(cstr!("h"), 1.4_f64);
|
||||
p_bad_t.append(cstr!("l"), 1.2_f64);
|
||||
p_bad_t.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_bad_t);
|
||||
// [4] WrongPointFieldType (`c` as Bool)
|
||||
let mut p_bad_c = RawDocumentBuf::new();
|
||||
p_bad_c.append(cstr!("t"), 0_i32);
|
||||
p_bad_c.append(cstr!("o"), 1.3_f64);
|
||||
p_bad_c.append(cstr!("h"), 1.4_f64);
|
||||
p_bad_c.append(cstr!("l"), 1.2_f64);
|
||||
p_bad_c.append(cstr!("c"), true);
|
||||
daily.push(p_bad_c);
|
||||
// [5] NonFiniteValue (`t` = NaN)
|
||||
let mut p_nan_t = RawDocumentBuf::new();
|
||||
p_nan_t.append(cstr!("t"), f64::NAN);
|
||||
p_nan_t.append(cstr!("o"), 1.3_f64);
|
||||
p_nan_t.append(cstr!("h"), 1.4_f64);
|
||||
p_nan_t.append(cstr!("l"), 1.2_f64);
|
||||
p_nan_t.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_nan_t);
|
||||
// [6] NonFiniteValue (`h` = +Inf)
|
||||
let mut p_inf_h = RawDocumentBuf::new();
|
||||
p_inf_h.append(cstr!("t"), 0_i32);
|
||||
p_inf_h.append(cstr!("o"), 1.3_f64);
|
||||
p_inf_h.append(cstr!("h"), f64::INFINITY);
|
||||
p_inf_h.append(cstr!("l"), 1.2_f64);
|
||||
p_inf_h.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_inf_h);
|
||||
// [7] NonFiniteValue (`l` = -Inf)
|
||||
let mut p_ninf_l = RawDocumentBuf::new();
|
||||
p_ninf_l.append(cstr!("t"), 0_i32);
|
||||
p_ninf_l.append(cstr!("o"), 1.3_f64);
|
||||
p_ninf_l.append(cstr!("h"), 1.4_f64);
|
||||
p_ninf_l.append(cstr!("l"), f64::NEG_INFINITY);
|
||||
p_ninf_l.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_ninf_l);
|
||||
// [8] DateOutOfRange (`i64::MIN`)
|
||||
let mut p_oor_min = RawDocumentBuf::new();
|
||||
p_oor_min.append(cstr!("t"), i64::MIN);
|
||||
p_oor_min.append(cstr!("o"), 1.3_f64);
|
||||
p_oor_min.append(cstr!("h"), 1.4_f64);
|
||||
p_oor_min.append(cstr!("l"), 1.2_f64);
|
||||
p_oor_min.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_oor_min);
|
||||
// [9] DateOutOfRange (`i64::MAX`)
|
||||
let mut p_oor_max = RawDocumentBuf::new();
|
||||
p_oor_max.append(cstr!("t"), i64::MAX);
|
||||
p_oor_max.append(cstr!("o"), 1.3_f64);
|
||||
p_oor_max.append(cstr!("h"), 1.4_f64);
|
||||
p_oor_max.append(cstr!("l"), 1.2_f64);
|
||||
p_oor_max.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_oor_max);
|
||||
// [10] DateOutOfRange (Double 1e20)
|
||||
let mut p_oor_f64 = RawDocumentBuf::new();
|
||||
p_oor_f64.append(cstr!("t"), 1e20_f64);
|
||||
p_oor_f64.append(cstr!("o"), 1.3_f64);
|
||||
p_oor_f64.append(cstr!("h"), 1.4_f64);
|
||||
p_oor_f64.append(cstr!("l"), 1.2_f64);
|
||||
p_oor_f64.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_oor_f64);
|
||||
// [11] Valid point
|
||||
let d_ok = day(2026, 2, 14);
|
||||
let mut p_ok = RawDocumentBuf::new();
|
||||
p_ok.append(cstr!("t"), i64::from(d_ok) * MILLIS_PER_DAY);
|
||||
p_ok.append(cstr!("o"), 1.38_f64);
|
||||
p_ok.append(cstr!("h"), 1.39_f64);
|
||||
p_ok.append(cstr!("l"), 1.37_f64);
|
||||
p_ok.append(cstr!("c"), 1.385_f64);
|
||||
daily.push(p_ok);
|
||||
|
||||
let doc5 = make_te_doc("UsdCad", daily);
|
||||
buf.extend_from_slice(doc5.as_bytes());
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_buffer(
|
||||
&buf,
|
||||
"USDCAD",
|
||||
|b| bars.push(b),
|
||||
|off, e| errors.push((off, e)),
|
||||
);
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert_eq!(stats.docs_in, 6);
|
||||
assert_eq!(stats.docs_matched, 1);
|
||||
assert_eq!(stats.docs_other_symbol, 0);
|
||||
assert_eq!(stats.rejected_missing_symbol, 1);
|
||||
assert_eq!(stats.rejected_empty_symbol, 1);
|
||||
assert_eq!(stats.rejected_wrong_symbol_type, 1);
|
||||
assert_eq!(stats.rejected_daily_missing, 1);
|
||||
assert_eq!(stats.rejected_daily_not_array, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 0);
|
||||
|
||||
assert_eq!(stats.points_in, 12);
|
||||
assert_eq!(stats.points_decoded, 1);
|
||||
assert_eq!(stats.rejected_point_not_document, 1);
|
||||
assert_eq!(stats.rejected_missing_field, 2);
|
||||
assert_eq!(stats.rejected_wrong_type, 2);
|
||||
assert_eq!(stats.rejected_non_finite, 3);
|
||||
assert_eq!(stats.rejected_date_out_of_range, 3);
|
||||
assert_eq!(stats.rejected_corrupt_point, 0);
|
||||
assert_eq!(bars.len(), 1);
|
||||
assert_eq!(bars[0].session_date, d_ok);
|
||||
|
||||
assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::MissingSymbol)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::EmptySymbol)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(
|
||||
e,
|
||||
BsonTeMarketDataError::WrongSymbolType {
|
||||
actual: ElementType::Int32
|
||||
}
|
||||
)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::MissingDaily)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(
|
||||
e,
|
||||
BsonTeMarketDataError::DailyNotArray {
|
||||
actual: ElementType::Int32
|
||||
}
|
||||
)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(
|
||||
e,
|
||||
BsonTeMarketDataError::PointNotDocument {
|
||||
point_index: 0,
|
||||
actual: ElementType::String
|
||||
}
|
||||
)));
|
||||
// Every error Display is single-line
|
||||
for (_, err) in &errors {
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "multiline error display: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_bson_bytes_and_streaming_rebase_offsets() {
|
||||
// 1. decode_te_market_data_bytes on truncated input
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_market_data_bytes(&[10, 0, 0, 0, 1], "USDCAD", |_| {}, |e| errs.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert!(matches!(
|
||||
errs.as_slice(),
|
||||
[BsonTeMarketDataError::TruncatedDocument { .. }]
|
||||
));
|
||||
|
||||
// 2. Streaming across tiny chunks rebases corrupt inner BSON offset accurately
|
||||
let mut good_daily = RawArrayBuf::new();
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), 0_i32);
|
||||
pt.append(cstr!("o"), 1.3_f64);
|
||||
pt.append(cstr!("h"), 1.4_f64);
|
||||
pt.append(cstr!("l"), 1.2_f64);
|
||||
pt.append(cstr!("c"), 1.35_f64);
|
||||
good_daily.push(pt);
|
||||
let doc1 = make_te_doc("USDCAD", good_daily);
|
||||
let doc1_len = doc1.as_bytes().len() as u64;
|
||||
|
||||
// Second doc: valid 4-byte length prefix (12 bytes) but invalid element type byte 0xFF
|
||||
let bad_doc: [u8; 12] = [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0];
|
||||
|
||||
let mut stream_bytes = Vec::new();
|
||||
stream_bytes.extend_from_slice(doc1.as_bytes());
|
||||
stream_bytes.extend_from_slice(&bad_doc);
|
||||
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut bars = Vec::new();
|
||||
let mut stream_errs = Vec::new();
|
||||
let stream_stats = decode_te_market_data_stream(
|
||||
std::io::Cursor::new(&stream_bytes),
|
||||
opts,
|
||||
"USDCAD",
|
||||
|b| bars.push(b),
|
||||
|off, err| stream_errs.push((off, err)),
|
||||
)
|
||||
.expect("stream framing itself is valid");
|
||||
|
||||
assert_stats_conserved(&stream_stats);
|
||||
assert_eq!(bars.len(), 1);
|
||||
assert_eq!(stream_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stream_errs.len(), 1);
|
||||
assert_eq!(stream_errs[0].0, doc1_len);
|
||||
match &stream_errs[0].1 {
|
||||
BsonTeMarketDataError::CorruptBson { offset, .. } => {
|
||||
assert_eq!(*offset as u64, doc1_len);
|
||||
}
|
||||
other => panic!("expected CorruptBson with rebased offset, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -13,7 +13,8 @@ use crate::bench::{
|
|||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_BARS_CMD_BENCH_ROWS,
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS,
|
||||
DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
|
|
@ -22,6 +23,7 @@ use crate::bench::{
|
|||
use crate::run_curate_adj::CurateAdjFactorsArgs;
|
||||
use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE};
|
||||
use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
|
||||
use crate::run_curate_fx::{CurateFx1dArgs, DEFAULT_TE_SYMBOL};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
|
|
@ -31,6 +33,7 @@ pub enum CliAction {
|
|||
CurateBars1d(CurateBars1dArgs),
|
||||
CurateAdjFactors(CurateAdjFactorsArgs),
|
||||
CurateCorporateActions(CurateCorporateActionsArgs),
|
||||
CurateFx1d(CurateFx1dArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
|
|
@ -53,6 +56,7 @@ pub enum CliAction {
|
|||
BenchCurateShorts(usize),
|
||||
BenchCurateEvents(usize),
|
||||
BenchCurateFx(usize),
|
||||
BenchCurateFxCmd(usize),
|
||||
BenchCurateAdj(usize),
|
||||
BenchCurateAdjCmd(usize),
|
||||
BenchCurateCorporateActions(usize),
|
||||
|
|
@ -73,6 +77,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Curate retrospective adj_factors from BSON + TSV + bars_1d Parquet into adj_factors/part.parquet\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> --provider-mapping <path> [--delistings <path>] --out <dir>\n\
|
||||
Curate corporate_actions from BSON + TSV files into corporate_actions/part.parquet\n\
|
||||
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
|
||||
Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\
|
||||
{name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
|
||||
{name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
|
||||
|
|
@ -95,6 +101,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
|
||||
{name} bench-curate-fx-cmd [rows] Run fixed-seed end-to-end curate-fx-1d file->Parquet benchmark (default: {DEFAULT_CURATE_FX_CMD_BENCH_ROWS})\n\
|
||||
{name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-curate-adj-cmd [events] Run fixed-seed end-to-end curate-adj-factors file->Parquet benchmark (default: {DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS})\n\
|
||||
{name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})\n\
|
||||
|
|
@ -111,6 +118,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> --provider-mapping <path> --listing-currencies <path> --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> --provider-mapping <path> [--delistings <path>] --out <dir>\n\
|
||||
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
|
|
@ -133,6 +141,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-curate-shorts [rows]\n\
|
||||
{name} bench-curate-events [rows]\n\
|
||||
{name} bench-curate-fx [rows]\n\
|
||||
{name} bench-curate-fx-cmd [rows]\n\
|
||||
{name} bench-curate-adj [events]\n\
|
||||
{name} bench-curate-adj-cmd [events]\n\
|
||||
{name} bench-curate-corporate-actions [events]\n\
|
||||
|
|
@ -371,6 +380,79 @@ fn parse_curate_corporate_actions_args(
|
|||
})
|
||||
}
|
||||
|
||||
fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
|
||||
let mut eod_prices: Option<PathBuf> = None;
|
||||
let mut te_market_data: Option<PathBuf> = None;
|
||||
let mut te_symbol: Option<String> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let token = args[i];
|
||||
if !token.starts_with("--") {
|
||||
return Err(format!(
|
||||
"unexpected positional argument '{token}' for curate-fx-1d"
|
||||
));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(k, v)
|
||||
} else {
|
||||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
||||
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate flag '{flag_name}'"));
|
||||
}
|
||||
if raw.is_empty() {
|
||||
return Err(format!("empty value for flag '{flag_name}'"));
|
||||
}
|
||||
*slot = Some(PathBuf::from(raw));
|
||||
Ok(())
|
||||
};
|
||||
|
||||
match flag {
|
||||
"--eod-prices" => set_path(&mut eod_prices, "--eod-prices", value)?,
|
||||
"--te-market-data" => set_path(&mut te_market_data, "--te-market-data", value)?,
|
||||
"--te-symbol" => {
|
||||
if te_symbol.is_some() {
|
||||
return Err("duplicate flag '--te-symbol'".to_string());
|
||||
}
|
||||
if value.trim().is_empty() {
|
||||
return Err(
|
||||
"invalid --te-symbol: must not be empty or whitespace-only".to_string()
|
||||
);
|
||||
}
|
||||
te_symbol = Some(value.to_string());
|
||||
}
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
other => return Err(format!("unknown flag '{other}' for curate-fx-1d")),
|
||||
}
|
||||
}
|
||||
|
||||
let eod_prices =
|
||||
eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?;
|
||||
let te_market_data =
|
||||
te_market_data.ok_or_else(|| "missing required flag '--te-market-data'".to_string())?;
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
|
||||
Ok(CurateFx1dArgs {
|
||||
eod_prices,
|
||||
te_market_data,
|
||||
te_symbol: te_symbol.unwrap_or_else(|| DEFAULT_TE_SYMBOL.to_string()),
|
||||
out_dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`].
|
||||
pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
let slices: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
|
|
@ -389,6 +471,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["curate-corporate-actions", rest @ ..] => {
|
||||
parse_curate_corporate_actions_args(rest).map(CliAction::CurateCorporateActions)
|
||||
}
|
||||
["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest).map(CliAction::CurateFx1d),
|
||||
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||
["bench-split", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),
|
||||
|
|
@ -617,6 +700,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()),
|
||||
["bench-curate-fx-cmd"] => Ok(CliAction::BenchCurateFxCmd(
|
||||
DEFAULT_CURATE_FX_CMD_BENCH_ROWS,
|
||||
)),
|
||||
["bench-curate-fx-cmd", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateFxCmd(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-fx-cmd", _, ..] => {
|
||||
Err("too many arguments for bench-curate-fx-cmd".to_string())
|
||||
}
|
||||
["bench-curate-adj"] => Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)),
|
||||
["bench-curate-adj", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdj(n)),
|
||||
|
|
@ -1616,4 +1711,205 @@ mod tests {
|
|||
let err = parse_args(&to_args(&pos)).unwrap_err();
|
||||
assert!(err.contains("unexpected positional argument"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_curate_fx_1d_and_bench_curate_fx_cmd_args() {
|
||||
// Usage strings include both new commands.
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
assert!(usage.contains("curate-fx-1d"), "{usage}");
|
||||
assert!(usage.contains("bench-curate-fx-cmd"), "{usage}");
|
||||
let usage_err = format_usage_stderr("curate-etl");
|
||||
assert!(usage_err.contains("curate-fx-1d"), "{usage_err}");
|
||||
assert!(usage_err.contains("bench-curate-fx-cmd"), "{usage_err}");
|
||||
|
||||
// Default --te-symbol with separated flags.
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"out_dir",
|
||||
])),
|
||||
Ok(CliAction::CurateFx1d(CurateFx1dArgs {
|
||||
eod_prices: PathBuf::from("eod.bson"),
|
||||
te_market_data: PathBuf::from("te.bson"),
|
||||
te_symbol: DEFAULT_TE_SYMBOL.to_string(),
|
||||
out_dir: PathBuf::from("out_dir"),
|
||||
}))
|
||||
);
|
||||
|
||||
// Explicit --te-symbol and `--flag=value` form.
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices=eod.bson",
|
||||
"--te-market-data=te.bson",
|
||||
"--te-symbol=usdcad",
|
||||
"--out=out_dir",
|
||||
])),
|
||||
Ok(CliAction::CurateFx1d(CurateFx1dArgs {
|
||||
eod_prices: PathBuf::from("eod.bson"),
|
||||
te_market_data: PathBuf::from("te.bson"),
|
||||
te_symbol: "usdcad".to_string(),
|
||||
out_dir: PathBuf::from("out_dir"),
|
||||
}))
|
||||
);
|
||||
|
||||
// Missing required flags.
|
||||
for (missing, args) in [
|
||||
(
|
||||
"--eod-prices",
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"--te-market-data",
|
||||
&["curate-fx-1d", "--eod-prices", "eod.bson", "--out", "out"][..],
|
||||
),
|
||||
(
|
||||
"--out",
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
][..],
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(args)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("missing required flag '{missing}'")),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Duplicate flags (including --te-symbol).
|
||||
for (dup_flag, args) in [
|
||||
(
|
||||
"--eod-prices",
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"a.bson",
|
||||
"--eod-prices=b.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"--te-symbol",
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--te-symbol",
|
||||
"USDCAD",
|
||||
"--te-symbol=USDCAD",
|
||||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(args)).unwrap_err();
|
||||
assert!(err.contains(&format!("duplicate flag '{dup_flag}'")), "{err}");
|
||||
}
|
||||
|
||||
// Unknown flag, missing value (end / followed by --), empty/whitespace, positional.
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"out",
|
||||
"--bogus",
|
||||
"1",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("unknown flag '--bogus'"), "{err}");
|
||||
|
||||
let err = parse_args(&to_args(&["curate-fx-1d", "--te-symbol"])).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--te-symbol'"), "{err}");
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.contains("missing value for flag '--eod-prices'"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--te-symbol",
|
||||
" ",
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("invalid --te-symbol"), "{err}");
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("empty value for flag '--out'"), "{err}");
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"eod.bson",
|
||||
"--te-market-data",
|
||||
"te.bson",
|
||||
"--out",
|
||||
"out",
|
||||
"extra",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("unexpected positional argument"), "{err}");
|
||||
|
||||
// bench-curate-fx-cmd parsing
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-fx-cmd"])),
|
||||
Ok(CliAction::BenchCurateFxCmd(DEFAULT_CURATE_FX_CMD_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-fx-cmd", "4000"])),
|
||||
Ok(CliAction::BenchCurateFxCmd(4_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "10", "20"])).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ pub mod bench;
|
|||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod bson_stream;
|
||||
pub mod bson_te_market_data;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
|
|
@ -42,9 +43,17 @@ pub use bson_qm_actions::{
|
|||
};
|
||||
pub use bson_stream::{
|
||||
decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks,
|
||||
decode_qm_dividend_stream, decode_qm_split_chunks, decode_qm_split_stream, BsonStreamError,
|
||||
BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
decode_qm_dividend_stream, decode_qm_split_chunks, decode_qm_split_stream,
|
||||
decode_te_market_data_chunks, decode_te_market_data_stream, BsonStreamError, BsonStreamOptions,
|
||||
RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES,
|
||||
MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
pub use bson_te_market_data::{
|
||||
decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc,
|
||||
te_epoch_i64_to_session_date, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, FIELD_DAILY,
|
||||
FIELD_MONTHLY, FIELD_POINT_C, FIELD_POINT_H, FIELD_POINT_L, FIELD_POINT_O, FIELD_POINT_T,
|
||||
FIELD_TE_SYMBOL, MILLIS_PER_DAY as TE_MILLIS_PER_DAY, SECONDS_PER_DAY as TE_SECONDS_PER_DAY,
|
||||
TE_EPOCH_MILLIS_THRESHOLD,
|
||||
};
|
||||
pub use corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow,
|
||||
|
|
@ -170,3 +179,9 @@ pub use run_curate_corporate_actions::{
|
|||
format_curate_corporate_actions_report, load_delistings_tsv, run_curate_corporate_actions,
|
||||
CurateCorporateActionsArgs, CurateCorporateActionsRunReport, RunCurateCorporateActionsError,
|
||||
};
|
||||
|
||||
pub mod run_curate_fx;
|
||||
pub use run_curate_fx::{
|
||||
format_curate_fx_report, run_curate_fx_1d, CurateFx1dArgs, CurateFx1dRunReport,
|
||||
RunCurateFxError, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,7 +9,8 @@ use curate_etl::bench::{
|
|||
run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark,
|
||||
run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark,
|
||||
run_curate_fx_benchmark, run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark,
|
||||
run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark,
|
||||
run_events_benchmark, run_fx_benchmark,
|
||||
run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
|
|
@ -21,6 +22,7 @@ use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d}
|
|||
use curate_etl::run_curate_corporate_actions::{
|
||||
format_curate_corporate_actions_report, run_curate_corporate_actions,
|
||||
};
|
||||
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
|
||||
|
||||
const NAME: &str = env!("CARGO_PKG_NAME");
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
|
@ -71,6 +73,16 @@ fn main() -> ExitCode {
|
|||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateFx1d(curate_args)) => match run_curate_fx_1d(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_fx_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::BenchSplit(rows)) => {
|
||||
let report = match run_split_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -1215,6 +1227,71 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateFxCmd(rows)) => {
|
||||
let report = match run_curate_fx_cmd_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-fx-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let b = &report.curate_stats.builder;
|
||||
println!("curate-etl bench-curate-fx-cmd");
|
||||
println!(
|
||||
" input: rows={} eod_docs={} eod_bytes={} te_docs={} te_points={} te_bytes={}",
|
||||
report.rows,
|
||||
report.eod_docs_framed,
|
||||
report.eod_bytes_read,
|
||||
report.te_docs_framed,
|
||||
report.te_decode.points_in,
|
||||
report.te_bytes_read
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s eod_kept={} eod_other={} eod_rejected={} te_matched={} te_other={} te_decoded={} te_rejected={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_rows_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.eod_cad_forex_kept,
|
||||
report.eod_other_symbol_skipped,
|
||||
report.eod_decode.rejected_total(),
|
||||
report.te_decode.docs_matched,
|
||||
report.te_decode.docs_other_symbol,
|
||||
report.te_decode.points_decoded,
|
||||
report.te_decode.rejected_total()
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} eod_out={} te_out={} te_superseded={} checksum=0x{:016x}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
b.eod_rows_out,
|
||||
b.te_rows_out,
|
||||
b.te_superseded_by_eod,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s checksum=0x{:016x}",
|
||||
report.total_elapsed_ms, report.total_rows_per_sec, report.checksum
|
||||
);
|
||||
println!(
|
||||
" overlap: checked={} within_tol={} mismatched={} max_rel={:.6}",
|
||||
b.overlap_checked,
|
||||
b.overlap_within_tolerance,
|
||||
b.overlap_mismatched,
|
||||
b.max_overlap_rel
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
599
tools/curate-etl/src/run_curate_fx.rs
Normal file
599
tools/curate-etl/src/run_curate_fx.rs
Normal file
|
|
@ -0,0 +1,599 @@
|
|||
//! 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`, blank `--te-symbol`, unreadable input files,
|
||||
//! corrupt/truncated BSON framing or element bytes, and zero decoded bars across both sources
|
||||
//! each return a typed [`RunCurateFxError`] before touching `args.out_dir`, leaving any
|
||||
//! pre-existing `<out_dir>/fx_1d/part.parquet` byte-identical.
|
||||
//!
|
||||
//! # 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";
|
||||
|
||||
/// 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,
|
||||
},
|
||||
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}': must not be empty or whitespace-only"
|
||||
)
|
||||
}
|
||||
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::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 { .. } => 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 te_symbol.trim().is_empty() {
|
||||
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> {
|
||||
// 1. Stream `eodPrices` and retain exact `CAD.FOREX` bars.
|
||||
let eod_file = File::open(&args.eod_prices).map_err(|source| RunCurateFxError::OpenInput {
|
||||
label: "eod-prices",
|
||||
path: args.eod_prices.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut eod_reader =
|
||||
RawBsonChunkReader::with_options(eod_file, BsonStreamOptions::default()).map_err(
|
||||
|source| RunCurateFxError::BsonStream {
|
||||
label: "eod-prices",
|
||||
path: args.eod_prices.clone(),
|
||||
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: args.eod_prices.clone(),
|
||||
offset,
|
||||
source,
|
||||
});
|
||||
}
|
||||
let eod_decode = eod_decode_res.map_err(|source| RunCurateFxError::BsonStream {
|
||||
label: "eod-prices",
|
||||
path: args.eod_prices.clone(),
|
||||
source,
|
||||
})?;
|
||||
let eod_docs_framed = eod_reader.docs_framed();
|
||||
let eod_bytes_read = eod_reader.bytes_read();
|
||||
|
||||
// 2. Stream `teMarketData` and retain points for `args.te_symbol` (ASCII case-insensitive).
|
||||
let te_file =
|
||||
File::open(&args.te_market_data).map_err(|source| RunCurateFxError::OpenInput {
|
||||
label: "te-market-data",
|
||||
path: args.te_market_data.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut te_reader =
|
||||
RawBsonChunkReader::with_options(te_file, BsonStreamOptions::default()).map_err(
|
||||
|source| RunCurateFxError::BsonStream {
|
||||
label: "te-market-data",
|
||||
path: args.te_market_data.clone(),
|
||||
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,
|
||||
&args.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: args.te_market_data.clone(),
|
||||
offset,
|
||||
source,
|
||||
});
|
||||
}
|
||||
let te_decode = te_decode_res.map_err(|source| RunCurateFxError::BsonStream {
|
||||
label: "te-market-data",
|
||||
path: args.te_market_data.clone(),
|
||||
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: args.eod_prices.clone(),
|
||||
te_path: args.te_market_data.clone(),
|
||||
te_symbol: args.te_symbol.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
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)?;
|
||||
|
||||
let write_report = curate_and_write_fx_1d(
|
||||
&args.out_dir,
|
||||
&decoded.eod_bars,
|
||||
&decoded.te_bars,
|
||||
Fx1dWriteOptions::default(),
|
||||
)
|
||||
.map_err(|source| RunCurateFxError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
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();
|
||||
|
||||
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;
|
||||
505
tools/curate-etl/src/run_curate_fx_tests.rs
Normal file
505
tools/curate-etl/src/run_curate_fx_tests.rs
Normal file
|
|
@ -0,0 +1,505 @@
|
|||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
use parquet::record::{Field, RowAccessor};
|
||||
|
||||
use super::*;
|
||||
use crate::bson_te_market_data::{MILLIS_PER_DAY, SECONDS_PER_DAY};
|
||||
use crate::curate_fx::fx_1d_utc_day_end_micros;
|
||||
use crate::fx::{FxSource, FX_PAIR_USDCAD};
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestTempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TestTempDir {
|
||||
fn new(prefix: &str) -> Self {
|
||||
let pid = std::process::id();
|
||||
let base = std::env::temp_dir();
|
||||
loop {
|
||||
let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let candidate = base.join(format!("curate-etl-{prefix}-{pid}-{seq}"));
|
||||
match fs::create_dir(&candidate) {
|
||||
Ok(()) => return Self { path: candidate },
|
||||
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(err) => panic!("failed to create temp dir {}: {err}", candidate.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestTempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn eod_doc(code: &str, date: &str, o: f64, h: f64, l: f64, c: f64, vol: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("open"), o);
|
||||
doc.append(cstr!("high"), h);
|
||||
doc.append(cstr!("low"), l);
|
||||
doc.append(cstr!("close"), c);
|
||||
doc.append(cstr!("volume"), vol);
|
||||
doc.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn te_point_secs(d: i32, o: f64, h: f64, l: f64, c: f64) -> RawDocumentBuf {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(d) * SECONDS_PER_DAY + 3_600);
|
||||
pt.append(cstr!("o"), o);
|
||||
pt.append(cstr!("h"), h);
|
||||
pt.append(cstr!("l"), l);
|
||||
pt.append(cstr!("c"), c);
|
||||
pt
|
||||
}
|
||||
|
||||
fn te_point_ms(d: i32, o: f64, h: f64, l: f64, c: f64) -> RawDocumentBuf {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(d) * MILLIS_PER_DAY + 43_200_000);
|
||||
pt.append(cstr!("o"), o);
|
||||
pt.append(cstr!("h"), h);
|
||||
pt.append(cstr!("l"), l);
|
||||
pt.append(cstr!("c"), c);
|
||||
pt
|
||||
}
|
||||
|
||||
fn assert_report_invariants(report: &CurateFx1dRunReport) {
|
||||
assert_eq!(report.eod_docs_framed as usize, report.eod_decode.docs_in);
|
||||
assert_eq!(
|
||||
report.eod_decode.docs_in,
|
||||
report.eod_decode.decoded + report.eod_decode.rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
report.eod_decode.decoded,
|
||||
report.eod_cad_forex_kept + report.eod_other_symbol_skipped
|
||||
);
|
||||
assert_eq!(
|
||||
report.eod_cad_forex_kept,
|
||||
report.curate_stats.builder.eod.rows_in
|
||||
);
|
||||
|
||||
assert_eq!(report.te_docs_framed as usize, report.te_decode.docs_in);
|
||||
assert_eq!(
|
||||
report.te_decode.docs_in,
|
||||
report.te_decode.docs_matched
|
||||
+ report.te_decode.docs_other_symbol
|
||||
+ report.te_decode.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
report.te_decode.points_in,
|
||||
report.te_decode.points_decoded + report.te_decode.rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
report.te_decode.points_decoded,
|
||||
report.curate_stats.builder.te.rows_in
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
report.curate_stats.rows_in,
|
||||
report.curate_stats.builder.rows_out
|
||||
);
|
||||
assert_eq!(report.curate_stats.rows_out, report.curate_stats.rows_in);
|
||||
assert_eq!(report.write_stats.rows_written, report.curate_stats.rows_out);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct ReadFxRow {
|
||||
pair: String,
|
||||
session_date: i32,
|
||||
ts_micros: i64,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
source: String,
|
||||
known_at_micros: i64,
|
||||
}
|
||||
|
||||
fn read_fx_parquet(path: &Path) -> Vec<ReadFxRow> {
|
||||
let file = File::open(path).expect("open fx_1d/part.parquet");
|
||||
let reader = SerializedFileReader::new(file).expect("parquet reader");
|
||||
let mut rows = Vec::new();
|
||||
for row_res in reader.get_row_iter(None).expect("row iter") {
|
||||
let row = row_res.expect("row");
|
||||
let session_date = match row.get_column_iter().nth(1).unwrap().1 {
|
||||
Field::Date(d) => *d,
|
||||
other => panic!("expected Date field at col 1, got {other:?}"),
|
||||
};
|
||||
rows.push(ReadFxRow {
|
||||
pair: row.get_string(0).unwrap().clone(),
|
||||
session_date,
|
||||
ts_micros: row.get_timestamp_micros(2).unwrap(),
|
||||
open: row.get_double(3).unwrap(),
|
||||
high: row.get_double(4).unwrap(),
|
||||
low: row.get_double(5).unwrap(),
|
||||
close: row.get_double(6).unwrap(),
|
||||
source: row.get_string(7).unwrap().clone(),
|
||||
known_at_micros: row.get_timestamp_micros(8).unwrap(),
|
||||
});
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn strip_timing_line(report_text: &str) -> String {
|
||||
report_text
|
||||
.lines()
|
||||
.filter(|l| !l.trim_start().starts_with("timing:"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_to_end_curation_precedence_gap_tail_and_permutation_invariance() {
|
||||
let tmp = TestTempDir::new("fx-e2e");
|
||||
let eod_path = tmp.path.join("eodPrices.bson");
|
||||
let te_path = tmp.path.join("teMarketData.bson");
|
||||
let out_a = tmp.path.join("out_a");
|
||||
let out_b = tmp.path.join("out_b");
|
||||
|
||||
let d1 = day(2025, 1, 2);
|
||||
let d2 = day(2025, 1, 3); // interior gap in EOD -> TE fills
|
||||
let d3 = day(2025, 1, 6);
|
||||
let d4 = day(2026, 1, 2); // post-EOD tail -> TE fills
|
||||
|
||||
// Build EOD docs: CAD.FOREX (d1, d3), wrong-case "cad.forex" (must be skipped!),
|
||||
// other symbol "AAPL.US" (skipped), and 1 malformed doc (missing close -> rejected).
|
||||
let mut malformed_eod = RawDocumentBuf::new();
|
||||
malformed_eod.append(cstr!("eodSearchCode"), "CAD.FOREX");
|
||||
malformed_eod.append(cstr!("date"), "2025-01-07");
|
||||
malformed_eod.append(cstr!("open"), 1.43_f64);
|
||||
malformed_eod.append(cstr!("high"), 1.44_f64);
|
||||
malformed_eod.append(cstr!("low"), 1.42_f64);
|
||||
malformed_eod.append(cstr!("volume"), 0.0_f64);
|
||||
|
||||
let eod_docs = vec![
|
||||
eod_doc("CAD.FOREX", "2025-01-02", 1.430, 1.440, 1.425, 1.435, 0.0),
|
||||
eod_doc("cad.forex", "2025-01-03", 9.990, 9.995, 9.985, 9.990, 0.0),
|
||||
eod_doc("AAPL.US", "2025-01-02", 240.0, 245.0, 239.0, 244.0, 1000.0),
|
||||
eod_doc("CAD.FOREX", "2025-01-06", 1.436, 1.442, 1.430, 1.438, 12.0),
|
||||
malformed_eod.as_bytes().to_vec(),
|
||||
];
|
||||
|
||||
// Build TE docs: other symbol ("EURUSD"), uppercase "USDCAD" (overlap d1 + gap d2 + bad point),
|
||||
// lowercase "usdcad" (tail d4 + ignored `monthly`).
|
||||
let mut other_te_daily = RawArrayBuf::new();
|
||||
other_te_daily.push(te_point_secs(d1, 1.05, 1.06, 1.04, 1.055));
|
||||
let mut other_te_doc = RawDocumentBuf::new();
|
||||
other_te_doc.append(cstr!("teSymbol"), "EURUSD");
|
||||
other_te_doc.append(cstr!("daily"), other_te_daily);
|
||||
|
||||
let mut bad_te_pt = RawDocumentBuf::new();
|
||||
bad_te_pt.append(cstr!("t"), i64::from(d4) * MILLIS_PER_DAY);
|
||||
bad_te_pt.append(cstr!("o"), f64::NAN);
|
||||
bad_te_pt.append(cstr!("h"), 1.39_f64);
|
||||
bad_te_pt.append(cstr!("l"), 1.37_f64);
|
||||
bad_te_pt.append(cstr!("c"), 1.38_f64);
|
||||
|
||||
let mut te_daily_1 = RawArrayBuf::new();
|
||||
te_daily_1.push(te_point_secs(d1, 1.431, 1.441, 1.426, 1.436)); // overlaps d1 -> EOD wins
|
||||
te_daily_1.push(te_point_ms(d2, 1.434, 1.439, 1.431, 1.437)); // interior gap -> TE fills
|
||||
te_daily_1.push(bad_te_pt);
|
||||
let mut te_doc_1 = RawDocumentBuf::new();
|
||||
te_doc_1.append(cstr!("teSymbol"), "USDCAD");
|
||||
te_doc_1.append(cstr!("daily"), te_daily_1);
|
||||
|
||||
let mut te_daily_2 = RawArrayBuf::new();
|
||||
te_daily_2.push(te_point_ms(d4, 1.380, 1.390, 1.375, 1.385)); // tail -> TE fills
|
||||
let mut ignored_monthly = RawArrayBuf::new();
|
||||
ignored_monthly.push("bad-monthly-ignored");
|
||||
let mut te_doc_2 = RawDocumentBuf::new();
|
||||
te_doc_2.append(cstr!("monthly"), ignored_monthly);
|
||||
te_doc_2.append(cstr!("daily"), te_daily_2);
|
||||
te_doc_2.append(cstr!("teSymbol"), "usdcad");
|
||||
|
||||
let te_docs = vec![
|
||||
other_te_doc.as_bytes().to_vec(),
|
||||
te_doc_1.as_bytes().to_vec(),
|
||||
te_doc_2.as_bytes().to_vec(),
|
||||
];
|
||||
|
||||
// Write run A in forward order
|
||||
fs::write(&eod_path, eod_docs.concat()).unwrap();
|
||||
fs::write(&te_path, te_docs.concat()).unwrap();
|
||||
|
||||
let args_a = CurateFx1dArgs {
|
||||
eod_prices: eod_path.clone(),
|
||||
te_market_data: te_path.clone(),
|
||||
te_symbol: DEFAULT_TE_SYMBOL.to_string(),
|
||||
out_dir: out_a.clone(),
|
||||
};
|
||||
let report_a = run_curate_fx_1d(&args_a).expect("run A succeeds");
|
||||
assert_report_invariants(&report_a);
|
||||
|
||||
assert_eq!(report_a.eod_docs_framed, 5);
|
||||
assert_eq!(report_a.eod_cad_forex_kept, 2);
|
||||
assert_eq!(report_a.eod_other_symbol_skipped, 2); // "cad.forex" + "AAPL.US"
|
||||
assert_eq!(report_a.eod_decode.rejected_missing_field, 1);
|
||||
|
||||
assert_eq!(report_a.te_docs_framed, 3);
|
||||
assert_eq!(report_a.te_decode.docs_matched, 2);
|
||||
assert_eq!(report_a.te_decode.docs_other_symbol, 1);
|
||||
assert_eq!(report_a.te_decode.points_in, 4);
|
||||
assert_eq!(report_a.te_decode.points_decoded, 3);
|
||||
assert_eq!(report_a.te_decode.rejected_non_finite, 1);
|
||||
|
||||
assert_eq!(report_a.curate_stats.rows_out, 4);
|
||||
assert_eq!(report_a.curate_stats.builder.eod_rows_out, 2);
|
||||
assert_eq!(report_a.curate_stats.builder.te_rows_out, 2);
|
||||
assert_eq!(report_a.curate_stats.builder.te_superseded_by_eod, 1);
|
||||
assert_eq!(report_a.curate_stats.builder.overlap_checked, 1);
|
||||
assert_eq!(report_a.curate_stats.builder.overlap_within_tolerance, 1);
|
||||
assert_eq!(report_a.write_stats.rows_written, 4);
|
||||
assert_eq!(report_a.write_stats.files_written, 1);
|
||||
|
||||
let parquet_a = out_a.join("fx_1d/part.parquet");
|
||||
let rows = read_fx_parquet(&parquet_a);
|
||||
assert_eq!(rows.len(), 4);
|
||||
|
||||
let expected_dates = [d1, d2, d3, d4];
|
||||
let expected_sources = [
|
||||
FxSource::EodCadForex.as_str(),
|
||||
FxSource::TeUsdCad.as_str(),
|
||||
FxSource::EodCadForex.as_str(),
|
||||
FxSource::TeUsdCad.as_str(),
|
||||
];
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
assert_eq!(row.pair, FX_PAIR_USDCAD);
|
||||
assert_eq!(row.session_date, expected_dates[i]);
|
||||
let expected_ts = fx_1d_utc_day_end_micros(expected_dates[i]).unwrap();
|
||||
assert_eq!(row.ts_micros, expected_ts);
|
||||
assert_eq!(row.known_at_micros, expected_ts);
|
||||
assert_eq!(row.source, expected_sources[i]);
|
||||
}
|
||||
// Strictly ascending & unique
|
||||
for w in rows.windows(2) {
|
||||
assert!(w[0].session_date < w[1].session_date);
|
||||
}
|
||||
// d1 EOD bitwise OHLC preserved
|
||||
assert_eq!(rows[0].open.to_bits(), 1.430_f64.to_bits());
|
||||
assert_eq!(rows[0].high.to_bits(), 1.440_f64.to_bits());
|
||||
assert_eq!(rows[0].low.to_bits(), 1.425_f64.to_bits());
|
||||
assert_eq!(rows[0].close.to_bits(), 1.435_f64.to_bits());
|
||||
// d2 TE gap fill
|
||||
assert_eq!(rows[1].close.to_bits(), 1.437_f64.to_bits());
|
||||
// d4 TE tail fill
|
||||
assert_eq!(rows[3].close.to_bits(), 1.385_f64.to_bits());
|
||||
|
||||
// Write run B in reversed doc order -> byte-identical Parquet and identical report (sans timing)
|
||||
let eod_rev: Vec<u8> = eod_docs.into_iter().rev().flatten().collect();
|
||||
let te_rev: Vec<u8> = te_docs.into_iter().rev().flatten().collect();
|
||||
let eod_rev_path = tmp.path.join("eodPrices_rev.bson");
|
||||
let te_rev_path = tmp.path.join("teMarketData_rev.bson");
|
||||
fs::write(&eod_rev_path, eod_rev).unwrap();
|
||||
fs::write(&te_rev_path, te_rev).unwrap();
|
||||
|
||||
let args_b = CurateFx1dArgs {
|
||||
eod_prices: eod_rev_path,
|
||||
te_market_data: te_rev_path,
|
||||
te_symbol: DEFAULT_TE_SYMBOL.to_string(),
|
||||
out_dir: out_b.clone(),
|
||||
};
|
||||
let report_b = run_curate_fx_1d(&args_b).expect("run B succeeds");
|
||||
assert_report_invariants(&report_b);
|
||||
|
||||
let parquet_b = out_b.join("fx_1d/part.parquet");
|
||||
assert_eq!(
|
||||
fs::read(&parquet_a).unwrap(),
|
||||
fs::read(&parquet_b).unwrap(),
|
||||
"shuffled BSON input must yield byte-identical fx_1d/part.parquet"
|
||||
);
|
||||
assert_eq!(
|
||||
strip_timing_line(&format_curate_fx_report(&report_a)),
|
||||
strip_timing_line(&format_curate_fx_report(&report_b))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_modes_return_typed_errors_and_preserve_existing_parquet() {
|
||||
let tmp = TestTempDir::new("fx-fail");
|
||||
let out_dir = tmp.path.join("out");
|
||||
let fx_dir = out_dir.join("fx_1d");
|
||||
fs::create_dir_all(&fx_dir).unwrap();
|
||||
let live_parquet = fx_dir.join("part.parquet");
|
||||
let sentinel = b"EXISTING-FX-PARQUET-SENTINEL-BYTES";
|
||||
fs::write(&live_parquet, sentinel).unwrap();
|
||||
|
||||
let valid_eod = tmp.path.join("valid_eod.bson");
|
||||
fs::write(
|
||||
&valid_eod,
|
||||
eod_doc("CAD.FOREX", "2025-01-02", 1.43, 1.44, 1.42, 1.435, 0.0),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let valid_te = tmp.path.join("valid_te.bson");
|
||||
let mut valid_te_daily = RawArrayBuf::new();
|
||||
valid_te_daily.push(te_point_secs(day(2025, 1, 2), 1.43, 1.44, 1.42, 1.435));
|
||||
let mut valid_te_doc = RawDocumentBuf::new();
|
||||
valid_te_doc.append(cstr!("teSymbol"), "USDCAD");
|
||||
valid_te_doc.append(cstr!("daily"), valid_te_daily);
|
||||
fs::write(&valid_te, valid_te_doc.as_bytes()).unwrap();
|
||||
|
||||
let check_sentinel = || {
|
||||
assert_eq!(
|
||||
fs::read(&live_parquet).unwrap(),
|
||||
sentinel,
|
||||
"existing fx_1d/part.parquet must remain byte-identical on failure"
|
||||
);
|
||||
};
|
||||
|
||||
// 1. Truncated BSON in eodPrices
|
||||
let trunc_eod = tmp.path.join("trunc_eod.bson");
|
||||
fs::write(&trunc_eod, [20, 0, 0, 0, 1, 2]).unwrap();
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: trunc_eod,
|
||||
te_market_data: valid_te.clone(),
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::BsonStream { label: "eod-prices", .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
|
||||
// 2. Truncated BSON in teMarketData
|
||||
let trunc_te = tmp.path.join("trunc_te.bson");
|
||||
fs::write(&trunc_te, [20, 0, 0, 0, 1, 2]).unwrap();
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
te_market_data: trunc_te,
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, RunCurateFxError::BsonStream { label: "te-market-data", .. }),
|
||||
"{err:?}"
|
||||
);
|
||||
check_sentinel();
|
||||
|
||||
// 3. Corrupt framed BSON bytes in eodPrices
|
||||
let corrupt_eod = tmp.path.join("corrupt_eod.bson");
|
||||
fs::write(&corrupt_eod, [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0]).unwrap();
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: corrupt_eod,
|
||||
te_market_data: valid_te.clone(),
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::CorruptEodBson { .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
|
||||
// 4. Corrupt BSON inside teMarketData `daily` array
|
||||
let corrupt_te = tmp.path.join("corrupt_te.bson");
|
||||
let mut bad_te_bytes = valid_te_doc.as_bytes().to_vec();
|
||||
// Corrupt the element type byte of the first element inside `daily` array.
|
||||
// Find `daily\0` in raw bytes; the array starts right after `daily\0` (4-byte len, then elem type).
|
||||
let daily_pos = bad_te_bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"daily\0")
|
||||
.expect("find daily key");
|
||||
let first_array_elem_type_idx = daily_pos + 6 + 4;
|
||||
bad_te_bytes[first_array_elem_type_idx] = 0xFF;
|
||||
fs::write(&corrupt_te, &bad_te_bytes).unwrap();
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
te_market_data: corrupt_te,
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
RunCurateFxError::CorruptTeBson {
|
||||
source: BsonTeMarketDataError::CorruptPointBson { .. },
|
||||
..
|
||||
}
|
||||
),
|
||||
"{err:?}"
|
||||
);
|
||||
check_sentinel();
|
||||
|
||||
// 5. Missing eodPrices file
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: tmp.path.join("does_not_exist_eod.bson"),
|
||||
te_market_data: valid_te.clone(),
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::OpenInput { label: "eod-prices", .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
|
||||
// 6. Missing teMarketData file
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
te_market_data: tmp.path.join("does_not_exist_te.bson"),
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, RunCurateFxError::OpenInput { label: "te-market-data", .. }),
|
||||
"{err:?}"
|
||||
);
|
||||
check_sentinel();
|
||||
|
||||
// 7. --out pointing at an existing regular file
|
||||
let out_file = tmp.path.join("regular_file");
|
||||
fs::write(&out_file, b"not-a-dir").unwrap();
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
te_market_data: valid_te.clone(),
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_file,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::InvalidOutDir { .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
|
||||
// 8. Blank te_symbol
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
te_market_data: valid_te.clone(),
|
||||
te_symbol: " ".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::InvalidTeSymbol { .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
|
||||
// 9. Zero decoded bars across both inputs (only non-matching symbols / empty daily)
|
||||
let other_eod = tmp.path.join("other_eod.bson");
|
||||
fs::write(
|
||||
&other_eod,
|
||||
eod_doc("EUR.FOREX", "2025-01-02", 1.10, 1.11, 1.09, 1.105, 0.0),
|
||||
)
|
||||
.unwrap();
|
||||
let empty_te = tmp.path.join("empty_te.bson");
|
||||
let mut empty_te_doc = RawDocumentBuf::new();
|
||||
empty_te_doc.append(cstr!("teSymbol"), "USDCAD");
|
||||
empty_te_doc.append(cstr!("daily"), RawArrayBuf::new());
|
||||
fs::write(&empty_te, empty_te_doc.as_bytes()).unwrap();
|
||||
let err = run_curate_fx_1d(&CurateFx1dArgs {
|
||||
eod_prices: other_eod,
|
||||
te_market_data: empty_te,
|
||||
te_symbol: "USDCAD".to_string(),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateFxError::NoDecodedBars { .. }), "{err:?}");
|
||||
check_sentinel();
|
||||
}
|
||||
|
|
@ -1056,3 +1056,153 @@ fn bench_curate_corporate_actions_cmd_small_run_is_deterministic_and_reports_sta
|
|||
assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum="));
|
||||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_fx_1d_cli_flag_errors_exit_nonzero_with_usage() {
|
||||
for args in [
|
||||
&["curate-fx-1d"][..],
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--te-market-data",
|
||||
"t.bson",
|
||||
][..],
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--te-market-data",
|
||||
"t.bson",
|
||||
"--te-symbol",
|
||||
"USDCAD",
|
||||
"--te-symbol=USDCAD",
|
||||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--te-market-data",
|
||||
"t.bson",
|
||||
"--out",
|
||||
"out",
|
||||
"--unknown",
|
||||
"1",
|
||||
][..],
|
||||
] {
|
||||
let out = run(args);
|
||||
assert!(!out.status.success(), "{args:?} should fail");
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}");
|
||||
assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout");
|
||||
let err = stderr(&out);
|
||||
assert!(err.contains("error:"), "{args:?}: {err}");
|
||||
assert!(err.contains("Usage:"), "{args:?}: {err}");
|
||||
assert!(err.contains("curate-fx-1d"), "{args:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_fx_1d_cli_happy_path_and_single_line_runtime_error() {
|
||||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
|
||||
let dir = CliTempDir::new("fx-1d-cli");
|
||||
let eod_path = dir.path.join("eodPrices.bson");
|
||||
let te_path = dir.path.join("teMarketData.bson");
|
||||
let empty_eod_path = dir.path.join("empty_eod.bson");
|
||||
let empty_te_path = dir.path.join("empty_te.bson");
|
||||
let out_dir = dir.path.join("out");
|
||||
let out_fail = dir.path.join("out_fail");
|
||||
|
||||
let mut eod_doc = RawDocumentBuf::new();
|
||||
eod_doc.append(cstr!("eodSearchCode"), "CAD.FOREX");
|
||||
eod_doc.append(cstr!("date"), "2025-01-02");
|
||||
eod_doc.append(cstr!("open"), 1.430_f64);
|
||||
eod_doc.append(cstr!("high"), 1.440_f64);
|
||||
eod_doc.append(cstr!("low"), 1.425_f64);
|
||||
eod_doc.append(cstr!("close"), 1.435_f64);
|
||||
eod_doc.append(cstr!("volume"), 0.0_f64);
|
||||
write_file(&eod_path, eod_doc.as_bytes());
|
||||
|
||||
let mut daily = RawArrayBuf::new();
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), 1_767_312_000_000_i64); // 2026-01-02 UTC in ms
|
||||
pt.append(cstr!("o"), 1.380_f64);
|
||||
pt.append(cstr!("h"), 1.390_f64);
|
||||
pt.append(cstr!("l"), 1.375_f64);
|
||||
pt.append(cstr!("c"), 1.385_f64);
|
||||
daily.push(pt);
|
||||
let mut te_doc = RawDocumentBuf::new();
|
||||
te_doc.append(cstr!("teSymbol"), "USDCAD");
|
||||
te_doc.append(cstr!("daily"), daily);
|
||||
write_file(&te_path, te_doc.as_bytes());
|
||||
|
||||
write_file(&empty_eod_path, b"");
|
||||
write_file(&empty_te_path, b"");
|
||||
|
||||
// 1. Happy path
|
||||
let res = run(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--te-market-data",
|
||||
te_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_dir.to_str().unwrap(),
|
||||
]);
|
||||
assert!(res.status.success(), "{}", stderr(&res));
|
||||
assert!(stderr(&res).is_empty(), "{}", stderr(&res));
|
||||
let text = stdout(&res);
|
||||
assert!(text.contains("curate-etl curate-fx-1d"), "{text}");
|
||||
assert!(text.contains("rows_written=2"), "{text}");
|
||||
assert!(out_dir.join("fx_1d/part.parquet").is_file());
|
||||
|
||||
// 2. Runtime error (zero decoded bars) -> single-line stderr, no Usage, no output
|
||||
let res_fail = run(&[
|
||||
"curate-fx-1d",
|
||||
"--eod-prices",
|
||||
empty_eod_path.to_str().unwrap(),
|
||||
"--te-market-data",
|
||||
empty_te_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_fail.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res_fail.status.success());
|
||||
assert_eq!(res_fail.status.code(), Some(1));
|
||||
assert!(stdout(&res_fail).is_empty());
|
||||
let err = stderr(&res_fail);
|
||||
assert_eq!(err.lines().count(), 1, "expected single-line stderr: {err}");
|
||||
assert!(err.contains("no FX bars decoded"), "{err}");
|
||||
assert!(!err.contains("Usage:"), "{err}");
|
||||
assert!(!out_fail.join("fx_1d").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_fx_cmd_small_run_is_deterministic_and_reports_stages() {
|
||||
let a = run(&["bench-curate-fx-cmd", "1000"]);
|
||||
let b = run(&["bench-curate-fx-cmd", "1000"]);
|
||||
assert!(a.status.success(), "{}", stderr(&a));
|
||||
assert!(b.status.success(), "{}", stderr(&b));
|
||||
assert!(stderr(&a).is_empty(), "{}", stderr(&a));
|
||||
assert!(stderr(&b).is_empty(), "{}", stderr(&b));
|
||||
|
||||
let text_a = stdout(&a);
|
||||
let text_b = stdout(&b);
|
||||
assert!(text_a.contains("curate-etl bench-curate-fx-cmd"), "{text_a}");
|
||||
assert!(text_a.contains("rows=1000 "), "{text_a}");
|
||||
assert!(text_a.contains("decode:"), "{text_a}");
|
||||
assert!(text_a.contains("curate:"), "{text_a}");
|
||||
assert!(text_a.contains("write:"), "{text_a}");
|
||||
assert!(text_a.contains("total:"), "{text_a}");
|
||||
assert!(text_a.contains("overlap:"), "{text_a}");
|
||||
assert!(text_a.contains("checksum=0x"), "{text_a}");
|
||||
|
||||
let field = |s: &str, prefix: &str| {
|
||||
s.split_whitespace()
|
||||
.find(|t| t.starts_with(prefix))
|
||||
.map(str::to_owned)
|
||||
};
|
||||
assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum="));
|
||||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue