T-110: M1.2z — tools/curate-etl: first runnable command curate-bars-1d (concatenated-BSON eodPrices + qmSplits files + provider_mapping / listing-currency TSV → bars_1d/year=YYYY/part.parquet) with end-to-end tests and local benchmark (no new crates, no MongoDB connection)
This commit is contained in:
parent
38cab8b4ca
commit
d63463a64a
8 changed files with 2756 additions and 7 deletions
|
|
@ -966,3 +966,74 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a
|
|||
- Stage (in-memory): `elapsed=933.02 ms`, `throughput=1071785 events/s`, `latency=933.02 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s`
|
||||
|
||||
## `curate-bars-1d` Command (`M1.2z`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` into `<out>/bars_1d/year=YYYY/part.parquet` with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-bars-1d \
|
||||
--eod-prices <path> # concatenated raw BSON (mongodump eodPrices.bson)
|
||||
--qm-splits <path> # concatenated raw BSON (mongodump qmSplits.bson)
|
||||
--provider-mapping <path> # headerless TSV (5 columns)
|
||||
--listing-currencies <path> # headerless TSV (2 columns)
|
||||
--out <dir> # dataset root -> bars_1d/year=YYYY/part.parquet
|
||||
[--rel-tolerance <f64>] # default: 0.01
|
||||
```
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted. Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`.
|
||||
|
||||
### TSV Formats (strict, headerless, `\t`-separated)
|
||||
|
||||
- `provider_mapping`: `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
||||
- `source` and `source_id` are preserved verbatim (never trimmed); blank/whitespace-only values are rejected.
|
||||
- Dates are parsed strictly with `YYYY-MM-DD` Gregorian validation; `listing_id` must be a strict positive ASCII integer.
|
||||
- `listing_currencies`: `listing_id \t currency`
|
||||
- Unique positive `listing_id` per row; non-blank currency code (`"USD"` and `"CAD"` are interned).
|
||||
- Both files accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number.
|
||||
|
||||
### Split Re-Keying, Early Filter & Missing-Currency Policy
|
||||
|
||||
1. **Split re-keying (`qmSearchCode` → `eodSearchCode`):** Each decoded `qmSplits` row with `ratio != 1.0` resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable`, then attaches the `SplitEvent` to every deduplicated `"eod"` `source_id` pointing at that `listing_id` (preventing ratio squaring when one `(listing_id, eod_source_id)` spans multiple date ranges). No ticker-text guessing is performed.
|
||||
2. **Early filter & key interning:** While streaming `eodPrices`, bars whose `eodSearchCode` has no `"eod"` range in `provider_mapping` are dropped before buffering (`bars_unmapped_source_dropped`). Retained bars share interned `Arc<str>` keys rather than allocating a `String` per bar.
|
||||
3. **Missing-currency behavior:** Delegated unchanged to `curate_bars_1d` — mapped listings absent from `--listing-currencies` (or blank) are dropped into `dropped_missing_currency` without failing the run.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, and `timing`):
|
||||
|
||||
- `splits_in == splits_applied + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_bson.rejected`
|
||||
- `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
|
||||
- `eod_bson.decoded == write.rows_written + bars_unmapped_source_dropped + builder.(invalid_ohlc + inconsistent_ohlc + invalid_vol + dup_collapsed + dup_conflict_dropped) + curate.(dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped)`
|
||||
|
||||
### `bench-curate-bars-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / curate / write splits separately, verifying Parquet footer row counts, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`):
|
||||
|
||||
1. **1,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000`):
|
||||
- Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2000`, `splits_bytes=184400`, `keys=2000`
|
||||
- Decode: `elapsed=209.16 ms`, `throughput=4781063 rows/s`, `scan=738.08 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`)
|
||||
- Curate: `elapsed=189.95 ms`, `throughput=5159326 rows/s`, `rows_out=968027` (`96.80%` retained), `listings_out=1981`
|
||||
- Write: `elapsed=457.98 ms`, `throughput=2113691 rows/s`, `write=55.21 MB/s`, `files=36`, `row_groups=36`, `bytes=26511909`, `read_back_rows=968027`
|
||||
- Total: `elapsed=857.09 ms`, `throughput=1166745 rows/s`, `throughput_mb=180.12 MB/s`
|
||||
2. **5,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000`):
|
||||
- Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4000`, `splits_bytes=368800`, `keys=6000`
|
||||
- Decode: `elapsed=961.48 ms`, `throughput=5200292 rows/s`, `scan=802.25 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`)
|
||||
- Curate: `elapsed=990.13 ms`, `throughput=4948906 rows/s`, `rows_out=4839077` (`96.78%` retained), `listings_out=5940`
|
||||
- Write: `elapsed=1319.36 ms`, `throughput=3667759 rows/s`, `write=76.59 MB/s`, `files=36`, `row_groups=36`, `bytes=105955512`, `read_back_rows=4839077`
|
||||
- Total: `elapsed=3270.97 ms`, `throughput=1528601 rows/s`, `throughput_mb=235.82 MB/s`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Full in-RAM buffering of mapped bars:** `curate-bars-1d` buffers every mapped bar in `Vec<EodDailyBar<Arc<str>>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist). For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB.
|
||||
- **No `rayon` sharding or direct MongoDB cursors yet:** single-threaded file-to-file execution only; hash/key-sharded `rayon` streaming and direct MongoDB cursors are deferred to a follow-up.
|
||||
- **`qmPrices` volume cross-check not wired yet:** `qm_volumes` is passed as empty because `qmPrices` does not yet have its own raw BSON decoder.
|
||||
- **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable<K>` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`.
|
||||
|
|
|
|||
|
|
@ -4892,6 +4892,530 @@ pub fn run_curate_bars_benchmark(rows: usize) -> Result<CurateBarsBenchReport, C
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_BARS_CMD_BENCH_ROWS: usize = 1_000_000;
|
||||
const CURATE_BARS_CMD_BENCH_SEED: u64 = 0x570C_4B07_C04A_C1D0;
|
||||
|
||||
/// Errors returned by [`run_curate_bars_cmd_benchmark`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateBarsCmdBenchError {
|
||||
FixtureIo {
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
Run(crate::run_curate_bars::RunCurateBarsError),
|
||||
Verify(ParquetBarsError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CurateBarsCmdBenchError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::FixtureIo { path, source } => {
|
||||
write!(f, "fixture I/O error at '{}': {source}", path.display())
|
||||
}
|
||||
Self::Run(err) => write!(f, "{err}"),
|
||||
Self::Verify(err) => write!(f, "parquet verify failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CurateBarsCmdBenchError {
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Metrics returned by [`run_curate_bars_cmd_benchmark`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateBarsCmdBenchReport {
|
||||
pub rows: usize,
|
||||
pub key_count: usize,
|
||||
pub eod_docs_framed: u64,
|
||||
pub eod_bytes_read: u64,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub bars_unmapped_source_dropped: usize,
|
||||
pub buffered_bars: usize,
|
||||
pub buffered_bar_bytes: usize,
|
||||
pub bytes_per_buffered_bar: f64,
|
||||
pub rows_out: usize,
|
||||
pub listings_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 total_mb_per_sec: f64,
|
||||
pub split_rekey: crate::run_curate_bars::SplitRekeyStats,
|
||||
pub eod_decode: BsonEodDecodeStats,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub curate_stats: crate::curate_bars::CurateBars1dStats,
|
||||
}
|
||||
|
||||
fn format_ymd_string(epoch_day: i32) -> String {
|
||||
let (y, m, d) = epoch_days_to_ymd(epoch_day);
|
||||
format!("{y:04}-{m:02}-{d:02}")
|
||||
}
|
||||
|
||||
fn build_weekday_pool(start_year: i32, end_year: i32) -> Vec<i32> {
|
||||
let start = ymd_to_epoch_days(start_year, 1, 1).expect("valid start year");
|
||||
let end = ymd_to_epoch_days(end_year, 12, 31).expect("valid end year");
|
||||
let mut days = Vec::with_capacity(((end - start + 1) as usize * 5) / 7 + 8);
|
||||
let mut d = start;
|
||||
while d <= end {
|
||||
let dow = (d + 4).rem_euclid(7);
|
||||
if dow != 0 && dow != 6 {
|
||||
days.push(d);
|
||||
}
|
||||
d += 1;
|
||||
}
|
||||
days
|
||||
}
|
||||
|
||||
fn gcd_usize(mut a: usize, mut b: usize) -> usize {
|
||||
while b != 0 {
|
||||
let t = a % b;
|
||||
a = b;
|
||||
b = t;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn choose_coprime_stride(len: usize, start: usize) -> usize {
|
||||
if len <= 1 {
|
||||
return 1;
|
||||
}
|
||||
let mut s = start.max(1) % len;
|
||||
if s == 0 {
|
||||
s = 1;
|
||||
}
|
||||
while gcd_usize(s, len) != 1 {
|
||||
s += 1;
|
||||
if s >= len {
|
||||
s = 1;
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn run_curate_bars_cmd_benchmark_tracked(
|
||||
rows: usize,
|
||||
) -> Result<(CurateBarsCmdBenchReport, PathBuf), CurateBarsCmdBenchError> {
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use crate::bson_eod_prices::MILLIS_PER_DAY;
|
||||
use crate::run_curate_bars::{
|
||||
run_curate_bars_1d_timed, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
const MIB: f64 = 1_048_576.0;
|
||||
|
||||
let temp = BenchTempDir::new_in_with_prefix(
|
||||
&std::env::temp_dir(),
|
||||
"curate-etl-bench-curate-bars-cmd",
|
||||
)
|
||||
.map_err(|(path, source)| CurateBarsCmdBenchError::FixtureIo { path, source })?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
let eod_path = temp.path.join("eodPrices.bson");
|
||||
let splits_path = temp.path.join("qmSplits.bson");
|
||||
let mapping_path = temp.path.join("provider_mapping.tsv");
|
||||
let currencies_path = temp.path.join("listing_currencies.tsv");
|
||||
let out_dir = temp.path.join("out");
|
||||
|
||||
let key_count = curate_bars_bench_key_count(rows.max(1));
|
||||
|
||||
// Precompute weekday date pools for 2008..=2025, 1990..=2007, and 1970..=1975.
|
||||
let main_days = build_weekday_pool(2008, 2025);
|
||||
let main_strs: Vec<String> = main_days.iter().copied().map(format_ymd_string).collect();
|
||||
let pre2008_days = build_weekday_pool(1990, 2007);
|
||||
let pre2008_strs: Vec<String> = pre2008_days
|
||||
.iter()
|
||||
.copied()
|
||||
.map(format_ymd_string)
|
||||
.collect();
|
||||
let pre1976_days = build_weekday_pool(1970, 1975);
|
||||
let pre1976_strs: Vec<String> = pre1976_days
|
||||
.iter()
|
||||
.copied()
|
||||
.map(format_ymd_string)
|
||||
.collect();
|
||||
|
||||
let mut rng = SplitMix64::new(CURATE_BARS_CMD_BENCH_SEED);
|
||||
|
||||
// 1. Write `provider_mapping.tsv` and `listing_currencies.tsv`.
|
||||
{
|
||||
let mut map_w = BufWriter::with_capacity(
|
||||
256 * 1024,
|
||||
File::create(&mapping_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
let mut curr_w = BufWriter::with_capacity(
|
||||
64 * 1024,
|
||||
File::create(¤cies_path).map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: currencies_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?,
|
||||
);
|
||||
|
||||
let mapped_keys = key_count - (key_count / 50).max(1);
|
||||
for k in 0..mapped_keys {
|
||||
let listing_id = (k + 1) as i32;
|
||||
let is_cad = k % 4 == 0;
|
||||
let suffix = if is_cad { "TO" } else { "US" };
|
||||
let eod_code = format!("CMD{k:05}.{suffix}");
|
||||
let qm_code = format!("QM{k:05}:{suffix}");
|
||||
|
||||
if k % 50 == 1 {
|
||||
// Ticker reuse with interior H2-2016 gap.
|
||||
let reuse_listing_id = (mapped_keys + k + 10) as i32;
|
||||
writeln!(map_w, "eod\t{eod_code}\t1990-01-01\t2016-06-30\t{listing_id}")
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
writeln!(map_w, "eod\t{eod_code}\t2017-01-01\t\t{reuse_listing_id}")
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t2016-06-30\t{listing_id}")
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
writeln!(map_w, "qm\t{qm_code}\t2017-01-01\t\t{reuse_listing_id}")
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let curr = if is_cad { "CAD" } else { "USD" };
|
||||
writeln!(curr_w, "{reuse_listing_id}\t{curr}").map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: currencies_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
} else {
|
||||
writeln!(map_w, "eod\t{eod_code}\t1990-01-01\t\t{listing_id}").map_err(
|
||||
|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t\t{listing_id}").map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
// Leave ~1% listings without currency to exercise `dropped_missing_currency`.
|
||||
if k % 100 != 99 {
|
||||
let curr = if is_cad { "CAD" } else { "USD" };
|
||||
writeln!(curr_w, "{listing_id}\t{curr}").map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: currencies_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
// One QM-only listing (no EOD partner) to exercise `splits_no_eod_partner`.
|
||||
let qm_only_listing = (key_count * 4 + 1) as i32;
|
||||
writeln!(map_w, "qm\tQM_ONLY:US\t1990-01-01\t\t{qm_only_listing}").map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
writeln!(curr_w, "{qm_only_listing}\tUSD").map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: currencies_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
map_w.flush().map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
curr_w.flush().map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: currencies_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 2. Stream-write `qmSplits.bson`.
|
||||
{
|
||||
let mut splits_w = BufWriter::with_capacity(
|
||||
256 * 1024,
|
||||
File::create(&splits_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
if rows > 0 {
|
||||
let mapped_keys = key_count - (key_count / 50).max(1);
|
||||
let split_count = key_count.min(4_000);
|
||||
const RATIOS: [f64; 6] = [2.0, 3.0, 4.0, 10.0, 0.5, 0.25];
|
||||
for i in 0..split_count {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
let date_idx = (rng.next_u64() as usize) % main_days.len();
|
||||
let date_str = &main_strs[date_idx];
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes));
|
||||
|
||||
if i % 20 == 0 {
|
||||
// 1:1 no-op split.
|
||||
let k = i % mapped_keys;
|
||||
let suffix = if k % 4 == 0 { "TO" } else { "US" };
|
||||
let qm_code = format!("QM{k:05}:{suffix}");
|
||||
doc.append(cstr!("qmSearchCode"), qm_code.as_str());
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), 1.0_f64);
|
||||
} else if i % 20 == 1 {
|
||||
// Unmapped QM code.
|
||||
doc.append(cstr!("qmSearchCode"), "QM_UNMAPPED:US");
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
} else if i % 20 == 2 {
|
||||
// Mapped QM listing with no EOD partner.
|
||||
doc.append(cstr!("qmSearchCode"), "QM_ONLY:US");
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
} else {
|
||||
let k = i % mapped_keys;
|
||||
let suffix = if k % 4 == 0 { "TO" } else { "US" };
|
||||
let qm_code = format!("QM{k:05}:{suffix}");
|
||||
let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()];
|
||||
doc.append(cstr!("qmSearchCode"), qm_code.as_str());
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
}
|
||||
splits_w
|
||||
.write_all(doc.as_bytes())
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
}
|
||||
splits_w
|
||||
.flush()
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 3. Stream-write `eodPrices.bson` directly to disk (never buffered in a Vec<u8>).
|
||||
{
|
||||
let mut eod_w = BufWriter::with_capacity(
|
||||
512 * 1024,
|
||||
File::create(&eod_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
let mapped_keys = key_count - (key_count / 50).max(1);
|
||||
let eod_codes: Vec<String> = (0..key_count)
|
||||
.map(|k| {
|
||||
let suffix = if k % 4 == 0 { "TO" } else { "US" };
|
||||
if k < mapped_keys {
|
||||
format!("CMD{k:05}.{suffix}")
|
||||
} else {
|
||||
format!("UNMAP{k:05}.{suffix}")
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Per-key coprime-stride cursors over `main_days` so 5M rows stay unique per key.
|
||||
let main_len = main_days.len();
|
||||
let stride = choose_coprime_stride(main_len, 17);
|
||||
let mut cursors: Vec<usize> = (0..key_count).map(|k| (k * 13) % main_len).collect();
|
||||
|
||||
for i in 0..rows {
|
||||
let k = i % key_count;
|
||||
let code = &eod_codes[k];
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
|
||||
let (epoch_day, date_str) = if roll < 20 {
|
||||
let idx = (rng.next_u64() as usize) % pre2008_days.len();
|
||||
(pre2008_days[idx], &pre2008_strs[idx])
|
||||
} else if roll < 22 {
|
||||
let idx = (rng.next_u64() as usize) % pre1976_days.len();
|
||||
(pre1976_days[idx], &pre1976_strs[idx])
|
||||
} else {
|
||||
let idx = cursors[k];
|
||||
cursors[k] = (idx + stride) % main_len;
|
||||
(main_days[idx], &main_strs[idx])
|
||||
};
|
||||
|
||||
let base_cents = 100 + (rng.next_u64() % 50_000) as i64;
|
||||
let open = base_cents as f64 / 100.0;
|
||||
let spread = 1.0 + (rng.next_u64() % 200) as f64 / 100.0;
|
||||
let high = open + spread;
|
||||
let low = (open - spread * 0.5).max(0.01);
|
||||
let close = low + (high - low) * ((rng.next_u64() % 100) as f64 / 100.0);
|
||||
let volume_i64 = 1_000 + (rng.next_u64() % 50_000_000) as i64;
|
||||
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes));
|
||||
doc.append(cstr!("eodSearchCode"), code.as_str());
|
||||
if i % 20 == 0 {
|
||||
doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(epoch_day) * 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);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), volume_i64);
|
||||
doc.append(cstr!("source"), "eod");
|
||||
|
||||
eod_w
|
||||
.write_all(doc.as_bytes())
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
eod_w
|
||||
.flush()
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 4. Run the full command path file -> Parquet with decode / curate / write timing.
|
||||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
provider_mapping: mapping_path,
|
||||
listing_currencies: currencies_path,
|
||||
out_dir: out_dir.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
let timed = run_curate_bars_1d_timed(&args).map_err(CurateBarsCmdBenchError::Run)?;
|
||||
|
||||
let read_back_rows = verify_parquet_bars_row_count(
|
||||
&out_dir,
|
||||
timed.report.write_stats.rows_by_year.keys().copied(),
|
||||
timed.report.write_stats.rows_written,
|
||||
)
|
||||
.map_err(CurateBarsCmdBenchError::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 (curate_rows_per_sec, _) =
|
||||
compute_rates(timed.report.buffered_bars, 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.splits_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 total_mb_per_sec = if total_elapsed_secs > 0.0 {
|
||||
(total_input_bytes as f64 / MIB) / total_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let bytes_per_buffered_bar = if timed.report.buffered_bars > 0 {
|
||||
timed.report.buffered_bar_bytes as f64 / timed.report.buffered_bars as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let report = CurateBarsCmdBenchReport {
|
||||
rows,
|
||||
key_count,
|
||||
eod_docs_framed: timed.report.eod_docs_framed,
|
||||
eod_bytes_read: timed.report.eod_bytes_read,
|
||||
splits_docs_framed: timed.report.splits_docs_framed,
|
||||
splits_bytes_read: timed.report.splits_bytes_read,
|
||||
bars_unmapped_source_dropped: timed.report.bars_unmapped_source_dropped,
|
||||
buffered_bars: timed.report.buffered_bars,
|
||||
buffered_bar_bytes: timed.report.buffered_bar_bytes,
|
||||
bytes_per_buffered_bar,
|
||||
rows_out: timed.report.curate_stats.rows_out,
|
||||
listings_out: timed.report.curate_stats.listings_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,
|
||||
total_mb_per_sec,
|
||||
split_rekey: timed.report.split_rekey,
|
||||
eod_decode: timed.report.eod_decode,
|
||||
splits_decode: timed.report.splits_decode,
|
||||
curate_stats: timed.report.curate_stats,
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
Ok((report, temp_path))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed end-to-end `curate-bars-1d` file -> Parquet benchmark for `rows`
|
||||
/// synthetic `eodPrices` BSON documents.
|
||||
pub fn run_curate_bars_cmd_benchmark(
|
||||
rows: usize,
|
||||
) -> Result<CurateBarsCmdBenchReport, CurateBarsCmdBenchError> {
|
||||
let (report, _) = run_curate_bars_cmd_benchmark_tracked(rows)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_SHORTS_BENCH_ROWS: usize = 2_000_000;
|
||||
const CURATE_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_C04A_5407;
|
||||
const CURATE_SHORTS_BENCH_KEY_COUNT: usize = 12_500;
|
||||
|
|
@ -7716,4 +8240,33 @@ mod tests {
|
|||
crate::curate_adj::CurateAdjFactorsStats::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_cmd_benchmark_small_run_cleans_up_and_conserves_counts() {
|
||||
let (report, dir) = run_curate_bars_cmd_benchmark_tracked(4_000).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.rows, 4_000);
|
||||
assert_eq!(report.eod_docs_framed, 4_000);
|
||||
assert_eq!(report.eod_decode.docs_in, 4_000);
|
||||
assert_eq!(
|
||||
report.eod_decode.decoded,
|
||||
report.buffered_bars + report.bars_unmapped_source_dropped
|
||||
);
|
||||
assert!(report.bars_unmapped_source_dropped > 0);
|
||||
assert!(report.rows_out > 0);
|
||||
assert_eq!(report.read_back_rows, report.rows_out);
|
||||
assert!(report.bytes_per_buffered_bar >= 64.0);
|
||||
assert_eq!(
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied
|
||||
+ report.split_rekey.splits_unmapped_qm
|
||||
+ report.split_rekey.splits_no_eod_partner
|
||||
+ report.split_rekey.splits_noop_dropped
|
||||
+ report.splits_decode.rejected_total()
|
||||
);
|
||||
assert!(report.split_rekey.splits_applied > 0);
|
||||
assert!(report.split_rekey.splits_unmapped_qm > 0);
|
||||
assert!(report.split_rekey.splits_no_eod_partner > 0);
|
||||
assert!(report.split_rekey.splits_noop_dropped > 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,24 +3,28 @@
|
|||
//! Kept inside the library crate so CLI argument parsing tests run under
|
||||
//! `cargo test --workspace --lib --offline`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_EVENTS_BENCH_ROWS, DEFAULT_CURATE_FX_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_CURATE_BARS_CMD_BENCH_ROWS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_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,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
};
|
||||
use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum CliAction {
|
||||
Help,
|
||||
Version,
|
||||
CurateBars1d(CurateBars1dArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
|
|
@ -39,6 +43,7 @@ pub enum CliAction {
|
|||
BenchBsonQmActions(usize),
|
||||
BenchBsonStream(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateBarsCmd(usize),
|
||||
BenchCurateShorts(usize),
|
||||
BenchCurateEvents(usize),
|
||||
BenchCurateFx(usize),
|
||||
|
|
@ -53,6 +58,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Usage:\n\
|
||||
{name} [--help | -h]\n\
|
||||
{name} [--version | -V]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> --provider-mapping <path> --listing-currencies <path> --out <dir> [--rel-tolerance <f64>]\n\
|
||||
Curate daily bars from BSON + TSV files into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE})\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\
|
||||
|
|
@ -71,6 +78,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars-cmd [rows] Run fixed-seed end-to-end curate-bars-1d file->Parquet benchmark (default: {DEFAULT_CURATE_BARS_CMD_BENCH_ROWS})\n\
|
||||
{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\
|
||||
|
|
@ -84,6 +92,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
"Usage:\n\
|
||||
{name} [--help | -h]\n\
|
||||
{name} [--version | -V]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> --provider-mapping <path> --listing-currencies <path> --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
|
|
@ -102,6 +111,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-bson-qm-actions [rows]\n\
|
||||
{name} bench-bson-stream [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-bars-cmd [rows]\n\
|
||||
{name} bench-curate-shorts [rows]\n\
|
||||
{name} bench-curate-events [rows]\n\
|
||||
{name} bench-curate-fx [rows]\n\
|
||||
|
|
@ -109,6 +119,93 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
)
|
||||
}
|
||||
|
||||
fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String> {
|
||||
let mut eod_prices: Option<PathBuf> = None;
|
||||
let mut qm_splits: Option<PathBuf> = None;
|
||||
let mut provider_mapping: Option<PathBuf> = None;
|
||||
let mut listing_currencies: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
let mut rel_tolerance: Option<f64> = 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-bars-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}'"));
|
||||
};
|
||||
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)?,
|
||||
"--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?,
|
||||
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
|
||||
"--listing-currencies" => {
|
||||
set_path(&mut listing_currencies, "--listing-currencies", value)?;
|
||||
}
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
"--rel-tolerance" => {
|
||||
if rel_tolerance.is_some() {
|
||||
return Err("duplicate flag '--rel-tolerance'".to_string());
|
||||
}
|
||||
let parsed = value.parse::<f64>().map_err(|_| {
|
||||
format!(
|
||||
"invalid --rel-tolerance '{value}' (expected a finite non-negative number)"
|
||||
)
|
||||
})?;
|
||||
if !parsed.is_finite() || parsed < 0.0 {
|
||||
return Err(format!(
|
||||
"invalid --rel-tolerance '{value}' (expected a finite non-negative number)"
|
||||
));
|
||||
}
|
||||
let normalized = if parsed == 0.0 { 0.0 } else { parsed };
|
||||
rel_tolerance = Some(normalized);
|
||||
}
|
||||
other => return Err(format!("unknown flag '{other}' for curate-bars-1d")),
|
||||
}
|
||||
}
|
||||
|
||||
let eod_prices =
|
||||
eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?;
|
||||
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
|
||||
let provider_mapping =
|
||||
provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let listing_currencies = listing_currencies
|
||||
.ok_or_else(|| "missing required flag '--listing-currencies'".to_string())?;
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
|
||||
Ok(CurateBars1dArgs {
|
||||
eod_prices,
|
||||
qm_splits,
|
||||
provider_mapping,
|
||||
listing_currencies,
|
||||
out_dir,
|
||||
rel_tolerance: rel_tolerance.unwrap_or(DEFAULT_CURATE_BARS_REL_TOLERANCE),
|
||||
})
|
||||
}
|
||||
|
||||
/// 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();
|
||||
|
|
@ -118,6 +215,9 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
[flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => {
|
||||
Err(format!("unexpected argument '{extra}' after '{flag}'"))
|
||||
}
|
||||
["curate-bars-1d", rest @ ..] => {
|
||||
parse_curate_bars_1d_args(rest).map(CliAction::CurateBars1d)
|
||||
}
|
||||
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||
["bench-split", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),
|
||||
|
|
@ -302,6 +402,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-curate-bars", _, ..] => {
|
||||
Err("too many arguments for bench-curate-bars".to_string())
|
||||
}
|
||||
["bench-curate-bars-cmd"] => Ok(CliAction::BenchCurateBarsCmd(
|
||||
DEFAULT_CURATE_BARS_CMD_BENCH_ROWS,
|
||||
)),
|
||||
["bench-curate-bars-cmd", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateBarsCmd(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-bars-cmd", _, ..] => {
|
||||
Err("too many arguments for bench-curate-bars-cmd".to_string())
|
||||
}
|
||||
["bench-curate-shorts"] => {
|
||||
Ok(CliAction::BenchCurateShorts(DEFAULT_CURATE_SHORTS_BENCH_ROWS))
|
||||
}
|
||||
|
|
@ -683,7 +795,9 @@ mod tests {
|
|||
assert!(full.contains("bench-bson-eod-prices"));
|
||||
assert!(full.contains("bench-bson-qm-actions"));
|
||||
assert!(full.contains("bench-bson-stream"));
|
||||
assert!(full.contains("curate-bars-1d"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-bars-cmd"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
assert!(full.contains("bench-curate-events"));
|
||||
assert!(full.contains("bench-curate-fx"));
|
||||
|
|
@ -707,7 +821,9 @@ mod tests {
|
|||
assert!(short.contains("bench-bson-eod-prices"));
|
||||
assert!(short.contains("bench-bson-qm-actions"));
|
||||
assert!(short.contains("bench-bson-stream"));
|
||||
assert!(short.contains("curate-bars-1d"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-bars-cmd"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
assert!(short.contains("bench-curate-events"));
|
||||
assert!(short.contains("bench-curate-fx"));
|
||||
|
|
@ -797,4 +913,145 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-curate-adj", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_bars_cmd_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-bars-cmd"])),
|
||||
Ok(CliAction::BenchCurateBarsCmd(
|
||||
DEFAULT_CURATE_BARS_CMD_BENCH_ROWS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-bars-cmd", "5000"])),
|
||||
Ok(CliAction::BenchCurateBarsCmd(5_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-bars-cmd", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_valid_curate_bars_1d_args() {
|
||||
let parsed = parse_args(&to_args(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"/tmp/eodPrices.bson",
|
||||
"--qm-splits",
|
||||
"/tmp/qmSplits.bson",
|
||||
"--provider-mapping",
|
||||
"/tmp/provider_mapping.tsv",
|
||||
"--listing-currencies",
|
||||
"/tmp/listing_currencies.tsv",
|
||||
"--out",
|
||||
"/tmp/out",
|
||||
]))
|
||||
.expect("valid curate-bars-1d args");
|
||||
assert_eq!(
|
||||
parsed,
|
||||
CliAction::CurateBars1d(CurateBars1dArgs {
|
||||
eod_prices: PathBuf::from("/tmp/eodPrices.bson"),
|
||||
qm_splits: PathBuf::from("/tmp/qmSplits.bson"),
|
||||
provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"),
|
||||
listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"),
|
||||
out_dir: PathBuf::from("/tmp/out"),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
);
|
||||
|
||||
let equals_style = parse_args(&to_args(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices=/tmp/e.bson",
|
||||
"--qm-splits=/tmp/s.bson",
|
||||
"--provider-mapping=/tmp/m.tsv",
|
||||
"--listing-currencies=/tmp/c.tsv",
|
||||
"--out=/tmp/o",
|
||||
"--rel-tolerance=-0.0",
|
||||
]))
|
||||
.expect("equals-style curate-bars-1d args");
|
||||
match equals_style {
|
||||
CliAction::CurateBars1d(a) => {
|
||||
assert_eq!(a.rel_tolerance.to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
other => panic!("unexpected action: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_curate_bars_1d_flags() {
|
||||
let full = [
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--listing-currencies",
|
||||
"c.tsv",
|
||||
"--out",
|
||||
"out",
|
||||
];
|
||||
|
||||
// Each required flag missing one at a time.
|
||||
for (drop_idx, expected_flag) in [
|
||||
(1, "--eod-prices"),
|
||||
(3, "--qm-splits"),
|
||||
(5, "--provider-mapping"),
|
||||
(7, "--listing-currencies"),
|
||||
(9, "--out"),
|
||||
] {
|
||||
let mut subset: Vec<&str> = Vec::new();
|
||||
for (idx, &tok) in full.iter().enumerate() {
|
||||
if idx != drop_idx && idx != drop_idx + 1 {
|
||||
subset.push(tok);
|
||||
}
|
||||
}
|
||||
let err = parse_args(&to_args(&subset)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(expected_flag),
|
||||
"expected missing {expected_flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Duplicate flags (including mixed `--flag val` and `--flag=val`).
|
||||
let mut dup = full.to_vec();
|
||||
dup.push("--out=other");
|
||||
let err = parse_args(&to_args(&dup)).unwrap_err();
|
||||
assert!(err.contains("duplicate flag '--out'"), "{err}");
|
||||
|
||||
// Unknown flag.
|
||||
let mut unk = full.to_vec();
|
||||
unk.extend(["--bogus", "1"]);
|
||||
let err = parse_args(&to_args(&unk)).unwrap_err();
|
||||
assert!(err.contains("unknown flag '--bogus'"), "{err}");
|
||||
|
||||
// Missing value for flag at end of args.
|
||||
let err = parse_args(&to_args(&["curate-bars-1d", "--out"])).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--out'"), "{err}");
|
||||
|
||||
// Empty path value.
|
||||
let mut empty_val = full.to_vec();
|
||||
empty_val[10] = "";
|
||||
let err = parse_args(&to_args(&empty_val)).unwrap_err();
|
||||
assert!(err.contains("empty value for flag '--out'"), "{err}");
|
||||
|
||||
// Unexpected positional argument.
|
||||
let mut pos = full.to_vec();
|
||||
pos.push("extra");
|
||||
let err = parse_args(&to_args(&pos)).unwrap_err();
|
||||
assert!(err.contains("unexpected positional argument"), "{err}");
|
||||
|
||||
// Invalid --rel-tolerance values.
|
||||
for bad in ["abc", "-0.01", "NaN", "inf", "-inf", ""] {
|
||||
let mut bad_tol = full.to_vec();
|
||||
bad_tol.extend(["--rel-tolerance", bad]);
|
||||
let err = parse_args(&to_args(&bad_tol)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("--rel-tolerance"),
|
||||
"expected --rel-tolerance error for '{bad}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -144,3 +144,10 @@ pub use curate_adj::{
|
|||
CurateAdjError, CurateAdjFactorsOutput, CurateAdjFactorsStats, CurateAdjFactorsWriteReport,
|
||||
CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION,
|
||||
};
|
||||
|
||||
pub mod run_curate_bars;
|
||||
pub use run_curate_bars::{
|
||||
format_curate_bars_report, load_listing_currencies_tsv, load_provider_mapping_tsv,
|
||||
run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport, RunCurateBarsError,
|
||||
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,14 +6,15 @@ use std::process::ExitCode;
|
|||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_bars_benchmark, run_curate_events_benchmark,
|
||||
run_curate_fx_benchmark, run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark,
|
||||
run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_bars_benchmark, run_curate_bars_cmd_benchmark,
|
||||
run_curate_events_benchmark, run_curate_fx_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,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d};
|
||||
|
||||
const NAME: &str = env!("CARGO_PKG_NAME");
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
|
@ -30,6 +31,16 @@ fn main() -> ExitCode {
|
|||
println!("{NAME} {VERSION}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::CurateBars1d(curate_args)) => match run_curate_bars_1d(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_bars_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,
|
||||
|
|
@ -650,6 +661,68 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBarsCmd(rows)) => {
|
||||
let report = match run_curate_bars_cmd_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-bars-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.rows > 0 {
|
||||
(report.rows_out as f64 / report.rows as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-bars-cmd");
|
||||
println!(
|
||||
" input: rows={} eod_bytes={} splits_docs={} splits_bytes={} keys={}",
|
||||
report.rows,
|
||||
report.eod_bytes_read,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s unmapped_dropped={} buffered_bars={} buffered_bytes={} ({:.1} bytes/bar)",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_rows_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.bars_unmapped_source_dropped,
|
||||
report.buffered_bars,
|
||||
report.buffered_bar_bytes,
|
||||
report.bytes_per_buffered_bar
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out
|
||||
);
|
||||
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 throughput_mb={:.2} MB/s splits_applied={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop={}",
|
||||
report.total_elapsed_ms,
|
||||
report.total_rows_per_sec,
|
||||
report.total_mb_per_sec,
|
||||
report.split_rekey.splits_applied,
|
||||
report.split_rekey.splits_unmapped_qm,
|
||||
report.split_rekey.splits_no_eod_partner,
|
||||
report.split_rekey.splits_noop_dropped
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateShorts(rows)) => {
|
||||
let report = match run_curate_shorts_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
766
tools/curate-etl/src/run_curate_bars.rs
Normal file
766
tools/curate-etl/src/run_curate_bars.rs
Normal file
|
|
@ -0,0 +1,766 @@
|
|||
//! File-to-file `curate-bars-1d` command runner (`M1.2z`).
|
||||
//!
|
||||
//! Streams concatenated raw BSON `eodPrices` and `qmSplits` dump files alongside
|
||||
//! `provider_mapping` and `listing_currencies` TSV files into an atomically published
|
||||
//! `<out_dir>/bars_1d/year=YYYY/part.parquet` dataset via [`curate_and_write_bars_1d`].
|
||||
//!
|
||||
//! # TSV Formats (strict, headerless, `\t`-separated)
|
||||
//! - `provider_mapping`:
|
||||
//! `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
||||
//! (`source` and `source_id` are preserved verbatim — never trimmed).
|
||||
//! - `listing_currencies`:
|
||||
//! `listing_id \t currency`
|
||||
//! (unique positive `listing_id` per row; non-blank currency code).
|
||||
//! - Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line.
|
||||
//!
|
||||
//! # Missing-Currency Behavior
|
||||
//! Delegated unchanged to [`curate_bars_1d`]: any mapped `listing_id` absent from
|
||||
//! `listing_currencies` (or mapping to a blank string) is dropped and counted in
|
||||
//! [`CurateBars1dStats::dropped_missing_currency`] rather than failing the run.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead, BufReader};
|
||||
use std::mem::size_of;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bars::EodDailyBar;
|
||||
use crate::bson_eod_prices::{parse_ymd_strict_days, BsonEodDecodeStats};
|
||||
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
||||
use crate::bson_stream::{
|
||||
decode_eod_price_chunks, decode_qm_split_chunks, BsonStreamError, RawBsonChunkReader,
|
||||
};
|
||||
use crate::curate_bars::{
|
||||
curate_and_write_bars_1d, curate_bars_1d, CurateBars1dStats, CurateBarsWriteError,
|
||||
};
|
||||
use crate::parquet_bars::{write_bars_1d_dataset, Bars1dWriteOptions, Bars1dWriteStats};
|
||||
use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::split::{SplitError, SplitEvent, SplitTable};
|
||||
|
||||
/// Default relative volume tolerance passed to `curate_bars_1d` (matches `bench-curate-bars`).
|
||||
pub const DEFAULT_CURATE_BARS_REL_TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// Parsed arguments for the `curate-bars-1d` CLI command.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateBars1dArgs {
|
||||
pub eod_prices: PathBuf,
|
||||
pub qm_splits: PathBuf,
|
||||
pub provider_mapping: PathBuf,
|
||||
pub listing_currencies: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
pub rel_tolerance: f64,
|
||||
}
|
||||
|
||||
/// Accounting counters for re-keying `qmSplits` (`qmSearchCode` -> `listing_id` -> `eodSearchCode`).
|
||||
///
|
||||
/// Conservation invariant (paired with `splits_decode: BsonQmActionDecodeStats`):
|
||||
/// `splits_in == splits_applied + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_decode.rejected_total()`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct SplitRekeyStats {
|
||||
/// Total `qmSplits` documents framed and fed into the decoder (`== splits_decode.docs_in`).
|
||||
pub splits_in: usize,
|
||||
/// Decoded `qmSplits` rows with `ratio == 1.0` dropped as no-ops before re-keying.
|
||||
pub splits_noop_dropped: usize,
|
||||
/// Non-no-op decoded splits whose `("qm", qm_search_code, ex_date)` had no mapping.
|
||||
pub splits_unmapped_qm: usize,
|
||||
/// Mapped splits whose `listing_id` had no `"eod"` `source_id` partner in `provider_mapping`.
|
||||
pub splits_no_eod_partner: usize,
|
||||
/// Distinct non-no-op splits attached to at least one `"eod"` `source_id`.
|
||||
pub splits_applied: usize,
|
||||
/// Total `(eod_source_id, SplitEvent)` pairs pushed into `SplitTable` (may exceed
|
||||
/// `splits_applied` when a listing has multiple `"eod"` `source_id`s).
|
||||
pub split_events_attached: usize,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_bars_1d`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateBars1dRunReport {
|
||||
pub eod_docs_framed: u64,
|
||||
pub eod_bytes_read: u64,
|
||||
pub eod_decode: BsonEodDecodeStats,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub split_rekey: SplitRekeyStats,
|
||||
pub bars_unmapped_source_dropped: usize,
|
||||
pub buffered_bars: usize,
|
||||
/// Approximate heap bytes occupied by the buffered `Vec<EodDailyBar<Arc<str>>>` capacity plus
|
||||
/// the interned `"eod"` `Arc<str>` key allocations.
|
||||
pub buffered_bar_bytes: usize,
|
||||
pub curate_stats: CurateBars1dStats,
|
||||
pub write_stats: Bars1dWriteStats,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Stage-timed run output used internally by `bench-curate-bars-cmd`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct CurateBars1dTimedRun {
|
||||
pub report: CurateBars1dRunReport,
|
||||
pub decode_elapsed_secs: f64,
|
||||
pub curate_elapsed_secs: f64,
|
||||
pub write_elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`run_curate_bars_1d`] and its TSV loaders.
|
||||
///
|
||||
/// Every variant's `Display` output is a single line naming the offending path (and 1-based line
|
||||
/// number for TSV parse errors).
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateBarsError {
|
||||
InvalidOutDir {
|
||||
path: PathBuf,
|
||||
detail: String,
|
||||
},
|
||||
OpenInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
ReadInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
TsvParse {
|
||||
path: PathBuf,
|
||||
line: usize,
|
||||
detail: String,
|
||||
},
|
||||
ProviderMapping {
|
||||
path: PathBuf,
|
||||
source: ProviderMappingError,
|
||||
},
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
SplitTable {
|
||||
path: PathBuf,
|
||||
source: SplitError,
|
||||
},
|
||||
CurateWrite {
|
||||
out_dir: PathBuf,
|
||||
source: CurateBarsWriteError,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateBarsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidOutDir { path, detail } => {
|
||||
write!(f, "invalid --out '{}': {detail}", path.display())
|
||||
}
|
||||
Self::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
|
||||
Self::ReadInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed to read {label} '{}': {source}", path.display()),
|
||||
Self::TsvParse { path, line, detail } => {
|
||||
write!(f, "{}:{line}: {detail}", path.display())
|
||||
}
|
||||
Self::ProviderMapping { path, source } => {
|
||||
write!(f, "invalid provider_mapping '{}': {source}", path.display())
|
||||
}
|
||||
Self::BsonStream {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
||||
Self::SplitTable { path, source } => {
|
||||
write!(f, "invalid split table from '{}': {source}", path.display())
|
||||
}
|
||||
Self::CurateWrite { out_dir, source } => {
|
||||
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateBarsError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
|
||||
Self::ProviderMapping { source, .. } => Some(source),
|
||||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::SplitTable { source, .. } => Some(source),
|
||||
Self::CurateWrite { source, .. } => Some(source),
|
||||
Self::InvalidOutDir { .. } | Self::TsvParse { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a strictly positive ASCII base-10 `i32` (no leading/trailing whitespace or sign).
|
||||
fn parse_strict_positive_i32(raw: &str) -> Option<i32> {
|
||||
if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let val = raw.parse::<i32>().ok()?;
|
||||
if val > 0 {
|
||||
Some(val)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams a strict headerless TSV file line by line, enforcing `\n`/`\r\n` endings, valid UTF-8,
|
||||
/// and at most one trailing blank line.
|
||||
fn read_tsv_lines<F>(
|
||||
path: &Path,
|
||||
label: &'static str,
|
||||
mut on_line: F,
|
||||
) -> Result<(), RunCurateBarsError>
|
||||
where
|
||||
F: FnMut(usize, &str) -> Result<(), String>,
|
||||
{
|
||||
let file = File::open(path).map_err(|source| RunCurateBarsError::OpenInput {
|
||||
label,
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let mut raw_buf: Vec<u8> = Vec::with_capacity(256);
|
||||
let mut line_no: usize = 0;
|
||||
let mut pending_blank_line: Option<usize> = None;
|
||||
|
||||
loop {
|
||||
raw_buf.clear();
|
||||
let bytes_read =
|
||||
reader
|
||||
.read_until(b'\n', &mut raw_buf)
|
||||
.map_err(|source| RunCurateBarsError::ReadInput {
|
||||
label,
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
if bytes_read == 0 {
|
||||
break;
|
||||
}
|
||||
line_no += 1;
|
||||
|
||||
let mut slice = raw_buf.as_slice();
|
||||
if slice.ends_with(b"\n") {
|
||||
slice = &slice[..slice.len() - 1];
|
||||
if slice.ends_with(b"\r") {
|
||||
slice = &slice[..slice.len() - 1];
|
||||
}
|
||||
}
|
||||
if slice.contains(&b'\r') {
|
||||
return Err(RunCurateBarsError::TsvParse {
|
||||
path: path.to_path_buf(),
|
||||
line: line_no,
|
||||
detail: "unexpected carriage return inside TSV line".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let text = std::str::from_utf8(slice).map_err(|_| RunCurateBarsError::TsvParse {
|
||||
path: path.to_path_buf(),
|
||||
line: line_no,
|
||||
detail: "invalid UTF-8 in TSV line".to_string(),
|
||||
})?;
|
||||
|
||||
if text.is_empty() {
|
||||
if pending_blank_line.is_some() {
|
||||
return Err(RunCurateBarsError::TsvParse {
|
||||
path: path.to_path_buf(),
|
||||
line: line_no,
|
||||
detail: "multiple trailing blank lines are not allowed".to_string(),
|
||||
});
|
||||
}
|
||||
pending_blank_line = Some(line_no);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(blank_line) = pending_blank_line.take() {
|
||||
return Err(RunCurateBarsError::TsvParse {
|
||||
path: path.to_path_buf(),
|
||||
line: blank_line,
|
||||
detail: "blank line is only allowed as a single trailing line".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
on_line(line_no, text).map_err(|detail| RunCurateBarsError::TsvParse {
|
||||
path: path.to_path_buf(),
|
||||
line: line_no,
|
||||
detail,
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads `provider_mapping.tsv` into raw [`ProviderMappingRow`] records.
|
||||
///
|
||||
/// Format (no header, 5 `\t`-separated columns):
|
||||
/// `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
||||
///
|
||||
/// `source` and `source_id` are preserved verbatim (never trimmed).
|
||||
pub fn load_provider_mapping_tsv(
|
||||
path: &Path,
|
||||
) -> Result<Vec<ProviderMappingRow>, RunCurateBarsError> {
|
||||
let mut rows = Vec::new();
|
||||
read_tsv_lines(path, "provider-mapping", |_line_no, line| {
|
||||
let mut fields = line.split('\t');
|
||||
let source = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 5 tab-separated columns".to_string())?;
|
||||
let source_id = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 5 tab-separated columns (got 1)".to_string())?;
|
||||
let valid_from_str = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 5 tab-separated columns (got 2)".to_string())?;
|
||||
let valid_to_str = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 5 tab-separated columns (got 3)".to_string())?;
|
||||
let listing_id_str = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 5 tab-separated columns (got 4)".to_string())?;
|
||||
if fields.next().is_some() {
|
||||
return Err("expected 5 tab-separated columns (got more than 5)".to_string());
|
||||
}
|
||||
|
||||
if source.trim().is_empty() {
|
||||
return Err("source column must not be empty or blank".to_string());
|
||||
}
|
||||
if source_id.trim().is_empty() {
|
||||
return Err("source_id column must not be empty or blank".to_string());
|
||||
}
|
||||
|
||||
let valid_from = parse_ymd_strict_days(valid_from_str).ok_or_else(|| {
|
||||
format!("invalid valid_from date '{valid_from_str}' (expected YYYY-MM-DD)")
|
||||
})?;
|
||||
let valid_to = if valid_to_str.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parse_ymd_strict_days(valid_to_str).ok_or_else(|| {
|
||||
format!("invalid valid_to date '{valid_to_str}' (expected YYYY-MM-DD or empty)")
|
||||
})?)
|
||||
};
|
||||
let listing_id = parse_strict_positive_i32(listing_id_str).ok_or_else(|| {
|
||||
format!("invalid listing_id '{listing_id_str}' (expected positive integer)")
|
||||
})?;
|
||||
|
||||
rows.push(ProviderMappingRow {
|
||||
source: source.to_owned(),
|
||||
source_id: source_id.to_owned(),
|
||||
valid_from,
|
||||
valid_to,
|
||||
listing_id,
|
||||
});
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Loads `listing_currencies.tsv` into a `listing_id -> currency` map.
|
||||
///
|
||||
/// Format (no header, 2 `\t`-separated columns):
|
||||
/// `listing_id \t currency`
|
||||
pub fn load_listing_currencies_tsv(
|
||||
path: &Path,
|
||||
) -> Result<HashMap<i32, Cow<'static, str>>, RunCurateBarsError> {
|
||||
let mut currencies: HashMap<i32, Cow<'static, str>> = HashMap::new();
|
||||
read_tsv_lines(path, "listing-currencies", |_line_no, line| {
|
||||
let mut fields = line.split('\t');
|
||||
let listing_id_str = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 2 tab-separated columns".to_string())?;
|
||||
let currency_str = fields
|
||||
.next()
|
||||
.ok_or_else(|| "expected 2 tab-separated columns (got 1)".to_string())?;
|
||||
if fields.next().is_some() {
|
||||
return Err("expected 2 tab-separated columns (got more than 2)".to_string());
|
||||
}
|
||||
|
||||
let listing_id = parse_strict_positive_i32(listing_id_str).ok_or_else(|| {
|
||||
format!("invalid listing_id '{listing_id_str}' (expected positive integer)")
|
||||
})?;
|
||||
if currency_str.trim().is_empty() {
|
||||
return Err("currency column must not be empty or blank".to_string());
|
||||
}
|
||||
|
||||
let currency: Cow<'static, str> = match currency_str {
|
||||
"USD" => Cow::Borrowed("USD"),
|
||||
"CAD" => Cow::Borrowed("CAD"),
|
||||
other => Cow::Owned(other.to_owned()),
|
||||
};
|
||||
|
||||
if currencies.insert(listing_id, currency).is_some() {
|
||||
return Err(format!(
|
||||
"duplicate listing_id {listing_id} in listing_currencies"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(currencies)
|
||||
}
|
||||
|
||||
struct LoadedCurateBarsInputs {
|
||||
mapping: ProviderMappingTable,
|
||||
currencies: HashMap<i32, Cow<'static, str>>,
|
||||
splits: SplitTable<Arc<str>>,
|
||||
bars: Vec<EodDailyBar<Arc<str>>>,
|
||||
eod_docs_framed: u64,
|
||||
eod_bytes_read: u64,
|
||||
eod_decode: BsonEodDecodeStats,
|
||||
splits_docs_framed: u64,
|
||||
splits_bytes_read: u64,
|
||||
splits_decode: BsonQmActionDecodeStats,
|
||||
split_rekey: SplitRekeyStats,
|
||||
bars_unmapped_source_dropped: usize,
|
||||
buffered_bars: usize,
|
||||
buffered_bar_bytes: usize,
|
||||
}
|
||||
|
||||
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> {
|
||||
if out_dir.exists() && !out_dir.is_dir() {
|
||||
return Err(RunCurateBarsError::InvalidOutDir {
|
||||
path: out_dir.to_path_buf(),
|
||||
detail: "path exists and is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_and_decode_inputs(
|
||||
args: &CurateBars1dArgs,
|
||||
) -> Result<LoadedCurateBarsInputs, RunCurateBarsError> {
|
||||
validate_out_dir(&args.out_dir)?;
|
||||
|
||||
let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping)?;
|
||||
let currencies = load_listing_currencies_tsv(&args.listing_currencies)?;
|
||||
|
||||
// Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
||||
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
||||
for row in &mapping_rows {
|
||||
if row.source == "eod" {
|
||||
let key = match eod_keys.get(row.source_id.as_str()) {
|
||||
Some(existing) => Arc::clone(existing),
|
||||
None => {
|
||||
let arc: Arc<str> = Arc::from(row.source_id.as_str());
|
||||
eod_keys.insert(Arc::clone(&arc));
|
||||
arc
|
||||
}
|
||||
};
|
||||
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
||||
}
|
||||
}
|
||||
for partners in eod_by_listing.values_mut() {
|
||||
partners.sort_unstable();
|
||||
partners.dedup();
|
||||
}
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateBarsError::ProviderMapping {
|
||||
path: args.provider_mapping.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
// Stream `qmSplits` and re-key `("qm", qmSearchCode, ex_date) -> listing_id -> [eodSearchCode]`.
|
||||
let splits_file =
|
||||
File::open(&args.qm_splits).map_err(|source| RunCurateBarsError::OpenInput {
|
||||
label: "qm-splits",
|
||||
path: args.qm_splits.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut splits_reader = RawBsonChunkReader::new(splits_file);
|
||||
let mut split_rekey = SplitRekeyStats::default();
|
||||
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
if split.ratio == 1.0 {
|
||||
split_rekey.splits_noop_dropped += 1;
|
||||
return;
|
||||
}
|
||||
let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date)
|
||||
else {
|
||||
split_rekey.splits_unmapped_qm += 1;
|
||||
return;
|
||||
};
|
||||
let Some(partners) = eod_by_listing.get(&listing_id) else {
|
||||
split_rekey.splits_no_eod_partner += 1;
|
||||
return;
|
||||
};
|
||||
if partners.is_empty() {
|
||||
split_rekey.splits_no_eod_partner += 1;
|
||||
return;
|
||||
}
|
||||
split_rekey.splits_applied += 1;
|
||||
let event = split.to_split_event();
|
||||
for eod_key in partners {
|
||||
split_events.push((Arc::clone(eod_key), event));
|
||||
}
|
||||
split_rekey.split_events_attached += partners.len();
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::BsonStream {
|
||||
label: "qm-splits",
|
||||
path: args.qm_splits.clone(),
|
||||
source,
|
||||
})?;
|
||||
let splits_docs_framed = splits_reader.docs_framed();
|
||||
let splits_bytes_read = splits_reader.bytes_read();
|
||||
split_rekey.splits_in = splits_decode.docs_in;
|
||||
|
||||
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
||||
RunCurateBarsError::SplitTable {
|
||||
path: args.qm_splits.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
// Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys.
|
||||
let eod_file =
|
||||
File::open(&args.eod_prices).map_err(|source| RunCurateBarsError::OpenInput {
|
||||
label: "eod-prices",
|
||||
path: args.eod_prices.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut eod_reader = RawBsonChunkReader::new(eod_file);
|
||||
let mut bars: Vec<EodDailyBar<Arc<str>>> = Vec::new();
|
||||
let mut bars_unmapped_source_dropped: usize = 0;
|
||||
let eod_decode = decode_eod_price_chunks(
|
||||
&mut eod_reader,
|
||||
|raw_bar| {
|
||||
if let Some(key) = eod_keys.get(raw_bar.eod_search_code) {
|
||||
bars.push(raw_bar.into_eod_daily_bar(|_, _| Arc::clone(key)));
|
||||
} else {
|
||||
bars_unmapped_source_dropped += 1;
|
||||
}
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::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();
|
||||
let buffered_bars = bars.len();
|
||||
let interned_key_bytes: usize = eod_keys
|
||||
.iter()
|
||||
.map(|k| 2 * size_of::<usize>() + k.len())
|
||||
.sum();
|
||||
let buffered_bar_bytes =
|
||||
bars.capacity() * size_of::<EodDailyBar<Arc<str>>>() + interned_key_bytes;
|
||||
|
||||
Ok(LoadedCurateBarsInputs {
|
||||
mapping,
|
||||
currencies,
|
||||
splits,
|
||||
bars,
|
||||
eod_docs_framed,
|
||||
eod_bytes_read,
|
||||
eod_decode,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
bars_unmapped_source_dropped,
|
||||
buffered_bars,
|
||||
buffered_bar_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the end-to-end `curate-bars-1d` file-to-Parquet pipeline via [`curate_and_write_bars_1d`].
|
||||
pub fn run_curate_bars_1d(
|
||||
args: &CurateBars1dArgs,
|
||||
) -> Result<CurateBars1dRunReport, RunCurateBarsError> {
|
||||
let start = Instant::now();
|
||||
let loaded = load_and_decode_inputs(args)?;
|
||||
|
||||
let write_report = curate_and_write_bars_1d(
|
||||
&args.out_dir,
|
||||
loaded.bars,
|
||||
&loaded.splits,
|
||||
std::iter::empty(),
|
||||
args.rel_tolerance,
|
||||
&loaded.mapping,
|
||||
"eod",
|
||||
&loaded.currencies,
|
||||
Bars1dWriteOptions::default(),
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
Ok(CurateBars1dRunReport {
|
||||
eod_docs_framed: loaded.eod_docs_framed,
|
||||
eod_bytes_read: loaded.eod_bytes_read,
|
||||
eod_decode: loaded.eod_decode,
|
||||
splits_docs_framed: loaded.splits_docs_framed,
|
||||
splits_bytes_read: loaded.splits_bytes_read,
|
||||
splits_decode: loaded.splits_decode,
|
||||
split_rekey: loaded.split_rekey,
|
||||
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
||||
buffered_bars: loaded.buffered_bars,
|
||||
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
||||
curate_stats: write_report.curate_stats,
|
||||
write_stats: write_report.write_stats,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Stage-timed variant of [`run_curate_bars_1d`] sharing [`load_and_decode_inputs`] and calling
|
||||
/// [`curate_bars_1d`] + [`write_bars_1d_dataset`] separately for `bench-curate-bars-cmd`.
|
||||
pub(crate) fn run_curate_bars_1d_timed(
|
||||
args: &CurateBars1dArgs,
|
||||
) -> Result<CurateBars1dTimedRun, RunCurateBarsError> {
|
||||
let total_start = Instant::now();
|
||||
|
||||
let decode_start = Instant::now();
|
||||
let loaded = load_and_decode_inputs(args)?;
|
||||
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
|
||||
|
||||
let curate_start = Instant::now();
|
||||
let curated = curate_bars_1d(
|
||||
loaded.bars,
|
||||
&loaded.splits,
|
||||
std::iter::empty(),
|
||||
args.rel_tolerance,
|
||||
&loaded.mapping,
|
||||
"eod",
|
||||
&loaded.currencies,
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source: CurateBarsWriteError::Curate(source),
|
||||
})?;
|
||||
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
||||
|
||||
let write_start = Instant::now();
|
||||
let write_stats =
|
||||
write_bars_1d_dataset(&args.out_dir, &curated.rows, Bars1dWriteOptions::default())
|
||||
.map_err(|source| RunCurateBarsError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source: CurateBarsWriteError::Parquet(source),
|
||||
})?;
|
||||
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
|
||||
|
||||
let report = CurateBars1dRunReport {
|
||||
eod_docs_framed: loaded.eod_docs_framed,
|
||||
eod_bytes_read: loaded.eod_bytes_read,
|
||||
eod_decode: loaded.eod_decode,
|
||||
splits_docs_framed: loaded.splits_docs_framed,
|
||||
splits_bytes_read: loaded.splits_bytes_read,
|
||||
splits_decode: loaded.splits_decode,
|
||||
split_rekey: loaded.split_rekey,
|
||||
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
||||
buffered_bars: loaded.buffered_bars,
|
||||
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
||||
};
|
||||
|
||||
Ok(CurateBars1dTimedRun {
|
||||
report,
|
||||
decode_elapsed_secs,
|
||||
curate_elapsed_secs,
|
||||
write_elapsed_secs,
|
||||
})
|
||||
}
|
||||
|
||||
/// Formats [`CurateBars1dRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
||||
let years = if report.write_stats.rows_by_year.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
report
|
||||
.write_stats
|
||||
.rows_by_year
|
||||
.iter()
|
||||
.map(|(year, count)| format!("{year:04}={count}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
};
|
||||
|
||||
format!(
|
||||
"curate-etl curate-bars-1d\n\
|
||||
\x20 eod_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
\x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
\x20 splits: splits_in={} splits_applied={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\
|
||||
\x20 filter: bars_unmapped_source_dropped={} buffered_bars={} buffered_bar_bytes={}\n\
|
||||
\x20 builder: bars_in={} rows_out={} keys_out={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} dup_collapsed={} dup_conflict_dropped={}\n\
|
||||
\x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} dropped_missing_currency={} dropped_ts_out_of_range={} listing_collision_collapsed={} listing_collision_dropped={}\n\
|
||||
\x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\
|
||||
\x20 years: {years}\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_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.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.splits_decode.docs_in,
|
||||
report.splits_decode.decoded,
|
||||
report.splits_decode.split_noop_ratio_one,
|
||||
report.splits_decode.rejected_total(),
|
||||
report.splits_decode.rejected_missing_field,
|
||||
report.splits_decode.rejected_empty_field,
|
||||
report.splits_decode.rejected_wrong_type,
|
||||
report.splits_decode.rejected_malformed_date,
|
||||
report.splits_decode.rejected_invalid_number,
|
||||
report.splits_decode.rejected_corrupt_document,
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied,
|
||||
report.split_rekey.splits_unmapped_qm,
|
||||
report.split_rekey.splits_no_eod_partner,
|
||||
report.split_rekey.splits_noop_dropped,
|
||||
report.split_rekey.split_events_attached,
|
||||
report.bars_unmapped_source_dropped,
|
||||
report.buffered_bars,
|
||||
report.buffered_bar_bytes,
|
||||
report.curate_stats.builder.bars_in,
|
||||
report.curate_stats.builder.rows_out,
|
||||
report.curate_stats.builder.keys_out,
|
||||
report.curate_stats.builder.dropped_invalid_ohlc,
|
||||
report.curate_stats.builder.dropped_inconsistent_ohlc,
|
||||
report.curate_stats.builder.dropped_invalid_volume,
|
||||
report.curate_stats.builder.duplicate_collapsed,
|
||||
report.curate_stats.builder.duplicate_conflict_dropped,
|
||||
report.curate_stats.rows_in,
|
||||
report.curate_stats.rows_out,
|
||||
report.curate_stats.listings_out,
|
||||
report.curate_stats.dropped_unmapped,
|
||||
report.curate_stats.dropped_missing_currency,
|
||||
report.curate_stats.dropped_ts_out_of_range,
|
||||
report.curate_stats.listing_collision_collapsed,
|
||||
report.curate_stats.listing_collision_dropped,
|
||||
report.write_stats.rows_written,
|
||||
report.write_stats.files_written,
|
||||
report.write_stats.row_groups_written,
|
||||
report.write_stats.bytes_written,
|
||||
report.elapsed_secs,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "run_curate_bars_tests.rs"]
|
||||
mod tests;
|
||||
741
tools/curate-etl/src/run_curate_bars_tests.rs
Normal file
741
tools/curate-etl/src/run_curate_bars_tests.rs
Normal file
|
|
@ -0,0 +1,741 @@
|
|||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
use parquet::record::{Field, RowAccessor};
|
||||
|
||||
use super::*;
|
||||
use crate::bson_stream::DEFAULT_MAX_DOC_BYTES;
|
||||
use crate::curate_bars::BARS_1D_SOURCE_EOD;
|
||||
use crate::session_close::et_session_close_utc_micros;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestTempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TestTempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let pid = std::process::id();
|
||||
let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!("curate-etl-run-bars-{tag}-{pid}-{seq}"));
|
||||
fs::create_dir_all(&path).expect("create test temp dir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestTempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn eod_doc(
|
||||
code: &str,
|
||||
date: &str,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("open"), open);
|
||||
doc.append(cstr!("high"), high);
|
||||
doc.append(cstr!("low"), low);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), volume);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn write_bytes(path: &Path, bytes: &[u8]) {
|
||||
let mut f = File::create(path).expect("create fixture file");
|
||||
f.write_all(bytes).expect("write fixture bytes");
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct ReadBarRow {
|
||||
listing_id: i32,
|
||||
ts_micros: i64,
|
||||
session_date: i32,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
vwap: Option<f64>,
|
||||
currency: String,
|
||||
source: String,
|
||||
known_at_micros: i64,
|
||||
}
|
||||
|
||||
fn read_parquet_bars(path: &Path) -> Vec<ReadBarRow> {
|
||||
let file = File::open(path).expect("open parquet file");
|
||||
let reader = SerializedFileReader::new(file).expect("open parquet reader");
|
||||
let iter = reader.get_row_iter(None).expect("row iter");
|
||||
let mut rows = Vec::new();
|
||||
for row_res in iter {
|
||||
let row = row_res.expect("read row");
|
||||
let vwap = row.get_double(8).ok();
|
||||
let session_date = match row.get_column_iter().nth(2).expect("session_date col").1 {
|
||||
Field::Date(d) => *d,
|
||||
other => panic!("expected Field::Date for session_date, got {other:?}"),
|
||||
};
|
||||
rows.push(ReadBarRow {
|
||||
listing_id: row.get_int(0).expect("listing_id"),
|
||||
ts_micros: row.get_timestamp_micros(1).expect("ts"),
|
||||
session_date,
|
||||
open: row.get_double(3).expect("open"),
|
||||
high: row.get_double(4).expect("high"),
|
||||
low: row.get_double(5).expect("low"),
|
||||
close: row.get_double(6).expect("close"),
|
||||
volume: row.get_double(7).expect("volume"),
|
||||
vwap,
|
||||
currency: row.get_string(9).expect("currency").to_owned(),
|
||||
source: row.get_string(10).expect("source").to_owned(),
|
||||
known_at_micros: row.get_timestamp_micros(11).expect("known_at"),
|
||||
});
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn strip_timing_line(report: &str) -> String {
|
||||
report
|
||||
.lines()
|
||||
.filter(|line| !line.trim_start().starts_with("timing:"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_to_end_happy_path_nvda_cross_provider_split() {
|
||||
let dir = TestTempDir::new("happy-nvda");
|
||||
let eod_path = dir.path().join("eodPrices.bson");
|
||||
let splits_path = dir.path().join("qmSplits.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
let out_dir = dir.path().join("out");
|
||||
|
||||
// NVDA: qmSearchCode = "NVDA:US", eodSearchCode = "NVDA.US", both -> listing_id 100.
|
||||
// SHOP: CAD listing in 2023 -> listing_id 200.
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2010-01-01\t\t100\n\
|
||||
qm\tNVDA:US\t2010-01-01\t\t100\n\
|
||||
eod\tSHOP.TO\t2015-01-01\t\t200\n",
|
||||
);
|
||||
write_bytes(&curr_path, b"100\tUSD\n200\tCAD\n");
|
||||
|
||||
// 10:1 forward split on 2024-06-10 keyed by qmSearchCode.
|
||||
write_bytes(&splits_path, &split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
|
||||
// Pre-split 2024-06-07: raw OHLC ~$1208, adj_volume = 410_000_000 (10x raw 41_000_000).
|
||||
// Ex-date 2024-06-10: raw OHLC ~$121, volume = 310_000_000 (not divided).
|
||||
// Post-split 2024-06-11: raw OHLC ~$121, volume = 220_000_000 (not divided).
|
||||
// 2023 bar for SHOP.TO.
|
||||
let mut eod_bytes = Vec::new();
|
||||
eod_bytes.extend_from_slice(&eod_doc(
|
||||
"NVDA.US",
|
||||
"2024-06-07",
|
||||
1197.70,
|
||||
1216.92,
|
||||
1180.22,
|
||||
1208.88,
|
||||
410_000_000.0,
|
||||
));
|
||||
eod_bytes.extend_from_slice(&eod_doc(
|
||||
"NVDA.US",
|
||||
"2024-06-10",
|
||||
120.37,
|
||||
123.10,
|
||||
117.01,
|
||||
121.79,
|
||||
310_000_000.0,
|
||||
));
|
||||
eod_bytes.extend_from_slice(&eod_doc(
|
||||
"NVDA.US",
|
||||
"2024-06-11",
|
||||
121.77,
|
||||
122.87,
|
||||
118.74,
|
||||
120.91,
|
||||
220_000_000.0,
|
||||
));
|
||||
eod_bytes.extend_from_slice(&eod_doc(
|
||||
"SHOP.TO",
|
||||
"2023-12-29",
|
||||
103.0,
|
||||
104.5,
|
||||
102.0,
|
||||
103.5,
|
||||
1_500_000.0,
|
||||
));
|
||||
write_bytes(&eod_path, &eod_bytes);
|
||||
|
||||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
let report = run_curate_bars_1d(&args).expect("curate-bars-1d happy path");
|
||||
assert_eq!(report.eod_docs_framed, 4);
|
||||
assert_eq!(report.eod_decode.decoded, 4);
|
||||
assert_eq!(report.splits_docs_framed, 1);
|
||||
assert_eq!(report.split_rekey.splits_applied, 1);
|
||||
assert_eq!(report.write_stats.rows_written, 4);
|
||||
assert_eq!(report.write_stats.files_written, 2);
|
||||
assert_eq!(report.write_stats.rows_by_year.get(&2023), Some(&1));
|
||||
assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&3));
|
||||
|
||||
let rows_2024 = read_parquet_bars(&out_dir.join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(rows_2024.len(), 3);
|
||||
|
||||
let d_pre = ymd_to_epoch_days(2024, 6, 7).unwrap();
|
||||
let d_ex = ymd_to_epoch_days(2024, 6, 10).unwrap();
|
||||
let d_post = ymd_to_epoch_days(2024, 6, 11).unwrap();
|
||||
|
||||
// Pre-split: volume divided by 10, OHLC bit-identical, raw dollar volume exact.
|
||||
assert_eq!(rows_2024[0].listing_id, 100);
|
||||
assert_eq!(rows_2024[0].session_date, d_pre);
|
||||
assert_eq!(rows_2024[0].ts_micros, et_session_close_utc_micros(d_pre).unwrap());
|
||||
assert_eq!(rows_2024[0].known_at_micros, rows_2024[0].ts_micros);
|
||||
assert_eq!(rows_2024[0].open.to_bits(), 1197.70_f64.to_bits());
|
||||
assert_eq!(rows_2024[0].high.to_bits(), 1216.92_f64.to_bits());
|
||||
assert_eq!(rows_2024[0].low.to_bits(), 1180.22_f64.to_bits());
|
||||
assert_eq!(rows_2024[0].close.to_bits(), 1208.88_f64.to_bits());
|
||||
assert_eq!(rows_2024[0].volume.to_bits(), 41_000_000.0_f64.to_bits());
|
||||
assert!((rows_2024[0].close * rows_2024[0].volume - 1208.88 * 41_000_000.0).abs() < 1e-6);
|
||||
assert_eq!(rows_2024[0].vwap, None);
|
||||
assert_eq!(rows_2024[0].currency, "USD");
|
||||
assert_eq!(rows_2024[0].source, BARS_1D_SOURCE_EOD);
|
||||
|
||||
// Ex-date: NOT divided.
|
||||
assert_eq!(rows_2024[1].session_date, d_ex);
|
||||
assert_eq!(rows_2024[1].close.to_bits(), 121.79_f64.to_bits());
|
||||
assert_eq!(rows_2024[1].volume.to_bits(), 310_000_000.0_f64.to_bits());
|
||||
assert!((rows_2024[1].close * rows_2024[1].volume - 121.79 * 310_000_000.0).abs() < 1e-6);
|
||||
|
||||
// Post-split: NOT divided.
|
||||
assert_eq!(rows_2024[2].session_date, d_post);
|
||||
assert_eq!(rows_2024[2].volume.to_bits(), 220_000_000.0_f64.to_bits());
|
||||
|
||||
let rows_2023 = read_parquet_bars(&out_dir.join("bars_1d/year=2023/part.parquet"));
|
||||
assert_eq!(rows_2023.len(), 1);
|
||||
assert_eq!(rows_2023[0].listing_id, 200);
|
||||
assert_eq!(rows_2023[0].currency, "CAD");
|
||||
assert_eq!(rows_2023[0].source, BARS_1D_SOURCE_EOD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_rekey_edge_cases_and_conservation_invariants() {
|
||||
let dir = TestTempDir::new("split-rekey");
|
||||
let eod_path = dir.path().join("eodPrices.bson");
|
||||
let splits_path = dir.path().join("qmSplits.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
let out_dir = dir.path().join("out");
|
||||
|
||||
// Listing 1: two distinct EOD source_ids ("DUAL1.US", "DUAL2.US") -> split applies to both.
|
||||
// Listing 2: two date ranges for the SAME EOD source_id ("MULTI.US") -> deduped, no squaring.
|
||||
// Listing 3: QM-only, no EOD partner -> splits_no_eod_partner.
|
||||
// Listing 4: QM mapped only for 2020-01-01..=2020-12-31; split in 2024 -> splits_unmapped_qm.
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tDUAL1.US\t2020-01-01\t2023-12-31\t1\n\
|
||||
eod\tDUAL2.US\t2024-01-01\t\t1\n\
|
||||
qm\tDUAL:US\t2020-01-01\t\t1\n\
|
||||
eod\tMULTI.US\t2020-01-01\t2021-12-31\t2\n\
|
||||
eod\tMULTI.US\t2022-01-01\t\t2\n\
|
||||
qm\tMULTI:US\t2020-01-01\t\t2\n\
|
||||
qm\tQMONLY:US\t2020-01-01\t\t3\n\
|
||||
eod\tEXPIRED.US\t2020-01-01\t\t4\n\
|
||||
qm\tEXPIRED:US\t2020-01-01\t2020-12-31\t4\n",
|
||||
);
|
||||
write_bytes(&curr_path, b"1\tUSD\n2\tUSD\n3\tUSD\n4\tUSD\n");
|
||||
|
||||
let mut splits_bytes = Vec::new();
|
||||
// 1. Applied to listing 1 (2 EOD partners)
|
||||
splits_bytes.extend_from_slice(&split_doc("DUAL:US", "2024-06-10", 4.0));
|
||||
// 2. Applied to listing 2 (1 EOD partner across 2 ranges -> must NOT square 2.0 into 4.0)
|
||||
splits_bytes.extend_from_slice(&split_doc("MULTI:US", "2024-06-10", 2.0));
|
||||
// 3. Unmapped QM code
|
||||
splits_bytes.extend_from_slice(&split_doc("UNKNOWN:US", "2024-06-10", 3.0));
|
||||
// 4. QM mapped only outside ex_date
|
||||
splits_bytes.extend_from_slice(&split_doc("EXPIRED:US", "2024-06-10", 3.0));
|
||||
// 5. No EOD partner
|
||||
splits_bytes.extend_from_slice(&split_doc("QMONLY:US", "2024-06-10", 2.0));
|
||||
// 6. 1:1 no-op
|
||||
splits_bytes.extend_from_slice(&split_doc("DUAL:US", "2024-05-01", 1.0));
|
||||
// 7. Malformed split (missing splitratio) -> decoder rejection
|
||||
let mut bad_split = RawDocumentBuf::new();
|
||||
bad_split.append(cstr!("qmSearchCode"), "DUAL:US");
|
||||
bad_split.append(cstr!("date"), "2024-05-02");
|
||||
splits_bytes.extend_from_slice(bad_split.as_bytes());
|
||||
write_bytes(&splits_path, &splits_bytes);
|
||||
|
||||
let mut eod_bytes = Vec::new();
|
||||
// Pre-split bars for both EOD partners of listing 1:
|
||||
eod_bytes.extend_from_slice(&eod_doc("DUAL1.US", "2023-12-29", 10.0, 11.0, 9.0, 10.5, 400.0));
|
||||
eod_bytes.extend_from_slice(&eod_doc("DUAL2.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 800.0));
|
||||
// Pre-split bar for listing 2 (multi-range same EOD key):
|
||||
eod_bytes.extend_from_slice(&eod_doc("MULTI.US", "2024-06-07", 20.0, 21.0, 19.0, 20.5, 200.0));
|
||||
write_bytes(&eod_path, &eod_bytes);
|
||||
|
||||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
let report = run_curate_bars_1d(&args).expect("split rekey test");
|
||||
assert_eq!(report.split_rekey.splits_in, 7);
|
||||
assert_eq!(report.split_rekey.splits_applied, 2);
|
||||
assert_eq!(report.split_rekey.split_events_attached, 3); // 2 for listing 1 + 1 for listing 2
|
||||
assert_eq!(report.split_rekey.splits_unmapped_qm, 2);
|
||||
assert_eq!(report.split_rekey.splits_no_eod_partner, 1);
|
||||
assert_eq!(report.split_rekey.splits_noop_dropped, 1);
|
||||
assert_eq!(report.splits_decode.rejected_total(), 1);
|
||||
assert_eq!(
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied
|
||||
+ report.split_rekey.splits_unmapped_qm
|
||||
+ report.split_rekey.splits_no_eod_partner
|
||||
+ report.split_rekey.splits_noop_dropped
|
||||
+ report.splits_decode.rejected_total()
|
||||
);
|
||||
|
||||
let rows_2023 = read_parquet_bars(&out_dir.join("bars_1d/year=2023/part.parquet"));
|
||||
assert_eq!(rows_2023.len(), 1);
|
||||
assert_eq!(rows_2023[0].listing_id, 1);
|
||||
assert_eq!(rows_2023[0].volume, 100.0); // 400 / 4
|
||||
|
||||
let rows_2024 = read_parquet_bars(&out_dir.join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(rows_2024.len(), 2);
|
||||
assert_eq!(rows_2024[0].listing_id, 1);
|
||||
assert_eq!(rows_2024[0].volume, 200.0); // 800 / 4
|
||||
assert_eq!(rows_2024[1].listing_id, 2);
|
||||
assert_eq!(rows_2024[1].volume, 100.0); // 200 / 2 (NOT 200 / 4!)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_filter_missing_currency_and_full_bar_accounting() {
|
||||
let dir = TestTempDir::new("accounting");
|
||||
let eod_path = dir.path().join("eodPrices.bson");
|
||||
let splits_path = dir.path().join("qmSplits.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
let out_dir = dir.path().join("out");
|
||||
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tKEEP.US\t2020-01-01\t\t1\n\
|
||||
eod\tNOCURR.US\t2020-01-01\t\t2\n",
|
||||
);
|
||||
// Listing 2 intentionally absent from listing_currencies.tsv.
|
||||
write_bytes(&curr_path, b"1\tUSD\n");
|
||||
write_bytes(&splits_path, b"");
|
||||
|
||||
let mut eod_bytes = Vec::new();
|
||||
// 1. Kept bar
|
||||
eod_bytes.extend_from_slice(&eod_doc("KEEP.US", "2024-01-02", 10.0, 11.0, 9.0, 10.5, 100.0));
|
||||
// 2. Unmapped EOD source_id -> early-filtered
|
||||
eod_bytes.extend_from_slice(&eod_doc("GHOST.US", "2024-01-02", 10.0, 11.0, 9.0, 10.5, 100.0));
|
||||
// 3. Mapped EOD source_id, date before valid_from -> dropped_unmapped in curate_bars_1d
|
||||
eod_bytes.extend_from_slice(&eod_doc("KEEP.US", "2019-12-31", 10.0, 11.0, 9.0, 10.5, 100.0));
|
||||
// 4. Mapped listing missing currency -> dropped_missing_currency without error
|
||||
eod_bytes.extend_from_slice(&eod_doc("NOCURR.US", "2024-01-02", 10.0, 11.0, 9.0, 10.5, 100.0));
|
||||
// 5. Decoder rejection (missing volume)
|
||||
let mut bad = RawDocumentBuf::new();
|
||||
bad.append(cstr!("eodSearchCode"), "KEEP.US");
|
||||
bad.append(cstr!("date"), "2024-01-03");
|
||||
bad.append(cstr!("open"), 10.0);
|
||||
bad.append(cstr!("high"), 11.0);
|
||||
bad.append(cstr!("low"), 9.0);
|
||||
bad.append(cstr!("close"), 10.5);
|
||||
eod_bytes.extend_from_slice(bad.as_bytes());
|
||||
write_bytes(&eod_path, &eod_bytes);
|
||||
|
||||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
let report = run_curate_bars_1d(&args).expect("accounting run");
|
||||
assert_eq!(report.eod_docs_framed, 5);
|
||||
assert_eq!(report.eod_decode.docs_in, 5);
|
||||
assert_eq!(report.eod_decode.decoded, 4);
|
||||
assert_eq!(report.eod_decode.rejected_total(), 1);
|
||||
assert_eq!(report.bars_unmapped_source_dropped, 1);
|
||||
assert_eq!(report.buffered_bars, 3);
|
||||
assert_eq!(report.curate_stats.dropped_unmapped, 1);
|
||||
assert_eq!(report.curate_stats.dropped_missing_currency, 1);
|
||||
assert_eq!(report.write_stats.rows_written, 1);
|
||||
|
||||
let total_accounted = report.write_stats.rows_written
|
||||
+ report.bars_unmapped_source_dropped
|
||||
+ report.curate_stats.builder.dropped_invalid_ohlc
|
||||
+ report.curate_stats.builder.dropped_inconsistent_ohlc
|
||||
+ report.curate_stats.builder.dropped_invalid_volume
|
||||
+ report.curate_stats.builder.duplicate_collapsed
|
||||
+ report.curate_stats.builder.duplicate_conflict_dropped
|
||||
+ report.curate_stats.dropped_unmapped
|
||||
+ report.curate_stats.dropped_missing_currency
|
||||
+ report.curate_stats.dropped_ts_out_of_range
|
||||
+ report.curate_stats.listing_collision_collapsed
|
||||
+ report.curate_stats.listing_collision_dropped;
|
||||
assert_eq!(report.eod_decode.decoded, total_accounted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsv_loaders_accept_crlf_trailing_blank_and_verbatim_whitespace_and_reject_malformed() {
|
||||
let dir = TestTempDir::new("tsv");
|
||||
|
||||
// Valid: CRLF, single trailing blank line, verbatim whitespace in source_id.
|
||||
let valid_map = dir.path().join("valid_map.tsv");
|
||||
write_bytes(
|
||||
&valid_map,
|
||||
b"eod\t SPACED.US \t2020-01-01\t2024-12-31\t42\r\n\r\n",
|
||||
);
|
||||
let rows = load_provider_mapping_tsv(&valid_map).expect("valid CRLF map");
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].source_id, " SPACED.US ");
|
||||
assert_eq!(rows[0].listing_id, 42);
|
||||
|
||||
let valid_curr = dir.path().join("valid_curr.tsv");
|
||||
write_bytes(&valid_curr, b"42\tUSD\r\n43\tCAD\r\n\r\n");
|
||||
let curr = load_listing_currencies_tsv(&valid_curr).expect("valid CRLF curr");
|
||||
assert_eq!(curr.get(&42).map(AsRef::as_ref), Some("USD"));
|
||||
assert_eq!(curr.get(&43).map(AsRef::as_ref), Some("CAD"));
|
||||
|
||||
// Invalid UTF-8 on line 2 -> reports line 2.
|
||||
let bad_utf8 = dir.path().join("bad_utf8.tsv");
|
||||
write_bytes(&bad_utf8, b"1\tUSD\n2\t\xFF\xFE\n");
|
||||
let err = load_listing_currencies_tsv(&bad_utf8).unwrap_err();
|
||||
match &err {
|
||||
RunCurateBarsError::TsvParse { line, .. } => assert_eq!(*line, 2),
|
||||
other => panic!("expected TsvParse, got {other:?}"),
|
||||
}
|
||||
assert!(err.to_string().contains(":2:"));
|
||||
|
||||
// Header row on line 1 rejected.
|
||||
let header_map = dir.path().join("header.tsv");
|
||||
write_bytes(
|
||||
&header_map,
|
||||
b"source\tsource_id\tvalid_from\tvalid_to\tlisting_id\n",
|
||||
);
|
||||
let err = load_provider_mapping_tsv(&header_map).unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::TsvParse { line: 1, .. }));
|
||||
|
||||
// Interior blank line rejected with blank line's 1-based line number.
|
||||
let interior_blank = dir.path().join("interior_blank.tsv");
|
||||
write_bytes(&interior_blank, b"1\tUSD\n\n2\tCAD\n");
|
||||
let err = load_listing_currencies_tsv(&interior_blank).unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. }));
|
||||
|
||||
// Multiple trailing blank lines rejected.
|
||||
let double_blank = dir.path().join("double_blank.tsv");
|
||||
write_bytes(&double_blank, b"1\tUSD\n\n\n");
|
||||
let err = load_listing_currencies_tsv(&double_blank).unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::TsvParse { line: 3, .. }));
|
||||
|
||||
// Duplicate listing_id in currencies rejected on line 2.
|
||||
let dup_curr = dir.path().join("dup_curr.tsv");
|
||||
write_bytes(&dup_curr, b"1\tUSD\n1\tCAD\n");
|
||||
let err = load_listing_currencies_tsv(&dup_curr).unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. }));
|
||||
|
||||
// Non-positive / signed listing_id rejected.
|
||||
for bad_id in ["0", "-1", "+1", " 1"] {
|
||||
let p = dir.path().join(format!("bad_id_{}.tsv", bad_id.trim()));
|
||||
write_bytes(&p, format!("{bad_id}\tUSD\n").as_bytes());
|
||||
let err = load_listing_currencies_tsv(&p).unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::TsvParse { line: 1, .. }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
||||
let dir = TestTempDir::new("failures");
|
||||
let valid_eod = dir.path().join("valid_eod.bson");
|
||||
let valid_splits = dir.path().join("valid_splits.bson");
|
||||
let valid_map = dir.path().join("valid_map.tsv");
|
||||
let valid_curr = dir.path().join("valid_curr.tsv");
|
||||
|
||||
write_bytes(
|
||||
&valid_eod,
|
||||
&eod_doc("AAPL.US", "2024-01-02", 100.0, 101.0, 99.0, 100.5, 1000.0),
|
||||
);
|
||||
write_bytes(&valid_splits, b"");
|
||||
write_bytes(&valid_map, b"eod\tAAPL.US\t2020-01-01\t\t1\n");
|
||||
write_bytes(&valid_curr, b"1\tUSD\n");
|
||||
|
||||
let assert_single_line_and_no_dataset = |err: &RunCurateBarsError, out: &Path| {
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "error must be single-line: {msg}");
|
||||
assert!(
|
||||
!out.join("bars_1d").exists(),
|
||||
"no bars_1d dataset should exist under {}",
|
||||
out.display()
|
||||
);
|
||||
};
|
||||
|
||||
// 1. Missing input file.
|
||||
let out1 = dir.path().join("out_missing");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: dir.path().join("does_not_exist.bson"),
|
||||
qm_splits: valid_splits.clone(),
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out1.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::OpenInput { .. }));
|
||||
assert_single_line_and_no_dataset(&err, &out1);
|
||||
|
||||
// 2. Truncated BSON mid-document.
|
||||
let trunc_eod = dir.path().join("trunc_eod.bson");
|
||||
let mut full_doc = eod_doc("AAPL.US", "2024-01-02", 100.0, 101.0, 99.0, 100.5, 1000.0);
|
||||
full_doc.truncate(full_doc.len() - 5);
|
||||
write_bytes(&trunc_eod, &full_doc);
|
||||
let out2 = dir.path().join("out_trunc");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: trunc_eod,
|
||||
qm_splits: valid_splits.clone(),
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out2.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
RunCurateBarsError::BsonStream {
|
||||
source: BsonStreamError::TruncatedDocument { .. },
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_single_line_and_no_dataset(&err, &out2);
|
||||
|
||||
// 3. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES).
|
||||
let huge_eod = dir.path().join("huge_eod.bson");
|
||||
let huge_len = (DEFAULT_MAX_DOC_BYTES as i32) + 1024;
|
||||
let mut huge_bytes = Vec::from(huge_len.to_le_bytes());
|
||||
huge_bytes.push(0);
|
||||
write_bytes(&huge_eod, &huge_bytes);
|
||||
let out3 = dir.path().join("out_huge");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: huge_eod,
|
||||
qm_splits: valid_splits.clone(),
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out3.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
RunCurateBarsError::BsonStream {
|
||||
source: BsonStreamError::CorruptDocumentLength { .. },
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_single_line_and_no_dataset(&err, &out3);
|
||||
|
||||
// 4. Malformed TSV line (names 1-based line number).
|
||||
let bad_map = dir.path().join("bad_map.tsv");
|
||||
write_bytes(
|
||||
&bad_map,
|
||||
b"eod\tAAPL.US\t2020-01-01\t\t1\neod\tBAD.US\tnot-a-date\t\t2\n",
|
||||
);
|
||||
let out4 = dir.path().join("out_bad_tsv");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
provider_mapping: bad_map,
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out4.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::TsvParse { line: 2, .. }));
|
||||
assert!(err.to_string().contains(":2:"));
|
||||
assert_single_line_and_no_dataset(&err, &out4);
|
||||
|
||||
// 5. Overlapping mapping ranges.
|
||||
let overlap_map = dir.path().join("overlap_map.tsv");
|
||||
write_bytes(
|
||||
&overlap_map,
|
||||
b"eod\tAAPL.US\t2020-01-01\t2022-12-31\t1\n\
|
||||
eod\tAAPL.US\t2022-06-01\t2024-12-31\t2\n",
|
||||
);
|
||||
let out5 = dir.path().join("out_overlap");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
provider_mapping: overlap_map,
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out5.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
RunCurateBarsError::ProviderMapping {
|
||||
source: ProviderMappingError::OverlappingRanges { .. },
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_single_line_and_no_dataset(&err, &out5);
|
||||
|
||||
// 6. Unwritable --out (existing regular file).
|
||||
let out_file = dir.path().join("out_is_a_file");
|
||||
write_bytes(&out_file, b"blocker");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod,
|
||||
qm_splits: valid_splits,
|
||||
provider_mapping: valid_map,
|
||||
listing_currencies: valid_curr,
|
||||
out_dir: out_file.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, RunCurateBarsError::InvalidOutDir { .. }));
|
||||
assert!(!err.to_string().contains('\n'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_parity() {
|
||||
let dir = TestTempDir::new("determinism");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2010-01-01\t\t10\n\
|
||||
qm\tNVDA:US\t2010-01-01\t\t10\n\
|
||||
eod\tSHOP.TO\t2015-01-01\t\t20\n\
|
||||
qm\tSHOP:TO\t2015-01-01\t\t20\n",
|
||||
);
|
||||
write_bytes(&curr_path, b"10\tUSD\n20\tCAD\n");
|
||||
|
||||
let eod_docs = [
|
||||
eod_doc("NVDA.US", "2023-12-28", 490.0, 498.0, 488.0, 495.0, 200_000_000.0),
|
||||
eod_doc("NVDA.US", "2024-06-07", 1197.0, 1216.0, 1180.0, 1208.0, 400_000_000.0),
|
||||
eod_doc("NVDA.US", "2024-06-10", 120.0, 123.0, 117.0, 121.0, 300_000_000.0),
|
||||
eod_doc("SHOP.TO", "2023-12-29", 103.0, 105.0, 102.0, 104.0, 1_000_000.0),
|
||||
eod_doc("SHOP.TO", "2024-01-03", 104.0, 106.0, 103.0, 105.0, 1_200_000.0),
|
||||
];
|
||||
let split_docs = [
|
||||
split_doc("NVDA:US", "2024-06-10", 10.0),
|
||||
split_doc("SHOP:TO", "2024-06-01", 2.0),
|
||||
];
|
||||
|
||||
let eod_a = dir.path().join("eod_a.bson");
|
||||
let splits_a = dir.path().join("splits_a.bson");
|
||||
write_bytes(&eod_a, &eod_docs.concat());
|
||||
write_bytes(&splits_a, &split_docs.concat());
|
||||
|
||||
let eod_shuf = dir.path().join("eod_shuf.bson");
|
||||
let splits_shuf = dir.path().join("splits_shuf.bson");
|
||||
let mut eod_rev = Vec::new();
|
||||
for doc in eod_docs.iter().rev() {
|
||||
eod_rev.extend_from_slice(doc);
|
||||
}
|
||||
let mut split_rev = Vec::new();
|
||||
for doc in split_docs.iter().rev() {
|
||||
split_rev.extend_from_slice(doc);
|
||||
}
|
||||
write_bytes(&eod_shuf, &eod_rev);
|
||||
write_bytes(&splits_shuf, &split_rev);
|
||||
|
||||
let out1 = dir.path().join("out1");
|
||||
let out2 = dir.path().join("out2");
|
||||
let out3 = dir.path().join("out3");
|
||||
let out_timed = dir.path().join("out_timed");
|
||||
|
||||
let r1 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_a.clone(),
|
||||
qm_splits: splits_a.clone(),
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out1.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
let r2 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_a.clone(),
|
||||
qm_splits: splits_a.clone(),
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out2.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
let r3 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_shuf,
|
||||
qm_splits: splits_shuf,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out3.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
let rt = run_curate_bars_1d_timed(&CurateBars1dArgs {
|
||||
eod_prices: eod_a,
|
||||
qm_splits: splits_a,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_timed.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let s1 = strip_timing_line(&format_curate_bars_report(&r1));
|
||||
let s2 = strip_timing_line(&format_curate_bars_report(&r2));
|
||||
let s3 = strip_timing_line(&format_curate_bars_report(&r3));
|
||||
let st = strip_timing_line(&format_curate_bars_report(&rt.report));
|
||||
assert_eq!(s1, s2);
|
||||
assert_eq!(s1, s3);
|
||||
assert_eq!(s1, st);
|
||||
|
||||
for year in [2023, 2024] {
|
||||
let rel = format!("bars_1d/year={year:04}/part.parquet");
|
||||
let b1 = fs::read(out1.join(&rel)).unwrap();
|
||||
let b2 = fs::read(out2.join(&rel)).unwrap();
|
||||
let b3 = fs::read(out3.join(&rel)).unwrap();
|
||||
let bt = fs::read(out_timed.join(&rel)).unwrap();
|
||||
assert_eq!(b1, b2, "run 1 vs run 2 mismatch for {rel}");
|
||||
assert_eq!(b1, b3, "run 1 vs shuffled mismatch for {rel}");
|
||||
assert_eq!(b1, bt, "run 1 vs timed parity mismatch for {rel}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,12 @@
|
|||
//! QA end-to-end tests for the `curate-etl` binary (T-47 / M1.2a CLI contract).
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
|
||||
fn run(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
|
|
@ -24,6 +30,8 @@ fn no_args_and_help_print_usage_and_succeed() {
|
|||
assert!(out.status.success(), "{args:?}: {}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("Usage:"), "{args:?}: {text}");
|
||||
assert!(text.contains("curate-bars-1d"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-curate-bars-cmd"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-split"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-fx"), "{args:?}: {text}");
|
||||
|
|
@ -238,3 +246,276 @@ fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() {
|
|||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes="));
|
||||
}
|
||||
|
||||
static CLI_TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct CliTempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl CliTempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let pid = std::process::id();
|
||||
let seq = CLI_TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!("curate-etl-cli-{tag}-{pid}-{seq}"));
|
||||
fs::create_dir_all(&path).expect("create cli test temp dir");
|
||||
Self { path }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CliTempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file(path: &std::path::Path, bytes: &[u8]) {
|
||||
let mut f = File::create(path).expect("create file");
|
||||
f.write_all(bytes).expect("write file");
|
||||
}
|
||||
|
||||
fn make_eod_doc(code: &str, date: &str, close: f64, volume: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("open"), close);
|
||||
doc.append(cstr!("high"), close + 1.0);
|
||||
doc.append(cstr!("low"), close - 1.0);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), volume);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn make_split_doc(code: &str, date: &str, ratio: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1d_cli_flag_errors_exit_nonzero_with_usage() {
|
||||
for args in [
|
||||
&["curate-bars-1d"][..],
|
||||
&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--listing-currencies",
|
||||
"c.tsv",
|
||||
][..],
|
||||
&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--eod-prices",
|
||||
"e2.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--listing-currencies",
|
||||
"c.tsv",
|
||||
"--out",
|
||||
"o",
|
||||
][..],
|
||||
&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--listing-currencies",
|
||||
"c.tsv",
|
||||
"--out",
|
||||
"o",
|
||||
"--bogus",
|
||||
"1",
|
||||
][..],
|
||||
&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--listing-currencies",
|
||||
"c.tsv",
|
||||
"--out",
|
||||
"o",
|
||||
"--rel-tolerance",
|
||||
"not-a-number",
|
||||
][..],
|
||||
] {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1d_cli_happy_path_and_determinism_with_shuffled_bson() {
|
||||
let dir = CliTempDir::new("happy");
|
||||
let eod_a = dir.path.join("eod_a.bson");
|
||||
let eod_b = dir.path.join("eod_b.bson");
|
||||
let splits_a = dir.path.join("splits_a.bson");
|
||||
let splits_b = dir.path.join("splits_b.bson");
|
||||
let map_path = dir.path.join("provider_mapping.tsv");
|
||||
let curr_path = dir.path.join("listing_currencies.tsv");
|
||||
let out_a = dir.path.join("out_a");
|
||||
let out_b = dir.path.join("out_b");
|
||||
|
||||
write_file(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2010-01-01\t\t100\nqm\tNVDA:US\t2010-01-01\t\t100\n",
|
||||
);
|
||||
write_file(&curr_path, b"100\tUSD\n");
|
||||
|
||||
let d1 = make_eod_doc("NVDA.US", "2024-06-07", 1208.88, 410_000_000.0);
|
||||
let d2 = make_eod_doc("NVDA.US", "2024-06-10", 121.79, 310_000_000.0);
|
||||
write_file(&eod_a, &[d1.as_slice(), d2.as_slice()].concat());
|
||||
write_file(&eod_b, &[d2.as_slice(), d1.as_slice()].concat());
|
||||
|
||||
let s1 = make_split_doc("NVDA:US", "2024-06-10", 10.0);
|
||||
write_file(&splits_a, &s1);
|
||||
write_file(&splits_b, &s1);
|
||||
|
||||
let run_a = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_a.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_a.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_a.to_str().unwrap(),
|
||||
]);
|
||||
assert!(run_a.status.success(), "{}", stderr(&run_a));
|
||||
assert!(stderr(&run_a).is_empty(), "{}", stderr(&run_a));
|
||||
|
||||
let run_b = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_b.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_b.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_b.to_str().unwrap(),
|
||||
]);
|
||||
assert!(run_b.status.success(), "{}", stderr(&run_b));
|
||||
assert!(stderr(&run_b).is_empty(), "{}", stderr(&run_b));
|
||||
|
||||
let strip_timing = |s: &str| {
|
||||
s.lines()
|
||||
.filter(|l| !l.trim_start().starts_with("timing:"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
};
|
||||
let text_a = stdout(&run_a);
|
||||
let text_b = stdout(&run_b);
|
||||
assert!(text_a.contains("curate-etl curate-bars-1d"), "{text_a}");
|
||||
assert!(text_a.contains("rows_written=2"), "{text_a}");
|
||||
assert!(text_a.contains("2024=2"), "{text_a}");
|
||||
assert_eq!(strip_timing(&text_a), strip_timing(&text_b));
|
||||
|
||||
let pq_a = fs::read(out_a.join("bars_1d/year=2024/part.parquet")).unwrap();
|
||||
let pq_b = fs::read(out_b.join("bars_1d/year=2024/part.parquet")).unwrap();
|
||||
assert_eq!(pq_a, pq_b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1d_cli_runtime_failures_single_line_stderr_and_no_partial_dataset() {
|
||||
let dir = CliTempDir::new("fail");
|
||||
let eod_ok = dir.path.join("eod.bson");
|
||||
let splits_ok = dir.path.join("splits.bson");
|
||||
let map_ok = dir.path.join("map.tsv");
|
||||
let curr_ok = dir.path.join("curr.tsv");
|
||||
write_file(&eod_ok, &make_eod_doc("NVDA.US", "2024-06-07", 100.0, 1000.0));
|
||||
write_file(&splits_ok, b"");
|
||||
write_file(&map_ok, b"eod\tNVDA.US\t2020-01-01\t\t1\n");
|
||||
write_file(&curr_ok, b"1\tUSD\n");
|
||||
|
||||
// 1. Malformed TSV line -> names path and 1-based line number, single-line stderr, no bars_1d.
|
||||
let bad_map = dir.path.join("bad_map.tsv");
|
||||
write_file(&bad_map, b"eod\tNVDA.US\t2020-01-01\t\t1\nbad_line\n");
|
||||
let out1 = dir.path.join("out1");
|
||||
let res = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_ok.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_ok.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
bad_map.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_ok.to_str().unwrap(),
|
||||
"--out",
|
||||
out1.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res.status.success());
|
||||
assert!(stdout(&res).is_empty());
|
||||
let err = stderr(&res);
|
||||
assert_eq!(err.lines().count(), 1, "expected single-line stderr: {err}");
|
||||
assert!(err.contains("bad_map.tsv:2:"), "{err}");
|
||||
assert!(!out1.join("bars_1d").exists());
|
||||
|
||||
// 2. Truncated BSON -> single-line stderr naming path, no bars_1d.
|
||||
let trunc_eod = dir.path.join("trunc.bson");
|
||||
let mut doc = make_eod_doc("NVDA.US", "2024-06-07", 100.0, 1000.0);
|
||||
doc.truncate(doc.len() - 4);
|
||||
write_file(&trunc_eod, &doc);
|
||||
let out2 = dir.path.join("out2");
|
||||
let res2 = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
trunc_eod.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_ok.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_ok.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_ok.to_str().unwrap(),
|
||||
"--out",
|
||||
out2.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res2.status.success());
|
||||
assert!(stdout(&res2).is_empty());
|
||||
let err2 = stderr(&res2);
|
||||
assert_eq!(err2.lines().count(), 1, "expected single-line stderr: {err2}");
|
||||
assert!(err2.contains("trunc.bson"), "{err2}");
|
||||
assert!(!out2.join("bars_1d").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_bars_cmd_small_run_succeeds_and_reports_splits() {
|
||||
let out = run(&["bench-curate-bars-cmd", "2000"]);
|
||||
assert!(out.status.success(), "{}", stderr(&out));
|
||||
assert!(stderr(&out).is_empty(), "{}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("curate-etl bench-curate-bars-cmd"), "{text}");
|
||||
assert!(text.contains("rows=2000 "), "{text}");
|
||||
assert!(text.contains("decode:"), "{text}");
|
||||
assert!(text.contains("curate:"), "{text}");
|
||||
assert!(text.contains("write:"), "{text}");
|
||||
assert!(text.contains("total:"), "{text}");
|
||||
assert!(text.contains("bytes/bar"), "{text}");
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue