T-111: M1.2aa — tools/curate-etl: second runnable command curate-adj-factors (concatenated-BSON qmSplits + qmDividends files + provider_mapping TSV + curated bars_1d Parquet for prev_close → adj_factors/part.parquet) with end-to-end tests and local benchmark (no new crates, no MongoDB connection)
This commit is contained in:
parent
b2fe28b873
commit
0abddd14a0
9 changed files with 3008 additions and 6 deletions
|
|
@ -1083,3 +1083,63 @@ Measured locally (`2026-11-29`):
|
|||
- **`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`.
|
||||
- **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild.
|
||||
|
||||
## `curate-adj-factors` Command (`M1.2aa`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_adj.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a column-projected `bars_1d` Parquet reader for strict pre-ex-date `prev_close`, and `curate_and_write_adj_factors` into an atomically published `<out>/adj_factors/part.parquet` retrospective snapshot with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-adj-factors \
|
||||
--qm-splits <path> # concatenated raw BSON (mongodump qmSplits.bson)
|
||||
--qm-dividends <path> # concatenated raw BSON (mongodump qmDividends.bson)
|
||||
--provider-mapping <path> # headerless TSV (5 columns, same format as curate-bars-1d)
|
||||
--bars-1d <dir> # bars_1d directory containing year=YYYY/part.parquet (or parent root containing bars_1d/)
|
||||
--out <dir> # dataset root -> adj_factors/part.parquet
|
||||
```
|
||||
|
||||
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, or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, missing/invalid `--bars-1d` directory, missing/wrong-schema/corrupt `part.parquet`, duplicate `(listing_id, session_date)` in `bars_1d`, malformed `provider_mapping.tsv` reporting 1-based line number, truncated/oversized BSON stream, or cross-key split/dividend curation conflict) prints a single-line stderr message naming the offending path, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/adj_factors/part.parquet` byte-identical).
|
||||
|
||||
### `prev_close` Lookup & Contract Rules
|
||||
|
||||
- **Column-projected `bars_1d` reader:** validates every discovered `year=YYYY/part.parquet` against `bars_1d_parquet_schema()` and reads only 4 of the 12 columns (`listing_id`, `session_date`, `close`, `currency`) in bounded `65,536`-row batches into a compact in-RAM index (`16 bytes/bar`, currency strings interned to `u16`).
|
||||
- **Strict pre-ex-date boundary:** for each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable` and attaches the raw `close` and `currency` of the last `bars_1d` session strictly before `ex_date` (`session_date < ex_date`; a bar on `ex_date` itself is never used). When no earlier bar exists (or the dividend is unmapped), `prev_close` and `prev_close_currency` are `None`.
|
||||
- **`usdFxRate` & `splitratio == 1`:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op handling and cross-key collision rules stay delegated unchanged to `curate_and_write_adj_factors`. Per-document BSON decode rejects are counted without aborting the run.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-adj-factors` prints deterministic `key=value` lines to stdout (`bars_1d`, `splits_bson`, `dividends_bson`, `prev_close`, `builder`, `curate`, `write`, and `timing`):
|
||||
|
||||
- **Splits:** `splits_bson.docs_framed == splits_bson.docs_in == splits_bson.rejected + curate.splits_unmapped + curate.splits_fenced + curate.splits_coll_collapsed + builder.splits_in`
|
||||
- **Dividends:** `dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.rejected + curate.divs_unmapped + curate.divs_fenced + curate.divs_coll_collapsed + builder.dividends_in`
|
||||
- **Dividend `prev_close` partition:** `dividends_bson.decoded == prev_close.with_prev_close + prev_close.without_prev_close + curate.divs_unmapped`
|
||||
|
||||
### `bench-curate-adj-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv`, a 16-year `bars_1d` Parquet dataset (`2010..=2025`, `62,720` bars across `3,920` mapped listings), `qmSplits.bson` (~4% of events incl. `1:1` no-ops, unmapped, identical cross-key aliases, and ~0.5% malformed decode rejects), and `qmDividends.bson` (~96% of events incl. USD/CAD with bogus `usdFxRate: 1`, `cash == 0.0`, unmapped, identical cross-key aliases, pre-first-bar dates for missing `prev_close`, currency mismatches, and ~0.5% malformed decode rejects) into a temp dir, timing `bars_load` / `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd [events]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`):
|
||||
|
||||
1. **100,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd 100000`):
|
||||
- Input: `events=100000`, `splits_docs=4000` (`422,398 B`), `dividends_docs=96000` (`11,592,112 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000`
|
||||
- `bars_load`: `elapsed=3.69 ms`, `throughput=17006461 bars/s` (`listings=3920`)
|
||||
- `decode`: `elapsed=31.13 ms`, `throughput=3211920 events/s`, `scan=368.02 MB/s`, `splits_rejected=20`, `divs_rejected=453`, `with_prev_close=89914`, `without_prev_close=2792`
|
||||
- `curate`: `elapsed=36.62 ms`, `throughput=2717561 events/s`, `rows_out=88215` (`88.22%` retained), `listings_out=3920`, `checksum=0xdacf704be0642aff`
|
||||
- `write`: `elapsed=24.36 ms`, `throughput=3621493 rows/s`, `write=49.47 MB/s`, `files=1`, `row_groups=1`, `bytes=1263546`, `read_back_rows=88215`
|
||||
- `total`: `elapsed=95.80 ms`, `throughput=1043793 events/s`, `checksum=0xdacf704be0642aff`
|
||||
2. **500,000 events** (default; two back-to-back runs with identical checksum `0x16b8d07222f35849`): `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd`
|
||||
- Input: `events=500000`, `splits_docs=20000` (`2,112,208 B`), `dividends_docs=480000` (`57,960,382 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000`
|
||||
- Output: `rows_out=431459` (`86.29%` retained), `listings_out=3920`, `files=1`, `row_groups=1`, `bytes=5539481`, `read_back_rows=431459`
|
||||
- Run 1: `bars_load=3.76 ms` (`16,702,636 bars/s`), `decode=129.61 ms` (`3,857,829 events/s`, `442.03 MB/s`), `curate=283.10 ms` (`1,758,001 events/s`), `write=84.42 ms` (`5,111,126 rows/s`, `62.58 MB/s`), `total=500.88 ms` (`998,252 events/s`), `checksum=0x16b8d07222f35849`
|
||||
- Run 2: `bars_load=3.73 ms` (`16,832,966 bars/s`), `decode=125.40 ms` (`3,987,232 events/s`, `456.85 MB/s`), `curate=228.61 ms` (`2,177,036 events/s`), `write=79.17 ms` (`5,449,842 rows/s`, `66.73 MB/s`), `total=436.90 ms` (`1,144,419 events/s`), `checksum=0x16b8d07222f35849`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Retrospective snapshot only:** `curate-adj-factors` publishes an unfenced `AdjSnapshotKind::RetrospectiveSnapshot` whose earlier cumulative factors embed later splits/dividends. Point-in-time readers (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically; use `curate_and_write_adj_factors_as_of` when a point-in-time or vault-fenced snapshot is required.
|
||||
- **In-RAM `bars_1d` close index:** loading `bars_1d` into `PrevCloseIndex` takes `16 bytes/bar` (plus `Vec` growth slack, ~1.6–2.5 GiB for 100M bars).
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding or direct MongoDB/PostgreSQL connections yet.
|
||||
|
|
|
|||
|
|
@ -6801,6 +6801,643 @@ pub fn run_curate_adj_benchmark(
|
|||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS: usize = 500_000;
|
||||
const CURATE_ADJ_CMD_BENCH_SEED: u64 = 0x570C_4B07_C04A_AD1C;
|
||||
const CURATE_ADJ_CMD_BENCH_KEY_COUNT: usize = 4_000;
|
||||
|
||||
/// Errors returned by [`run_curate_adj_cmd_benchmark`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateAdjCmdBenchError {
|
||||
FixtureIo {
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
FixtureBars(ParquetBarsError),
|
||||
Run(crate::run_curate_adj::RunCurateAdjError),
|
||||
Verify(ParquetAdjError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CurateAdjCmdBenchError {
|
||||
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::FixtureBars(err) => write!(f, "fixture bars_1d write failed: {err}"),
|
||||
Self::Run(err) => write!(f, "{err}"),
|
||||
Self::Verify(err) => write!(f, "parquet verify failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CurateAdjCmdBenchError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::FixtureIo { source, .. } => Some(source),
|
||||
Self::FixtureBars(err) => Some(err),
|
||||
Self::Run(err) => Some(err),
|
||||
Self::Verify(err) => Some(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Metrics returned by [`run_curate_adj_cmd_benchmark`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateAdjCmdBenchReport {
|
||||
pub events: usize,
|
||||
pub key_count: usize,
|
||||
pub bars_files_read: usize,
|
||||
pub bars_rows_loaded: usize,
|
||||
pub bars_listings_indexed: usize,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub dividends_docs_framed: u64,
|
||||
pub dividends_bytes_read: u64,
|
||||
pub dividends_with_prev_close: usize,
|
||||
pub dividends_without_prev_close: usize,
|
||||
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 bars_load_elapsed_ms: f64,
|
||||
pub bars_load_rows_per_sec: f64,
|
||||
pub decode_elapsed_ms: f64,
|
||||
pub decode_events_per_sec: f64,
|
||||
pub input_mb_per_sec: f64,
|
||||
pub curate_elapsed_ms: f64,
|
||||
pub curate_events_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_events_per_sec: f64,
|
||||
pub checksum: u64,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub dividends_decode: BsonQmActionDecodeStats,
|
||||
pub curate_stats: crate::curate_adj::CurateAdjFactorsStats,
|
||||
}
|
||||
|
||||
fn run_curate_adj_cmd_benchmark_tracked(
|
||||
events: usize,
|
||||
) -> Result<(CurateAdjCmdBenchReport, PathBuf), CurateAdjCmdBenchError> {
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use crate::bson_eod_prices::MILLIS_PER_DAY;
|
||||
use crate::curate_bars::BARS_1D_SOURCE_EOD;
|
||||
use crate::run_curate_adj::{run_curate_adj_factors_timed, CurateAdjFactorsArgs};
|
||||
use crate::session_close::et_session_close_utc_micros;
|
||||
|
||||
const MIB: f64 = 1_048_576.0;
|
||||
|
||||
let temp = BenchTempDir::new_in_with_prefix(
|
||||
&std::env::temp_dir(),
|
||||
"curate-etl-bench-curate-adj-cmd",
|
||||
)
|
||||
.map_err(|(path, source)| CurateAdjCmdBenchError::FixtureIo { path, source })?;
|
||||
let temp_path = temp.path.clone();
|
||||
|
||||
let splits_path = temp.path.join("qmSplits.bson");
|
||||
let dividends_path = temp.path.join("qmDividends.bson");
|
||||
let mapping_path = temp.path.join("provider_mapping.tsv");
|
||||
let bars_root = temp.path.join("bars_root");
|
||||
let out_dir = temp.path.join("out");
|
||||
|
||||
fs::create_dir_all(&bars_root).map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: bars_root.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let key_count = CURATE_ADJ_CMD_BENCH_KEY_COUNT;
|
||||
|
||||
if events == 0 {
|
||||
for p in [&splits_path, ÷nds_path, &mapping_path] {
|
||||
File::create(p).map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: p.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
let args = CurateAdjFactorsArgs {
|
||||
qm_splits: splits_path,
|
||||
qm_dividends: dividends_path,
|
||||
provider_mapping: mapping_path,
|
||||
bars_1d_dir: bars_root,
|
||||
out_dir: out_dir.clone(),
|
||||
};
|
||||
let timed = run_curate_adj_factors_timed(&args).map_err(CurateAdjCmdBenchError::Run)?;
|
||||
let read_back_rows =
|
||||
verify_parquet_adj_row_count(&out_dir, timed.report.write_stats.rows_written)
|
||||
.map_err(CurateAdjCmdBenchError::Verify)?;
|
||||
let report = CurateAdjCmdBenchReport {
|
||||
events: 0,
|
||||
key_count,
|
||||
bars_files_read: timed.report.bars_files_read,
|
||||
bars_rows_loaded: timed.report.bars_rows_loaded,
|
||||
bars_listings_indexed: timed.report.bars_listings_indexed,
|
||||
splits_docs_framed: 0,
|
||||
splits_bytes_read: 0,
|
||||
dividends_docs_framed: 0,
|
||||
dividends_bytes_read: 0,
|
||||
dividends_with_prev_close: 0,
|
||||
dividends_without_prev_close: 0,
|
||||
rows_out: 0,
|
||||
listings_out: 0,
|
||||
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,
|
||||
bars_load_elapsed_ms: 0.0,
|
||||
bars_load_rows_per_sec: 0.0,
|
||||
decode_elapsed_ms: 0.0,
|
||||
decode_events_per_sec: 0.0,
|
||||
input_mb_per_sec: 0.0,
|
||||
curate_elapsed_ms: 0.0,
|
||||
curate_events_per_sec: 0.0,
|
||||
write_elapsed_ms: 0.0,
|
||||
write_rows_per_sec: 0.0,
|
||||
write_mb_per_sec: 0.0,
|
||||
total_elapsed_ms: 0.0,
|
||||
total_events_per_sec: 0.0,
|
||||
checksum: timed.checksum,
|
||||
splits_decode: timed.report.splits_decode,
|
||||
dividends_decode: timed.report.dividends_decode,
|
||||
curate_stats: timed.report.curate_stats,
|
||||
};
|
||||
drop(temp);
|
||||
return Ok((report, temp_path));
|
||||
}
|
||||
|
||||
let mapped_keys = key_count - (key_count / 50).max(1);
|
||||
let mut all_listings: Vec<i32> = Vec::with_capacity(mapped_keys + (mapped_keys / 50) + 1);
|
||||
|
||||
// 1. Write `provider_mapping.tsv`.
|
||||
{
|
||||
let mut map_w = BufWriter::with_capacity(
|
||||
256 * 1024,
|
||||
File::create(&mapping_path).map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
for k in 0..mapped_keys {
|
||||
let listing_id = (k + 1) as i32;
|
||||
let suffix = if listing_id % 4 == 0 { "TO" } else { "US" };
|
||||
let qm_code = format!("QM{k:05}:{suffix}");
|
||||
if k % 50 == 1 {
|
||||
let reuse_lid = (mapped_keys + k + 10) as i32;
|
||||
writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t2016-06-30\t{listing_id}").map_err(
|
||||
|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
writeln!(map_w, "qm\t{qm_code}\t2017-01-01\t\t{reuse_lid}").map_err(|source| {
|
||||
CurateAdjCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
all_listings.push(listing_id);
|
||||
all_listings.push(reuse_lid);
|
||||
} else if k % 50 == 2 {
|
||||
let base_lid = (k - 2 + 1) as i32;
|
||||
let alias_suffix = if base_lid % 4 == 0 { "TO" } else { "US" };
|
||||
let alias_qm_code = format!("QM{k:05}:{alias_suffix}");
|
||||
writeln!(map_w, "qm\t{alias_qm_code}\t1990-01-01\t\t{base_lid}").map_err(
|
||||
|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
} else {
|
||||
writeln!(map_w, "qm\t{qm_code}\t1990-01-01\t\t{listing_id}").map_err(|source| {
|
||||
CurateAdjCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
all_listings.push(listing_id);
|
||||
}
|
||||
}
|
||||
map_w
|
||||
.flush()
|
||||
.map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: mapping_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 2. Write a compact multi-year `bars_1d` Parquet dataset (16 yearly bars per listing, 2010..=2025).
|
||||
all_listings.sort_unstable();
|
||||
all_listings.dedup();
|
||||
let bar_dates: Vec<(i32, i64)> = (2010..=2025)
|
||||
.map(|year| {
|
||||
let mut d = ymd_to_epoch_days(year, 1, 15).expect("valid bar date");
|
||||
let dow = (d + 4).rem_euclid(7);
|
||||
if dow == 6 {
|
||||
d += 2;
|
||||
} else if dow == 0 {
|
||||
d += 1;
|
||||
}
|
||||
let ts = et_session_close_utc_micros(d).expect("valid bar ts");
|
||||
(d, ts)
|
||||
})
|
||||
.collect();
|
||||
{
|
||||
let mut bar_rows: Vec<Bars1dParquetRow> =
|
||||
Vec::with_capacity(all_listings.len() * bar_dates.len());
|
||||
for &lid in &all_listings {
|
||||
let curr: Cow<'static, str> = if lid % 4 == 0 {
|
||||
Cow::Borrowed("CAD")
|
||||
} else {
|
||||
Cow::Borrowed("USD")
|
||||
};
|
||||
let base_price = 30.0 + ((lid % 200) as f64);
|
||||
for (yi, &(session_date, ts_micros)) in bar_dates.iter().enumerate() {
|
||||
let close = base_price + (yi as f64) * 1.5;
|
||||
bar_rows.push(Bars1dParquetRow {
|
||||
listing_id: lid,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: close - 0.5,
|
||||
high: close + 1.0,
|
||||
low: close - 1.0,
|
||||
close,
|
||||
volume: 250_000.0,
|
||||
vwap: None,
|
||||
currency: curr.clone(),
|
||||
source: Cow::Borrowed(BARS_1D_SOURCE_EOD),
|
||||
known_at_micros: ts_micros,
|
||||
});
|
||||
}
|
||||
}
|
||||
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default())
|
||||
.map_err(CurateAdjCmdBenchError::FixtureBars)?;
|
||||
}
|
||||
|
||||
// Weekday pool strictly after 2010-01-18 so dividends have a valid `prev_close` in `bars_1d`.
|
||||
let main_days: Vec<i32> = build_weekday_pool(2010, 2025)
|
||||
.into_iter()
|
||||
.filter(|&d| d > bar_dates[0].0)
|
||||
.collect();
|
||||
let main_strs: Vec<String> = main_days.iter().copied().map(format_ymd_string).collect();
|
||||
let main_len = main_days.len();
|
||||
let stride = choose_coprime_stride(main_len, 19);
|
||||
|
||||
let qm_codes: Vec<String> = (0..mapped_keys)
|
||||
.map(|k| {
|
||||
let lid = if k % 50 == 2 {
|
||||
(k - 2 + 1) as i32
|
||||
} else {
|
||||
(k + 1) as i32
|
||||
};
|
||||
let suffix = if lid % 4 == 0 { "TO" } else { "US" };
|
||||
format!("QM{k:05}:{suffix}")
|
||||
})
|
||||
.collect();
|
||||
|
||||
let non_alias_keys: Vec<usize> = (0..mapped_keys)
|
||||
.filter(|&k| k % 50 != 0 && k % 50 != 2)
|
||||
.collect();
|
||||
let alias_base_keys: Vec<usize> = (0..mapped_keys)
|
||||
.filter(|&k| k % 50 == 0 && k + 2 < mapped_keys)
|
||||
.collect();
|
||||
|
||||
let mut alias_split_cursors: Vec<usize> = (0..alias_base_keys.len())
|
||||
.map(|idx| (idx * 11) % main_len)
|
||||
.collect();
|
||||
let mut alias_div_cursors: Vec<usize> = (0..alias_base_keys.len())
|
||||
.map(|idx| (idx * 23 + 7) % main_len)
|
||||
.collect();
|
||||
|
||||
let mut rng = SplitMix64::new(CURATE_ADJ_CMD_BENCH_SEED);
|
||||
let split_target = (events * 4) / 100;
|
||||
let div_target = events - split_target;
|
||||
|
||||
// 3. Stream-write `qmSplits.bson`.
|
||||
{
|
||||
const RATIOS: [f64; 6] = [2.0, 3.0, 4.0, 10.0, 0.5, 0.25];
|
||||
let mut splits_w = BufWriter::with_capacity(
|
||||
256 * 1024,
|
||||
File::create(&splits_path).map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
let mut pending_alias: Option<(usize, usize, f64)> = None;
|
||||
for i in 0..split_target {
|
||||
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));
|
||||
|
||||
if let Some((alias_k, date_idx, ratio)) = pending_alias.take() {
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[alias_k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 5 {
|
||||
// Malformed date -> decode reject.
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[0].as_str());
|
||||
doc.append(cstr!("date"), "2023-02-29");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
} else if roll < 55 {
|
||||
// 1:1 no-op split.
|
||||
let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()];
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("splitratio"), 1.0_f64);
|
||||
} else if roll < 85 {
|
||||
// Unmapped QM code.
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
doc.append(cstr!("qmSearchCode"), "QM_UNMAP:US");
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
} else if roll < 185 && i + 1 < split_target && !alias_base_keys.is_empty() {
|
||||
let slot = (rng.next_u64() as usize) % alias_base_keys.len();
|
||||
let base_k = alias_base_keys[slot];
|
||||
let date_idx = alias_split_cursors[slot];
|
||||
alias_split_cursors[slot] = (date_idx + stride) % main_len;
|
||||
let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()];
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[base_k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
pending_alias = Some((base_k + 2, date_idx, ratio));
|
||||
} else {
|
||||
let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()];
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
let ratio = RATIOS[(rng.next_u64() as usize) % RATIOS.len()];
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
if i % 20 == 0 {
|
||||
doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(main_days[date_idx]) * MILLIS_PER_DAY),
|
||||
);
|
||||
} else {
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
}
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
}
|
||||
}
|
||||
|
||||
splits_w
|
||||
.write_all(doc.as_bytes())
|
||||
.map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
splits_w
|
||||
.flush()
|
||||
.map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 4. Stream-write `qmDividends.bson`.
|
||||
{
|
||||
let mut divs_w = BufWriter::with_capacity(
|
||||
512 * 1024,
|
||||
File::create(÷nds_path).map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: dividends_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
let mut pending_alias: Option<(usize, usize, f64, &'static str)> = None;
|
||||
for i in 0..div_target {
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
oid_bytes[0] = 2;
|
||||
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));
|
||||
|
||||
if let Some((alias_k, date_idx, cash, curr)) = pending_alias.take() {
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[alias_k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), curr);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else {
|
||||
let roll = rng.next_u64() % 1_000;
|
||||
if roll < 5 {
|
||||
// Malformed date or negative amount -> decode reject.
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[0].as_str());
|
||||
if i % 2 == 0 {
|
||||
doc.append(cstr!("date"), "2023-02-29");
|
||||
doc.append(cstr!("amount"), 0.25_f64);
|
||||
} else {
|
||||
doc.append(cstr!("date"), "2023-06-15");
|
||||
doc.append(cstr!("amount"), -0.25_f64);
|
||||
}
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else if roll < 20 {
|
||||
// Zero cash dividend.
|
||||
let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()];
|
||||
let lid = (k + 1) as i32;
|
||||
let curr = if lid % 4 == 0 { "CAD" } else { "USD" };
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("amount"), 0.0_f64);
|
||||
doc.append(cstr!("currency"), curr);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else if roll < 50 {
|
||||
// Unmapped dividend.
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
doc.append(cstr!("qmSearchCode"), "QM_UNMAP:US");
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("amount"), 0.50_f64);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else if roll < 80 {
|
||||
// Pre-first-bar date -> mapped but missing `prev_close`.
|
||||
let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()];
|
||||
let lid = (k + 1) as i32;
|
||||
let curr = if lid % 4 == 0 { "CAD" } else { "USD" };
|
||||
let cash = (5 + (rng.next_u64() % 150)) as f64 / 100.0;
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
doc.append(cstr!("date"), "2009-06-15");
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), curr);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else if roll < 100 {
|
||||
// Dedicated mismatch keys (`k % 50 == 3`) always emit the opposite currency
|
||||
// of their `bars_1d` bars so no single listing ever gets two conflicting
|
||||
// dividend currencies on the same `ex_date`.
|
||||
let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()];
|
||||
let lid = (k + 1) as i32;
|
||||
let curr = if k % 50 == 3 {
|
||||
if lid % 4 == 0 { "USD" } else { "CAD" }
|
||||
} else if lid % 4 == 0 {
|
||||
"CAD"
|
||||
} else {
|
||||
"USD"
|
||||
};
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
let cash = (5 + (rng.next_u64() % 150)) as f64 / 100.0;
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), curr);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
} else if roll < 160 && i + 1 < div_target && !alias_base_keys.is_empty() {
|
||||
let slot = (rng.next_u64() as usize) % alias_base_keys.len();
|
||||
let base_k = alias_base_keys[slot];
|
||||
let base_lid = (base_k + 1) as i32;
|
||||
let curr = if base_lid % 4 == 0 { "CAD" } else { "USD" };
|
||||
let date_idx = alias_div_cursors[slot];
|
||||
alias_div_cursors[slot] = (date_idx + stride) % main_len;
|
||||
let cash = (10 + (rng.next_u64() % 200)) as f64 / 100.0;
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[base_k].as_str());
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), curr);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
pending_alias = Some((base_k + 2, date_idx, cash, curr));
|
||||
} else {
|
||||
let k = non_alias_keys[(rng.next_u64() as usize) % non_alias_keys.len()];
|
||||
let lid = (k + 1) as i32;
|
||||
let curr = if k % 50 == 3 {
|
||||
if lid % 4 == 0 { "USD" } else { "CAD" }
|
||||
} else if lid % 4 == 0 {
|
||||
"CAD"
|
||||
} else {
|
||||
"USD"
|
||||
};
|
||||
let date_idx = (rng.next_u64() as usize) % main_len;
|
||||
let cash = (5 + (rng.next_u64() % 250)) as f64 / 100.0;
|
||||
doc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
if i % 20 == 0 {
|
||||
doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(main_days[date_idx]) * MILLIS_PER_DAY),
|
||||
);
|
||||
} else {
|
||||
doc.append(cstr!("date"), main_strs[date_idx].as_str());
|
||||
}
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), curr);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
}
|
||||
}
|
||||
|
||||
divs_w
|
||||
.write_all(doc.as_bytes())
|
||||
.map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: dividends_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
divs_w
|
||||
.flush()
|
||||
.map_err(|source| CurateAdjCmdBenchError::FixtureIo {
|
||||
path: dividends_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 5. Run stage-timed end-to-end command and verify Parquet footer row count.
|
||||
let args = CurateAdjFactorsArgs {
|
||||
qm_splits: splits_path,
|
||||
qm_dividends: dividends_path,
|
||||
provider_mapping: mapping_path,
|
||||
bars_1d_dir: bars_root.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
};
|
||||
let timed = run_curate_adj_factors_timed(&args).map_err(CurateAdjCmdBenchError::Run)?;
|
||||
let read_back_rows =
|
||||
verify_parquet_adj_row_count(&out_dir, timed.report.write_stats.rows_written)
|
||||
.map_err(CurateAdjCmdBenchError::Verify)?;
|
||||
|
||||
let bars_load_elapsed_ms = timed.bars_load_elapsed_secs * 1_000.0;
|
||||
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.bars_load_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 (bars_load_rows_per_sec, _) =
|
||||
compute_rates(timed.report.bars_rows_loaded, timed.bars_load_elapsed_secs);
|
||||
let (decode_events_per_sec, _) = compute_rates(events, timed.decode_elapsed_secs);
|
||||
let decoded_events = timed.report.curate_stats.splits_in + timed.report.curate_stats.dividends_in;
|
||||
let (curate_events_per_sec, _) = compute_rates(decoded_events, timed.curate_elapsed_secs);
|
||||
let (write_rows_per_sec, _) =
|
||||
compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs);
|
||||
let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs);
|
||||
|
||||
let total_input_bytes = timed.report.splits_bytes_read + timed.report.dividends_bytes_read;
|
||||
let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 {
|
||||
(total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 {
|
||||
(timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let report = CurateAdjCmdBenchReport {
|
||||
events,
|
||||
key_count,
|
||||
bars_files_read: timed.report.bars_files_read,
|
||||
bars_rows_loaded: timed.report.bars_rows_loaded,
|
||||
bars_listings_indexed: timed.report.bars_listings_indexed,
|
||||
splits_docs_framed: timed.report.splits_docs_framed,
|
||||
splits_bytes_read: timed.report.splits_bytes_read,
|
||||
dividends_docs_framed: timed.report.dividends_docs_framed,
|
||||
dividends_bytes_read: timed.report.dividends_bytes_read,
|
||||
dividends_with_prev_close: timed.report.dividends_with_prev_close,
|
||||
dividends_without_prev_close: timed.report.dividends_without_prev_close,
|
||||
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,
|
||||
bars_load_elapsed_ms,
|
||||
bars_load_rows_per_sec,
|
||||
decode_elapsed_ms,
|
||||
decode_events_per_sec,
|
||||
input_mb_per_sec,
|
||||
curate_elapsed_ms,
|
||||
curate_events_per_sec,
|
||||
write_elapsed_ms,
|
||||
write_rows_per_sec,
|
||||
write_mb_per_sec,
|
||||
total_elapsed_ms,
|
||||
total_events_per_sec,
|
||||
checksum: timed.checksum,
|
||||
splits_decode: timed.report.splits_decode,
|
||||
dividends_decode: timed.report.dividends_decode,
|
||||
curate_stats: timed.report.curate_stats,
|
||||
};
|
||||
|
||||
drop(temp);
|
||||
Ok((report, temp_path))
|
||||
}
|
||||
|
||||
/// Runs the fixed-seed end-to-end `curate-adj-factors` file -> Parquet benchmark for `events`
|
||||
/// synthetic `qmSplits` (~4%) and `qmDividends` (~96%) BSON documents with a multi-year `bars_1d`
|
||||
/// Parquet dataset.
|
||||
pub fn run_curate_adj_cmd_benchmark(
|
||||
events: usize,
|
||||
) -> Result<CurateAdjCmdBenchReport, CurateAdjCmdBenchError> {
|
||||
let (report, _) = run_curate_adj_cmd_benchmark_tracked(events)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub const DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 520_000;
|
||||
const CURATE_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C04A_AC72;
|
||||
const CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT: usize = 20_000;
|
||||
|
|
@ -8921,4 +9558,72 @@ mod tests {
|
|||
assert!(report.curate_stats.listing_collision_dropped > 0);
|
||||
assert!(report.curate_stats.dropped_missing_currency > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_adj_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() {
|
||||
let (a, dir_a) = run_curate_adj_cmd_benchmark_tracked(5_000).unwrap();
|
||||
let (b, dir_b) = run_curate_adj_cmd_benchmark_tracked(5_000).unwrap();
|
||||
|
||||
assert!(
|
||||
!dir_a.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_a.display()
|
||||
);
|
||||
assert!(
|
||||
!dir_b.exists(),
|
||||
"temp dir {} should be removed",
|
||||
dir_b.display()
|
||||
);
|
||||
assert_eq!(a.events, 5_000);
|
||||
assert_eq!(a.splits_docs_framed + a.dividends_docs_framed, 5_000);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_ne!(a.checksum, 0);
|
||||
assert_eq!(a.rows_out, b.rows_out);
|
||||
assert_eq!(a.read_back_rows, a.rows_out);
|
||||
assert_eq!(a.bytes_written, b.bytes_written);
|
||||
assert!(a.bars_files_read >= 16);
|
||||
assert!(a.bars_rows_loaded > 0);
|
||||
assert!(a.dividends_with_prev_close > 0);
|
||||
assert!(a.dividends_without_prev_close > 0);
|
||||
assert!(a.curate_stats.splits_dropped_unmapped > 0);
|
||||
assert!(a.curate_stats.dividends_dropped_unmapped > 0);
|
||||
assert!(a.curate_stats.splits_collision_collapsed > 0);
|
||||
assert!(a.curate_stats.dividends_collision_collapsed > 0);
|
||||
assert!(a.curate_stats.builder.split_noops_dropped > 0);
|
||||
assert!(a.curate_stats.builder.dividend_zero_cash_dropped > 0);
|
||||
assert!(a.curate_stats.builder.dividends_currency_mismatch > 0);
|
||||
assert_eq!(
|
||||
a.splits_docs_framed as usize,
|
||||
a.splits_decode.rejected_total()
|
||||
+ a.curate_stats.splits_dropped_unmapped
|
||||
+ a.curate_stats.splits_dropped_fenced
|
||||
+ a.curate_stats.splits_collision_collapsed
|
||||
+ a.curate_stats.builder.split_events_in
|
||||
);
|
||||
assert_eq!(
|
||||
a.dividends_docs_framed as usize,
|
||||
a.dividends_decode.rejected_total()
|
||||
+ a.curate_stats.dividends_dropped_unmapped
|
||||
+ a.curate_stats.dividends_dropped_fenced
|
||||
+ a.curate_stats.dividends_collision_collapsed
|
||||
+ a.curate_stats.builder.dividend_events_in
|
||||
);
|
||||
assert_eq!(
|
||||
a.dividends_decode.decoded,
|
||||
a.dividends_with_prev_close
|
||||
+ a.dividends_without_prev_close
|
||||
+ a.curate_stats.dividends_dropped_unmapped
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_adj_cmd_benchmark_zero_events_handles_cleanly() {
|
||||
let (report, dir) = run_curate_adj_cmd_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.events, 0);
|
||||
assert_eq!(report.rows_out, 0);
|
||||
assert_eq!(report.read_back_rows, 0);
|
||||
assert_eq!(report.splits_docs_framed, 0);
|
||||
assert_eq!(report.dividends_docs_framed, 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,15 +9,16 @@ 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_BARS_CMD_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_BARS_CMD_BENCH_ROWS,
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, 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_adj::CurateAdjFactorsArgs;
|
||||
use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE};
|
||||
|
||||
/// Parsed CLI command to execute.
|
||||
|
|
@ -26,6 +27,7 @@ pub enum CliAction {
|
|||
Help,
|
||||
Version,
|
||||
CurateBars1d(CurateBars1dArgs),
|
||||
CurateAdjFactors(CurateAdjFactorsArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
|
|
@ -49,6 +51,7 @@ pub enum CliAction {
|
|||
BenchCurateEvents(usize),
|
||||
BenchCurateFx(usize),
|
||||
BenchCurateAdj(usize),
|
||||
BenchCurateAdjCmd(usize),
|
||||
BenchCurateCorporateActions(usize),
|
||||
}
|
||||
|
||||
|
|
@ -62,6 +65,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{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} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
Curate retrospective adj_factors from BSON + TSV + bars_1d Parquet into adj_factors/part.parquet\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\
|
||||
|
|
@ -85,6 +90,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
|
||||
{name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-curate-adj-cmd [events] Run fixed-seed end-to-end curate-adj-factors file->Parquet benchmark (default: {DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS})\n\
|
||||
{name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})"
|
||||
)
|
||||
}
|
||||
|
|
@ -96,6 +102,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{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} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
{name} bench-corporate-actions [events]\n\
|
||||
|
|
@ -119,6 +126,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-curate-events [rows]\n\
|
||||
{name} bench-curate-fx [rows]\n\
|
||||
{name} bench-curate-adj [events]\n\
|
||||
{name} bench-curate-adj-cmd [events]\n\
|
||||
{name} bench-curate-corporate-actions [events]"
|
||||
)
|
||||
}
|
||||
|
|
@ -213,6 +221,74 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
|
|||
})
|
||||
}
|
||||
|
||||
fn parse_curate_adj_factors_args(args: &[&str]) -> Result<CurateAdjFactorsArgs, String> {
|
||||
let mut qm_splits: Option<PathBuf> = None;
|
||||
let mut qm_dividends: Option<PathBuf> = None;
|
||||
let mut provider_mapping: Option<PathBuf> = None;
|
||||
let mut bars_1d_dir: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let token = args[i];
|
||||
if !token.starts_with("--") {
|
||||
return Err(format!(
|
||||
"unexpected positional argument '{token}' for curate-adj-factors"
|
||||
));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(k, v)
|
||||
} else {
|
||||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
||||
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate flag '{flag_name}'"));
|
||||
}
|
||||
if raw.is_empty() {
|
||||
return Err(format!("empty value for flag '{flag_name}'"));
|
||||
}
|
||||
*slot = Some(PathBuf::from(raw));
|
||||
Ok(())
|
||||
};
|
||||
|
||||
match flag {
|
||||
"--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?,
|
||||
"--qm-dividends" => set_path(&mut qm_dividends, "--qm-dividends", value)?,
|
||||
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
|
||||
"--bars-1d" => set_path(&mut bars_1d_dir, "--bars-1d", value)?,
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
other => return Err(format!("unknown flag '{other}' for curate-adj-factors")),
|
||||
}
|
||||
}
|
||||
|
||||
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
|
||||
let qm_dividends =
|
||||
qm_dividends.ok_or_else(|| "missing required flag '--qm-dividends'".to_string())?;
|
||||
let provider_mapping =
|
||||
provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let bars_1d_dir = bars_1d_dir.ok_or_else(|| "missing required flag '--bars-1d'".to_string())?;
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
|
||||
Ok(CurateAdjFactorsArgs {
|
||||
qm_splits,
|
||||
qm_dividends,
|
||||
provider_mapping,
|
||||
bars_1d_dir,
|
||||
out_dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`].
|
||||
pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
let slices: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
|
|
@ -225,6 +301,9 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["curate-bars-1d", rest @ ..] => {
|
||||
parse_curate_bars_1d_args(rest).map(CliAction::CurateBars1d)
|
||||
}
|
||||
["curate-adj-factors", rest @ ..] => {
|
||||
parse_curate_adj_factors_args(rest).map(CliAction::CurateAdjFactors)
|
||||
}
|
||||
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||
["bench-split", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),
|
||||
|
|
@ -461,6 +540,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-curate-adj", _, ..] => Err("too many arguments for bench-curate-adj".to_string()),
|
||||
["bench-curate-adj-cmd"] => Ok(CliAction::BenchCurateAdjCmd(
|
||||
DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS,
|
||||
)),
|
||||
["bench-curate-adj-cmd", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdjCmd(n)),
|
||||
_ => Err(format!(
|
||||
"invalid event count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-adj-cmd", _, ..] => {
|
||||
Err("too many arguments for bench-curate-adj-cmd".to_string())
|
||||
}
|
||||
["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions(
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
)),
|
||||
|
|
@ -815,12 +906,14 @@ mod tests {
|
|||
assert!(full.contains("bench-bson-qm-actions"));
|
||||
assert!(full.contains("bench-bson-stream"));
|
||||
assert!(full.contains("curate-bars-1d"));
|
||||
assert!(full.contains("curate-adj-factors"));
|
||||
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"));
|
||||
assert!(full.contains("bench-curate-adj"));
|
||||
assert!(full.contains("bench-curate-adj-cmd"));
|
||||
assert!(full.contains("bench-curate-corporate-actions"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
|
|
@ -842,12 +935,14 @@ mod tests {
|
|||
assert!(short.contains("bench-bson-qm-actions"));
|
||||
assert!(short.contains("bench-bson-stream"));
|
||||
assert!(short.contains("curate-bars-1d"));
|
||||
assert!(short.contains("curate-adj-factors"));
|
||||
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"));
|
||||
assert!(short.contains("bench-curate-adj"));
|
||||
assert!(short.contains("bench-curate-adj-cmd"));
|
||||
assert!(short.contains("bench-curate-corporate-actions"));
|
||||
}
|
||||
|
||||
|
|
@ -1112,4 +1207,151 @@ mod tests {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_adj_cmd_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-adj-cmd"])),
|
||||
Ok(CliAction::BenchCurateAdjCmd(
|
||||
DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-adj-cmd", "5000"])),
|
||||
Ok(CliAction::BenchCurateAdjCmd(5_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj-cmd", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_valid_curate_adj_factors_args() {
|
||||
let parsed = parse_args(&to_args(&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
"/tmp/qmSplits.bson",
|
||||
"--qm-dividends",
|
||||
"/tmp/qmDividends.bson",
|
||||
"--provider-mapping",
|
||||
"/tmp/provider_mapping.tsv",
|
||||
"--bars-1d",
|
||||
"/tmp/bars_1d",
|
||||
"--out",
|
||||
"/tmp/out",
|
||||
]))
|
||||
.expect("valid curate-adj-factors args");
|
||||
assert_eq!(
|
||||
parsed,
|
||||
CliAction::CurateAdjFactors(CurateAdjFactorsArgs {
|
||||
qm_splits: PathBuf::from("/tmp/qmSplits.bson"),
|
||||
qm_dividends: PathBuf::from("/tmp/qmDividends.bson"),
|
||||
provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"),
|
||||
bars_1d_dir: PathBuf::from("/tmp/bars_1d"),
|
||||
out_dir: PathBuf::from("/tmp/out"),
|
||||
})
|
||||
);
|
||||
|
||||
let equals_style = parse_args(&to_args(&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits=/tmp/s.bson",
|
||||
"--qm-dividends=/tmp/d.bson",
|
||||
"--provider-mapping=/tmp/m.tsv",
|
||||
"--bars-1d=/tmp/bars",
|
||||
"--out=--literal-out-dir",
|
||||
]))
|
||||
.expect("equals-style curate-adj-factors args");
|
||||
assert_eq!(
|
||||
equals_style,
|
||||
CliAction::CurateAdjFactors(CurateAdjFactorsArgs {
|
||||
qm_splits: PathBuf::from("/tmp/s.bson"),
|
||||
qm_dividends: PathBuf::from("/tmp/d.bson"),
|
||||
provider_mapping: PathBuf::from("/tmp/m.tsv"),
|
||||
bars_1d_dir: PathBuf::from("/tmp/bars"),
|
||||
out_dir: PathBuf::from("--literal-out-dir"),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_curate_adj_factors_flags() {
|
||||
let full = [
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--qm-dividends",
|
||||
"d.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--bars-1d",
|
||||
"bars",
|
||||
"--out",
|
||||
"out",
|
||||
];
|
||||
|
||||
for (drop_idx, expected_flag) in [
|
||||
(1, "--qm-splits"),
|
||||
(3, "--qm-dividends"),
|
||||
(5, "--provider-mapping"),
|
||||
(7, "--bars-1d"),
|
||||
(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 flag.
|
||||
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 at end.
|
||||
let err = parse_args(&to_args(&["curate-adj-factors", "--out"])).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--out'"), "{err}");
|
||||
|
||||
// Separated flag followed immediately by another `--` token.
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--qm-dividends",
|
||||
"d.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--bars-1d",
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--bars-1d'"), "{err}");
|
||||
|
||||
// Empty 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 arg.
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1176,7 +1176,7 @@ fn build_snapshot_key_value_metadata(
|
|||
]
|
||||
}
|
||||
|
||||
fn write_adj_factors_snapshot_parquet(
|
||||
pub(crate) fn write_adj_factors_snapshot_parquet(
|
||||
out_dir: &Path,
|
||||
rows: &[AdjFactorsParquetRow],
|
||||
snapshot_kind: AdjSnapshotKind,
|
||||
|
|
|
|||
|
|
@ -158,3 +158,9 @@ pub use run_curate_bars::{
|
|||
run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport, RunCurateBarsError,
|
||||
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_adj;
|
||||
pub use run_curate_adj::{
|
||||
format_curate_adj_report, run_curate_adj_factors, CurateAdjFactorsArgs,
|
||||
CurateAdjFactorsRunReport, RunCurateAdjError,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ 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_bars_cmd_benchmark,
|
||||
run_curate_corporate_actions_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark,
|
||||
run_curate_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,
|
||||
|
|
@ -15,6 +15,7 @@ use curate_etl::bench::{
|
|||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
use curate_etl::run_curate_adj::{format_curate_adj_report, run_curate_adj_factors};
|
||||
use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d};
|
||||
|
||||
const NAME: &str = env!("CARGO_PKG_NAME");
|
||||
|
|
@ -42,6 +43,18 @@ fn main() -> ExitCode {
|
|||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateAdjFactors(curate_args)) => {
|
||||
match run_curate_adj_factors(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_adj_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,
|
||||
|
|
@ -977,6 +990,82 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateAdjCmd(events)) => {
|
||||
let report = match run_curate_adj_cmd_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-adj-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-adj-cmd");
|
||||
println!(
|
||||
" input: events={} splits_docs={} splits_bytes={} dividends_docs={} dividends_bytes={} bars_files={} bars_rows={} keys={}",
|
||||
report.events,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.dividends_docs_framed,
|
||||
report.dividends_bytes_read,
|
||||
report.bars_files_read,
|
||||
report.bars_rows_loaded,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" bars_load: elapsed={:.2} ms throughput={:.0} bars/s files={} rows={} listings={}",
|
||||
report.bars_load_elapsed_ms,
|
||||
report.bars_load_rows_per_sec,
|
||||
report.bars_files_read,
|
||||
report.bars_rows_loaded,
|
||||
report.bars_listings_indexed
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} events/s scan={:.2} MB/s splits_rejected={} divs_rejected={} with_prev_close={} without_prev_close={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_events_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.splits_decode.rejected_total(),
|
||||
report.dividends_decode.rejected_total(),
|
||||
report.dividends_with_prev_close,
|
||||
report.dividends_without_prev_close
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} events/s rows_out={} ({:.2}% retained) listings_out={} splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} split_noops={} zero_div={} missing_prev_close={} curr_mismatch={} checksum=0x{:016x}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_events_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.curate_stats.splits_dropped_unmapped,
|
||||
report.curate_stats.dividends_dropped_unmapped,
|
||||
report.curate_stats.splits_collision_collapsed,
|
||||
report.curate_stats.dividends_collision_collapsed,
|
||||
report.curate_stats.builder.split_noops_dropped,
|
||||
report.curate_stats.builder.dividend_zero_cash_dropped,
|
||||
report.curate_stats.builder.dividends_missing_prev_close,
|
||||
report.curate_stats.builder.dividends_currency_mismatch,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s checksum=0x{:016x}",
|
||||
report.total_elapsed_ms, report.total_events_per_sec, report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateCorporateActions(events)) => {
|
||||
let report = match run_curate_corporate_actions_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
991
tools/curate-etl/src/run_curate_adj.rs
Normal file
991
tools/curate-etl/src/run_curate_adj.rs
Normal file
|
|
@ -0,0 +1,991 @@
|
|||
//! File-to-file `curate-adj-factors` command runner (`M1.2aa`).
|
||||
//!
|
||||
//! Streams concatenated raw BSON `qmSplits` and `qmDividends` dump files alongside
|
||||
//! `provider_mapping.tsv` and a curated `bars_1d/year=YYYY/part.parquet` dataset into an
|
||||
//! atomically published retrospective `<out_dir>/adj_factors/part.parquet` snapshot via
|
||||
//! [`curate_and_write_adj_factors`].
|
||||
//!
|
||||
//! # `prev_close` Information Boundary
|
||||
//! - Loads only 4 of the 12 `bars_1d` columns (`listing_id`, `session_date`, `close`, `currency`)
|
||||
//! in bounded `65_536`-row batches into a compact in-RAM [`PrevCloseIndex`] (`16 bytes/bar`,
|
||||
//! currency strings interned to `u16`).
|
||||
//! - For each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date)` via
|
||||
//! [`ProviderMappingTable`]. When mapped, attaches the raw `close` and `currency` of the last
|
||||
//! `bars_1d` session **strictly before** `ex_date` (`session_date < ex_date`); a bar on
|
||||
//! `ex_date` itself is never used. When no earlier bar exists (or the dividend is unmapped),
|
||||
//! `prev_close` and `prev_close_currency` are `None`.
|
||||
//! - `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op
|
||||
//! handling stays delegated unchanged to [`curate_and_write_adj_factors`].
|
||||
//!
|
||||
//! # Counter Conservation Invariants
|
||||
//! Every successful [`CurateAdjFactorsRunReport`] satisfies:
|
||||
//! - Splits:
|
||||
//! `splits_docs_framed as usize == splits_decode.docs_in`
|
||||
//! `splits_decode.docs_in == splits_decode.rejected_total() + curate_stats.splits_dropped_unmapped + curate_stats.splits_dropped_fenced + curate_stats.splits_collision_collapsed + curate_stats.builder.split_events_in`
|
||||
//! - Dividends:
|
||||
//! `dividends_docs_framed as usize == dividends_decode.docs_in`
|
||||
//! `dividends_decode.docs_in == dividends_decode.rejected_total() + curate_stats.dividends_dropped_unmapped + curate_stats.dividends_dropped_fenced + curate_stats.dividends_collision_collapsed + curate_stats.builder.dividend_events_in`
|
||||
//! `dividends_decode.decoded == dividends_with_prev_close + dividends_without_prev_close + curate_stats.dividends_dropped_unmapped`
|
||||
//!
|
||||
//! # Retrospective Snapshot Caveat
|
||||
//! `curate-adj-factors` publishes an unfenced [`crate::curate_adj::AdjSnapshotKind::RetrospectiveSnapshot`]
|
||||
//! whose earlier cumulative factors embed later splits/dividends. Point-in-time readers
|
||||
//! (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use parquet::column::reader::ColumnReader;
|
||||
use parquet::data_type::ByteArray;
|
||||
use parquet::errors::ParquetError;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
use crate::adj::DividendEvent;
|
||||
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
||||
use crate::bson_stream::{
|
||||
decode_qm_dividend_chunks, decode_qm_split_chunks, BsonStreamError, BsonStreamOptions,
|
||||
RawBsonChunkReader,
|
||||
};
|
||||
use crate::curate_adj::{
|
||||
curate_adj_factors, curate_and_write_adj_factors, write_adj_factors_snapshot_parquet,
|
||||
CurateAdjFactorsStats, CurateAdjWriteError,
|
||||
};
|
||||
use crate::parquet_adj::{AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats};
|
||||
use crate::parquet_bars::bars_1d_parquet_schema;
|
||||
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
|
||||
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
||||
use crate::split::SplitEvent;
|
||||
|
||||
/// Bounded per-batch row count for column-projected `bars_1d` Parquet reads.
|
||||
const BARS_READ_BATCH_ROWS: usize = 65_536;
|
||||
|
||||
/// Column indices in [`bars_1d_parquet_schema`].
|
||||
const COL_BARS_LISTING_ID: usize = 0;
|
||||
const COL_BARS_SESSION_DATE: usize = 2;
|
||||
const COL_BARS_CLOSE: usize = 6;
|
||||
const COL_BARS_CURRENCY: usize = 9;
|
||||
|
||||
/// Parsed arguments for the `curate-adj-factors` CLI command.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateAdjFactorsArgs {
|
||||
pub qm_splits: PathBuf,
|
||||
pub qm_dividends: PathBuf,
|
||||
pub provider_mapping: PathBuf,
|
||||
pub bars_1d_dir: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_adj_factors`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `splits_docs_framed as usize == splits_decode.docs_in == splits_decode.rejected_total() + curate_stats.splits_dropped_unmapped + curate_stats.splits_dropped_fenced + curate_stats.splits_collision_collapsed + curate_stats.builder.split_events_in`
|
||||
/// - `dividends_docs_framed as usize == dividends_decode.docs_in == dividends_decode.rejected_total() + curate_stats.dividends_dropped_unmapped + curate_stats.dividends_dropped_fenced + curate_stats.dividends_collision_collapsed + curate_stats.builder.dividend_events_in`
|
||||
/// - `dividends_decode.decoded == dividends_with_prev_close + dividends_without_prev_close + curate_stats.dividends_dropped_unmapped`
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateAdjFactorsRunReport {
|
||||
pub bars_files_read: usize,
|
||||
pub bars_rows_loaded: usize,
|
||||
pub bars_listings_indexed: usize,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub dividends_docs_framed: u64,
|
||||
pub dividends_bytes_read: u64,
|
||||
pub dividends_decode: BsonQmActionDecodeStats,
|
||||
pub dividends_with_prev_close: usize,
|
||||
pub dividends_without_prev_close: usize,
|
||||
pub curate_stats: CurateAdjFactorsStats,
|
||||
pub write_stats: AdjFactorsWriteStats,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Stage-timed run output used internally by `bench-curate-adj-cmd`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct CurateAdjFactorsTimedRun {
|
||||
pub report: CurateAdjFactorsRunReport,
|
||||
pub bars_load_elapsed_secs: f64,
|
||||
pub decode_elapsed_secs: f64,
|
||||
pub curate_elapsed_secs: f64,
|
||||
pub write_elapsed_secs: f64,
|
||||
pub checksum: u64,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`run_curate_adj_factors`].
|
||||
///
|
||||
/// 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 RunCurateAdjError {
|
||||
InvalidOutDir {
|
||||
path: PathBuf,
|
||||
detail: String,
|
||||
},
|
||||
InvalidBars1dDir {
|
||||
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,
|
||||
},
|
||||
BarsParquetSchemaMismatch {
|
||||
path: PathBuf,
|
||||
},
|
||||
BarsParquetRead {
|
||||
path: PathBuf,
|
||||
source: ParquetError,
|
||||
},
|
||||
BarsParquetIntegrity {
|
||||
path: PathBuf,
|
||||
detail: String,
|
||||
},
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
CurateWrite {
|
||||
out_dir: PathBuf,
|
||||
source: CurateAdjWriteError,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateAdjError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidOutDir { path, detail } => {
|
||||
write!(f, "invalid --out '{}': {detail}", path.display())
|
||||
}
|
||||
Self::InvalidBars1dDir { path, detail } => {
|
||||
write!(f, "invalid --bars-1d '{}': {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::BarsParquetSchemaMismatch { path } => {
|
||||
write!(f, "bars_1d Parquet schema mismatch at '{}'", path.display())
|
||||
}
|
||||
Self::BarsParquetRead { path, source } => {
|
||||
write!(
|
||||
f,
|
||||
"failed reading bars_1d Parquet '{}': {source}",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
Self::BarsParquetIntegrity { path, detail } => {
|
||||
write!(
|
||||
f,
|
||||
"bars_1d Parquet integrity error at '{}': {detail}",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
Self::BsonStream {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
||||
Self::CurateWrite { out_dir, source } => {
|
||||
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateAdjError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
|
||||
Self::ProviderMapping { source, .. } => Some(source),
|
||||
Self::BarsParquetRead { source, .. } => Some(source),
|
||||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::CurateWrite { source, .. } => Some(source),
|
||||
Self::InvalidOutDir { .. }
|
||||
| Self::InvalidBars1dDir { .. }
|
||||
| Self::TsvParse { .. }
|
||||
| Self::BarsParquetSchemaMismatch { .. }
|
||||
| Self::BarsParquetIntegrity { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct BarCloseEntry {
|
||||
close: f64,
|
||||
session_date: i32,
|
||||
currency_id: u16,
|
||||
}
|
||||
|
||||
const _: () = assert!(std::mem::size_of::<BarCloseEntry>() == 16);
|
||||
|
||||
#[derive(Default)]
|
||||
struct CurrencyInterner {
|
||||
to_id: HashMap<String, u16>,
|
||||
strings: Vec<String>,
|
||||
}
|
||||
|
||||
impl CurrencyInterner {
|
||||
fn intern(&mut self, value: &str, path: &Path) -> Result<u16, RunCurateAdjError> {
|
||||
if let Some(&id) = self.to_id.get(value) {
|
||||
return Ok(id);
|
||||
}
|
||||
let next_id = u16::try_from(self.strings.len()).map_err(|_| {
|
||||
RunCurateAdjError::BarsParquetIntegrity {
|
||||
path: path.to_path_buf(),
|
||||
detail: "more than 65536 distinct currencies in bars_1d".to_string(),
|
||||
}
|
||||
})?;
|
||||
self.strings.push(value.to_owned());
|
||||
self.to_id.insert(value.to_owned(), next_id);
|
||||
Ok(next_id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get(&self, id: u16) -> &str {
|
||||
self.strings[usize::from(id)].as_str()
|
||||
}
|
||||
}
|
||||
|
||||
struct PrevCloseIndex {
|
||||
by_listing: HashMap<i32, Vec<BarCloseEntry>>,
|
||||
currencies: CurrencyInterner,
|
||||
files_read: usize,
|
||||
rows_loaded: usize,
|
||||
}
|
||||
|
||||
impl PrevCloseIndex {
|
||||
/// Returns `(close, currency)` of the last `bars_1d` session strictly before `ex_date`
|
||||
/// (`session_date < ex_date`) for `listing_id`, or `None` if no earlier bar exists.
|
||||
#[inline]
|
||||
fn lookup(&self, listing_id: i32, ex_date: i32) -> Option<(f64, &str)> {
|
||||
let entries = self.by_listing.get(&listing_id)?;
|
||||
let idx = entries.partition_point(|e| e.session_date < ex_date);
|
||||
if idx == 0 {
|
||||
return None;
|
||||
}
|
||||
let entry = entries[idx - 1];
|
||||
Some((entry.close, self.currencies.get(entry.currency_id)))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateAdjError> {
|
||||
if out_dir.exists() && !out_dir.is_dir() {
|
||||
return Err(RunCurateAdjError::InvalidOutDir {
|
||||
path: out_dir.to_path_buf(),
|
||||
detail: "path exists and is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_year_partition_name(name: &str) -> Option<i32> {
|
||||
let suffix = name.strip_prefix("year=")?;
|
||||
if suffix.len() != 4 || !suffix.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
suffix.parse::<i32>().ok()
|
||||
}
|
||||
|
||||
fn collect_year_partitions(dir: &Path) -> Result<Vec<(i32, PathBuf)>, RunCurateAdjError> {
|
||||
let read_dir = fs::read_dir(dir).map_err(|source| RunCurateAdjError::ReadInput {
|
||||
label: "bars-1d",
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let mut partitions = Vec::new();
|
||||
for entry_res in read_dir {
|
||||
let entry = entry_res.map_err(|source| RunCurateAdjError::ReadInput {
|
||||
label: "bars-1d",
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let file_name = entry.file_name();
|
||||
let Some(name_str) = file_name.to_str() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(year) = parse_year_partition_name(name_str) {
|
||||
partitions.push((year, entry.path()));
|
||||
}
|
||||
}
|
||||
partitions.sort_unstable_by_key(|(year, _)| *year);
|
||||
Ok(partitions)
|
||||
}
|
||||
|
||||
fn discover_bars_1d_part_files(bars_1d_dir: &Path) -> Result<Vec<PathBuf>, RunCurateAdjError> {
|
||||
if !bars_1d_dir.exists() {
|
||||
return Err(RunCurateAdjError::InvalidBars1dDir {
|
||||
path: bars_1d_dir.to_path_buf(),
|
||||
detail: "directory does not exist".to_string(),
|
||||
});
|
||||
}
|
||||
if !bars_1d_dir.is_dir() {
|
||||
return Err(RunCurateAdjError::InvalidBars1dDir {
|
||||
path: bars_1d_dir.to_path_buf(),
|
||||
detail: "path is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut partitions = collect_year_partitions(bars_1d_dir)?;
|
||||
if partitions.is_empty() {
|
||||
let nested = bars_1d_dir.join("bars_1d");
|
||||
if nested.is_dir() {
|
||||
partitions = collect_year_partitions(&nested)?;
|
||||
}
|
||||
}
|
||||
|
||||
let mut files = Vec::with_capacity(partitions.len());
|
||||
for (_year, part_dir) in partitions {
|
||||
if !part_dir.is_dir() {
|
||||
return Err(RunCurateAdjError::InvalidBars1dDir {
|
||||
path: part_dir,
|
||||
detail: "year partition entry is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
let part_file = part_dir.join("part.parquet");
|
||||
if !part_file.is_file() {
|
||||
return Err(RunCurateAdjError::InvalidBars1dDir {
|
||||
path: part_file,
|
||||
detail: "missing part.parquet in year partition".to_string(),
|
||||
});
|
||||
}
|
||||
files.push(part_file);
|
||||
}
|
||||
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn load_prev_close_index(bars_1d_dir: &Path) -> Result<PrevCloseIndex, RunCurateAdjError> {
|
||||
let part_files = discover_bars_1d_part_files(bars_1d_dir)?;
|
||||
let expected_schema =
|
||||
bars_1d_parquet_schema().map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: bars_1d_dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let mut by_listing: HashMap<i32, Vec<BarCloseEntry>> = HashMap::new();
|
||||
let mut currencies = CurrencyInterner::default();
|
||||
let mut rows_loaded: usize = 0;
|
||||
|
||||
let mut batch_listing_ids: Vec<i32> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
|
||||
let mut batch_session_dates: Vec<i32> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
|
||||
let mut batch_closes: Vec<f64> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
|
||||
let mut batch_currencies: Vec<ByteArray> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
|
||||
|
||||
for part_path in &part_files {
|
||||
let file = File::open(part_path).map_err(|source| RunCurateAdjError::OpenInput {
|
||||
label: "bars-1d",
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let reader =
|
||||
SerializedFileReader::new(file).map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
if reader.metadata().file_metadata().schema_descr().root_schema()
|
||||
!= expected_schema.as_ref()
|
||||
{
|
||||
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
|
||||
path: part_path.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let file_meta = reader.metadata();
|
||||
for rg_idx in 0..file_meta.num_row_groups() {
|
||||
let rg_reader = reader.get_row_group(rg_idx).map_err(|source| {
|
||||
RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let num_rows = usize::try_from(file_meta.row_group(rg_idx).num_rows()).map_err(|_| {
|
||||
RunCurateAdjError::BarsParquetIntegrity {
|
||||
path: part_path.clone(),
|
||||
detail: "negative or overflowing row-group row count".to_string(),
|
||||
}
|
||||
})?;
|
||||
|
||||
let mut listing_col = match rg_reader
|
||||
.get_column_reader(COL_BARS_LISTING_ID)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})? {
|
||||
ColumnReader::Int32ColumnReader(r) => r,
|
||||
_ => {
|
||||
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
|
||||
path: part_path.clone(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let mut date_col = match rg_reader
|
||||
.get_column_reader(COL_BARS_SESSION_DATE)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})? {
|
||||
ColumnReader::Int32ColumnReader(r) => r,
|
||||
_ => {
|
||||
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
|
||||
path: part_path.clone(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let mut close_col = match rg_reader
|
||||
.get_column_reader(COL_BARS_CLOSE)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})? {
|
||||
ColumnReader::DoubleColumnReader(r) => r,
|
||||
_ => {
|
||||
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
|
||||
path: part_path.clone(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let mut curr_col = match rg_reader
|
||||
.get_column_reader(COL_BARS_CURRENCY)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})? {
|
||||
ColumnReader::ByteArrayColumnReader(r) => r,
|
||||
_ => {
|
||||
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
|
||||
path: part_path.clone(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let mut remaining = num_rows;
|
||||
while remaining > 0 {
|
||||
let batch = remaining.min(BARS_READ_BATCH_ROWS);
|
||||
batch_listing_ids.clear();
|
||||
batch_session_dates.clear();
|
||||
batch_closes.clear();
|
||||
batch_currencies.clear();
|
||||
|
||||
let (n_lid, _, _) = listing_col
|
||||
.read_records(batch, None, None, &mut batch_listing_ids)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let (n_date, _, _) = date_col
|
||||
.read_records(batch, None, None, &mut batch_session_dates)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let (n_close, _, _) = close_col
|
||||
.read_records(batch, None, None, &mut batch_closes)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let (n_curr, _, _) = curr_col
|
||||
.read_records(batch, None, None, &mut batch_currencies)
|
||||
.map_err(|source| RunCurateAdjError::BarsParquetRead {
|
||||
path: part_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
if n_lid != batch
|
||||
|| n_date != batch
|
||||
|| n_close != batch
|
||||
|| n_curr != batch
|
||||
|| batch_listing_ids.len() != batch
|
||||
|| batch_session_dates.len() != batch
|
||||
|| batch_closes.len() != batch
|
||||
|| batch_currencies.len() != batch
|
||||
{
|
||||
return Err(RunCurateAdjError::BarsParquetIntegrity {
|
||||
path: part_path.clone(),
|
||||
detail: format!(
|
||||
"column batch length mismatch: expected {batch}, got ({n_lid}, {n_date}, {n_close}, {n_curr})"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
for i in 0..batch {
|
||||
let curr_str =
|
||||
std::str::from_utf8(batch_currencies[i].data()).map_err(|_| {
|
||||
RunCurateAdjError::BarsParquetIntegrity {
|
||||
path: part_path.clone(),
|
||||
detail: "non-UTF8 currency value in bars_1d Parquet".to_string(),
|
||||
}
|
||||
})?;
|
||||
let currency_id = currencies.intern(curr_str, part_path)?;
|
||||
by_listing
|
||||
.entry(batch_listing_ids[i])
|
||||
.or_default()
|
||||
.push(BarCloseEntry {
|
||||
close: batch_closes[i],
|
||||
session_date: batch_session_dates[i],
|
||||
currency_id,
|
||||
});
|
||||
}
|
||||
|
||||
rows_loaded += batch;
|
||||
remaining -= batch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (&listing_id, entries) in &mut by_listing {
|
||||
entries.sort_unstable_by_key(|e| e.session_date);
|
||||
for pair in entries.windows(2) {
|
||||
if pair[0].session_date == pair[1].session_date {
|
||||
return Err(RunCurateAdjError::BarsParquetIntegrity {
|
||||
path: bars_1d_dir.to_path_buf(),
|
||||
detail: format!(
|
||||
"duplicate (listing_id={listing_id}, session_date={}) across bars_1d partitions",
|
||||
pair[0].session_date
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(PrevCloseIndex {
|
||||
by_listing,
|
||||
currencies,
|
||||
files_read: part_files.len(),
|
||||
rows_loaded,
|
||||
})
|
||||
}
|
||||
|
||||
fn load_provider_mapping_table(path: &Path) -> Result<ProviderMappingTable, RunCurateAdjError> {
|
||||
let mapping_rows = load_provider_mapping_tsv(path).map_err(|err| match err {
|
||||
RunCurateBarsError::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => RunCurateAdjError::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
},
|
||||
RunCurateBarsError::ReadInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => RunCurateAdjError::ReadInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
},
|
||||
RunCurateBarsError::TsvParse { path, line, detail } => {
|
||||
RunCurateAdjError::TsvParse { path, line, detail }
|
||||
}
|
||||
RunCurateBarsError::ProviderMapping { path, source } => {
|
||||
RunCurateAdjError::ProviderMapping { path, source }
|
||||
}
|
||||
other => RunCurateAdjError::TsvParse {
|
||||
path: path.to_path_buf(),
|
||||
line: 0,
|
||||
detail: other.to_string(),
|
||||
},
|
||||
})?;
|
||||
|
||||
ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateAdjError::ProviderMapping {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct DecodedAdjInputs {
|
||||
mapping: ProviderMappingTable,
|
||||
splits: Vec<(Arc<str>, SplitEvent)>,
|
||||
dividends: Vec<(Arc<str>, DividendEvent)>,
|
||||
splits_docs_framed: u64,
|
||||
splits_bytes_read: u64,
|
||||
splits_decode: BsonQmActionDecodeStats,
|
||||
dividends_docs_framed: u64,
|
||||
dividends_bytes_read: u64,
|
||||
dividends_decode: BsonQmActionDecodeStats,
|
||||
dividends_with_prev_close: usize,
|
||||
dividends_without_prev_close: usize,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn intern_qm_key(keys: &mut HashSet<Arc<str>>, raw: &str) -> Arc<str> {
|
||||
if let Some(existing) = keys.get(raw) {
|
||||
return Arc::clone(existing);
|
||||
}
|
||||
let arc: Arc<str> = Arc::from(raw);
|
||||
keys.insert(Arc::clone(&arc));
|
||||
arc
|
||||
}
|
||||
|
||||
fn decode_mapping_and_bson_inputs(
|
||||
args: &CurateAdjFactorsArgs,
|
||||
prev_close_index: &PrevCloseIndex,
|
||||
) -> Result<DecodedAdjInputs, RunCurateAdjError> {
|
||||
let mapping = load_provider_mapping_table(&args.provider_mapping)?;
|
||||
let mut qm_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
|
||||
// Stream `qmSplits`.
|
||||
let splits_file =
|
||||
File::open(&args.qm_splits).map_err(|source| RunCurateAdjError::OpenInput {
|
||||
label: "qm-splits",
|
||||
path: args.qm_splits.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut splits_reader =
|
||||
RawBsonChunkReader::with_options(splits_file, BsonStreamOptions::default()).map_err(
|
||||
|source| RunCurateAdjError::BsonStream {
|
||||
label: "qm-splits",
|
||||
path: args.qm_splits.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
let mut splits: Vec<(Arc<str>, SplitEvent)> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
let key = intern_qm_key(&mut qm_keys, split.qm_search_code);
|
||||
splits.push((key, split.to_split_event()));
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateAdjError::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();
|
||||
|
||||
// Stream `qmDividends` and attach strict pre-ex-date `prev_close` from `bars_1d`.
|
||||
let dividends_file =
|
||||
File::open(&args.qm_dividends).map_err(|source| RunCurateAdjError::OpenInput {
|
||||
label: "qm-dividends",
|
||||
path: args.qm_dividends.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut dividends_reader =
|
||||
RawBsonChunkReader::with_options(dividends_file, BsonStreamOptions::default()).map_err(
|
||||
|source| RunCurateAdjError::BsonStream {
|
||||
label: "qm-dividends",
|
||||
path: args.qm_dividends.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
let mut dividends: Vec<(Arc<str>, DividendEvent)> = Vec::new();
|
||||
let mut dividends_with_prev_close: usize = 0;
|
||||
let mut dividends_without_prev_close: usize = 0;
|
||||
let dividends_decode = decode_qm_dividend_chunks(
|
||||
&mut dividends_reader,
|
||||
|div| {
|
||||
let key = intern_qm_key(&mut qm_keys, div.qm_search_code);
|
||||
let (prev_close, prev_close_currency) =
|
||||
match mapping.resolve("qm", div.qm_search_code, div.ex_date) {
|
||||
Some(listing_id) => match prev_close_index.lookup(listing_id, div.ex_date) {
|
||||
Some((close, curr)) => {
|
||||
dividends_with_prev_close += 1;
|
||||
(Some(close), Some(curr.to_owned()))
|
||||
}
|
||||
None => {
|
||||
dividends_without_prev_close += 1;
|
||||
(None, None)
|
||||
}
|
||||
},
|
||||
None => (None, None),
|
||||
};
|
||||
dividends.push((key, div.to_dividend_event(prev_close, prev_close_currency)));
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateAdjError::BsonStream {
|
||||
label: "qm-dividends",
|
||||
path: args.qm_dividends.clone(),
|
||||
source,
|
||||
})?;
|
||||
let dividends_docs_framed = dividends_reader.docs_framed();
|
||||
let dividends_bytes_read = dividends_reader.bytes_read();
|
||||
|
||||
Ok(DecodedAdjInputs {
|
||||
mapping,
|
||||
splits,
|
||||
dividends,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
dividends_docs_framed,
|
||||
dividends_bytes_read,
|
||||
dividends_decode,
|
||||
dividends_with_prev_close,
|
||||
dividends_without_prev_close,
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the end-to-end `curate-adj-factors` file-to-Parquet pipeline via
|
||||
/// [`curate_and_write_adj_factors`].
|
||||
///
|
||||
/// Any input, schema, mapping, or curation error returns before touching `args.out_dir`,
|
||||
/// leaving any pre-existing `<out_dir>/adj_factors/part.parquet` byte-identical.
|
||||
pub fn run_curate_adj_factors(
|
||||
args: &CurateAdjFactorsArgs,
|
||||
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
|
||||
let start = Instant::now();
|
||||
validate_out_dir(&args.out_dir)?;
|
||||
|
||||
let prev_close_index = load_prev_close_index(&args.bars_1d_dir)?;
|
||||
let bars_files_read = prev_close_index.files_read;
|
||||
let bars_rows_loaded = prev_close_index.rows_loaded;
|
||||
let bars_listings_indexed = prev_close_index.by_listing.len();
|
||||
|
||||
let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?;
|
||||
drop(prev_close_index);
|
||||
|
||||
let write_report = curate_and_write_adj_factors(
|
||||
&args.out_dir,
|
||||
&decoded.mapping,
|
||||
"qm",
|
||||
decoded.splits,
|
||||
decoded.dividends,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.map_err(|source| RunCurateAdjError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
Ok(CurateAdjFactorsRunReport {
|
||||
bars_files_read,
|
||||
bars_rows_loaded,
|
||||
bars_listings_indexed,
|
||||
splits_docs_framed: decoded.splits_docs_framed,
|
||||
splits_bytes_read: decoded.splits_bytes_read,
|
||||
splits_decode: decoded.splits_decode,
|
||||
dividends_docs_framed: decoded.dividends_docs_framed,
|
||||
dividends_bytes_read: decoded.dividends_bytes_read,
|
||||
dividends_decode: decoded.dividends_decode,
|
||||
dividends_with_prev_close: decoded.dividends_with_prev_close,
|
||||
dividends_without_prev_close: decoded.dividends_without_prev_close,
|
||||
curate_stats: write_report.curate_stats,
|
||||
write_stats: write_report.write_stats,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_rows_checksum(rows: &[AdjFactorsParquetRow]) -> u64 {
|
||||
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
|
||||
let mix = |mut h: u64, v: u64| -> u64 {
|
||||
h ^= v;
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
h
|
||||
};
|
||||
for row in rows {
|
||||
hash = mix(hash, row.listing_id as u64);
|
||||
hash = mix(hash, row.ex_date as u64);
|
||||
hash = mix(hash, row.split_factor.to_bits());
|
||||
hash = mix(hash, row.div_cash.to_bits());
|
||||
match row.div_currency.as_deref() {
|
||||
Some(c) => {
|
||||
hash = mix(hash, 1);
|
||||
for &b in c.as_bytes() {
|
||||
hash = mix(hash, u64::from(b));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
hash = mix(hash, 0);
|
||||
}
|
||||
}
|
||||
hash = mix(hash, row.cum_split_factor.to_bits());
|
||||
hash = mix(hash, row.cum_total_factor.to_bits());
|
||||
hash = mix(hash, row.known_at_micros as u64);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// Stage-timed variant of [`run_curate_adj_factors`] used internally by `bench-curate-adj-cmd`.
|
||||
///
|
||||
/// Times `bars_load`, `decode` (mapping + BSON streams + `prev_close` attach), `curate`, and
|
||||
/// `write` (`write_adj_factors_snapshot_parquet`, identical footer-verified snapshot as
|
||||
/// [`curate_and_write_adj_factors`]) separately.
|
||||
pub(crate) fn run_curate_adj_factors_timed(
|
||||
args: &CurateAdjFactorsArgs,
|
||||
) -> Result<CurateAdjFactorsTimedRun, RunCurateAdjError> {
|
||||
let total_start = Instant::now();
|
||||
validate_out_dir(&args.out_dir)?;
|
||||
|
||||
let bars_start = Instant::now();
|
||||
let prev_close_index = load_prev_close_index(&args.bars_1d_dir)?;
|
||||
let bars_load_elapsed_secs = bars_start.elapsed().as_secs_f64();
|
||||
let bars_files_read = prev_close_index.files_read;
|
||||
let bars_rows_loaded = prev_close_index.rows_loaded;
|
||||
let bars_listings_indexed = prev_close_index.by_listing.len();
|
||||
|
||||
let decode_start = Instant::now();
|
||||
let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?;
|
||||
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
|
||||
drop(prev_close_index);
|
||||
|
||||
let curate_start = Instant::now();
|
||||
let curated = curate_adj_factors(
|
||||
&decoded.mapping,
|
||||
"qm",
|
||||
decoded.splits,
|
||||
decoded.dividends,
|
||||
)
|
||||
.map_err(|source| RunCurateAdjError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source: CurateAdjWriteError::Curate(source),
|
||||
})?;
|
||||
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
||||
|
||||
let checksum = compute_rows_checksum(&curated.rows);
|
||||
|
||||
let write_start = Instant::now();
|
||||
let write_stats = write_adj_factors_snapshot_parquet(
|
||||
&args.out_dir,
|
||||
&curated.rows,
|
||||
curated.snapshot_kind,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.map_err(|source| RunCurateAdjError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source: CurateAdjWriteError::Parquet(source),
|
||||
})?;
|
||||
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
|
||||
|
||||
let report = CurateAdjFactorsRunReport {
|
||||
bars_files_read,
|
||||
bars_rows_loaded,
|
||||
bars_listings_indexed,
|
||||
splits_docs_framed: decoded.splits_docs_framed,
|
||||
splits_bytes_read: decoded.splits_bytes_read,
|
||||
splits_decode: decoded.splits_decode,
|
||||
dividends_docs_framed: decoded.dividends_docs_framed,
|
||||
dividends_bytes_read: decoded.dividends_bytes_read,
|
||||
dividends_decode: decoded.dividends_decode,
|
||||
dividends_with_prev_close: decoded.dividends_with_prev_close,
|
||||
dividends_without_prev_close: decoded.dividends_without_prev_close,
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
||||
};
|
||||
|
||||
Ok(CurateAdjFactorsTimedRun {
|
||||
report,
|
||||
bars_load_elapsed_secs,
|
||||
decode_elapsed_secs,
|
||||
curate_elapsed_secs,
|
||||
write_elapsed_secs,
|
||||
checksum,
|
||||
})
|
||||
}
|
||||
|
||||
/// Formats [`CurateAdjFactorsRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_adj_report(report: &CurateAdjFactorsRunReport) -> String {
|
||||
format!(
|
||||
"curate-etl curate-adj-factors\n\
|
||||
\x20 bars_1d: files_read={} rows_loaded={} listings_indexed={}\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 dividends_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
\x20 prev_close: with_prev_close={} without_prev_close={} unmapped={}\n\
|
||||
\x20 builder: splits_in={} dividends_in={} rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}\n\
|
||||
\x20 curate: splits_in={} dividends_in={} rows_out={} listings_out={} splits_unmapped={} divs_unmapped={} splits_fenced={} divs_fenced={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}\n\
|
||||
\x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\
|
||||
\x20 timing: elapsed_secs={:.6}",
|
||||
report.bars_files_read,
|
||||
report.bars_rows_loaded,
|
||||
report.bars_listings_indexed,
|
||||
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.dividends_docs_framed,
|
||||
report.dividends_bytes_read,
|
||||
report.dividends_decode.docs_in,
|
||||
report.dividends_decode.decoded,
|
||||
report.dividends_decode.rejected_total(),
|
||||
report.dividends_decode.rejected_missing_field,
|
||||
report.dividends_decode.rejected_empty_field,
|
||||
report.dividends_decode.rejected_wrong_type,
|
||||
report.dividends_decode.rejected_malformed_date,
|
||||
report.dividends_decode.rejected_invalid_number,
|
||||
report.dividends_decode.rejected_corrupt_document,
|
||||
report.dividends_with_prev_close,
|
||||
report.dividends_without_prev_close,
|
||||
report.curate_stats.dividends_dropped_unmapped,
|
||||
report.curate_stats.builder.split_events_in,
|
||||
report.curate_stats.builder.dividend_events_in,
|
||||
report.curate_stats.builder.rows_out,
|
||||
report.curate_stats.builder.keys_out,
|
||||
report.curate_stats.builder.split_noops_dropped,
|
||||
report.curate_stats.builder.dividend_zero_cash_dropped,
|
||||
report.curate_stats.builder.dividends_missing_prev_close,
|
||||
report.curate_stats.builder.dividends_currency_mismatch,
|
||||
report.curate_stats.builder.dividends_not_below_prev_close,
|
||||
report.curate_stats.splits_in,
|
||||
report.curate_stats.dividends_in,
|
||||
report.curate_stats.rows_out,
|
||||
report.curate_stats.listings_out,
|
||||
report.curate_stats.splits_dropped_unmapped,
|
||||
report.curate_stats.dividends_dropped_unmapped,
|
||||
report.curate_stats.splits_dropped_fenced,
|
||||
report.curate_stats.dividends_dropped_fenced,
|
||||
report.curate_stats.splits_collision_collapsed,
|
||||
report.curate_stats.dividends_collision_collapsed,
|
||||
report.curate_stats.listing_collision_collapsed,
|
||||
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_adj_tests.rs"]
|
||||
mod tests;
|
||||
743
tools/curate-etl/src/run_curate_adj_tests.rs
Normal file
743
tools/curate-etl/src/run_curate_adj_tests.rs
Normal file
|
|
@ -0,0 +1,743 @@
|
|||
use std::borrow::Cow;
|
||||
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 super::*;
|
||||
use crate::bson_stream::DEFAULT_MAX_DOC_BYTES;
|
||||
use crate::curate_adj::{
|
||||
adj_factors_for_bar, read_adj_factors_dataset, read_adj_factors_dataset_as_of,
|
||||
AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError,
|
||||
};
|
||||
use crate::curate_bars::BARS_1D_SOURCE_EOD;
|
||||
use crate::parquet_bars::{write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions};
|
||||
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-adj-{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 write_bytes(path: &Path, bytes: &[u8]) {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("create parent dirs");
|
||||
}
|
||||
let mut f = File::create(path).expect("create fixture file");
|
||||
f.write_all(bytes).expect("write fixture 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 div_doc(code: &str, date: &str, cash: f64, currency: &str, usd_fx_rate: Option<f64>) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
if let Some(fx) = usd_fx_rate {
|
||||
doc.append(cstr!("usdFxRate"), fx);
|
||||
}
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn bar_row(listing_id: i32, y: i32, m: u32, d: u32, close: f64, currency: &'static str) -> Bars1dParquetRow {
|
||||
let session_date = ymd_to_epoch_days(y, m, d).expect("valid bar date");
|
||||
let ts_micros = et_session_close_utc_micros(session_date).expect("valid ts");
|
||||
Bars1dParquetRow {
|
||||
listing_id,
|
||||
ts_micros,
|
||||
session_date,
|
||||
open: close - 0.5,
|
||||
high: close + 1.0,
|
||||
low: close - 1.0,
|
||||
close,
|
||||
volume: 100_000.0,
|
||||
vwap: None,
|
||||
currency: Cow::Borrowed(currency),
|
||||
source: Cow::Borrowed(BARS_1D_SOURCE_EOD),
|
||||
known_at_micros: ts_micros,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_row_bit_eq(a: &AdjFactorsParquetRow, b: &AdjFactorsParquetRow) {
|
||||
assert_eq!(a.listing_id, b.listing_id);
|
||||
assert_eq!(a.ex_date, b.ex_date);
|
||||
assert_eq!(a.split_factor.to_bits(), b.split_factor.to_bits());
|
||||
assert_eq!(a.div_cash.to_bits(), b.div_cash.to_bits());
|
||||
assert_eq!(a.div_currency, b.div_currency);
|
||||
assert_eq!(a.cum_split_factor.to_bits(), b.cum_split_factor.to_bits());
|
||||
assert_eq!(a.cum_total_factor.to_bits(), b.cum_total_factor.to_bits());
|
||||
assert_eq!(a.known_at_micros, b.known_at_micros);
|
||||
}
|
||||
|
||||
fn assert_conservation(report: &CurateAdjFactorsRunReport) {
|
||||
assert_eq!(
|
||||
report.splits_docs_framed as usize, report.splits_decode.docs_in,
|
||||
"splits_docs_framed must equal splits_decode.docs_in"
|
||||
);
|
||||
assert_eq!(
|
||||
report.splits_decode.docs_in,
|
||||
report.splits_decode.rejected_total()
|
||||
+ report.curate_stats.splits_dropped_unmapped
|
||||
+ report.curate_stats.splits_dropped_fenced
|
||||
+ report.curate_stats.splits_collision_collapsed
|
||||
+ report.curate_stats.builder.split_events_in,
|
||||
"split conservation invariant failed: {report:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
report.dividends_docs_framed as usize, report.dividends_decode.docs_in,
|
||||
"dividends_docs_framed must equal dividends_decode.docs_in"
|
||||
);
|
||||
assert_eq!(
|
||||
report.dividends_decode.docs_in,
|
||||
report.dividends_decode.rejected_total()
|
||||
+ report.curate_stats.dividends_dropped_unmapped
|
||||
+ report.curate_stats.dividends_dropped_fenced
|
||||
+ report.curate_stats.dividends_collision_collapsed
|
||||
+ report.curate_stats.builder.dividend_events_in,
|
||||
"dividend conservation invariant failed: {report:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
report.dividends_decode.decoded,
|
||||
report.dividends_with_prev_close
|
||||
+ report.dividends_without_prev_close
|
||||
+ report.curate_stats.dividends_dropped_unmapped,
|
||||
"dividend prev_close conservation invariant failed: {report:?}"
|
||||
);
|
||||
}
|
||||
|
||||
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_round_trip_matches_direct_curate_adj_factors_bitwise_and_is_deterministic() {
|
||||
let dir = TestTempDir::new("e2e-roundtrip");
|
||||
let splits_a = dir.path().join("splits_a.bson");
|
||||
let splits_b = dir.path().join("splits_b.bson");
|
||||
let divs_a = dir.path().join("divs_a.bson");
|
||||
let divs_b = dir.path().join("divs_b.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let bars_root = dir.path().join("bars_root");
|
||||
let out_a = dir.path().join("out_a");
|
||||
let out_b = dir.path().join("out_b");
|
||||
let out_timed = dir.path().join("out_timed");
|
||||
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"qm\tNVDA:US\t2010-01-01\t\t100\n\
|
||||
qm\tRY:CA\t2010-01-01\t\t200\n\
|
||||
qm\tRY_ALT:CA\t2010-01-01\t\t200\n",
|
||||
);
|
||||
|
||||
// Write multi-year bars_1d dataset via write_bars_1d_dataset.
|
||||
let bar_rows = vec![
|
||||
bar_row(100, 2021, 7, 19, 751.19, "USD"),
|
||||
bar_row(100, 2021, 7, 20, 186.12, "USD"),
|
||||
bar_row(100, 2024, 6, 7, 1208.88, "USD"),
|
||||
bar_row(100, 2024, 6, 10, 121.79, "USD"),
|
||||
bar_row(100, 2024, 6, 11, 120.91, "USD"),
|
||||
bar_row(200, 2024, 4, 24, 136.50, "CAD"),
|
||||
bar_row(200, 2024, 4, 25, 135.00, "CAD"),
|
||||
];
|
||||
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
// Splits: NVDA 4:1 (2021-07-20) + 10:1 (2024-06-10) + 1:1 no-op + unmapped.
|
||||
let s1 = split_doc("NVDA:US", "2021-07-20", 4.0);
|
||||
let s2 = split_doc("NVDA:US", "2024-06-10", 10.0);
|
||||
let s3 = split_doc("NVDA:US", "2022-03-01", 1.0);
|
||||
let s4 = split_doc("UNKNOWN:US", "2023-01-05", 2.0);
|
||||
write_bytes(&splits_a, &[&s1[..], &s2[..], &s3[..], &s4[..]].concat());
|
||||
write_bytes(&splits_b, &[&s4[..], &s2[..], &s3[..], &s1[..]].concat());
|
||||
|
||||
// Dividends: NVDA USD div on 2024-06-11 (prev_close = 121.79 on 2024-06-10),
|
||||
// RY:CA + RY_ALT:CA identical CAD div on 2024-04-25 with bogus usdFxRate: 1 (prev_close = 136.50 on 2024-04-24).
|
||||
let d1 = div_doc("NVDA:US", "2024-06-11", 0.01, "USD", Some(1.0));
|
||||
let d2 = div_doc("RY:CA", "2024-04-25", 1.38, "CAD", Some(1.0));
|
||||
let d3 = div_doc("RY_ALT:CA", "2024-04-25", 1.38, "CAD", Some(1.0));
|
||||
write_bytes(&divs_a, &[&d1[..], &d2[..], &d3[..]].concat());
|
||||
write_bytes(&divs_b, &[&d3[..], &d1[..], &d2[..]].concat());
|
||||
|
||||
let args_a = CurateAdjFactorsArgs {
|
||||
qm_splits: splits_a,
|
||||
qm_dividends: divs_a,
|
||||
provider_mapping: map_path.clone(),
|
||||
bars_1d_dir: bars_root.join("bars_1d"),
|
||||
out_dir: out_a.clone(),
|
||||
};
|
||||
let report_a = run_curate_adj_factors(&args_a).expect("run_curate_adj_factors A");
|
||||
assert_conservation(&report_a);
|
||||
|
||||
// Compare against calling curate_adj_factors directly on the same in-memory events.
|
||||
let mapping = load_provider_mapping_table(&map_path).unwrap();
|
||||
let direct = curate_adj_factors(
|
||||
&mapping,
|
||||
"qm",
|
||||
vec![
|
||||
(
|
||||
"NVDA:US",
|
||||
SplitEvent {
|
||||
ex_date: ymd_to_epoch_days(2021, 7, 20).unwrap(),
|
||||
ratio: 4.0,
|
||||
},
|
||||
),
|
||||
(
|
||||
"NVDA:US",
|
||||
SplitEvent {
|
||||
ex_date: ymd_to_epoch_days(2024, 6, 10).unwrap(),
|
||||
ratio: 10.0,
|
||||
},
|
||||
),
|
||||
(
|
||||
"NVDA:US",
|
||||
SplitEvent {
|
||||
ex_date: ymd_to_epoch_days(2022, 3, 1).unwrap(),
|
||||
ratio: 1.0,
|
||||
},
|
||||
),
|
||||
(
|
||||
"UNKNOWN:US",
|
||||
SplitEvent {
|
||||
ex_date: ymd_to_epoch_days(2023, 1, 5).unwrap(),
|
||||
ratio: 2.0,
|
||||
},
|
||||
),
|
||||
],
|
||||
vec![
|
||||
(
|
||||
"NVDA:US",
|
||||
DividendEvent {
|
||||
ex_date: ymd_to_epoch_days(2024, 6, 11).unwrap(),
|
||||
cash: 0.01,
|
||||
currency: "USD".to_string(),
|
||||
prev_close: Some(121.79),
|
||||
prev_close_currency: Some("USD".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
"RY:CA",
|
||||
DividendEvent {
|
||||
ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(),
|
||||
cash: 1.38,
|
||||
currency: "CAD".to_string(),
|
||||
prev_close: Some(136.50),
|
||||
prev_close_currency: Some("CAD".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
"RY_ALT:CA",
|
||||
DividendEvent {
|
||||
ex_date: ymd_to_epoch_days(2024, 4, 25).unwrap(),
|
||||
cash: 1.38,
|
||||
currency: "CAD".to_string(),
|
||||
prev_close: Some(136.50),
|
||||
prev_close_currency: Some("CAD".to_string()),
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
.expect("direct curate_adj_factors");
|
||||
|
||||
let snap_a = read_adj_factors_dataset(&out_a).expect("read_adj_factors_dataset");
|
||||
assert_eq!(snap_a.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot);
|
||||
assert_eq!(snap_a.rows.len(), direct.rows.len());
|
||||
for (got, expected) in snap_a.rows.iter().zip(direct.rows.iter()) {
|
||||
assert_row_bit_eq(got, expected);
|
||||
}
|
||||
|
||||
// Point-in-time reader must reject the retrospective snapshot automatically.
|
||||
let pit_err = read_adj_factors_dataset_as_of(
|
||||
&out_a,
|
||||
AdjPointInTimeFence::as_of(et_session_close_utc_micros(ymd_to_epoch_days(2024, 6, 11).unwrap()).unwrap()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
pit_err,
|
||||
CurateAdjReadError::RetrospectiveSnapshotRejected { .. }
|
||||
));
|
||||
|
||||
// Shuffled BSON + root bars_1d dir layout produces byte-identical Parquet and identical non-timing report.
|
||||
let args_b = CurateAdjFactorsArgs {
|
||||
qm_splits: splits_b,
|
||||
qm_dividends: divs_b,
|
||||
provider_mapping: map_path,
|
||||
bars_1d_dir: bars_root, // parent root containing `bars_1d/`
|
||||
out_dir: out_b.clone(),
|
||||
};
|
||||
let report_b = run_curate_adj_factors(&args_b).expect("run_curate_adj_factors B");
|
||||
assert_conservation(&report_b);
|
||||
assert_eq!(
|
||||
strip_timing_line(&format_curate_adj_report(&report_a)),
|
||||
strip_timing_line(&format_curate_adj_report(&report_b))
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(out_a.join("adj_factors/part.parquet")).unwrap(),
|
||||
fs::read(out_b.join("adj_factors/part.parquet")).unwrap()
|
||||
);
|
||||
|
||||
// Stage-timed helper produces byte-identical Parquet as well.
|
||||
let args_timed = CurateAdjFactorsArgs {
|
||||
out_dir: out_timed.clone(),
|
||||
..args_a
|
||||
};
|
||||
let timed = run_curate_adj_factors_timed(&args_timed).expect("run_curate_adj_factors_timed");
|
||||
assert_conservation(&timed.report);
|
||||
assert_eq!(
|
||||
fs::read(out_a.join("adj_factors/part.parquet")).unwrap(),
|
||||
fs::read(out_timed.join("adj_factors/part.parquet")).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prev_close_strictly_before_ex_date_and_none_when_missing_or_unmapped() {
|
||||
let dir = TestTempDir::new("prev-close-boundary");
|
||||
let splits_path = dir.path().join("splits.bson");
|
||||
let divs_path = dir.path().join("divs.bson");
|
||||
let map_path = dir.path().join("map.tsv");
|
||||
let bars_root = dir.path().join("bars_root");
|
||||
let out_dir = dir.path().join("out");
|
||||
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"qm\tAAA:US\t2020-01-01\t\t1\n\
|
||||
qm\tNOBAR:US\t2020-01-01\t\t2\n",
|
||||
);
|
||||
|
||||
// Listing 1 has bars on Friday 2024-05-03 (close=100.0) and Monday 2024-05-06 (close=50.0).
|
||||
// Listing 2 has no bars at all.
|
||||
let bar_rows = vec![
|
||||
bar_row(1, 2024, 5, 3, 100.0, "USD"),
|
||||
bar_row(1, 2024, 5, 6, 50.0, "USD"),
|
||||
];
|
||||
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
write_bytes(&splits_path, b"");
|
||||
let mut divs = Vec::new();
|
||||
// 1. Ex-date 2024-05-06 (Monday): bar on 2024-05-06 (close=50.0) MUST NOT be used;
|
||||
// must use Friday 2024-05-03 (close=100.0) -> div_factor = 1 - 2.0 / 100.0 = 0.98.
|
||||
divs.extend_from_slice(&div_doc("AAA:US", "2024-05-06", 2.0, "USD", None));
|
||||
// 2. Ex-date 2024-05-03 (same day as earliest bar): no bar strictly before -> prev_close = None -> factor 1.0.
|
||||
divs.extend_from_slice(&div_doc("AAA:US", "2024-05-03", 1.0, "USD", None));
|
||||
// 3. Listing 2 has no bars -> prev_close = None -> factor 1.0.
|
||||
divs.extend_from_slice(&div_doc("NOBAR:US", "2024-05-10", 1.0, "USD", None));
|
||||
// 4. Unmapped dividend -> dropped as unmapped, not counted in with/without prev_close.
|
||||
divs.extend_from_slice(&div_doc("UNMAPPED:US", "2024-05-10", 1.0, "USD", None));
|
||||
write_bytes(&divs_path, &divs);
|
||||
|
||||
let report = run_curate_adj_factors(&CurateAdjFactorsArgs {
|
||||
qm_splits: splits_path,
|
||||
qm_dividends: divs_path,
|
||||
provider_mapping: map_path,
|
||||
bars_1d_dir: bars_root.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.expect("run_curate_adj_factors");
|
||||
assert_conservation(&report);
|
||||
|
||||
assert_eq!(report.dividends_with_prev_close, 1);
|
||||
assert_eq!(report.dividends_without_prev_close, 2);
|
||||
assert_eq!(report.curate_stats.dividends_dropped_unmapped, 1);
|
||||
assert_eq!(report.curate_stats.builder.dividends_missing_prev_close, 2);
|
||||
|
||||
let snap = read_adj_factors_dataset(&out_dir).unwrap();
|
||||
assert_eq!(snap.rows.len(), 3);
|
||||
|
||||
let d_may03 = ymd_to_epoch_days(2024, 5, 3).unwrap();
|
||||
let d_may06 = ymd_to_epoch_days(2024, 5, 6).unwrap();
|
||||
let row_may03 = snap
|
||||
.rows
|
||||
.iter()
|
||||
.find(|r| r.listing_id == 1 && r.ex_date == d_may03)
|
||||
.unwrap();
|
||||
let row_may06 = snap
|
||||
.rows
|
||||
.iter()
|
||||
.find(|r| r.listing_id == 1 && r.ex_date == d_may06)
|
||||
.unwrap();
|
||||
|
||||
// If 2024-05-06 had wrongly used its own close (50.0), factor would be 50 / (50 - 2) = 50 / 48.
|
||||
// Using strictly prior close (100.0) gives 100 / (100 - 2) = 100 / 98.
|
||||
let expected_factor = 100.0 / 98.0;
|
||||
assert!((row_may06.cum_total_factor - expected_factor).abs() < 1e-12);
|
||||
// 2024-05-03 had no earlier bar (div factor = 1.0), compounded with 2024-05-06 -> 100 / 98.
|
||||
assert!((row_may03.cum_total_factor - expected_factor).abs() < 1e-12);
|
||||
|
||||
let row_nobar = snap.rows.iter().find(|r| r.listing_id == 2).unwrap();
|
||||
assert_eq!(row_nobar.cum_total_factor, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn financial_invariants_nvda_chain_noop_cad_fx_ignore_mismatch_and_malformed_bson_rejects() {
|
||||
let dir = TestTempDir::new("financial-invariants");
|
||||
let splits_path = dir.path().join("splits.bson");
|
||||
let divs_path = dir.path().join("divs.bson");
|
||||
let map_path = dir.path().join("map.tsv");
|
||||
let bars_root = dir.path().join("bars_root");
|
||||
let out_dir = dir.path().join("out");
|
||||
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"qm\tNVDA:US\t2015-01-01\t\t10\n\
|
||||
qm\tSHOP:CA\t2015-01-01\t\t20\n\
|
||||
qm\tMISMATCH:CA\t2015-01-01\t\t30\n",
|
||||
);
|
||||
|
||||
let bar_rows = vec![
|
||||
bar_row(20, 2024, 5, 1, 100.0, "CAD"),
|
||||
bar_row(30, 2024, 5, 1, 100.0, "CAD"),
|
||||
];
|
||||
write_bars_1d_dataset(&bars_root, &bar_rows, Bars1dWriteOptions::default()).unwrap();
|
||||
|
||||
// Splits: NVDA 4:1 (2021-07-20), NVDA 10:1 (2024-06-10), 1:1 no-op, plus 2 malformed BSON docs
|
||||
// (one invalid date, one internally-corrupt length-framed doc).
|
||||
let mut splits = Vec::new();
|
||||
splits.extend_from_slice(&split_doc("NVDA:US", "2021-07-20", 4.0));
|
||||
splits.extend_from_slice(&split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
splits.extend_from_slice(&split_doc("NVDA:US", "2023-01-10", 1.0));
|
||||
splits.extend_from_slice(&split_doc("NVDA:US", "2023-02-29", 2.0)); // malformed date reject
|
||||
// Valid outer 4-byte length prefix (12 bytes), invalid interior BSON bytes -> CorruptBson reject.
|
||||
let mut corrupt_doc = Vec::from(12_i32.to_le_bytes());
|
||||
corrupt_doc.extend_from_slice(&[0x7f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x01]);
|
||||
splits.extend_from_slice(&corrupt_doc);
|
||||
write_bytes(&splits_path, &splits);
|
||||
|
||||
// Dividends:
|
||||
// - CAD dividend with bogus usdFxRate: 1 -> curated in CAD using CAD prev_close=100.0 -> factor = 0.95.
|
||||
// - USD dividend on CAD bar -> currency mismatch -> factor = 1.0.
|
||||
// - Malformed dividend (negative cash) -> decode reject without aborting.
|
||||
let mut divs = Vec::new();
|
||||
divs.extend_from_slice(&div_doc("SHOP:CA", "2024-05-02", 5.0, "CAD", Some(1.0)));
|
||||
divs.extend_from_slice(&div_doc("MISMATCH:CA", "2024-05-02", 5.0, "USD", Some(1.0)));
|
||||
divs.extend_from_slice(&div_doc("SHOP:CA", "2024-05-03", -1.0, "CAD", Some(1.0)));
|
||||
write_bytes(&divs_path, &divs);
|
||||
|
||||
let report = run_curate_adj_factors(&CurateAdjFactorsArgs {
|
||||
qm_splits: splits_path,
|
||||
qm_dividends: divs_path,
|
||||
provider_mapping: map_path,
|
||||
bars_1d_dir: bars_root.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.expect("run_curate_adj_factors");
|
||||
assert_conservation(&report);
|
||||
|
||||
assert_eq!(report.splits_docs_framed, 5);
|
||||
assert_eq!(report.splits_decode.rejected_total(), 2);
|
||||
assert_eq!(report.splits_decode.split_noop_ratio_one, 1);
|
||||
assert_eq!(report.curate_stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(report.dividends_docs_framed, 3);
|
||||
assert_eq!(report.dividends_decode.rejected_total(), 1);
|
||||
assert_eq!(report.curate_stats.builder.dividends_currency_mismatch, 1);
|
||||
|
||||
let snap = read_adj_factors_dataset(&out_dir).unwrap();
|
||||
|
||||
// NVDA 4:1 then 10:1 chain: cum_split_factor 40 -> 10 on rows, and 40 -> 10 -> 1 across dates.
|
||||
let d_2021 = ymd_to_epoch_days(2021, 7, 20).unwrap();
|
||||
let d_2024 = ymd_to_epoch_days(2024, 6, 10).unwrap();
|
||||
let nvda_rows: Vec<&AdjFactorsParquetRow> =
|
||||
snap.rows.iter().filter(|r| r.listing_id == 10).collect();
|
||||
assert_eq!(nvda_rows.len(), 2, "1:1 no-op must not emit a row");
|
||||
assert_eq!(nvda_rows[0].ex_date, d_2021);
|
||||
assert_eq!(nvda_rows[0].cum_split_factor, 40.0);
|
||||
assert_eq!(nvda_rows[1].ex_date, d_2024);
|
||||
assert_eq!(nvda_rows[1].cum_split_factor, 10.0);
|
||||
|
||||
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2021 - 1), (40.0, 40.0));
|
||||
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2021), (10.0, 10.0));
|
||||
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2024 - 1), (10.0, 10.0));
|
||||
assert_eq!(adj_factors_for_bar(&snap.rows, 10, d_2024), (1.0, 1.0));
|
||||
|
||||
// CAD dividend ignores bogus usdFxRate: 1 and uses CAD prev_close = 100.0 -> 100 / 95.
|
||||
let shop_row = snap.rows.iter().find(|r| r.listing_id == 20).unwrap();
|
||||
assert_eq!(shop_row.div_currency.as_deref(), Some("CAD"));
|
||||
assert!((shop_row.cum_total_factor - (100.0 / 95.0)).abs() < 1e-12);
|
||||
|
||||
// Currency-mismatched dividend falls back to factor 1.0.
|
||||
let mismatch_row = snap.rows.iter().find(|r| r.listing_id == 30).unwrap();
|
||||
assert_eq!(mismatch_row.div_currency.as_deref(), Some("USD"));
|
||||
assert_eq!(mismatch_row.cum_total_factor, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_modes_preserve_preexisting_adj_factors_snapshot_byte_for_byte() {
|
||||
let dir = TestTempDir::new("atomicity-failures");
|
||||
let splits_ok = dir.path().join("splits_ok.bson");
|
||||
let divs_ok = dir.path().join("divs_ok.bson");
|
||||
let map_ok = dir.path().join("map_ok.tsv");
|
||||
let bars_ok = dir.path().join("bars_ok");
|
||||
let out_dir = dir.path().join("out");
|
||||
|
||||
write_bytes(&map_ok, b"qm\tNVDA:US\t2015-01-01\t\t10\n");
|
||||
write_bars_1d_dataset(
|
||||
&bars_ok,
|
||||
&[bar_row(10, 2024, 6, 7, 1200.0, "USD")],
|
||||
Bars1dWriteOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
write_bytes(&splits_ok, &split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
write_bytes(&divs_ok, b"");
|
||||
|
||||
// Seed a valid pre-existing snapshot at `<out_dir>/adj_factors/part.parquet`.
|
||||
run_curate_adj_factors(&CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
})
|
||||
.expect("seed baseline snapshot");
|
||||
let live_part = out_dir.join("adj_factors/part.parquet");
|
||||
let baseline_bytes = fs::read(&live_part).expect("read baseline snapshot");
|
||||
assert!(!baseline_bytes.is_empty());
|
||||
|
||||
let assert_failed_atomically = |args: CurateAdjFactorsArgs, expected_substr: &str| {
|
||||
let err = run_curate_adj_factors(&args).expect_err("expected failure");
|
||||
let msg = err.to_string();
|
||||
assert_eq!(msg.lines().count(), 1, "error must be single-line: {msg}");
|
||||
assert!(
|
||||
msg.contains(expected_substr),
|
||||
"expected error containing '{expected_substr}', got: {msg}"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(&live_part).expect("live snapshot still exists"),
|
||||
baseline_bytes,
|
||||
"pre-existing adj_factors/part.parquet must remain byte-identical after failure ({msg})"
|
||||
);
|
||||
};
|
||||
|
||||
// 1. Missing qmSplits file.
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: dir.path().join("missing_splits.bson"),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"missing_splits.bson",
|
||||
);
|
||||
|
||||
// 2. Missing qmDividends file.
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: dir.path().join("missing_divs.bson"),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"missing_divs.bson",
|
||||
);
|
||||
|
||||
// 3. Missing provider_mapping file.
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: dir.path().join("missing_map.tsv"),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"missing_map.tsv",
|
||||
);
|
||||
|
||||
// 4. Missing bars_1d dir.
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: dir.path().join("missing_bars_dir"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"missing_bars_dir",
|
||||
);
|
||||
|
||||
// 5. Non-directory bars_1d path.
|
||||
let not_a_dir = dir.path().join("bars_file.txt");
|
||||
write_bytes(¬_a_dir, b"nope");
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: not_a_dir,
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"bars_file.txt",
|
||||
);
|
||||
|
||||
// 6. Wrong-schema bars_1d part.parquet (place adj_factors part.parquet inside year=2024/).
|
||||
let wrong_schema_bars = dir.path().join("wrong_schema_bars");
|
||||
write_bytes(
|
||||
&wrong_schema_bars.join("year=2024/part.parquet"),
|
||||
&baseline_bytes,
|
||||
);
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: wrong_schema_bars,
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"schema mismatch",
|
||||
);
|
||||
|
||||
// 7. Corrupt bars_1d part.parquet.
|
||||
let corrupt_bars = dir.path().join("corrupt_bars");
|
||||
write_bytes(&corrupt_bars.join("year=2024/part.parquet"), b"not parquet");
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: corrupt_bars,
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"part.parquet",
|
||||
);
|
||||
|
||||
// 8. Missing part.parquet in year=YYYY partition.
|
||||
let missing_part_bars = dir.path().join("missing_part_bars");
|
||||
fs::create_dir_all(missing_part_bars.join("year=2024")).unwrap();
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: missing_part_bars,
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"part.parquet",
|
||||
);
|
||||
|
||||
// 9. Malformed provider_mapping.tsv (reports 1-based line number).
|
||||
let bad_map = dir.path().join("bad_map.tsv");
|
||||
write_bytes(&bad_map, b"qm\tNVDA:US\t2015-01-01\t\t10\nbad_row\n");
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: bad_map,
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"bad_map.tsv:2:",
|
||||
);
|
||||
|
||||
// 10. Truncated BSON stream.
|
||||
let trunc_splits = dir.path().join("trunc_splits.bson");
|
||||
let mut doc = split_doc("NVDA:US", "2024-06-10", 10.0);
|
||||
doc.truncate(doc.len() - 3);
|
||||
write_bytes(&trunc_splits, &doc);
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: trunc_splits,
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"trunc_splits.bson",
|
||||
);
|
||||
|
||||
// 11. Oversized BSON document (> DEFAULT_MAX_DOC_BYTES).
|
||||
let huge_divs = dir.path().join("huge_divs.bson");
|
||||
let huge_len = (DEFAULT_MAX_DOC_BYTES as i32) + 512;
|
||||
let mut huge_bytes = Vec::from(huge_len.to_le_bytes());
|
||||
huge_bytes.push(0);
|
||||
write_bytes(&huge_divs, &huge_bytes);
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok.clone(),
|
||||
qm_dividends: huge_divs,
|
||||
provider_mapping: map_ok.clone(),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"huge_divs.bson",
|
||||
);
|
||||
|
||||
// 12. Conflicting cross-key split curation error.
|
||||
let alias_map = dir.path().join("alias_map.tsv");
|
||||
write_bytes(
|
||||
&alias_map,
|
||||
b"qm\tNVDA:US\t2015-01-01\t\t10\nqm\tNVDA_ALT:US\t2015-01-01\t\t10\n",
|
||||
);
|
||||
let conflict_splits = dir.path().join("conflict_splits.bson");
|
||||
write_bytes(
|
||||
&conflict_splits,
|
||||
&[
|
||||
&split_doc("NVDA:US", "2024-06-10", 10.0)[..],
|
||||
&split_doc("NVDA_ALT:US", "2024-06-10", 4.0)[..],
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: conflict_splits,
|
||||
qm_dividends: divs_ok.clone(),
|
||||
provider_mapping: alias_map.clone(),
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir: out_dir.clone(),
|
||||
},
|
||||
"conflicting cross-key splits",
|
||||
);
|
||||
|
||||
// 13. Conflicting cross-key dividend curation error.
|
||||
let conflict_divs = dir.path().join("conflict_divs.bson");
|
||||
write_bytes(
|
||||
&conflict_divs,
|
||||
&[
|
||||
&div_doc("NVDA:US", "2024-06-11", 0.10, "USD", None)[..],
|
||||
&div_doc("NVDA_ALT:US", "2024-06-11", 0.20, "USD", None)[..],
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
assert_failed_atomically(
|
||||
CurateAdjFactorsArgs {
|
||||
qm_splits: splits_ok,
|
||||
qm_dividends: conflict_divs,
|
||||
provider_mapping: alias_map,
|
||||
bars_1d_dir: bars_ok.join("bars_1d"),
|
||||
out_dir,
|
||||
},
|
||||
"conflicting cross-key dividends",
|
||||
);
|
||||
}
|
||||
|
|
@ -31,7 +31,9 @@ fn no_args_and_help_print_usage_and_succeed() {
|
|||
let text = stdout(&out);
|
||||
assert!(text.contains("Usage:"), "{args:?}: {text}");
|
||||
assert!(text.contains("curate-bars-1d"), "{args:?}: {text}");
|
||||
assert!(text.contains("curate-adj-factors"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-curate-bars-cmd"), "{args:?}: {text}");
|
||||
assert!(text.contains("bench-curate-adj-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}");
|
||||
|
|
@ -697,3 +699,167 @@ fn bench_curate_bars_cmd_small_run_succeeds_and_reports_splits() {
|
|||
assert!(text.contains("total:"), "{text}");
|
||||
assert!(text.contains("bytes/bar"), "{text}");
|
||||
}
|
||||
|
||||
fn make_div_doc(code: &str, date: &str, cash: f64, currency: &str) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_adj_factors_cli_flag_errors_exit_nonzero_with_usage() {
|
||||
for args in [
|
||||
&["curate-adj-factors"][..],
|
||||
&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--qm-dividends",
|
||||
"d.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--bars-1d",
|
||||
"bars",
|
||||
][..],
|
||||
&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--qm-splits",
|
||||
"s2.bson",
|
||||
"--qm-dividends",
|
||||
"d.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--bars-1d",
|
||||
"bars",
|
||||
"--out",
|
||||
"out",
|
||||
][..],
|
||||
&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--qm-dividends",
|
||||
"d.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--bars-1d",
|
||||
"bars",
|
||||
"--out",
|
||||
"out",
|
||||
"--unknown",
|
||||
"1",
|
||||
][..],
|
||||
] {
|
||||
let out = run(args);
|
||||
assert!(!out.status.success(), "{args:?} should fail");
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}");
|
||||
assert!(stdout(&out).is_empty(), "{args:?} wrote to stdout");
|
||||
let err = stderr(&out);
|
||||
assert!(err.contains("error:"), "{args:?}: {err}");
|
||||
assert!(err.contains("Usage:"), "{args:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_adj_factors_cli_happy_path_publishes_verified_snapshot() {
|
||||
let dir = CliTempDir::new("adj-happy");
|
||||
let eod_path = dir.path.join("eod.bson");
|
||||
let splits_path = dir.path.join("splits.bson");
|
||||
let divs_path = dir.path.join("divs.bson");
|
||||
let map_path = dir.path.join("provider_mapping.tsv");
|
||||
let curr_path = dir.path.join("listing_currencies.tsv");
|
||||
let bars_out = dir.path.join("bars_out");
|
||||
let adj_out = dir.path.join("adj_out");
|
||||
|
||||
write_file(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2015-01-01\t\t100\nqm\tNVDA:US\t2015-01-01\t\t100\n",
|
||||
);
|
||||
write_file(&curr_path, b"100\tUSD\n");
|
||||
write_file(
|
||||
&eod_path,
|
||||
&[
|
||||
make_eod_doc("NVDA.US", "2024-06-07", 1208.88, 410_000_000.0).as_slice(),
|
||||
make_eod_doc("NVDA.US", "2024-06-10", 121.79, 310_000_000.0).as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
write_file(&splits_path, &make_split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
write_file(
|
||||
&divs_path,
|
||||
&make_div_doc("NVDA:US", "2024-06-11", 0.01, "USD"),
|
||||
);
|
||||
|
||||
// First produce curated bars_1d via curate-bars-1d.
|
||||
let bars_res = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
bars_out.to_str().unwrap(),
|
||||
]);
|
||||
assert!(bars_res.status.success(), "{}", stderr(&bars_res));
|
||||
|
||||
// Then run curate-adj-factors against that bars_1d dataset.
|
||||
let adj_res = run(&[
|
||||
"curate-adj-factors",
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--qm-dividends",
|
||||
divs_path.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--bars-1d",
|
||||
bars_out.join("bars_1d").to_str().unwrap(),
|
||||
"--out",
|
||||
adj_out.to_str().unwrap(),
|
||||
]);
|
||||
assert!(adj_res.status.success(), "{}", stderr(&adj_res));
|
||||
assert!(stderr(&adj_res).is_empty(), "{}", stderr(&adj_res));
|
||||
let text = stdout(&adj_res);
|
||||
assert!(text.contains("curate-etl curate-adj-factors"), "{text}");
|
||||
assert!(text.contains("with_prev_close=1"), "{text}");
|
||||
assert!(text.contains("rows_written=2"), "{text}");
|
||||
assert!(adj_out.join("adj_factors/part.parquet").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_adj_cmd_small_run_is_deterministic_and_reports_stages() {
|
||||
let a = run(&["bench-curate-adj-cmd", "2000"]);
|
||||
let b = run(&["bench-curate-adj-cmd", "2000"]);
|
||||
assert!(a.status.success(), "{}", stderr(&a));
|
||||
assert!(b.status.success(), "{}", stderr(&b));
|
||||
assert!(stderr(&a).is_empty(), "{}", stderr(&a));
|
||||
assert!(stderr(&b).is_empty(), "{}", stderr(&b));
|
||||
|
||||
let text_a = stdout(&a);
|
||||
let text_b = stdout(&b);
|
||||
assert!(text_a.contains("curate-etl bench-curate-adj-cmd"), "{text_a}");
|
||||
assert!(text_a.contains("events=2000 "), "{text_a}");
|
||||
assert!(text_a.contains("bars_load:"), "{text_a}");
|
||||
assert!(text_a.contains("decode:"), "{text_a}");
|
||||
assert!(text_a.contains("curate:"), "{text_a}");
|
||||
assert!(text_a.contains("write:"), "{text_a}");
|
||||
assert!(text_a.contains("total:"), "{text_a}");
|
||||
assert!(text_a.contains("checksum=0x"), "{text_a}");
|
||||
|
||||
let field = |s: &str, prefix: &str| {
|
||||
s.split_whitespace()
|
||||
.find(|t| t.starts_with(prefix))
|
||||
.map(str::to_owned)
|
||||
};
|
||||
assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum="));
|
||||
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue