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
d63463a64a
commit
54b7276e59
7 changed files with 679 additions and 53 deletions
|
|
@ -983,7 +983,7 @@ curate-etl curate-bars-1d \
|
|||
[--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`.
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, 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)
|
||||
|
||||
|
|
@ -996,7 +996,7 @@ Both `--flag value` and `--flag=value` forms are accepted. Invalid/missing/dupli
|
|||
|
||||
### 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.
|
||||
1. **Split re-keying (`qmSearchCode` → `eodSearchCode`):** Each decoded `qmSplits` row with `ratio != 1.0` resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable`. Before fanning out to `"eod"` partners, mapped splits are compacted by `(listing_id, ex_date)` using the same cross-key policy as `curate_adj_factors`: single-QM-key same-day groups pass through unchanged, multi-QM-key alias groups with bitwise-identical ratios collapse to one event (`splits_collision_collapsed`), and multi-QM-key groups with conflicting ratios fail closed (`ConflictingCrossKeySplit`). Surviving events are attached 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.
|
||||
|
||||
|
|
@ -1004,13 +1004,13 @@ Both `--flag value` and `--flag=value` forms are accepted. Invalid/missing/dupli
|
|||
|
||||
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`
|
||||
- `splits_in == splits_applied + splits_collision_collapsed + 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:
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `provider_mapping.tsv`, and `listing_currencies.tsv` (covering unmapped source keys, ticker reuse gaps, missing currencies, pre-1976 out-of-range timestamps, cross-key EOD listing aliases with both identical collapses and conflicting drops, and cross-key QM split aliases) 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]
|
||||
|
|
@ -1019,17 +1019,17 @@ 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`
|
||||
- Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `keys=2000`
|
||||
- Decode: `elapsed=206.25 ms`, `throughput=4848457 rows/s`, `scan=748.50 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`)
|
||||
- Curate: `elapsed=192.34 ms`, `throughput=5095195 rows/s`, `rows_out=938023` (`93.80%` retained), `listings_out=1941`, `unmapped=595`, `missing_curr=9500`, `ts_oor=1842`, `coll_collapsed=10000`, `coll_dropped=20000`
|
||||
- Write: `elapsed=466.67 ms`, `throughput=2010036 rows/s`, `write=52.52 MB/s`, `files=36`, `row_groups=36`, `bytes=25699104`, `read_back_rows=938023`
|
||||
- Total: `elapsed=865.26 ms`, `throughput=1155723 rows/s`, `throughput_mb=178.42 MB/s`, `splits_applied=1699`, `splits_coll_collapsed=40`, `splits_unmapped_qm=101`, `splits_no_eod_partner=100`, `splits_noop=100`
|
||||
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`
|
||||
- Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4080`, `splits_bytes=376160`, `keys=6000`
|
||||
- Decode: `elapsed=958.74 ms`, `throughput=5215176 rows/s`, `scan=804.55 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`)
|
||||
- Curate: `elapsed=1029.67 ms`, `throughput=4758857 rows/s`, `rows_out=4691865` (`93.84%` retained), `listings_out=5822`, `unmapped=2879`, `missing_curr=48328`, `ts_oor=9132`, `coll_collapsed=49206`, `coll_dropped=98256`
|
||||
- Write: `elapsed=1318.31 ms`, `throughput=3558995 rows/s`, `write=74.91 MB/s`, `files=36`, `row_groups=36`, `bytes=103552480`, `read_back_rows=4691865`
|
||||
- Total: `elapsed=3306.72 ms`, `throughput=1512073 rows/s`, `throughput_mb=233.27 MB/s`, `splits_applied=3399`, `splits_coll_collapsed=80`, `splits_unmapped_qm=201`, `splits_no_eod_partner=200`, `splits_noop=200`
|
||||
|
||||
### Known Limits
|
||||
|
||||
|
|
|
|||
|
|
@ -5083,7 +5083,7 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
let qm_code = format!("QM{k:05}:{suffix}");
|
||||
|
||||
if k % 50 == 1 {
|
||||
// Ticker reuse with interior H2-2016 gap.
|
||||
// Ticker reuse with interior H2-2016 gap (starts 1990 so pre-1976 + gap -> unmapped).
|
||||
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 {
|
||||
|
|
@ -5112,14 +5112,37 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
source,
|
||||
}
|
||||
})?;
|
||||
} else if k % 50 == 2 {
|
||||
// Cross-key EOD + QM alias sharing listing_id with `k - 2` (currency already
|
||||
// emitted by `k - 2`; starts 1970-01-01).
|
||||
let base_listing_id = (k - 2 + 1) as i32;
|
||||
writeln!(
|
||||
map_w,
|
||||
"eod\t{eod_code}\t1970-01-01\t\t{base_listing_id}"
|
||||
)
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
writeln!(
|
||||
map_w,
|
||||
"qm\t{qm_code}\t1970-01-01\t\t{base_listing_id}"
|
||||
)
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
continue;
|
||||
} else {
|
||||
writeln!(map_w, "eod\t{eod_code}\t1990-01-01\t\t{listing_id}").map_err(
|
||||
// Covering mapping from 1970-01-01 so pre-1976 bars reach timestamp validation
|
||||
// and exercise `dropped_ts_out_of_range`.
|
||||
writeln!(map_w, "eod\t{eod_code}\t1970-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| {
|
||||
writeln!(map_w, "qm\t{qm_code}\t1970-01-01\t\t{listing_id}").map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
|
|
@ -5204,13 +5227,38 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
} else {
|
||||
let k = i % mapped_keys;
|
||||
let mut k = i % mapped_keys;
|
||||
if k % 50 == 2 {
|
||||
k -= 2;
|
||||
}
|
||||
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);
|
||||
|
||||
// Emit an identical split under the QM alias key `k + 2` to exercise
|
||||
// `splits_collision_collapsed` without introducing ratio conflicts.
|
||||
if k % 50 == 0 && k + 2 < mapped_keys {
|
||||
splits_w.write_all(doc.as_bytes()).map_err(|source| {
|
||||
CurateBarsCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let alias_k = k + 2;
|
||||
let alias_suffix = if alias_k % 4 == 0 { "TO" } else { "US" };
|
||||
let alias_qm_code = format!("QM{alias_k:05}:{alias_suffix}");
|
||||
let mut alias_oid = [0u8; 12];
|
||||
alias_oid[0] = 1;
|
||||
alias_oid[4..12].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), ObjectId::from_bytes(alias_oid));
|
||||
doc.append(cstr!("qmSearchCode"), alias_qm_code.as_str());
|
||||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
}
|
||||
}
|
||||
splits_w
|
||||
.write_all(doc.as_bytes())
|
||||
|
|
@ -5250,16 +5298,34 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
.collect();
|
||||
|
||||
// Per-key coprime-stride cursors over `main_days` so 5M rows stay unique per key.
|
||||
// Alias keys (`k % 50 == 2`) share the starting cursor of their base key (`k - 2`)
|
||||
// so both land on identical `(listing_id, session_date)` pairs.
|
||||
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();
|
||||
let mut cursors: Vec<usize> = (0..key_count)
|
||||
.map(|k| {
|
||||
let base_k = if k < mapped_keys && k % 50 == 2 {
|
||||
k - 2
|
||||
} else {
|
||||
k
|
||||
};
|
||||
(base_k * 13) % main_len
|
||||
})
|
||||
.collect();
|
||||
|
||||
for i in 0..rows {
|
||||
let k = i % key_count;
|
||||
let pass = i / key_count;
|
||||
let code = &eod_codes[k];
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
let is_alias_base = k < mapped_keys && k % 50 == 0 && k + 2 < mapped_keys;
|
||||
let is_alias_key = k < mapped_keys && k % 50 == 2;
|
||||
|
||||
let (epoch_day, date_str) = if roll < 20 {
|
||||
let (epoch_day, date_str) = if is_alias_base || is_alias_key {
|
||||
let idx = cursors[k];
|
||||
cursors[k] = (idx + stride) % main_len;
|
||||
(main_days[idx], &main_strs[idx])
|
||||
} else if roll < 20 {
|
||||
let idx = (rng.next_u64() as usize) % pre2008_days.len();
|
||||
(pre2008_days[idx], &pre2008_strs[idx])
|
||||
} else if roll < 22 {
|
||||
|
|
@ -5271,13 +5337,32 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
(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 (open, high, low, close, volume_i64) = if is_alias_base || is_alias_key {
|
||||
// Deterministic OHLCV keyed by `(base_k, epoch_day)`: identical on even passes
|
||||
// (`listing_collision_collapsed`) and differing on odd passes (`listing_collision_dropped`).
|
||||
let base_k = if is_alias_key { k - 2 } else { k };
|
||||
let base = 50.0 + ((base_k % 200) as f64) + ((epoch_day.rem_euclid(50)) as f64) * 0.25;
|
||||
let bump = if is_alias_key && pass % 2 == 1 {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let open = base + bump;
|
||||
let high = open + 2.0;
|
||||
let low = open - 1.0;
|
||||
let close = open + 0.5;
|
||||
let volume_i64 = 100_000 + ((base_k as i64) * 100) + ((epoch_day as i64) & 0x3ff);
|
||||
(open, high, low, close, volume_i64)
|
||||
} else {
|
||||
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;
|
||||
(open, high, low, close, volume_i64)
|
||||
};
|
||||
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
|
|
@ -8259,14 +8344,20 @@ mod tests {
|
|||
assert_eq!(
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied
|
||||
+ report.split_rekey.splits_collision_collapsed
|
||||
+ 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_collision_collapsed > 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);
|
||||
assert!(report.curate_stats.dropped_ts_out_of_range > 0);
|
||||
assert!(report.curate_stats.listing_collision_collapsed > 0);
|
||||
assert!(report.curate_stats.listing_collision_dropped > 0);
|
||||
assert!(report.curate_stats.dropped_missing_currency > 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -143,6 +143,9 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
|
|||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
|
@ -966,12 +969,13 @@ mod tests {
|
|||
"--qm-splits=/tmp/s.bson",
|
||||
"--provider-mapping=/tmp/m.tsv",
|
||||
"--listing-currencies=/tmp/c.tsv",
|
||||
"--out=/tmp/o",
|
||||
"--out=--literal-out-dir",
|
||||
"--rel-tolerance=-0.0",
|
||||
]))
|
||||
.expect("equals-style curate-bars-1d args");
|
||||
match equals_style {
|
||||
CliAction::CurateBars1d(a) => {
|
||||
assert_eq!(a.out_dir, PathBuf::from("--literal-out-dir"));
|
||||
assert_eq!(a.rel_tolerance.to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
other => panic!("unexpected action: {other:?}"),
|
||||
|
|
@ -1031,6 +1035,24 @@ mod tests {
|
|||
let err = parse_args(&to_args(&["curate-bars-1d", "--out"])).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--out'"), "{err}");
|
||||
|
||||
// Separated flag followed immediately by another `--` option token (e.g. unset `$OUT`
|
||||
// before a misspelled flag) must fail as missing value rather than consuming it as a path.
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"e.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--listing-currencies",
|
||||
"c.tsv",
|
||||
"--out",
|
||||
"--rel-tolerence=0.01",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--out'"), "{err}");
|
||||
|
||||
// Empty path value.
|
||||
let mut empty_val = full.to_vec();
|
||||
empty_val[10] = "";
|
||||
|
|
|
|||
|
|
@ -694,12 +694,17 @@ fn main() -> ExitCode {
|
|||
report.bytes_per_buffered_bar
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={}",
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} unmapped={} missing_curr={} ts_oor={} coll_collapsed={} coll_dropped={}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out
|
||||
report.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
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
|
|
@ -712,11 +717,12 @@ fn main() -> ExitCode {
|
|||
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={}",
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s throughput_mb={:.2} MB/s splits_applied={} splits_coll_collapsed={} 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_collision_collapsed,
|
||||
report.split_rekey.splits_unmapped_qm,
|
||||
report.split_rekey.splits_no_eod_partner,
|
||||
report.split_rekey.splits_noop_dropped
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ pub struct CurateBars1dArgs {
|
|||
/// 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()`.
|
||||
/// `splits_in == splits_applied + splits_collision_collapsed + 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`).
|
||||
|
|
@ -70,7 +70,10 @@ pub struct SplitRekeyStats {
|
|||
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`.
|
||||
/// Cross-key QM alias split documents on the same `(listing_id, ex_date)` with bitwise
|
||||
/// identical ratio collapsed before fanning out to `"eod"` partners.
|
||||
pub splits_collision_collapsed: usize,
|
||||
/// Non-no-op splits attached to at least one `"eod"` `source_id` after cross-key compaction.
|
||||
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).
|
||||
|
|
@ -144,6 +147,15 @@ pub enum RunCurateBarsError {
|
|||
path: PathBuf,
|
||||
source: SplitError,
|
||||
},
|
||||
ConflictingCrossKeySplit {
|
||||
path: PathBuf,
|
||||
listing_id: i32,
|
||||
ex_date: i32,
|
||||
first_key: String,
|
||||
first_ratio: f64,
|
||||
second_key: String,
|
||||
second_ratio: f64,
|
||||
},
|
||||
CurateWrite {
|
||||
out_dir: PathBuf,
|
||||
source: CurateBarsWriteError,
|
||||
|
|
@ -180,6 +192,19 @@ impl fmt::Display for RunCurateBarsError {
|
|||
Self::SplitTable { path, source } => {
|
||||
write!(f, "invalid split table from '{}': {source}", path.display())
|
||||
}
|
||||
Self::ConflictingCrossKeySplit {
|
||||
path,
|
||||
listing_id,
|
||||
ex_date,
|
||||
first_key,
|
||||
first_ratio,
|
||||
second_key,
|
||||
second_ratio,
|
||||
} => write!(
|
||||
f,
|
||||
"conflicting cross-key split in '{}': listing_id={listing_id} ex_date={ex_date} '{first_key}' ({first_ratio}) vs '{second_key}' ({second_ratio})",
|
||||
path.display()
|
||||
),
|
||||
Self::CurateWrite { out_dir, source } => {
|
||||
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
||||
}
|
||||
|
|
@ -195,7 +220,9 @@ impl Error for RunCurateBarsError {
|
|||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::SplitTable { source, .. } => Some(source),
|
||||
Self::CurateWrite { source, .. } => Some(source),
|
||||
Self::InvalidOutDir { .. } | Self::TsvParse { .. } => None,
|
||||
Self::InvalidOutDir { .. }
|
||||
| Self::TsvParse { .. }
|
||||
| Self::ConflictingCrossKeySplit { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -433,6 +460,123 @@ fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
struct MappedQmSplit {
|
||||
listing_id: i32,
|
||||
ex_date: i32,
|
||||
qm_key: String,
|
||||
ratio: f64,
|
||||
}
|
||||
|
||||
/// Applies the `curate_adj` cross-key split policy by `(listing_id, ex_date)` before fanning out
|
||||
/// to `"eod"` partners:
|
||||
/// - Single-QM-key groups pass through unchanged (preserving `SplitTable` same-day multiplication).
|
||||
/// - Multi-QM-key groups with bitwise-identical ratios collapse to one event (`collapsed += n - 1`).
|
||||
/// - Multi-QM-key groups with conflicting ratios fail closed with `ConflictingCrossKeySplit`.
|
||||
fn compact_mapped_qm_splits(
|
||||
path: &Path,
|
||||
mut mapped: Vec<MappedQmSplit>,
|
||||
) -> Result<(Vec<(i32, SplitEvent)>, usize), RunCurateBarsError> {
|
||||
mapped.sort_unstable_by(|a, b| {
|
||||
a.listing_id
|
||||
.cmp(&b.listing_id)
|
||||
.then_with(|| a.ex_date.cmp(&b.ex_date))
|
||||
.then_with(|| a.qm_key.cmp(&b.qm_key))
|
||||
.then_with(|| a.ratio.total_cmp(&b.ratio))
|
||||
});
|
||||
|
||||
let mut out: Vec<(i32, SplitEvent)> = Vec::with_capacity(mapped.len());
|
||||
let mut collapsed_total = 0usize;
|
||||
let mut iter = mapped.into_iter().peekable();
|
||||
let mut group: Vec<MappedQmSplit> = Vec::with_capacity(4);
|
||||
|
||||
while let Some(first) = iter.next() {
|
||||
let listing_id = first.listing_id;
|
||||
let ex_date = first.ex_date;
|
||||
group.clear();
|
||||
group.push(first);
|
||||
while let Some(next) = iter.peek() {
|
||||
if next.listing_id == listing_id && next.ex_date == ex_date {
|
||||
group.push(iter.next().expect("peeked split"));
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let group_len = group.len();
|
||||
if group_len == 1 {
|
||||
let item = group.pop().expect("single split");
|
||||
out.push((
|
||||
listing_id,
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: item.ratio,
|
||||
},
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let first_key = group[0].qm_key.as_str();
|
||||
let last_key = group[group_len - 1].qm_key.as_str();
|
||||
if first_key == last_key {
|
||||
for item in group.drain(..) {
|
||||
out.push((
|
||||
listing_id,
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: item.ratio,
|
||||
},
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let first_ratio = group[0].ratio;
|
||||
let first_ratio_bits = first_ratio.to_bits();
|
||||
let all_identical = group[1..]
|
||||
.iter()
|
||||
.all(|other| other.ratio.to_bits() == first_ratio_bits);
|
||||
|
||||
if all_identical {
|
||||
collapsed_total += group_len - 1;
|
||||
out.push((
|
||||
listing_id,
|
||||
SplitEvent {
|
||||
ex_date,
|
||||
ratio: first_ratio,
|
||||
},
|
||||
));
|
||||
} else {
|
||||
let (lhs, rhs) = if let Some(other) = group[1..]
|
||||
.iter()
|
||||
.find(|e| e.qm_key.as_str() != first_key && e.ratio.to_bits() != first_ratio_bits)
|
||||
{
|
||||
(&group[0], other)
|
||||
} else {
|
||||
let bad = group[1..]
|
||||
.iter()
|
||||
.find(|e| e.ratio.to_bits() != first_ratio_bits)
|
||||
.expect("non-identical split exists");
|
||||
let other_key = group[1..]
|
||||
.iter()
|
||||
.find(|e| e.qm_key.as_str() != first_key)
|
||||
.expect("distinct source key exists");
|
||||
(bad, other_key)
|
||||
};
|
||||
return Err(RunCurateBarsError::ConflictingCrossKeySplit {
|
||||
path: path.to_path_buf(),
|
||||
listing_id,
|
||||
ex_date,
|
||||
first_key: lhs.qm_key.clone(),
|
||||
first_ratio: lhs.ratio,
|
||||
second_key: rhs.qm_key.clone(),
|
||||
second_ratio: rhs.ratio,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok((out, collapsed_total))
|
||||
}
|
||||
|
||||
fn load_and_decode_inputs(
|
||||
args: &CurateBars1dArgs,
|
||||
) -> Result<LoadedCurateBarsInputs, RunCurateBarsError> {
|
||||
|
|
@ -469,7 +613,7 @@ fn load_and_decode_inputs(
|
|||
}
|
||||
})?;
|
||||
|
||||
// Stream `qmSplits` and re-key `("qm", qmSearchCode, ex_date) -> listing_id -> [eodSearchCode]`.
|
||||
// Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`.
|
||||
let splits_file =
|
||||
File::open(&args.qm_splits).map_err(|source| RunCurateBarsError::OpenInput {
|
||||
label: "qm-splits",
|
||||
|
|
@ -478,7 +622,7 @@ fn load_and_decode_inputs(
|
|||
})?;
|
||||
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 mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
|
|
@ -491,20 +635,19 @@ fn load_and_decode_inputs(
|
|||
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() {
|
||||
let has_eod_partner = eod_by_listing
|
||||
.get(&listing_id)
|
||||
.is_some_and(|partners| !partners.is_empty());
|
||||
if !has_eod_partner {
|
||||
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();
|
||||
mapped_splits.push(MappedQmSplit {
|
||||
listing_id,
|
||||
ex_date: split.ex_date,
|
||||
qm_key: split.qm_search_code.to_owned(),
|
||||
ratio: split.ratio,
|
||||
});
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
|
|
@ -517,6 +660,21 @@ fn load_and_decode_inputs(
|
|||
let splits_bytes_read = splits_reader.bytes_read();
|
||||
split_rekey.splits_in = splits_decode.docs_in;
|
||||
|
||||
// Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys.
|
||||
let (compacted_splits, splits_collision_collapsed) =
|
||||
compact_mapped_qm_splits(&args.qm_splits, mapped_splits)?;
|
||||
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
|
||||
|
||||
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
|
||||
for (listing_id, event) in compacted_splits {
|
||||
let partners = &eod_by_listing[&listing_id];
|
||||
split_rekey.splits_applied += 1;
|
||||
for eod_key in partners {
|
||||
split_events.push((Arc::clone(eod_key), event));
|
||||
}
|
||||
split_rekey.split_events_attached += partners.len();
|
||||
}
|
||||
|
||||
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
||||
RunCurateBarsError::SplitTable {
|
||||
path: args.qm_splits.clone(),
|
||||
|
|
@ -698,7 +856,7 @@ pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
|||
"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 splits: splits_in={} splits_applied={} splits_collision_collapsed={} 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\
|
||||
|
|
@ -730,6 +888,7 @@ pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
|||
report.splits_decode.rejected_corrupt_document,
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied,
|
||||
report.split_rekey.splits_collision_collapsed,
|
||||
report.split_rekey.splits_unmapped_qm,
|
||||
report.split_rekey.splits_no_eod_partner,
|
||||
report.split_rekey.splits_noop_dropped,
|
||||
|
|
|
|||
|
|
@ -316,6 +316,7 @@ fn split_rekey_edge_cases_and_conservation_invariants() {
|
|||
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.splits_collision_collapsed, 0);
|
||||
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);
|
||||
|
|
@ -324,6 +325,7 @@ fn split_rekey_edge_cases_and_conservation_invariants() {
|
|||
assert_eq!(
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied
|
||||
+ report.split_rekey.splits_collision_collapsed
|
||||
+ report.split_rekey.splits_unmapped_qm
|
||||
+ report.split_rekey.splits_no_eod_partner
|
||||
+ report.split_rekey.splits_noop_dropped
|
||||
|
|
@ -343,6 +345,146 @@ fn split_rekey_edge_cases_and_conservation_invariants() {
|
|||
assert_eq!(rows_2024[1].volume, 100.0); // 200 / 2 (NOT 200 / 4!)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_alias_splits_collapse_identical_and_reject_conflicting_with_parquet_readback() {
|
||||
let dir = TestTempDir::new("qm-alias-splits");
|
||||
let eod_path = dir.path().join("eodPrices.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
|
||||
// Listing 100: two QM aliases ("NVDA:US", "NVDA_ALT:US") -> one EOD key ("NVDA.US").
|
||||
// Listing 200: single QM key ("COMBO:US") -> one EOD key ("COMBO.US") for same-day multi-split check.
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2010-01-01\t\t100\n\
|
||||
qm\tNVDA:US\t2010-01-01\t\t100\n\
|
||||
qm\tNVDA_ALT:US\t2010-01-01\t\t100\n\
|
||||
eod\tCOMBO.US\t2010-01-01\t\t200\n\
|
||||
qm\tCOMBO:US\t2010-01-01\t\t200\n",
|
||||
);
|
||||
write_bytes(&curr_path, b"100\tUSD\n200\tUSD\n");
|
||||
|
||||
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(
|
||||
"COMBO.US",
|
||||
"2024-06-07",
|
||||
50.0,
|
||||
52.0,
|
||||
49.0,
|
||||
51.0,
|
||||
300.0,
|
||||
));
|
||||
write_bytes(&eod_path, &eod_bytes);
|
||||
|
||||
// 1. Identical cross-key QM alias splits (10:1 under both NVDA:US and NVDA_ALT:US) must
|
||||
// collapse to a single 10:1 split rather than multiplying to 100:1, while two same-day
|
||||
// splits under one QM key (COMBO:US 2:1 and 1.5:1) still multiply to 3:1.
|
||||
let splits_ok = dir.path().join("splits_alias_ok.bson");
|
||||
let mut splits_ok_bytes = Vec::new();
|
||||
splits_ok_bytes.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
splits_ok_bytes.extend_from_slice(&split_doc("NVDA_ALT:US", "2024-06-10", 10.0));
|
||||
splits_ok_bytes.extend_from_slice(&split_doc("COMBO:US", "2024-06-10", 2.0));
|
||||
splits_ok_bytes.extend_from_slice(&split_doc("COMBO:US", "2024-06-10", 1.5));
|
||||
write_bytes(&splits_ok, &splits_ok_bytes);
|
||||
|
||||
let out_ok = dir.path().join("out_ok");
|
||||
let report = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path.clone(),
|
||||
qm_splits: splits_ok,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out_ok.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.expect("identical QM alias splits should collapse cleanly");
|
||||
|
||||
assert_eq!(report.split_rekey.splits_in, 4);
|
||||
assert_eq!(report.split_rekey.splits_collision_collapsed, 1);
|
||||
assert_eq!(report.split_rekey.splits_applied, 3); // 1 collapsed NVDA + 2 same-key COMBO
|
||||
assert_eq!(report.split_rekey.split_events_attached, 3);
|
||||
assert_eq!(
|
||||
report.split_rekey.splits_in,
|
||||
report.split_rekey.splits_applied
|
||||
+ report.split_rekey.splits_collision_collapsed
|
||||
+ 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_2024 = read_parquet_bars(&out_ok.join("bars_1d/year=2024/part.parquet"));
|
||||
assert_eq!(rows_2024.len(), 3);
|
||||
// NVDA pre-split: 410M / 10 = 41M (NOT 4.1M!).
|
||||
assert_eq!(rows_2024[0].listing_id, 100);
|
||||
assert_eq!(rows_2024[0].open.to_bits(), 1197.70_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);
|
||||
// NVDA ex-date untouched:
|
||||
assert_eq!(rows_2024[1].listing_id, 100);
|
||||
assert_eq!(rows_2024[1].volume.to_bits(), 310_000_000.0_f64.to_bits());
|
||||
// COMBO single-key same-day splits (2.0 * 1.5 = 3.0): 300 / 3 = 100.
|
||||
assert_eq!(rows_2024[2].listing_id, 200);
|
||||
assert_eq!(rows_2024[2].volume.to_bits(), 100.0_f64.to_bits());
|
||||
|
||||
// 2. Conflicting cross-key QM alias splits (10:1 vs 4:1) must fail closed and write nothing.
|
||||
let splits_conflict = dir.path().join("splits_alias_conflict.bson");
|
||||
let mut splits_conflict_bytes = Vec::new();
|
||||
splits_conflict_bytes.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
splits_conflict_bytes.extend_from_slice(&split_doc("NVDA_ALT:US", "2024-06-10", 4.0));
|
||||
write_bytes(&splits_conflict, &splits_conflict_bytes);
|
||||
|
||||
let out_conflict = dir.path().join("out_conflict");
|
||||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_conflict,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_conflict.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
match &err {
|
||||
RunCurateBarsError::ConflictingCrossKeySplit {
|
||||
listing_id,
|
||||
first_key,
|
||||
first_ratio,
|
||||
second_key,
|
||||
second_ratio,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(*listing_id, 100);
|
||||
assert_eq!(first_key, "NVDA:US");
|
||||
assert_eq!(*first_ratio, 10.0);
|
||||
assert_eq!(second_key, "NVDA_ALT:US");
|
||||
assert_eq!(*second_ratio, 4.0);
|
||||
}
|
||||
other => panic!("expected ConflictingCrossKeySplit, got {other:?}"),
|
||||
}
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "error must be single-line: {msg}");
|
||||
assert!(msg.contains("splits_alias_conflict.bson"), "{msg}");
|
||||
assert!(!out_conflict.join("bars_1d").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_filter_missing_currency_and_full_bar_accounting() {
|
||||
let dir = TestTempDir::new("accounting");
|
||||
|
|
@ -618,20 +760,48 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
));
|
||||
assert_single_line_and_no_dataset(&err, &out5);
|
||||
|
||||
// 6. Unwritable --out (existing regular file).
|
||||
// 6. Unwritable --out (existing regular file fails fast in validate_out_dir).
|
||||
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,
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
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'));
|
||||
|
||||
// 7. Writer-reaching output obstruction: --out is a valid directory, but `<out>/bars_1d`
|
||||
// is occupied by a regular file so curation completes and the Parquet writer fails.
|
||||
let out_obstructed = dir.path().join("out_obstructed");
|
||||
fs::create_dir_all(&out_obstructed).expect("create obstructed out dir");
|
||||
let bars_1d_blocker = out_obstructed.join("bars_1d");
|
||||
write_bytes(&bars_1d_blocker, b"sentinel");
|
||||
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_obstructed.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
RunCurateBarsError::CurateWrite {
|
||||
source: CurateBarsWriteError::Parquet(_),
|
||||
..
|
||||
}
|
||||
));
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "error must be single-line: {msg}");
|
||||
assert!(msg.contains("out_obstructed"), "{msg}");
|
||||
assert!(bars_1d_blocker.is_file());
|
||||
assert_eq!(fs::read(&bars_1d_blocker).unwrap(), b"sentinel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -503,6 +503,184 @@ fn curate_bars_1d_cli_runtime_failures_single_line_stderr_and_no_partial_dataset
|
|||
assert_eq!(err2.lines().count(), 1, "expected single-line stderr: {err2}");
|
||||
assert!(err2.contains("trunc.bson"), "{err2}");
|
||||
assert!(!out2.join("bars_1d").exists());
|
||||
|
||||
// 3. Missing input file -> single-line stderr naming path, no bars_1d.
|
||||
let missing_eod = dir.path.join("missing_eod.bson");
|
||||
let out3 = dir.path.join("out3");
|
||||
let res3 = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
missing_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",
|
||||
out3.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res3.status.success());
|
||||
assert!(stdout(&res3).is_empty());
|
||||
let err3 = stderr(&res3);
|
||||
assert_eq!(err3.lines().count(), 1, "expected single-line stderr: {err3}");
|
||||
assert!(err3.contains("missing_eod.bson"), "{err3}");
|
||||
assert!(!out3.join("bars_1d").exists());
|
||||
|
||||
// 4. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES) -> single-line stderr naming path, no bars_1d.
|
||||
let huge_eod = dir.path.join("huge_eod.bson");
|
||||
let huge_len = (curate_etl::bson_stream::DEFAULT_MAX_DOC_BYTES as i32) + 1024;
|
||||
let mut huge_bytes = Vec::from(huge_len.to_le_bytes());
|
||||
huge_bytes.push(0);
|
||||
write_file(&huge_eod, &huge_bytes);
|
||||
let out4 = dir.path.join("out4");
|
||||
let res4 = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
huge_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",
|
||||
out4.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res4.status.success());
|
||||
assert!(stdout(&res4).is_empty());
|
||||
let err4 = stderr(&res4);
|
||||
assert_eq!(err4.lines().count(), 1, "expected single-line stderr: {err4}");
|
||||
assert!(err4.contains("huge_eod.bson"), "{err4}");
|
||||
assert!(!out4.join("bars_1d").exists());
|
||||
|
||||
// 5. Overlapping mapping ranges -> single-line stderr naming path, no bars_1d.
|
||||
let overlap_map = dir.path.join("overlap_map.tsv");
|
||||
write_file(
|
||||
&overlap_map,
|
||||
b"eod\tNVDA.US\t2020-01-01\t2022-12-31\t1\neod\tNVDA.US\t2022-06-01\t2024-12-31\t2\n",
|
||||
);
|
||||
let out5 = dir.path.join("out5");
|
||||
let res5 = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_ok.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_ok.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
overlap_map.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_ok.to_str().unwrap(),
|
||||
"--out",
|
||||
out5.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res5.status.success());
|
||||
assert!(stdout(&res5).is_empty());
|
||||
let err5 = stderr(&res5);
|
||||
assert_eq!(err5.lines().count(), 1, "expected single-line stderr: {err5}");
|
||||
assert!(err5.contains("overlap_map.tsv"), "{err5}");
|
||||
assert!(!out5.join("bars_1d").exists());
|
||||
|
||||
// 6. Conflicting cross-key QM alias splits -> single-line stderr naming path, no bars_1d.
|
||||
let alias_map = dir.path.join("alias_map.tsv");
|
||||
write_file(
|
||||
&alias_map,
|
||||
b"eod\tNVDA.US\t2020-01-01\t\t1\nqm\tNVDA:US\t2020-01-01\t\t1\nqm\tNVDA_ALT:US\t2020-01-01\t\t1\n",
|
||||
);
|
||||
let conflict_splits = dir.path.join("conflict_splits.bson");
|
||||
let c1 = make_split_doc("NVDA:US", "2024-06-10", 10.0);
|
||||
let c2 = make_split_doc("NVDA_ALT:US", "2024-06-10", 4.0);
|
||||
write_file(&conflict_splits, &[c1.as_slice(), c2.as_slice()].concat());
|
||||
let out6 = dir.path.join("out6");
|
||||
let res6 = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_ok.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
conflict_splits.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
alias_map.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_ok.to_str().unwrap(),
|
||||
"--out",
|
||||
out6.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res6.status.success());
|
||||
assert!(stdout(&res6).is_empty());
|
||||
let err6 = stderr(&res6);
|
||||
assert_eq!(err6.lines().count(), 1, "expected single-line stderr: {err6}");
|
||||
assert!(err6.contains("conflict_splits.bson"), "{err6}");
|
||||
assert!(!out6.join("bars_1d").exists());
|
||||
|
||||
// 7. Output write failure reaching the Parquet writer: `--out` is a valid directory, but
|
||||
// `<out>/bars_1d` is occupied by a regular file.
|
||||
let out7 = dir.path.join("out7_obstructed");
|
||||
fs::create_dir_all(&out7).expect("create out7 dir");
|
||||
let bars_1d_file = out7.join("bars_1d");
|
||||
write_file(&bars_1d_file, b"sentinel");
|
||||
let res7 = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_ok.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",
|
||||
out7.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res7.status.success());
|
||||
assert!(stdout(&res7).is_empty());
|
||||
let err7 = stderr(&res7);
|
||||
assert_eq!(err7.lines().count(), 1, "expected single-line stderr: {err7}");
|
||||
assert!(err7.contains("out7_obstructed"), "{err7}");
|
||||
assert!(bars_1d_file.is_file());
|
||||
assert_eq!(fs::read(&bars_1d_file).unwrap(), b"sentinel");
|
||||
assert!(!out7.join("bars_1d/year=2024/part.parquet").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1d_cli_rejects_following_option_token_as_out_value_without_writing() {
|
||||
let dir = CliTempDir::new("missing-out-opt");
|
||||
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");
|
||||
|
||||
let res = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.current_dir(&dir.path)
|
||||
.args([
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_ok.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",
|
||||
"--rel-tolerence=0.01",
|
||||
])
|
||||
.output()
|
||||
.expect("spawn curate-etl binary");
|
||||
|
||||
assert!(!res.status.success());
|
||||
assert_eq!(res.status.code(), Some(1));
|
||||
assert!(stdout(&res).is_empty());
|
||||
let err = stderr(&res);
|
||||
assert!(err.contains("missing value for flag '--out'"), "{err}");
|
||||
assert!(err.contains("Usage:"), "{err}");
|
||||
assert!(
|
||||
!dir.path.join("--rel-tolerence=0.01").exists(),
|
||||
"must not create output directory named after following option token"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue