T-94: M1.2l — tools/curate-etl: Zstd Parquet writer for fx_1d/part.parquet (contract schema, atomic single-file publish) with round-trip tests and local benchmark (no new crates)
This commit is contained in:
parent
f15b01a739
commit
4e93497625
8 changed files with 3448 additions and 11 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, and the `M1.2k` streaming Zstd Parquet writer for `events`.
|
||||
Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, and the `M1.2l` streaming Zstd Parquet writer for `fx_1d`.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -76,7 +76,7 @@ Rules:
|
|||
|
||||
## `fx_1d` Builder (`M1.2e`)
|
||||
|
||||
`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) matching the `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (excluding `ts`/`known_at` timestamps, which belong to the later writer task).
|
||||
`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) matching the `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (the `M1.2l` Parquet writer takes caller-supplied `ts`/`known_at` timestamps; timestamp derivation policy belongs to the Mongo-streaming wiring task).
|
||||
|
||||
Rules:
|
||||
1. **Quote convention:** Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (`CADUSD.FOREX` inversion is out of scope).
|
||||
|
|
@ -92,7 +92,7 @@ Rules:
|
|||
- Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out`
|
||||
- Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod`
|
||||
|
||||
Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation (later writer task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends.
|
||||
Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation policy (the `M1.2l` Parquet writer accepts caller-supplied timestamps; derivation belongs to the Mongo-streaming wiring task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends.
|
||||
|
||||
## `shorts` Builder (`M1.2f`)
|
||||
|
||||
|
|
@ -297,6 +297,48 @@ Rules:
|
|||
- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000`
|
||||
- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x`
|
||||
|
||||
## `fx_1d` Parquet Writer (`M1.2l`)
|
||||
|
||||
`write_fx_1d_dataset` (`src/parquet_fx.rs`) streams strictly ascending `(pair, session_date)` `Fx1dParquetRow` records (with zero-allocation `Fx1dParquetRow::from_fx_row(&Fx1dRow, ts_micros, known_at_micros)` construction from `build_fx_1d`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A).
|
||||
|
||||
1. **Exact 9-column contract schema (`fx_1d_parquet_schema`):**
|
||||
- `pair` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
|
||||
- `session_date` (`INT32`, `REQUIRED`, `DATE`)
|
||||
- `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
|
||||
- `open`, `high`, `low`, `close` (`DOUBLE`, `REQUIRED`)
|
||||
- `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
|
||||
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
|
||||
2. **Layout, compression & streaming:**
|
||||
- Writes `<out_dir>/fx_1d/part.parquet` (unpartitioned).
|
||||
- Empty input returns `Ok(Fx1dWriteStats::default())` without creating `<out_dir>/fx_1d` and without modifying or removing any pre-existing `part.parquet`.
|
||||
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Fx1dWriteOptions::zstd_level`).
|
||||
- Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Fx1dWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with string interning for `pair` and `source` and reused buffers across row groups), flushing and clearing on every row-group boundary.
|
||||
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
|
||||
3. **Validation, concurrency & atomic publish rules:**
|
||||
- Caller supplies `ts_micros` and `known_at_micros` (FX timestamp derivation policy belongs to the Mongo-streaming wiring task).
|
||||
- Every streamed row is validated before publication: `pair` and `source` must be non-empty after trimming; every OHLC value must be finite and `> 0.0` with `high >= low` and `open`, `close` inside `[low, high]`; `ts_micros` must fall inside the UTC day `[session_date * 86_400_000_000, +1 day)` (computed in `i128` to avoid overflow on pre-1970 or extreme `i32` dates); `known_at_micros >= ts_micros` is enforced; and input must be strictly ascending and unique by `(pair, session_date)`.
|
||||
- Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `<out_dir>/fx_1d` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flush, and `File::sync_all()`; pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`.
|
||||
4. **Typed errors (`ParquetFxError`):**
|
||||
- `InvalidRowGroupRows` (`row_group_rows == 0`)
|
||||
- `InvalidZstdLevel { level }`
|
||||
- `UnsortedInput { prev_pair, prev_session_date, pair, session_date }`
|
||||
- `DuplicateKey { pair, session_date }`
|
||||
- `EmptyPair { session_date }`
|
||||
- `EmptySource { pair, session_date }`
|
||||
- `InvalidOhlc { pair, session_date, open, high, low, close }`
|
||||
- `InconsistentOhlc { pair, session_date, open, high, low, close }`
|
||||
- `TsOutsideSessionDate { pair, session_date, ts_micros }`
|
||||
- `KnownAtBeforeTs { pair, session_date, ts_micros, known_at_micros }`
|
||||
- `LockTimeout { path, waited }`
|
||||
- `RollbackFailed { cause, failures }`
|
||||
- `Io { path, source }`
|
||||
- `Parquet { path, source }`
|
||||
5. **Measured baseline (`2026-11-28`):**
|
||||
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-fx`
|
||||
- Input: `rows=1000000`, `pairs=80`, `raw_row_bytes=70` (weekday dates `1971..=2026`, mixing `eod_cad_forex` and `te_usdcad`)
|
||||
- Output: `files=1`, `row_groups=1`, `bytes=22102946`, `read_back_rows=1000000`
|
||||
- Perf: `elapsed=228.82 ms`, `throughput=4370208 rows/s`, `write=92.12 MB/s`, `size=22.10 bytes/row`, `compression=3.17x`
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
### `bench-split`
|
||||
|
|
@ -453,13 +495,27 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa
|
|||
- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000`
|
||||
- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x`
|
||||
|
||||
### `bench-parquet-fx`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `Fx1dParquetRow` rows across `80` currency pairs on weekday dates (`1971..=2026`, mixing `eod_cad_forex` and `te_usdcad`), writing `fx_1d/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-parquet-fx [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-fx`
|
||||
|
||||
- Input: `rows=1000000`, `pairs=80`, `raw_row_bytes=70`
|
||||
- Output: `files=1`, `row_groups=1`, `bytes=22102946`, `read_back_rows=1000000`
|
||||
- Perf: `elapsed=228.82 ms`, `throughput=4370208 rows/s`, `write=92.12 MB/s`, `size=22.10 bytes/row`, `compression=3.17x`
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add:
|
||||
|
||||
- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata
|
||||
- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends
|
||||
- Zstd Parquet writers for the remaining curated tables (`adj_factors`, `corporate_actions`, `fx_1d`) and `qmPrices` OHLC cross-check
|
||||
- Zstd Parquet writers for the remaining curated tables (`adj_factors`, `corporate_actions`) and `qmPrices` OHLC cross-check
|
||||
- Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`)
|
||||
- PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32`
|
||||
- `rayon` parallel sharding across symbol/date partitions
|
||||
|
|
|
|||
|
|
@ -22,13 +22,16 @@ use crate::events::{
|
|||
EventsStats, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING,
|
||||
KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG,
|
||||
};
|
||||
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar};
|
||||
use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD};
|
||||
use crate::parquet_bars::{
|
||||
write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError,
|
||||
};
|
||||
use crate::parquet_events::{
|
||||
write_events_dataset, EventsParquetRow, EventsWriteOptions, ParquetEventsError,
|
||||
};
|
||||
use crate::parquet_fx::{
|
||||
write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, ParquetFxError,
|
||||
};
|
||||
use crate::parquet_shorts::{
|
||||
write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions,
|
||||
};
|
||||
|
|
@ -54,6 +57,8 @@ pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84;
|
|||
pub const DEFAULT_PARQUET_SHORTS_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const PARQUET_SHORTS_RAW_ROW_BYTES: usize = 50;
|
||||
pub const DEFAULT_PARQUET_EVENTS_BENCH_ROWS: usize = 500_000;
|
||||
pub const DEFAULT_PARQUET_FX_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const PARQUET_FX_RAW_ROW_BYTES: usize = 70;
|
||||
pub const BENCH_KEY_COUNT: usize = 20_000;
|
||||
pub const BENCH_EVENT_COUNT: usize = 19_000;
|
||||
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
|
||||
|
|
@ -61,6 +66,7 @@ const SHORTS_BENCH_KEY_COUNT: usize = 12_500;
|
|||
const PARQUET_BARS_BENCH_BASE_LISTINGS: usize = 2_000;
|
||||
const PARQUET_SHORTS_BENCH_BASE_LISTINGS: usize = 12_500;
|
||||
const PARQUET_EVENTS_BENCH_BASE_LISTINGS: usize = 5_000;
|
||||
const PARQUET_FX_BENCH_BASE_PAIRS: usize = 80;
|
||||
|
||||
const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57;
|
||||
const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70;
|
||||
|
|
@ -73,6 +79,7 @@ const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00;
|
|||
const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45;
|
||||
const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404;
|
||||
const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4;
|
||||
const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D;
|
||||
const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05];
|
||||
|
||||
/// Deterministic SplitMix64 generator (zero external dependencies).
|
||||
|
|
@ -1695,6 +1702,11 @@ impl BenchTempDir {
|
|||
Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-events")
|
||||
.map_err(|(path, source)| ParquetEventsError::Io { path, source })
|
||||
}
|
||||
|
||||
fn new_fx() -> Result<Self, ParquetFxError> {
|
||||
Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-fx")
|
||||
.map_err(|(path, source)| ParquetFxError::Io { path, source })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BenchTempDir {
|
||||
|
|
@ -2602,6 +2614,314 @@ pub fn run_parquet_events_benchmark(
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_parquet_fx_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct ParquetFxBenchReport {
|
||||
pub rows: usize,
|
||||
pub read_back_rows: usize,
|
||||
pub pair_count: usize,
|
||||
pub files_written: usize,
|
||||
pub row_groups_written: usize,
|
||||
pub bytes_written: u64,
|
||||
pub raw_row_bytes: usize,
|
||||
pub elapsed_ms: f64,
|
||||
pub rows_per_sec: f64,
|
||||
pub mb_per_sec: f64,
|
||||
pub bytes_per_row: f64,
|
||||
pub compression_ratio: f64,
|
||||
}
|
||||
|
||||
const BENCH_FX_STATIC_PAIRS: [&str; 79] = [
|
||||
"FX0000", "FX0001", "FX0002", "FX0003", "FX0004", "FX0005", "FX0006", "FX0007", "FX0008",
|
||||
"FX0009", "FX0010", "FX0011", "FX0012", "FX0013", "FX0014", "FX0015", "FX0016", "FX0017",
|
||||
"FX0018", "FX0019", "FX0020", "FX0021", "FX0022", "FX0023", "FX0024", "FX0025", "FX0026",
|
||||
"FX0027", "FX0028", "FX0029", "FX0030", "FX0031", "FX0032", "FX0033", "FX0034", "FX0035",
|
||||
"FX0036", "FX0037", "FX0038", "FX0039", "FX0040", "FX0041", "FX0042", "FX0043", "FX0044",
|
||||
"FX0045", "FX0046", "FX0047", "FX0048", "FX0049", "FX0050", "FX0051", "FX0052", "FX0053",
|
||||
"FX0054", "FX0055", "FX0056", "FX0057", "FX0058", "FX0059", "FX0060", "FX0061", "FX0062",
|
||||
"FX0063", "FX0064", "FX0065", "FX0066", "FX0067", "FX0068", "FX0069", "FX0070", "FX0071",
|
||||
"FX0072", "FX0073", "FX0074", "FX0075", "FX0076", "FX0077", "FX0078",
|
||||
];
|
||||
|
||||
fn collect_bench_weekdays_1971_2026() -> Vec<i32> {
|
||||
let start = ymd_to_epoch_days(1971, 1, 4).expect("valid start date");
|
||||
let end = ymd_to_epoch_days(2026, 12, 31).expect("valid end date");
|
||||
let mut days = Vec::with_capacity(15_000);
|
||||
let mut d = start;
|
||||
while d <= end {
|
||||
let dow = (d + 4).rem_euclid(7);
|
||||
if (1..=5).contains(&dow) {
|
||||
days.push(d);
|
||||
}
|
||||
d += 1;
|
||||
}
|
||||
days
|
||||
}
|
||||
|
||||
struct ParquetFxBenchIter {
|
||||
weekdays: Vec<i32>,
|
||||
te_tail_start_day: i32,
|
||||
pair_count: usize,
|
||||
base_per_pair: usize,
|
||||
rem_pairs: usize,
|
||||
cur_pair_idx: usize,
|
||||
cur_day_idx: usize,
|
||||
cur_pair_rows: usize,
|
||||
cur_rate: f64,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl ParquetFxBenchIter {
|
||||
fn new(rows: usize, weekdays: Vec<i32>) -> Self {
|
||||
let min_pairs = if rows == 0 {
|
||||
PARQUET_FX_BENCH_BASE_PAIRS
|
||||
} else {
|
||||
rows.div_ceil(weekdays.len())
|
||||
.max(PARQUET_FX_BENCH_BASE_PAIRS)
|
||||
};
|
||||
let active_pairs = rows.min(min_pairs);
|
||||
let base_per_pair = if active_pairs == 0 {
|
||||
0
|
||||
} else {
|
||||
rows / active_pairs
|
||||
};
|
||||
let rem_pairs = if active_pairs == 0 {
|
||||
0
|
||||
} else {
|
||||
rows % active_pairs
|
||||
};
|
||||
let te_tail_start_day = ymd_to_epoch_days(2026, 1, 1).expect("valid tail date");
|
||||
let mut iter = Self {
|
||||
weekdays,
|
||||
te_tail_start_day,
|
||||
pair_count: active_pairs,
|
||||
base_per_pair,
|
||||
rem_pairs,
|
||||
cur_pair_idx: 0,
|
||||
cur_day_idx: 0,
|
||||
cur_pair_rows: 0,
|
||||
cur_rate: 1.35,
|
||||
rng: SplitMix64::new(PARQUET_FX_BENCH_SEED),
|
||||
};
|
||||
if active_pairs > 0 {
|
||||
iter.setup_pair(0);
|
||||
}
|
||||
iter
|
||||
}
|
||||
|
||||
fn setup_pair(&mut self, pair_idx: usize) {
|
||||
self.cur_pair_idx = pair_idx;
|
||||
self.cur_day_idx = 0;
|
||||
self.cur_pair_rows = self.base_per_pair + usize::from(pair_idx < self.rem_pairs);
|
||||
self.cur_rate = 0.95 + ((self.rng.next_u64() % 60) as f64) * 0.01;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn pair_label(&self, pair_idx: usize) -> Cow<'static, str> {
|
||||
// Place canonical "USDCAD" last so lexicographic order ("FX0000" < ... < "USDCAD")
|
||||
// is strictly ascending and zero-allocation for up to 80 pairs (~1.16M rows).
|
||||
if pair_idx + 1 == self.pair_count {
|
||||
Cow::Borrowed(FX_PAIR_USDCAD)
|
||||
} else if let Some(&static_pair) = BENCH_FX_STATIC_PAIRS.get(pair_idx) {
|
||||
Cow::Borrowed(static_pair)
|
||||
} else {
|
||||
Cow::Owned(format!("FX{pair_idx:04}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for ParquetFxBenchIter {
|
||||
type Item = Fx1dParquetRow;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.cur_pair_idx >= self.pair_count {
|
||||
return None;
|
||||
}
|
||||
if self.cur_day_idx >= self.cur_pair_rows {
|
||||
let next_pair = self.cur_pair_idx + 1;
|
||||
if next_pair >= self.pair_count {
|
||||
self.cur_pair_idx = next_pair;
|
||||
return None;
|
||||
}
|
||||
self.setup_pair(next_pair);
|
||||
}
|
||||
|
||||
let pair = self.pair_label(self.cur_pair_idx);
|
||||
let w = self.weekdays.len();
|
||||
let n = self.cur_pair_rows;
|
||||
let date_pos = if n == 1 {
|
||||
(self.cur_pair_idx.wrapping_mul(131)) % w
|
||||
} else {
|
||||
(self.cur_day_idx * w) / n
|
||||
};
|
||||
let session_date = self.weekdays[date_pos];
|
||||
self.cur_day_idx += 1;
|
||||
|
||||
let r1 = self.rng.next_u64();
|
||||
let step = ((r1 % 201) as f64 - 100.0) * 0.0001;
|
||||
let next_rate = (self.cur_rate + step).clamp(0.92, 1.60);
|
||||
let half_spread = (((r1 >> 8) % 80) + 10) as f64 * 0.0001;
|
||||
let low = (next_rate - half_spread).max(0.50);
|
||||
let high = next_rate + half_spread;
|
||||
let open = low + (high - low) * (((r1 >> 16) % 100) as f64 * 0.01);
|
||||
let close = next_rate;
|
||||
self.cur_rate = next_rate;
|
||||
|
||||
let source = if session_date >= self.te_tail_start_day || ((r1 >> 24) % 20) == 0 {
|
||||
FxSource::TeUsdCad
|
||||
} else {
|
||||
FxSource::EodCadForex
|
||||
};
|
||||
let ts_micros = i64::from(session_date) * 86_400_000_000 + 22 * 3_600_000_000;
|
||||
let known_at_micros = ts_micros + 900_000_000;
|
||||
|
||||
Some(Fx1dParquetRow {
|
||||
pair,
|
||||
session_date,
|
||||
ts_micros,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
source: Cow::Borrowed(source.as_str()),
|
||||
known_at_micros,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_parquet_fx_row_count(
|
||||
out_dir: &Path,
|
||||
expected_rows: usize,
|
||||
) -> Result<usize, ParquetFxError> {
|
||||
if expected_rows == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let path = out_dir.join("fx_1d/part.parquet");
|
||||
let file = File::open(&path).map_err(|source| ParquetFxError::Io {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let reader = SerializedFileReader::new(file).map_err(|source| ParquetFxError::Parquet {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err(
|
||||
|_| ParquetFxError::Parquet {
|
||||
path: path.clone(),
|
||||
source: ParquetError::General(format!(
|
||||
"negative or overflowing Parquet footer row count: {}",
|
||||
reader.metadata().file_metadata().num_rows()
|
||||
)),
|
||||
},
|
||||
)?;
|
||||
|
||||
if read_back_rows != expected_rows {
|
||||
return Err(ParquetFxError::Parquet {
|
||||
path,
|
||||
source: ParquetError::General(format!(
|
||||
"parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}"
|
||||
)),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(read_back_rows)
|
||||
}
|
||||
|
||||
fn run_parquet_fx_benchmark_tracked(
|
||||
rows: usize,
|
||||
) -> Result<(ParquetFxBenchReport, PathBuf), ParquetFxError> {
|
||||
let temp = BenchTempDir::new_fx()?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
if rows == 0 {
|
||||
let stats = write_fx_1d_dataset(
|
||||
&temp.path,
|
||||
std::iter::empty::<Fx1dParquetRow>(),
|
||||
Fx1dWriteOptions::default(),
|
||||
)?;
|
||||
let read_back_rows = verify_parquet_fx_row_count(&temp.path, 0)?;
|
||||
let report = ParquetFxBenchReport {
|
||||
rows: 0,
|
||||
read_back_rows,
|
||||
pair_count: 0,
|
||||
files_written: stats.files_written,
|
||||
row_groups_written: stats.row_groups_written,
|
||||
bytes_written: stats.bytes_written,
|
||||
raw_row_bytes: PARQUET_FX_RAW_ROW_BYTES,
|
||||
elapsed_ms: 0.0,
|
||||
rows_per_sec: 0.0,
|
||||
mb_per_sec: 0.0,
|
||||
bytes_per_row: 0.0,
|
||||
compression_ratio: 0.0,
|
||||
};
|
||||
drop(temp);
|
||||
return Ok((report, temp_path));
|
||||
}
|
||||
|
||||
let weekdays = collect_bench_weekdays_1971_2026();
|
||||
let iter = ParquetFxBenchIter::new(rows, weekdays);
|
||||
let pair_count = iter.pair_count;
|
||||
|
||||
let start = Instant::now();
|
||||
let stats = write_fx_1d_dataset(&temp.path, iter, Fx1dWriteOptions::default())?;
|
||||
let elapsed_secs = start.elapsed().as_secs_f64();
|
||||
let elapsed_ms = elapsed_secs * 1_000.0;
|
||||
|
||||
if stats.rows_written != rows {
|
||||
return Err(ParquetFxError::Parquet {
|
||||
path: temp.path.join("fx_1d/part.parquet"),
|
||||
source: ParquetError::General(format!(
|
||||
"writer row count mismatch: expected {rows}, stats reported {}",
|
||||
stats.rows_written
|
||||
)),
|
||||
});
|
||||
}
|
||||
|
||||
let read_back_rows = verify_parquet_fx_row_count(&temp.path, rows)?;
|
||||
|
||||
let (rows_per_sec, _) = compute_rates(rows, elapsed_secs);
|
||||
let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() {
|
||||
(stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let bytes_per_row = stats.bytes_written as f64 / rows as f64;
|
||||
let raw_bytes = (rows as f64) * (PARQUET_FX_RAW_ROW_BYTES as f64);
|
||||
let compression_ratio = if stats.bytes_written > 0 {
|
||||
raw_bytes / (stats.bytes_written as f64)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
|
||||
Ok((
|
||||
ParquetFxBenchReport {
|
||||
rows,
|
||||
read_back_rows,
|
||||
pair_count,
|
||||
files_written: stats.files_written,
|
||||
row_groups_written: stats.row_groups_written,
|
||||
bytes_written: stats.bytes_written,
|
||||
raw_row_bytes: PARQUET_FX_RAW_ROW_BYTES,
|
||||
elapsed_ms,
|
||||
rows_per_sec,
|
||||
mb_per_sec,
|
||||
bytes_per_row,
|
||||
compression_ratio,
|
||||
},
|
||||
temp_path,
|
||||
))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed Zstd Parquet `fx_1d` writer benchmark for `rows` sorted daily FX rows
|
||||
/// spanning `1971..=2026` across up to `80` currency pairs (scaling automatically for larger row
|
||||
/// counts), reads back the Parquet footer row count, and deletes its temporary output directory.
|
||||
pub fn run_parquet_fx_benchmark(rows: usize) -> Result<ParquetFxBenchReport, ParquetFxError> {
|
||||
let (report, _) = run_parquet_fx_benchmark_tracked(rows)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -3170,4 +3490,66 @@ mod tests {
|
|||
"error must report expected (255) and actual (250) row counts, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parquet_fx_benchmark_small_run_is_deterministic_and_cleans_up() {
|
||||
let (a, dir_a) = run_parquet_fx_benchmark_tracked(25_000).unwrap();
|
||||
let (b, dir_b) = run_parquet_fx_benchmark_tracked(25_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, 25_000);
|
||||
assert_eq!(a.read_back_rows, 25_000);
|
||||
assert_eq!(a.pair_count, PARQUET_FX_BENCH_BASE_PAIRS);
|
||||
assert_eq!(a.files_written, 1);
|
||||
assert_eq!(a.files_written, b.files_written);
|
||||
assert_eq!(a.row_groups_written, b.row_groups_written);
|
||||
assert_eq!(a.bytes_written, b.bytes_written);
|
||||
assert!(a.bytes_written > 0);
|
||||
assert_eq!(a.raw_row_bytes, PARQUET_FX_RAW_ROW_BYTES);
|
||||
assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0);
|
||||
assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0);
|
||||
assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0);
|
||||
assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parquet_fx_benchmark_zero_rows_handles_cleanly() {
|
||||
let (report, dir) = run_parquet_fx_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.pair_count, 0);
|
||||
assert_eq!(report.files_written, 0);
|
||||
assert_eq!(report.row_groups_written, 0);
|
||||
assert_eq!(report.bytes_written, 0);
|
||||
assert_eq!(report.raw_row_bytes, PARQUET_FX_RAW_ROW_BYTES);
|
||||
assert_eq!(report.elapsed_ms, 0.0);
|
||||
assert_eq!(report.rows_per_sec, 0.0);
|
||||
assert_eq!(report.mb_per_sec, 0.0);
|
||||
assert_eq!(report.bytes_per_row, 0.0);
|
||||
assert_eq!(report.compression_ratio, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_parquet_fx_row_count_returns_error_on_mismatch() {
|
||||
let temp = BenchTempDir::new_fx().unwrap();
|
||||
let weekdays = collect_bench_weekdays_1971_2026();
|
||||
let iter = ParquetFxBenchIter::new(250, weekdays);
|
||||
write_fx_1d_dataset(&temp.path, iter, Fx1dWriteOptions::default()).unwrap();
|
||||
|
||||
let matched = verify_parquet_fx_row_count(&temp.path, 250).unwrap();
|
||||
assert_eq!(matched, 250);
|
||||
|
||||
let err = verify_parquet_fx_row_count(&temp.path, 255).unwrap_err();
|
||||
let msg = err.to_string();
|
||||
assert!(
|
||||
matches!(err, ParquetFxError::Parquet { .. }),
|
||||
"expected Parquet error, got {err:?}"
|
||||
);
|
||||
assert!(
|
||||
msg.contains("255") && msg.contains("250"),
|
||||
"error must report expected (255) and actual (250) row counts, got: {msg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,8 +7,8 @@ use crate::bench::{
|
|||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS,
|
||||
DEFAULT_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -27,6 +27,7 @@ pub enum CliAction {
|
|||
BenchParquetBars(usize),
|
||||
BenchParquetShorts(usize),
|
||||
BenchParquetEvents(usize),
|
||||
BenchParquetFx(usize),
|
||||
}
|
||||
|
||||
/// Formats full help text including binary name and version.
|
||||
|
|
@ -47,7 +48,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\
|
||||
{name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-events [rows] Run fixed-seed events Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_EVENTS_BENCH_ROWS})"
|
||||
{name} bench-parquet-events [rows] Run fixed-seed events Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_EVENTS_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-fx [rows] Run fixed-seed fx_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_FX_BENCH_ROWS})"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -67,7 +69,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-provider-mapping [lookups]\n\
|
||||
{name} bench-parquet-bars [rows]\n\
|
||||
{name} bench-parquet-shorts [rows]\n\
|
||||
{name} bench-parquet-events [rows]"
|
||||
{name} bench-parquet-events [rows]\n\
|
||||
{name} bench-parquet-fx [rows]"
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -188,6 +191,16 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-parquet-events", _, ..] => {
|
||||
Err("too many arguments for bench-parquet-events".to_string())
|
||||
}
|
||||
["bench-parquet-fx"] => Ok(CliAction::BenchParquetFx(DEFAULT_PARQUET_FX_BENCH_ROWS)),
|
||||
["bench-parquet-fx", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchParquetFx(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-parquet-fx", _, ..] => {
|
||||
Err("too many arguments for bench-parquet-fx".to_string())
|
||||
}
|
||||
[other, ..] => Err(format!("unknown argument '{other}'")),
|
||||
}
|
||||
}
|
||||
|
|
@ -407,6 +420,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-parquet-events", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_parquet_fx_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-parquet-fx"])),
|
||||
Ok(CliAction::BenchParquetFx(DEFAULT_PARQUET_FX_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-parquet-fx", "20000"])),
|
||||
Ok(CliAction::BenchParquetFx(20_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-parquet-fx", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-parquet-fx", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-parquet-fx", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-parquet-fx", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -421,6 +450,7 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-bars"));
|
||||
assert!(full.contains("bench-parquet-shorts"));
|
||||
assert!(full.contains("bench-parquet-events"));
|
||||
assert!(full.contains("bench-parquet-fx"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
assert!(short.contains("bench-split"));
|
||||
|
|
@ -434,5 +464,6 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-bars"));
|
||||
assert!(short.contains("bench-parquet-shorts"));
|
||||
assert!(short.contains("bench-parquet-events"));
|
||||
assert!(short.contains("bench-parquet-fx"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ pub mod events;
|
|||
pub mod fx;
|
||||
pub mod parquet_bars;
|
||||
pub mod parquet_events;
|
||||
pub mod parquet_fx;
|
||||
mod parquet_publish;
|
||||
pub mod parquet_shorts;
|
||||
pub mod provider_mapping;
|
||||
|
|
@ -49,6 +50,10 @@ pub use parquet_events::{
|
|||
events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions,
|
||||
EventsWriteStats, ParquetEventsError,
|
||||
};
|
||||
pub use parquet_fx::{
|
||||
fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats,
|
||||
ParquetFxError,
|
||||
};
|
||||
pub use parquet_shorts::{
|
||||
shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow,
|
||||
ShortsWriteOptions, ShortsWriteStats,
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ use std::process::ExitCode;
|
|||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark,
|
||||
run_fx_benchmark, run_parquet_bars_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_shorts_benchmark, run_provider_mapping_benchmark, run_shorts_benchmark,
|
||||
run_split_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -386,6 +386,36 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchParquetFx(rows)) => {
|
||||
let report = match run_parquet_fx_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: parquet fx benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-parquet-fx");
|
||||
println!(
|
||||
" input: rows={} pairs={} raw_row_bytes={}",
|
||||
report.rows, report.pair_count, report.raw_row_bytes
|
||||
);
|
||||
println!(
|
||||
" output: files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x",
|
||||
report.elapsed_ms,
|
||||
report.rows_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.bytes_per_row,
|
||||
report.compression_ratio
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
1291
tools/curate-etl/src/parquet_fx.rs
Normal file
1291
tools/curate-etl/src/parquet_fx.rs
Normal file
File diff suppressed because it is too large
Load diff
973
tools/curate-etl/src/parquet_fx_tests.rs
Normal file
973
tools/curate-etl/src/parquet_fx_tests.rs
Normal file
|
|
@ -0,0 +1,973 @@
|
|||
use std::borrow::Cow;
|
||||
use std::error::Error as StdError;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use parquet::basic::Encoding;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use super::tests::{
|
||||
assert_no_transient_files, assert_row_bitwise_eq, close_ts_micros, day, make_row,
|
||||
read_parquet_rows, TempDirGuard,
|
||||
};
|
||||
use super::{
|
||||
write_fx_1d_dataset, write_fx_1d_dataset_with_hooks, Fx1dParquetRow, Fx1dWriteOptions,
|
||||
ParquetFxError,
|
||||
};
|
||||
use crate::fx::{FxSource, FX_PAIR_USDCAD};
|
||||
|
||||
fn seed_existing(out_dir: &Path) -> (PathBuf, Vec<u8>) {
|
||||
let seed = vec![
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 1, 15),
|
||||
1.340,
|
||||
1.348,
|
||||
1.337,
|
||||
1.344,
|
||||
FxSource::EodCadForex,
|
||||
),
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 1, 16),
|
||||
1.344,
|
||||
1.352,
|
||||
1.341,
|
||||
1.349,
|
||||
FxSource::TeUsdCad,
|
||||
),
|
||||
];
|
||||
write_fx_1d_dataset(out_dir, &seed, Fx1dWriteOptions::default()).unwrap();
|
||||
let part = out_dir.join("fx_1d/part.parquet");
|
||||
let before = fs::read(&part).unwrap();
|
||||
(part, before)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_row_and_row_group_boundary_counts_with_multi_pair_and_pre_1970() {
|
||||
let tmp = TempDirGuard::new("rg-boundaries");
|
||||
|
||||
// 1 row (including negative pre-1970 epoch day)
|
||||
let out_1 = tmp.path().join("one");
|
||||
let single = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(1969, 12, 31),
|
||||
1.073,
|
||||
1.076,
|
||||
1.071,
|
||||
1.074,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
let stats_1 = write_fx_1d_dataset(&out_1, &single, Fx1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats_1.rows_written, 1);
|
||||
assert_eq!(stats_1.files_written, 1);
|
||||
assert_eq!(stats_1.row_groups_written, 1);
|
||||
let actual_1 = read_parquet_rows(&out_1.join("fx_1d/part.parquet"));
|
||||
assert_eq!(actual_1.len(), 1);
|
||||
assert_row_bitwise_eq(&actual_1[0], &single[0]);
|
||||
assert_eq!(actual_1[0].session_date, -1);
|
||||
|
||||
// Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group)
|
||||
let base = day(2024, 1, 2);
|
||||
let rows_exact: Vec<Fx1dParquetRow> = (0..4_i32)
|
||||
.map(|i| {
|
||||
let open = 1.33 + f64::from(i) * 0.005;
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
base + i,
|
||||
open,
|
||||
open + 0.008,
|
||||
open - 0.004,
|
||||
open + 0.002,
|
||||
if i % 2 == 0 {
|
||||
FxSource::EodCadForex
|
||||
} else {
|
||||
FxSource::TeUsdCad
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let out_exact = tmp.path().join("exact");
|
||||
let opts = Fx1dWriteOptions {
|
||||
row_group_rows: 4,
|
||||
..Fx1dWriteOptions::default()
|
||||
};
|
||||
let stats_exact = write_fx_1d_dataset(&out_exact, &rows_exact, opts).unwrap();
|
||||
assert_eq!(stats_exact.rows_written, 4);
|
||||
assert_eq!(stats_exact.row_groups_written, 1);
|
||||
let reader_exact =
|
||||
SerializedFileReader::new(File::open(out_exact.join("fx_1d/part.parquet")).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(reader_exact.metadata().num_row_groups(), 1);
|
||||
assert_eq!(reader_exact.metadata().row_group(0).num_rows(), 4);
|
||||
|
||||
// row_group_rows + 1 (5 rows, row_group_rows = 4 => 2 row groups: [4, 1])
|
||||
// Multi-pair + negative pre-1970 date + both sources.
|
||||
let rows_plus_one = vec![
|
||||
make_row(
|
||||
"EURUSD",
|
||||
day(1969, 6, 15),
|
||||
1.120,
|
||||
1.125,
|
||||
1.118,
|
||||
1.122,
|
||||
FxSource::EodCadForex,
|
||||
),
|
||||
make_row(
|
||||
"EURUSD",
|
||||
base,
|
||||
1.090,
|
||||
1.096,
|
||||
1.087,
|
||||
1.093,
|
||||
FxSource::TeUsdCad,
|
||||
),
|
||||
make_row(
|
||||
"GBPUSD",
|
||||
base,
|
||||
1.265,
|
||||
1.272,
|
||||
1.261,
|
||||
1.268,
|
||||
FxSource::EodCadForex,
|
||||
),
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(1969, 12, 31),
|
||||
1.073,
|
||||
1.075,
|
||||
1.071,
|
||||
1.074,
|
||||
FxSource::EodCadForex,
|
||||
),
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
base,
|
||||
1.345,
|
||||
1.351,
|
||||
1.342,
|
||||
1.348,
|
||||
FxSource::TeUsdCad,
|
||||
),
|
||||
];
|
||||
let out_plus = tmp.path().join("plus-one");
|
||||
let stats_plus = write_fx_1d_dataset(&out_plus, &rows_plus_one, opts).unwrap();
|
||||
assert_eq!(stats_plus.rows_written, 5);
|
||||
assert_eq!(stats_plus.row_groups_written, 2);
|
||||
let p_plus = out_plus.join("fx_1d/part.parquet");
|
||||
let reader_plus = SerializedFileReader::new(File::open(&p_plus).unwrap()).unwrap();
|
||||
let rg_sizes: Vec<i64> = (0..reader_plus.metadata().num_row_groups())
|
||||
.map(|i| reader_plus.metadata().row_group(i).num_rows())
|
||||
.collect();
|
||||
assert_eq!(rg_sizes, vec![4, 1]);
|
||||
let actual_plus = read_parquet_rows(&p_plus);
|
||||
assert_eq!(actual_plus.len(), rows_plus_one.len());
|
||||
for (a, e) in actual_plus.iter().zip(&rows_plus_one) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
assert_no_transient_files(&out_plus.join("fx_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pair_and_source_columns_use_dictionary_encoding_and_invalid_options_preserve_state() {
|
||||
let tmp = TempDirGuard::new("dict-zstd");
|
||||
let base = day(2024, 1, 2);
|
||||
let rows: Vec<Fx1dParquetRow> = (0..64_i32)
|
||||
.map(|i| {
|
||||
let pair = if i < 32 { "EURUSD" } else { FX_PAIR_USDCAD };
|
||||
let d = base + (i % 32);
|
||||
let open = 1.20 + f64::from(i % 32) * 0.001;
|
||||
make_row(
|
||||
pair,
|
||||
d,
|
||||
open,
|
||||
open + 0.005,
|
||||
open - 0.003,
|
||||
open + 0.001,
|
||||
if i % 3 == 0 {
|
||||
FxSource::TeUsdCad
|
||||
} else {
|
||||
FxSource::EodCadForex
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let out_ok = tmp.path().join("lvl-3");
|
||||
write_fx_1d_dataset(&out_ok, &rows, Fx1dWriteOptions::default()).unwrap();
|
||||
let p = out_ok.join("fx_1d/part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap();
|
||||
let rg0 = reader.metadata().row_group(0);
|
||||
|
||||
for (col_idx, name) in [(0usize, "pair"), (7usize, "source")] {
|
||||
let col = rg0.column(col_idx);
|
||||
assert!(
|
||||
col.encodings().any(|e| {
|
||||
matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)
|
||||
}),
|
||||
"expected dictionary encoding on {name} column, got {:?}",
|
||||
col.encodings().collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
// Invalid row_group_rows and zstd_level in fresh dir
|
||||
let out_bad = tmp.path().join("bad-opts-fresh");
|
||||
assert!(matches!(
|
||||
write_fx_1d_dataset(
|
||||
&out_bad,
|
||||
&rows,
|
||||
Fx1dWriteOptions {
|
||||
row_group_rows: 0,
|
||||
..Fx1dWriteOptions::default()
|
||||
}
|
||||
),
|
||||
Err(ParquetFxError::InvalidRowGroupRows)
|
||||
));
|
||||
assert!(matches!(
|
||||
write_fx_1d_dataset(
|
||||
&out_bad,
|
||||
&rows,
|
||||
Fx1dWriteOptions {
|
||||
zstd_level: 23,
|
||||
..Fx1dWriteOptions::default()
|
||||
}
|
||||
),
|
||||
Err(ParquetFxError::InvalidZstdLevel { level: 23 })
|
||||
));
|
||||
assert!(matches!(
|
||||
write_fx_1d_dataset(
|
||||
&out_bad,
|
||||
&rows,
|
||||
Fx1dWriteOptions {
|
||||
zstd_level: 99,
|
||||
..Fx1dWriteOptions::default()
|
||||
}
|
||||
),
|
||||
Err(ParquetFxError::InvalidZstdLevel { level: 99 })
|
||||
));
|
||||
assert!(!out_bad.exists(), "invalid options must not create out_dir");
|
||||
|
||||
// Invalid options in seeded dir leave existing part.parquet byte-identical
|
||||
let out_seeded = tmp.path().join("bad-opts-seeded");
|
||||
let (part, before) = seed_existing(&out_seeded);
|
||||
assert!(matches!(
|
||||
write_fx_1d_dataset(
|
||||
&out_seeded,
|
||||
&rows,
|
||||
Fx1dWriteOptions {
|
||||
row_group_rows: 0,
|
||||
..Fx1dWriteOptions::default()
|
||||
}
|
||||
),
|
||||
Err(ParquetFxError::InvalidRowGroupRows)
|
||||
));
|
||||
assert!(matches!(
|
||||
write_fx_1d_dataset(
|
||||
&out_seeded,
|
||||
&rows,
|
||||
Fx1dWriteOptions {
|
||||
zstd_level: 23,
|
||||
..Fx1dWriteOptions::default()
|
||||
}
|
||||
),
|
||||
Err(ParquetFxError::InvalidZstdLevel { level: 23 })
|
||||
));
|
||||
assert_eq!(fs::read(&part).unwrap(), before);
|
||||
assert_no_transient_files(&out_seeded.join("fx_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overwrite_replaces_existing_part_parquet_and_leaves_no_transients() {
|
||||
let tmp = TempDirGuard::new("overwrite");
|
||||
let (part, before) = seed_existing(tmp.path());
|
||||
|
||||
let replacement = vec![
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2025, 4, 15),
|
||||
1.385,
|
||||
1.392,
|
||||
1.380,
|
||||
1.389,
|
||||
FxSource::EodCadForex,
|
||||
),
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2025, 4, 16),
|
||||
1.389,
|
||||
1.395,
|
||||
1.386,
|
||||
1.391,
|
||||
FxSource::TeUsdCad,
|
||||
),
|
||||
];
|
||||
let stats =
|
||||
write_fx_1d_dataset(tmp.path(), &replacement, Fx1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, 2);
|
||||
assert_eq!(stats.files_written, 1);
|
||||
|
||||
let after = fs::read(&part).unwrap();
|
||||
assert_ne!(after, before);
|
||||
let actual = read_parquet_rows(&part);
|
||||
assert_eq!(actual.len(), replacement.len());
|
||||
for (a, e) in actual.iter().zip(&replacement) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_and_known_at_boundaries_pass_and_extreme_dates_do_not_overflow() {
|
||||
let tmp = TempDirGuard::new("ts-bounds");
|
||||
let neg_day = day(1969, 12, 31); // -1
|
||||
let pos_day = day(2024, 3, 15);
|
||||
let micros_per_day = 86_400_000_000_i64;
|
||||
|
||||
// First microsecond and last microsecond of both negative and positive days pass,
|
||||
// including known_at_micros == ts_micros.
|
||||
let valid_rows = vec![
|
||||
Fx1dParquetRow {
|
||||
ts_micros: i64::from(neg_day) * micros_per_day,
|
||||
known_at_micros: i64::from(neg_day) * micros_per_day,
|
||||
..make_row(
|
||||
"EURUSD",
|
||||
neg_day,
|
||||
1.05,
|
||||
1.06,
|
||||
1.04,
|
||||
1.055,
|
||||
FxSource::EodCadForex,
|
||||
)
|
||||
},
|
||||
Fx1dParquetRow {
|
||||
ts_micros: i64::from(neg_day + 1) * micros_per_day - 1,
|
||||
known_at_micros: i64::from(neg_day + 1) * micros_per_day - 1,
|
||||
..make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
neg_day,
|
||||
1.073,
|
||||
1.076,
|
||||
1.071,
|
||||
1.074,
|
||||
FxSource::EodCadForex,
|
||||
)
|
||||
},
|
||||
Fx1dParquetRow {
|
||||
ts_micros: i64::from(pos_day) * micros_per_day,
|
||||
known_at_micros: i64::from(pos_day) * micros_per_day,
|
||||
..make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
pos_day,
|
||||
1.350,
|
||||
1.358,
|
||||
1.347,
|
||||
1.354,
|
||||
FxSource::TeUsdCad,
|
||||
)
|
||||
},
|
||||
Fx1dParquetRow {
|
||||
ts_micros: i64::from(pos_day + 1) * micros_per_day - 1,
|
||||
known_at_micros: i64::from(pos_day + 1) * micros_per_day - 1,
|
||||
..make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
pos_day + 1,
|
||||
1.354,
|
||||
1.360,
|
||||
1.350,
|
||||
1.356,
|
||||
FxSource::TeUsdCad,
|
||||
)
|
||||
},
|
||||
];
|
||||
// Fix row 3 ts_micros to be last microsecond of pos_day + 1
|
||||
let mut valid_rows = valid_rows;
|
||||
valid_rows[3].ts_micros = i64::from(pos_day + 2) * micros_per_day - 1;
|
||||
valid_rows[3].known_at_micros = valid_rows[3].ts_micros;
|
||||
|
||||
let out = tmp.path().join("valid");
|
||||
let stats = write_fx_1d_dataset(&out, &valid_rows, Fx1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, 4);
|
||||
let actual = read_parquet_rows(&out.join("fx_1d/part.parquet"));
|
||||
for (a, e) in actual.iter().zip(&valid_rows) {
|
||||
assert_row_bitwise_eq(a, e);
|
||||
}
|
||||
|
||||
// One microsecond before day_start or at day_end fails (both negative and positive days),
|
||||
// and extreme i32::MIN / i32::MAX do not overflow.
|
||||
let bad_ts_cases = [
|
||||
(neg_day, i64::from(neg_day) * micros_per_day - 1),
|
||||
(neg_day, i64::from(neg_day + 1) * micros_per_day),
|
||||
(pos_day, i64::from(pos_day) * micros_per_day - 1),
|
||||
(pos_day, i64::from(pos_day + 1) * micros_per_day),
|
||||
(i32::MIN, i64::MIN),
|
||||
(i32::MAX, i64::MAX),
|
||||
];
|
||||
let bad_out = tmp.path().join("bad-ts");
|
||||
for (session_date, ts_micros) in bad_ts_cases {
|
||||
let row = Fx1dParquetRow {
|
||||
pair: Cow::Borrowed(FX_PAIR_USDCAD),
|
||||
session_date,
|
||||
ts_micros,
|
||||
open: 1.35,
|
||||
high: 1.36,
|
||||
low: 1.34,
|
||||
close: 1.355,
|
||||
source: Cow::Borrowed(FxSource::EodCadForex.as_str()),
|
||||
known_at_micros: ts_micros,
|
||||
};
|
||||
let err =
|
||||
write_fx_1d_dataset(&bad_out, &[row], Fx1dWriteOptions::default()).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::TsOutsideSessionDate {
|
||||
session_date: sd,
|
||||
ts_micros: ts,
|
||||
..
|
||||
} if sd == session_date && ts == ts_micros
|
||||
),
|
||||
"expected TsOutsideSessionDate for ({session_date}, {ts_micros}), got {err:?}"
|
||||
);
|
||||
}
|
||||
assert!(!bad_out.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_inputs_return_typed_errors_in_fresh_and_seeded_dirs() {
|
||||
let tmp = TempDirGuard::new("invalid-inputs");
|
||||
let fresh = tmp.path().join("fresh");
|
||||
let seeded = tmp.path().join("seeded");
|
||||
let (part, before) = seed_existing(&seeded);
|
||||
let d1 = day(2024, 3, 15);
|
||||
let d2 = day(2024, 3, 18);
|
||||
|
||||
let check_both = |rows: &[Fx1dParquetRow], check: &dyn Fn(&ParquetFxError)| {
|
||||
let err_fresh =
|
||||
write_fx_1d_dataset(&fresh, rows, Fx1dWriteOptions::default()).unwrap_err();
|
||||
check(&err_fresh);
|
||||
assert!(
|
||||
!fresh.join("fx_1d/part.parquet").exists(),
|
||||
"fresh dir must not contain part.parquet after error: {err_fresh}"
|
||||
);
|
||||
assert_no_transient_files(&fresh.join("fx_1d"));
|
||||
|
||||
let err_seeded =
|
||||
write_fx_1d_dataset(&seeded, rows, Fx1dWriteOptions::default()).unwrap_err();
|
||||
check(&err_seeded);
|
||||
assert_eq!(fs::read(&part).unwrap(), before);
|
||||
assert_no_transient_files(&seeded.join("fx_1d"));
|
||||
};
|
||||
|
||||
// 1. Unsorted (pair goes backwards)
|
||||
let unsorted_pair = vec![
|
||||
make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex),
|
||||
make_row("EURUSD", d2, 1.09, 1.10, 1.08, 1.095, FxSource::EodCadForex),
|
||||
];
|
||||
check_both(&unsorted_pair, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::UnsortedInput {
|
||||
prev_pair,
|
||||
prev_session_date,
|
||||
pair,
|
||||
session_date,
|
||||
} if prev_pair == FX_PAIR_USDCAD
|
||||
&& *prev_session_date == d1
|
||||
&& pair == "EURUSD"
|
||||
&& *session_date == d2
|
||||
),
|
||||
"got {err:?}"
|
||||
);
|
||||
});
|
||||
|
||||
// 2. Unsorted (session_date goes backwards for same pair)
|
||||
let unsorted_date = vec![
|
||||
make_row(FX_PAIR_USDCAD, d2, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex),
|
||||
make_row(FX_PAIR_USDCAD, d1, 1.34, 1.35, 1.33, 1.345, FxSource::EodCadForex),
|
||||
];
|
||||
check_both(&unsorted_date, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::UnsortedInput {
|
||||
prev_pair,
|
||||
prev_session_date,
|
||||
pair,
|
||||
session_date,
|
||||
} if prev_pair == FX_PAIR_USDCAD
|
||||
&& *prev_session_date == d2
|
||||
&& pair == FX_PAIR_USDCAD
|
||||
&& *session_date == d1
|
||||
),
|
||||
"got {err:?}"
|
||||
);
|
||||
});
|
||||
|
||||
// 3. Duplicate (pair, session_date)
|
||||
let duplicate = vec![
|
||||
make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex),
|
||||
make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::TeUsdCad),
|
||||
];
|
||||
check_both(&duplicate, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::DuplicateKey { pair, session_date }
|
||||
if pair == FX_PAIR_USDCAD && *session_date == d1
|
||||
),
|
||||
"got {err:?}"
|
||||
);
|
||||
});
|
||||
|
||||
// 4. EmptyPair (empty & whitespace, both first row and after a valid row)
|
||||
for bad_pair in ["", " ", "\t\n"] {
|
||||
let first_bad = vec![Fx1dParquetRow {
|
||||
pair: Cow::Owned(bad_pair.to_string()),
|
||||
..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}];
|
||||
check_both(&first_bad, &|err| {
|
||||
assert!(
|
||||
matches!(err, ParquetFxError::EmptyPair { session_date } if *session_date == d1),
|
||||
"expected EmptyPair for {bad_pair:?}, got {err:?}"
|
||||
);
|
||||
});
|
||||
|
||||
// Second row empty pair must report EmptyPair (not UnsortedInput)
|
||||
let second_bad = vec![
|
||||
make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex),
|
||||
Fx1dParquetRow {
|
||||
pair: Cow::Owned(bad_pair.to_string()),
|
||||
..make_row(FX_PAIR_USDCAD, d2, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
},
|
||||
];
|
||||
check_both(&second_bad, &|err| {
|
||||
assert!(
|
||||
matches!(err, ParquetFxError::EmptyPair { session_date } if *session_date == d2),
|
||||
"expected EmptyPair on row 2 for {bad_pair:?}, got {err:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// 5. EmptySource (empty & whitespace)
|
||||
for bad_source in ["", " ", "\t\n"] {
|
||||
let rows = vec![Fx1dParquetRow {
|
||||
source: Cow::Owned(bad_source.to_string()),
|
||||
..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}];
|
||||
check_both(&rows, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::EmptySource { pair, session_date }
|
||||
if pair == FX_PAIR_USDCAD && *session_date == d1
|
||||
),
|
||||
"expected EmptySource for {bad_source:?}, got {err:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// 6. InvalidOhlc (NaN, +inf, -inf, 0.0, -0.0, negative)
|
||||
let invalid_ohlc_cases = [
|
||||
(f64::NAN, 1.36, 1.34, 1.35),
|
||||
(1.35, f64::INFINITY, 1.34, 1.35),
|
||||
(1.35, 1.36, f64::NEG_INFINITY, 1.35),
|
||||
(1.35, 1.36, 1.34, 0.0),
|
||||
(-0.0, 1.36, 1.34, 1.35),
|
||||
(1.35, 1.36, -0.01, 1.35),
|
||||
];
|
||||
for (o, h, l, c) in invalid_ohlc_cases {
|
||||
let rows = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
d1,
|
||||
o,
|
||||
h,
|
||||
l,
|
||||
c,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
check_both(&rows, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::InvalidOhlc { pair, session_date, .. }
|
||||
if pair == FX_PAIR_USDCAD && *session_date == d1
|
||||
),
|
||||
"expected InvalidOhlc for ({o}, {h}, {l}, {c}), got {err:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// 7. InconsistentOhlc (high < low, open < low, open > high, close < low, close > high)
|
||||
let inconsistent_ohlc_cases = [
|
||||
(1.35, 1.33, 1.36, 1.35), // high < low
|
||||
(1.33, 1.36, 1.34, 1.35), // open < low
|
||||
(1.37, 1.36, 1.34, 1.35), // open > high
|
||||
(1.35, 1.36, 1.34, 1.33), // close < low
|
||||
(1.35, 1.36, 1.34, 1.37), // close > high
|
||||
];
|
||||
for (o, h, l, c) in inconsistent_ohlc_cases {
|
||||
let rows = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
d1,
|
||||
o,
|
||||
h,
|
||||
l,
|
||||
c,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
check_both(&rows, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::InconsistentOhlc { pair, session_date, .. }
|
||||
if pair == FX_PAIR_USDCAD && *session_date == d1
|
||||
),
|
||||
"expected InconsistentOhlc for ({o}, {h}, {l}, {c}), got {err:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// 8. TsOutsideSessionDate
|
||||
let day_start = i64::from(d1) * 86_400_000_000;
|
||||
for bad_ts in [day_start - 1, day_start + 86_400_000_000] {
|
||||
let rows = vec![Fx1dParquetRow {
|
||||
ts_micros: bad_ts,
|
||||
known_at_micros: bad_ts,
|
||||
..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}];
|
||||
check_both(&rows, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::TsOutsideSessionDate { pair, session_date, ts_micros }
|
||||
if pair == FX_PAIR_USDCAD && *session_date == d1 && *ts_micros == bad_ts
|
||||
),
|
||||
"expected TsOutsideSessionDate for {bad_ts}, got {err:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// 9. KnownAtBeforeTs
|
||||
let ts = close_ts_micros(d1);
|
||||
let bad_known = vec![Fx1dParquetRow {
|
||||
ts_micros: ts,
|
||||
known_at_micros: ts - 1,
|
||||
..make_row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}];
|
||||
check_both(&bad_known, &|err| {
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
ParquetFxError::KnownAtBeforeTs {
|
||||
pair,
|
||||
session_date,
|
||||
ts_micros,
|
||||
known_at_micros,
|
||||
} if pair == FX_PAIR_USDCAD
|
||||
&& *session_date == d1
|
||||
&& *ts_micros == ts
|
||||
&& *known_at_micros == ts - 1
|
||||
),
|
||||
"expected KnownAtBeforeTs, got {err:?}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mid_stream_failure_after_flushed_row_groups_preserves_existing_part_parquet() {
|
||||
let tmp = TempDirGuard::new("mid-stream-fail");
|
||||
let (part, before) = seed_existing(tmp.path());
|
||||
let base = day(2024, 1, 2);
|
||||
|
||||
let mut rows = vec![
|
||||
make_row(FX_PAIR_USDCAD, base, 1.33, 1.34, 1.32, 1.335, FxSource::EodCadForex),
|
||||
make_row(FX_PAIR_USDCAD, base + 1, 1.335, 1.345, 1.33, 1.34, FxSource::EodCadForex),
|
||||
make_row(FX_PAIR_USDCAD, base + 2, 1.34, 1.35, 1.335, 1.345, FxSource::TeUsdCad),
|
||||
make_row(FX_PAIR_USDCAD, base + 3, 1.345, 1.355, 1.34, 1.35, FxSource::TeUsdCad),
|
||||
];
|
||||
// 5th row fails after 2 row groups of size 2 have already been flushed to staging.
|
||||
rows.push(make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
base + 4,
|
||||
-1.0,
|
||||
1.36,
|
||||
1.34,
|
||||
1.35,
|
||||
FxSource::TeUsdCad,
|
||||
));
|
||||
|
||||
let err = write_fx_1d_dataset(
|
||||
tmp.path(),
|
||||
&rows,
|
||||
Fx1dWriteOptions {
|
||||
row_group_rows: 2,
|
||||
..Fx1dWriteOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, ParquetFxError::InvalidOhlc { .. }));
|
||||
assert_eq!(fs::read(&part).unwrap(), before);
|
||||
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_dir_or_fx_1d_occupied_by_regular_file_returns_io_error() {
|
||||
let tmp = TempDirGuard::new("io-blocker");
|
||||
let rows = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 3, 15),
|
||||
1.35,
|
||||
1.36,
|
||||
1.34,
|
||||
1.355,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
|
||||
let file_as_out = tmp.path().join("not-a-dir");
|
||||
fs::write(&file_as_out, b"sentinel").unwrap();
|
||||
let err = write_fx_1d_dataset(&file_as_out, &rows, Fx1dWriteOptions::default()).unwrap_err();
|
||||
assert!(matches!(err, ParquetFxError::Io { .. }));
|
||||
assert!(StdError::source(&err).is_some());
|
||||
assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel");
|
||||
|
||||
let out_with_file_fx = tmp.path().join("fx-is-file");
|
||||
fs::create_dir_all(&out_with_file_fx).unwrap();
|
||||
let fx_file = out_with_file_fx.join("fx_1d");
|
||||
fs::write(&fx_file, b"file-not-dir").unwrap();
|
||||
let err2 =
|
||||
write_fx_1d_dataset(&out_with_file_fx, &rows, Fx1dWriteOptions::default()).unwrap_err();
|
||||
assert!(matches!(err2, ParquetFxError::Io { .. }));
|
||||
assert_eq!(fs::read(&fx_file).unwrap(), b"file-not-dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_lock_times_out_leaving_lock_and_existing_part_intact() {
|
||||
let tmp = TempDirGuard::new("stale-lock");
|
||||
let (part, before) = seed_existing(tmp.path());
|
||||
let lock_path = tmp.path().join("fx_1d/.write.lock");
|
||||
fs::write(&lock_path, b"999999\n").unwrap();
|
||||
|
||||
let rows = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 6, 15),
|
||||
1.37,
|
||||
1.38,
|
||||
1.36,
|
||||
1.375,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
let err = write_fx_1d_dataset_with_hooks(
|
||||
tmp.path(),
|
||||
&rows,
|
||||
Fx1dWriteOptions::default(),
|
||||
Duration::from_millis(30),
|
||||
|_, _| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
matches!(err, ParquetFxError::LockTimeout { ref path, .. } if path == &lock_path),
|
||||
"expected LockTimeout, got {err:?}"
|
||||
);
|
||||
assert!(
|
||||
lock_path.exists(),
|
||||
"stale lock must not be deleted by timed-out writer"
|
||||
);
|
||||
assert_eq!(fs::read(&part).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_part_parquet_stays_readable_between_backup_and_rename() {
|
||||
let tmp = TempDirGuard::new("live-readable");
|
||||
let (part, before) = seed_existing(tmp.path());
|
||||
|
||||
let replacement = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 9, 15),
|
||||
1.360,
|
||||
1.365,
|
||||
1.355,
|
||||
1.362,
|
||||
FxSource::TeUsdCad,
|
||||
)];
|
||||
let observed_live = Arc::new(Mutex::new(false));
|
||||
let observed_clone = Arc::clone(&observed_live);
|
||||
|
||||
write_fx_1d_dataset_with_hooks(
|
||||
tmp.path(),
|
||||
&replacement,
|
||||
Fx1dWriteOptions::default(),
|
||||
Duration::from_secs(5),
|
||||
move |final_path, backup_path| {
|
||||
assert!(
|
||||
backup_path.is_some(),
|
||||
"expected backup path for existing file"
|
||||
);
|
||||
assert_eq!(fs::read(final_path).unwrap(), before);
|
||||
assert_eq!(fs::read(backup_path.unwrap()).unwrap(), before);
|
||||
*observed_clone.lock().unwrap() = true;
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(*observed_live.lock().unwrap());
|
||||
let actual = read_parquet_rows(&part);
|
||||
assert_eq!(actual.len(), 1);
|
||||
assert_row_bitwise_eq(&actual[0], &replacement[0]);
|
||||
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() {
|
||||
let tmp = TempDirGuard::new("rename-blocker");
|
||||
let fx_dir = tmp.path().join("fx_1d");
|
||||
let blocking_dir = fx_dir.join("part.parquet");
|
||||
fs::create_dir_all(&blocking_dir).unwrap();
|
||||
|
||||
let unowned_tmp = fx_dir.join("part.parquet.unowned-other-run.tmp");
|
||||
fs::write(&unowned_tmp, b"keep-me").unwrap();
|
||||
|
||||
let rows = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 3, 15),
|
||||
1.35,
|
||||
1.36,
|
||||
1.34,
|
||||
1.355,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
let err = write_fx_1d_dataset(tmp.path(), &rows, Fx1dWriteOptions::default()).unwrap_err();
|
||||
assert!(matches!(err, ParquetFxError::Io { .. }), "got {err:?}");
|
||||
assert!(blocking_dir.is_dir(), "directory blocker must remain intact");
|
||||
assert_eq!(
|
||||
fs::read(&unowned_tmp).unwrap(),
|
||||
b"keep-me",
|
||||
"unowned .tmp file must be preserved"
|
||||
);
|
||||
|
||||
let mut entries: Vec<String> = fs::read_dir(&fx_dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
entries.sort();
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec![
|
||||
"part.parquet".to_string(),
|
||||
"part.parquet.unowned-other-run.tmp".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_in_process_writers_serialize_cleanly() {
|
||||
let tmp = TempDirGuard::new("concurrent-unit");
|
||||
let out = Arc::new(tmp.path().to_path_buf());
|
||||
|
||||
let out_1 = Arc::clone(&out);
|
||||
let handle_1 = thread::spawn(move || {
|
||||
let iter = (0..2_i32).map(move |i| {
|
||||
if i == 1 {
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
}
|
||||
make_row(
|
||||
"EURUSD",
|
||||
day(2024, 1, 15) + i,
|
||||
1.09,
|
||||
1.10,
|
||||
1.08,
|
||||
1.095,
|
||||
FxSource::EodCadForex,
|
||||
)
|
||||
});
|
||||
write_fx_1d_dataset(out_1.as_path(), iter, Fx1dWriteOptions::default())
|
||||
});
|
||||
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
let out_2 = Arc::clone(&out);
|
||||
let handle_2 = thread::spawn(move || {
|
||||
let iter = (0..2_i32).map(move |i| {
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 2, 15) + i,
|
||||
1.35,
|
||||
1.36,
|
||||
1.34,
|
||||
1.355,
|
||||
FxSource::TeUsdCad,
|
||||
)
|
||||
});
|
||||
write_fx_1d_dataset(out_2.as_path(), iter, Fx1dWriteOptions::default())
|
||||
});
|
||||
|
||||
let s1 = handle_1.join().unwrap().unwrap();
|
||||
let s2 = handle_2.join().unwrap().unwrap();
|
||||
assert_eq!(s1.rows_written, 2);
|
||||
assert_eq!(s2.rows_written, 2);
|
||||
|
||||
let got = read_parquet_rows(&tmp.path().join("fx_1d/part.parquet"));
|
||||
assert_eq!(got.len(), 2);
|
||||
assert!(
|
||||
got.iter().all(|r| r.pair == "EURUSD") || got.iter().all(|r| r.pair == FX_PAIR_USDCAD),
|
||||
"output must come entirely from one writer generation"
|
||||
);
|
||||
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panicking_iterator_cleans_up_staging_file_and_releases_lock() {
|
||||
let tmp = TempDirGuard::new("panic-unwind");
|
||||
let (part, before) = seed_existing(tmp.path());
|
||||
|
||||
let out = tmp.path().to_path_buf();
|
||||
let opts = Fx1dWriteOptions {
|
||||
row_group_rows: 2,
|
||||
..Fx1dWriteOptions::default()
|
||||
};
|
||||
let result = std::panic::catch_unwind(move || {
|
||||
let base = day(2024, 3, 15);
|
||||
let iter = (0..5_i32).map(move |i| {
|
||||
if i == 3 {
|
||||
panic!("simulated iterator panic after row-group flush");
|
||||
}
|
||||
make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
base + i,
|
||||
1.35,
|
||||
1.36,
|
||||
1.34,
|
||||
1.355,
|
||||
FxSource::EodCadForex,
|
||||
)
|
||||
});
|
||||
let _ = write_fx_1d_dataset(&out, iter, opts);
|
||||
});
|
||||
assert!(result.is_err(), "iterator must have panicked");
|
||||
|
||||
// Pre-existing live file stays byte-identical and both staging `.tmp` and `.write.lock`
|
||||
// are removed during unwind.
|
||||
assert_eq!(fs::read(&part).unwrap(), before);
|
||||
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
||||
|
||||
// Subsequent writer succeeds immediately without hanging on a stale lock.
|
||||
let replacement = vec![make_row(
|
||||
FX_PAIR_USDCAD,
|
||||
day(2024, 6, 15),
|
||||
1.37,
|
||||
1.38,
|
||||
1.36,
|
||||
1.375,
|
||||
FxSource::TeUsdCad,
|
||||
)];
|
||||
let stats =
|
||||
write_fx_1d_dataset(tmp.path(), &replacement, Fx1dWriteOptions::default()).unwrap();
|
||||
assert_eq!(stats.rows_written, 1);
|
||||
let got = read_parquet_rows(&part);
|
||||
assert_eq!(got.len(), 1);
|
||||
assert_row_bitwise_eq(&got[0], &replacement[0]);
|
||||
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
||||
}
|
||||
669
tools/curate-etl/tests/parquet_fx_contract.rs
Normal file
669
tools/curate-etl/tests/parquet_fx_contract.rs
Normal file
|
|
@ -0,0 +1,669 @@
|
|||
//! Contract tests for the public `fx_1d` Parquet writer API (T-94 / M1.2l).
|
||||
//!
|
||||
//! Uses only the crate's public surface (`build_fx_1d`, `Fx1dParquetRow::from_fx_row`,
|
||||
//! `write_fx_1d_dataset`, `fx_1d_parquet_schema`, the `curate-etl` binary) plus an independent
|
||||
//! Parquet column reader, guarding the `design/DATA-CONTRACTS.md` §3A `fx_1d/part.parquet`
|
||||
//! schema, atomic single-file publish semantics, validation errors, concurrency serialization,
|
||||
//! determinism, and the `bench-parquet-fx` CLI contract.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Barrier};
|
||||
use std::thread;
|
||||
|
||||
use curate_etl::{
|
||||
build_fx_1d, fx_1d_parquet_schema, write_fx_1d_dataset, ymd_to_epoch_days, Fx1dParquetRow,
|
||||
Fx1dWriteOptions, Fx1dWriteStats, FxDailyBar, FxSource, ParquetFxError, FX_PAIR_USDCAD,
|
||||
};
|
||||
use parquet::basic::{
|
||||
Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType,
|
||||
};
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-etl-pq-fx-contract-{tag}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid fixture date")
|
||||
}
|
||||
|
||||
fn part_path(out: &Path) -> PathBuf {
|
||||
out.join("fx_1d/part.parquet")
|
||||
}
|
||||
|
||||
fn ts_for_day(session_date: i32) -> i64 {
|
||||
i64::from(session_date) * 86_400_000_000 + 22 * 3_600_000_000
|
||||
}
|
||||
|
||||
fn row(
|
||||
pair: &'static str,
|
||||
session_date: i32,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
source: FxSource,
|
||||
) -> Fx1dParquetRow {
|
||||
let ts_micros = ts_for_day(session_date);
|
||||
Fx1dParquetRow {
|
||||
pair: Cow::Borrowed(pair),
|
||||
session_date,
|
||||
ts_micros,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
source: Cow::Borrowed(source.as_str()),
|
||||
known_at_micros: ts_micros + 60_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_rows(path: &Path) -> Vec<Fx1dParquetRow> {
|
||||
let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader");
|
||||
let meta = reader.metadata();
|
||||
let mut out = Vec::new();
|
||||
for rg in 0..meta.num_row_groups() {
|
||||
let n = meta.row_group(rg).num_rows() as usize;
|
||||
let g = reader.get_row_group(rg).expect("row group");
|
||||
let col = |i: usize| g.get_column_reader(i).expect("column reader");
|
||||
|
||||
let i32s = |c: ColumnReader| -> Vec<i32> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::Int32ColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected INT32"),
|
||||
}
|
||||
v
|
||||
};
|
||||
let i64s = |c: ColumnReader| -> Vec<i64> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::Int64ColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected INT64"),
|
||||
}
|
||||
v
|
||||
};
|
||||
let f64s = |c: ColumnReader| -> Vec<f64> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::DoubleColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected DOUBLE"),
|
||||
}
|
||||
v
|
||||
};
|
||||
let strs = |c: ColumnReader| -> Vec<String> {
|
||||
let mut v = Vec::new();
|
||||
match c {
|
||||
ColumnReader::ByteArrayColumnReader(mut r) => {
|
||||
assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n);
|
||||
}
|
||||
_ => panic!("expected BYTE_ARRAY"),
|
||||
}
|
||||
v.iter()
|
||||
.map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string())
|
||||
.collect()
|
||||
};
|
||||
|
||||
let pairs = strs(col(0));
|
||||
let dates = i32s(col(1));
|
||||
let tss = i64s(col(2));
|
||||
let opens = f64s(col(3));
|
||||
let highs = f64s(col(4));
|
||||
let lows = f64s(col(5));
|
||||
let closes = f64s(col(6));
|
||||
let sources = strs(col(7));
|
||||
let known_ats = i64s(col(8));
|
||||
|
||||
for i in 0..n {
|
||||
out.push(Fx1dParquetRow {
|
||||
pair: Cow::Owned(pairs[i].clone()),
|
||||
session_date: dates[i],
|
||||
ts_micros: tss[i],
|
||||
open: opens[i],
|
||||
high: highs[i],
|
||||
low: lows[i],
|
||||
close: closes[i],
|
||||
source: Cow::Owned(sources[i].clone()),
|
||||
known_at_micros: known_ats[i],
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn assert_rows_bitwise(actual: &[Fx1dParquetRow], expected: &[Fx1dParquetRow]) {
|
||||
assert_eq!(actual.len(), expected.len(), "row count");
|
||||
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
|
||||
assert_eq!(a.pair, e.pair, "row {i} pair");
|
||||
assert_eq!(a.session_date, e.session_date, "row {i} session_date");
|
||||
assert_eq!(a.ts_micros, e.ts_micros, "row {i} ts");
|
||||
assert_eq!(a.open.to_bits(), e.open.to_bits(), "row {i} open");
|
||||
assert_eq!(a.high.to_bits(), e.high.to_bits(), "row {i} high");
|
||||
assert_eq!(a.low.to_bits(), e.low.to_bits(), "row {i} low");
|
||||
assert_eq!(a.close.to_bits(), e.close.to_bits(), "row {i} close");
|
||||
assert_eq!(a.source, e.source, "row {i} source");
|
||||
assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at");
|
||||
}
|
||||
}
|
||||
|
||||
fn list_files(dir: &Path) -> Vec<String> {
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if path.is_dir() {
|
||||
walk(root, &path, out);
|
||||
} else {
|
||||
out.push(path.strip_prefix(root).unwrap().display().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, dir, &mut out);
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_fx_1d_round_trip_matches_contract_schema_zstd_dict_and_bitwise_values() {
|
||||
let tmp = TempDir::new("contract");
|
||||
let eod = [
|
||||
FxDailyBar {
|
||||
session_date: day(1969, 12, 31), // pre-1970 negative epoch day (-1)
|
||||
open: 1.0731,
|
||||
high: 1.0755,
|
||||
low: 1.0710,
|
||||
close: 1.0742,
|
||||
},
|
||||
FxDailyBar {
|
||||
session_date: day(1971, 1, 4),
|
||||
open: 1.0105,
|
||||
high: 1.0120,
|
||||
low: 1.0090,
|
||||
close: 1.0112,
|
||||
},
|
||||
FxDailyBar {
|
||||
session_date: day(2025, 1, 2),
|
||||
open: 1.4305,
|
||||
high: 1.4402,
|
||||
low: 1.4251,
|
||||
close: 1.4357,
|
||||
},
|
||||
];
|
||||
let te = [
|
||||
FxDailyBar {
|
||||
session_date: day(2025, 1, 2), // overlaps EOD -> EOD wins
|
||||
open: 1.4310,
|
||||
high: 1.4410,
|
||||
low: 1.4260,
|
||||
close: 1.4360,
|
||||
},
|
||||
FxDailyBar {
|
||||
session_date: day(2025, 1, 3), // interior/tail gap -> TE fills
|
||||
open: 1.4340,
|
||||
high: 1.4395,
|
||||
low: 1.4310,
|
||||
close: 1.4375,
|
||||
},
|
||||
FxDailyBar {
|
||||
session_date: day(2026, 1, 2),
|
||||
open: 1.3805,
|
||||
high: 1.3900,
|
||||
low: 1.3750,
|
||||
close: 1.3855,
|
||||
},
|
||||
];
|
||||
|
||||
let built = build_fx_1d(&eod, &te);
|
||||
assert_eq!(built.rows.len(), 5);
|
||||
let rows: Vec<Fx1dParquetRow> = built
|
||||
.rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let ts = ts_for_day(r.session_date);
|
||||
Fx1dParquetRow::from_fx_row(r, ts, ts + 300_000_000)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let opts = Fx1dWriteOptions {
|
||||
row_group_rows: 2,
|
||||
..Fx1dWriteOptions::default()
|
||||
};
|
||||
let stats = write_fx_1d_dataset(&tmp.0, &rows, opts).unwrap();
|
||||
assert_eq!(stats.rows_written, 5);
|
||||
assert_eq!(stats.files_written, 1);
|
||||
assert_eq!(stats.row_groups_written, 3);
|
||||
|
||||
let path = part_path(&tmp.0);
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
let meta = reader.metadata();
|
||||
let file_schema = meta.file_metadata().schema();
|
||||
let public_schema = fx_1d_parquet_schema().unwrap();
|
||||
assert_eq!(file_schema, public_schema.as_ref());
|
||||
|
||||
let expected: [(
|
||||
&str,
|
||||
PhysicalType,
|
||||
Repetition,
|
||||
Option<LogicalType>,
|
||||
ConvertedType,
|
||||
); 9] = [
|
||||
(
|
||||
"pair",
|
||||
PhysicalType::BYTE_ARRAY,
|
||||
Repetition::REQUIRED,
|
||||
Some(LogicalType::String),
|
||||
ConvertedType::UTF8,
|
||||
),
|
||||
(
|
||||
"session_date",
|
||||
PhysicalType::INT32,
|
||||
Repetition::REQUIRED,
|
||||
Some(LogicalType::Date),
|
||||
ConvertedType::DATE,
|
||||
),
|
||||
(
|
||||
"ts",
|
||||
PhysicalType::INT64,
|
||||
Repetition::REQUIRED,
|
||||
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
|
||||
ConvertedType::TIMESTAMP_MICROS,
|
||||
),
|
||||
(
|
||||
"open",
|
||||
PhysicalType::DOUBLE,
|
||||
Repetition::REQUIRED,
|
||||
None,
|
||||
ConvertedType::NONE,
|
||||
),
|
||||
(
|
||||
"high",
|
||||
PhysicalType::DOUBLE,
|
||||
Repetition::REQUIRED,
|
||||
None,
|
||||
ConvertedType::NONE,
|
||||
),
|
||||
(
|
||||
"low",
|
||||
PhysicalType::DOUBLE,
|
||||
Repetition::REQUIRED,
|
||||
None,
|
||||
ConvertedType::NONE,
|
||||
),
|
||||
(
|
||||
"close",
|
||||
PhysicalType::DOUBLE,
|
||||
Repetition::REQUIRED,
|
||||
None,
|
||||
ConvertedType::NONE,
|
||||
),
|
||||
(
|
||||
"source",
|
||||
PhysicalType::BYTE_ARRAY,
|
||||
Repetition::REQUIRED,
|
||||
Some(LogicalType::String),
|
||||
ConvertedType::UTF8,
|
||||
),
|
||||
(
|
||||
"known_at",
|
||||
PhysicalType::INT64,
|
||||
Repetition::REQUIRED,
|
||||
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
|
||||
ConvertedType::TIMESTAMP_MICROS,
|
||||
),
|
||||
];
|
||||
let fields = file_schema.get_fields();
|
||||
assert_eq!(fields.len(), expected.len());
|
||||
for (i, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() {
|
||||
assert_eq!(fields[i].name(), name);
|
||||
assert_eq!(fields[i].get_physical_type(), phys);
|
||||
assert_eq!(fields[i].get_basic_info().repetition(), rep);
|
||||
assert_eq!(fields[i].get_basic_info().logical_type_ref().cloned(), logical);
|
||||
assert_eq!(fields[i].get_basic_info().converted_type(), converted);
|
||||
}
|
||||
|
||||
for rg in meta.row_groups() {
|
||||
for c in rg.columns() {
|
||||
assert!(
|
||||
matches!(c.compression(), Compression::ZSTD(_)),
|
||||
"{} not ZSTD",
|
||||
c.column_path()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
rg.column(0)
|
||||
.encodings()
|
||||
.any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)),
|
||||
"pair column must use dictionary encoding"
|
||||
);
|
||||
assert!(
|
||||
rg.column(7)
|
||||
.encodings()
|
||||
.any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)),
|
||||
"source column must use dictionary encoding"
|
||||
);
|
||||
}
|
||||
|
||||
let got = read_rows(&path);
|
||||
assert_rows_bitwise(&got, &rows);
|
||||
for (actual, built_row) in got.iter().zip(&built.rows) {
|
||||
assert_eq!(actual.pair.as_ref(), built_row.pair);
|
||||
assert_eq!(actual.session_date, built_row.session_date);
|
||||
assert_eq!(actual.open.to_bits(), built_row.open.to_bits());
|
||||
assert_eq!(actual.high.to_bits(), built_row.high.to_bits());
|
||||
assert_eq!(actual.low.to_bits(), built_row.low.to_bits());
|
||||
assert_eq!(actual.close.to_bits(), built_row.close.to_bits());
|
||||
assert_eq!(actual.source.as_ref(), built_row.source.as_str());
|
||||
}
|
||||
assert_eq!(list_files(&tmp.0.join("fx_1d")), ["part.parquet"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_group_boundaries_overwrite_empty_and_byte_identical_rerun() {
|
||||
let tmp = TempDir::new("edges");
|
||||
let base = day(2024, 1, 2);
|
||||
let rows = vec![
|
||||
row("EURUSD", base, 1.09, 1.10, 1.08, 1.095, FxSource::EodCadForex),
|
||||
row("EURUSD", base + 1, 1.095, 1.105, 1.09, 1.10, FxSource::TeUsdCad),
|
||||
row(FX_PAIR_USDCAD, day(1969, 12, 31), 1.073, 1.076, 1.071, 1.074, FxSource::EodCadForex),
|
||||
row(FX_PAIR_USDCAD, base, 1.34, 1.35, 1.335, 1.345, FxSource::EodCadForex),
|
||||
row(FX_PAIR_USDCAD, base + 1, 1.345, 1.355, 1.34, 1.35, FxSource::TeUsdCad),
|
||||
];
|
||||
|
||||
let opts = Fx1dWriteOptions {
|
||||
row_group_rows: 4,
|
||||
..Fx1dWriteOptions::default()
|
||||
};
|
||||
let s_eq = write_fx_1d_dataset(&tmp.0, &rows[..4], opts).unwrap();
|
||||
assert_eq!(s_eq.row_groups_written, 1);
|
||||
|
||||
// Overwrite with 5 rows -> 2 row groups [4, 1]
|
||||
let s_plus = write_fx_1d_dataset(&tmp.0, &rows, opts).unwrap();
|
||||
assert_eq!(s_plus.rows_written, 5);
|
||||
assert_eq!(s_plus.row_groups_written, 2);
|
||||
assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &rows);
|
||||
assert_eq!(list_files(&tmp.0.join("fx_1d")), ["part.parquet"]);
|
||||
|
||||
// Empty input does not destroy existing part.parquet
|
||||
let bytes_before = fs::read(part_path(&tmp.0)).unwrap();
|
||||
let s_empty =
|
||||
write_fx_1d_dataset(&tmp.0, std::iter::empty::<Fx1dParquetRow>(), opts).unwrap();
|
||||
assert_eq!(s_empty, Fx1dWriteStats::default());
|
||||
assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), bytes_before);
|
||||
|
||||
// Determinism: second directory yields byte-identical file
|
||||
let tmp2 = TempDir::new("edges-rerun");
|
||||
write_fx_1d_dataset(&tmp2.0, &rows, opts).unwrap();
|
||||
assert_eq!(fs::read(part_path(&tmp2.0)).unwrap(), bytes_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_inputs_return_typed_errors_and_leave_existing_file_byte_identical() {
|
||||
let tmp = TempDir::new("invalid");
|
||||
let fresh = tmp.0.join("fresh");
|
||||
let seeded = tmp.0.join("seeded");
|
||||
let d1 = day(2024, 3, 15);
|
||||
let d2 = day(2024, 3, 18);
|
||||
let seed = vec![row(
|
||||
FX_PAIR_USDCAD,
|
||||
d1,
|
||||
1.35,
|
||||
1.36,
|
||||
1.34,
|
||||
1.355,
|
||||
FxSource::EodCadForex,
|
||||
)];
|
||||
write_fx_1d_dataset(&seeded, &seed, Fx1dWriteOptions::default()).unwrap();
|
||||
let before = fs::read(part_path(&seeded)).unwrap();
|
||||
|
||||
// Option validation errors
|
||||
for opts in [
|
||||
Fx1dWriteOptions {
|
||||
row_group_rows: 0,
|
||||
..Fx1dWriteOptions::default()
|
||||
},
|
||||
Fx1dWriteOptions {
|
||||
zstd_level: 99,
|
||||
..Fx1dWriteOptions::default()
|
||||
},
|
||||
] {
|
||||
let e1 = write_fx_1d_dataset(&fresh, &seed, opts).unwrap_err();
|
||||
let e2 = write_fx_1d_dataset(&seeded, &seed, opts).unwrap_err();
|
||||
if opts.row_group_rows == 0 {
|
||||
assert!(matches!(e1, ParquetFxError::InvalidRowGroupRows));
|
||||
assert!(matches!(e2, ParquetFxError::InvalidRowGroupRows));
|
||||
} else {
|
||||
assert!(matches!(e1, ParquetFxError::InvalidZstdLevel { level: 99 }));
|
||||
assert!(matches!(e2, ParquetFxError::InvalidZstdLevel { level: 99 }));
|
||||
}
|
||||
assert!(!part_path(&fresh).exists());
|
||||
assert_eq!(fs::read(part_path(&seeded)).unwrap(), before);
|
||||
}
|
||||
|
||||
let ts = ts_for_day(d1);
|
||||
let day_start = i64::from(d1) * 86_400_000_000;
|
||||
let cases: Vec<(&str, Vec<Fx1dParquetRow>)> = vec![
|
||||
(
|
||||
"unsorted",
|
||||
vec![
|
||||
row(FX_PAIR_USDCAD, d2, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex),
|
||||
row(FX_PAIR_USDCAD, d1, 1.34, 1.35, 1.33, 1.345, FxSource::EodCadForex),
|
||||
],
|
||||
),
|
||||
(
|
||||
"duplicate",
|
||||
vec![
|
||||
row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex),
|
||||
row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::TeUsdCad),
|
||||
],
|
||||
),
|
||||
(
|
||||
"empty_pair",
|
||||
vec![Fx1dParquetRow {
|
||||
pair: Cow::Borrowed(" "),
|
||||
..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}],
|
||||
),
|
||||
(
|
||||
"empty_source",
|
||||
vec![Fx1dParquetRow {
|
||||
source: Cow::Borrowed(""),
|
||||
..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}],
|
||||
),
|
||||
(
|
||||
"invalid_ohlc",
|
||||
vec![row(FX_PAIR_USDCAD, d1, f64::NAN, 1.36, 1.34, 1.35, FxSource::EodCadForex)],
|
||||
),
|
||||
(
|
||||
"inconsistent_ohlc",
|
||||
vec![row(FX_PAIR_USDCAD, d1, 1.35, 1.33, 1.36, 1.35, FxSource::EodCadForex)],
|
||||
),
|
||||
(
|
||||
"ts_outside",
|
||||
vec![Fx1dParquetRow {
|
||||
ts_micros: day_start - 1,
|
||||
known_at_micros: day_start - 1,
|
||||
..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}],
|
||||
),
|
||||
(
|
||||
"known_at_before_ts",
|
||||
vec![Fx1dParquetRow {
|
||||
ts_micros: ts,
|
||||
known_at_micros: ts - 1,
|
||||
..row(FX_PAIR_USDCAD, d1, 1.35, 1.36, 1.34, 1.355, FxSource::EodCadForex)
|
||||
}],
|
||||
),
|
||||
];
|
||||
|
||||
for (label, bad_rows) in cases {
|
||||
for (dir_label, dir) in [("fresh", &fresh), ("seeded", &seeded)] {
|
||||
let err =
|
||||
write_fx_1d_dataset(dir, &bad_rows, Fx1dWriteOptions::default()).unwrap_err();
|
||||
match (label, &err) {
|
||||
("unsorted", ParquetFxError::UnsortedInput { .. }) => {}
|
||||
("duplicate", ParquetFxError::DuplicateKey { .. }) => {}
|
||||
("empty_pair", ParquetFxError::EmptyPair { .. }) => {}
|
||||
("empty_source", ParquetFxError::EmptySource { .. }) => {}
|
||||
("invalid_ohlc", ParquetFxError::InvalidOhlc { .. }) => {}
|
||||
("inconsistent_ohlc", ParquetFxError::InconsistentOhlc { .. }) => {}
|
||||
("ts_outside", ParquetFxError::TsOutsideSessionDate { .. }) => {}
|
||||
("known_at_before_ts", ParquetFxError::KnownAtBeforeTs { .. }) => {}
|
||||
other => panic!("unexpected error for case {label} ({dir_label}): {other:?}"),
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!part_path(&fresh).exists(),
|
||||
"case {label} created part.parquet in fresh dir"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(part_path(&seeded)).unwrap(),
|
||||
before,
|
||||
"case {label} modified existing part.parquet"
|
||||
);
|
||||
assert_eq!(
|
||||
list_files(&seeded.join("fx_1d")),
|
||||
["part.parquet"],
|
||||
"case {label} left transient files behind"
|
||||
);
|
||||
}
|
||||
|
||||
// out_dir occupied by a regular file returns Io error
|
||||
let file_out = tmp.0.join("not-a-dir");
|
||||
fs::write(&file_out, b"x").unwrap();
|
||||
let io_err = write_fx_1d_dataset(&file_out, &seed, Fx1dWriteOptions::default()).unwrap_err();
|
||||
assert!(matches!(io_err, ParquetFxError::Io { .. }));
|
||||
assert!(std::error::Error::source(&io_err).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_in_process_writers_publish_one_complete_generation_and_no_transients() {
|
||||
let tmp = TempDir::new("concurrent");
|
||||
let out = Arc::new(tmp.0.clone());
|
||||
let base = day(2020, 1, 2);
|
||||
let make = |base_rate: f64| -> Vec<Fx1dParquetRow> {
|
||||
(0..1_000_i32)
|
||||
.map(|i| {
|
||||
let open = base_rate + f64::from(i) * 0.0001;
|
||||
row(
|
||||
FX_PAIR_USDCAD,
|
||||
base + i,
|
||||
open,
|
||||
open + 0.005,
|
||||
open - 0.004,
|
||||
open + 0.001,
|
||||
if i % 4 == 0 {
|
||||
FxSource::TeUsdCad
|
||||
} else {
|
||||
FxSource::EodCadForex
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let gens = Arc::new([make(1.25), make(1.40)]);
|
||||
let barrier = Arc::new(Barrier::new(2));
|
||||
let handles: Vec<_> = (0..2)
|
||||
.map(|g| {
|
||||
let (out, gens, barrier) = (out.clone(), gens.clone(), barrier.clone());
|
||||
thread::spawn(move || {
|
||||
barrier.wait();
|
||||
let opts = Fx1dWriteOptions {
|
||||
row_group_rows: 131,
|
||||
..Fx1dWriteOptions::default()
|
||||
};
|
||||
write_fx_1d_dataset(out.as_path(), &gens[g], opts)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for h in handles {
|
||||
let stats = h.join().expect("writer thread").expect("writer result");
|
||||
assert_eq!(stats.rows_written, 1_000);
|
||||
assert_eq!(stats.files_written, 1);
|
||||
}
|
||||
|
||||
let got = read_rows(&part_path(&tmp.0));
|
||||
let g = if got.first().map(|r| r.open) == Some(1.25) {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
};
|
||||
assert_rows_bitwise(&got, &gens[g]);
|
||||
assert_eq!(list_files(&tmp.0.join("fx_1d")), ["part.parquet"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_parquet_fx_cli_prints_metrics_and_removes_its_temp_dir() {
|
||||
let tmp = TempDir::new("cli");
|
||||
let out = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(["bench-parquet-fx", "20000"])
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("spawn curate-etl");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
for needle in [
|
||||
"curate-etl bench-parquet-fx",
|
||||
"rows=20000",
|
||||
"read_back_rows=20000",
|
||||
"row_groups=",
|
||||
"bytes=",
|
||||
"elapsed=",
|
||||
"rows/s",
|
||||
"MB/s",
|
||||
"bytes/row",
|
||||
"compression=",
|
||||
] {
|
||||
assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}");
|
||||
}
|
||||
let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect();
|
||||
assert!(
|
||||
leftovers.is_empty(),
|
||||
"benchmark left files in TMPDIR: {leftovers:?}"
|
||||
);
|
||||
|
||||
let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(["bench-parquet-fx", "0"])
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("spawn curate-etl");
|
||||
assert!(!bad.status.success());
|
||||
assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-fx"));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue