T-114: M1.2ad — tools/curate-etl: fifth runnable command curate-shorts (concatenated-BSON ceoShorts file + provider_mapping TSV → shorts/part.parquet) with a zero-copy ceoShorts decoder, end-to-end tests and local benchmark (no new crates, no MongoDB connection)

This commit is contained in:
Studio 2026-11-29 03:42:40 -05:00
parent f6daec2801
commit d4671f39d5
13 changed files with 3678 additions and 9 deletions

View file

@ -1312,3 +1312,76 @@ Measured locally (`2026-11-29`, post-fix `curate-fx-1d` with full-document corru
- **Unverified live `teMarketData` schema & `t` unit:** `bson_te_market_data::FIELD_*` constants and the `|t| >= 100_000_000_000` ms/s threshold are derived from `market-data-fetch.action.ts` and have not yet been verified against a live `mongodump` export.
- **`eodPrices` `volume` field:** `decode_eod_price_chunks` still requires a non-negative `volume` field on `CAD.FOREX` documents (ignored when mapping to `FxDailyBar`); if a live `CAD.FOREX` dump omits `volume`, those docs will surface in `eod_bson.rejected (missing=...)`.
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB connection, and `fx_1m` is out of scope.
## `curate-shorts` Command (`M1.2ad`)
End-to-end file-to-Parquet CLI command (`src/run_curate_shorts.rs`) wiring `RawBsonChunkReader`, the zero-copy `ceoShorts` decoder (`src/bson_ceo_shorts.rs`, `decode_ceo_shorts_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_shorts` into an atomically published `<out>/shorts/part.parquet` dataset (`+4` Canadian TSX business days at `17:00 America/Toronto`, `source = "ceo_shorts"`) with zero extra crates and no database connections.
### Invocation
```bash
curate-etl curate-shorts \
--ceo-shorts ceoShorts.bson \
--provider-mapping provider_mapping.tsv \
--out ./out \
--shares-short-field <name> \
[--key-field symbol] \
[--report-date-field timestamp] \
[--net-change-field <name>] \
[--pct-float-field <name>] \
[--mapping-source ceo]
```
Inputs and output:
- `--ceo-shorts <path>` *(required)*: concatenated raw BSON (`mongodump` `ceoShorts.bson`).
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
- `--out <dir>` *(required)*: dataset root where `shorts/part.parquet` is atomically published.
- `--shares-short-field <name>` *(required, no default)*: BSON field name holding the short-share count (intentionally has no default because live `ceoShorts` value field names are unverified in the repo).
- `--key-field <name>` *(optional, default `symbol`)*: BSON field name holding the security key (passed verbatim to `provider_mapping` without trimming or suffix stripping).
- `--report-date-field <name>` *(optional, default `timestamp`)*: BSON field name holding the report period date.
- `--net-change-field <name>` *(optional)*: BSON field name holding optional net change vs. prior report.
- `--pct-float-field <name>` *(optional)*: BSON field name holding optional percent-of-float short.
- `--mapping-source <name>` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, report_date) -> listing_id`.
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 `--`). Missing required flags (including `--shares-short-field`), duplicate flags, unknown flags, empty/blank field names or `--mapping-source`, positional arguments, and any two configured roles resolving to the same BSON field name (checked after applying defaults) exit non-zero with usage on stderr. Any runtime error (missing input file, malformed or overlapping `provider_mapping.tsv`, truncated/corrupt/oversized BSON framing or element bytes, out-of-range `report_date`, or obstructed `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/shorts/part.parquet` byte-identical).
### `ceoShorts` Decoder Rules
- Scans every element of each `RawDocument` to completion before applying semantic skip priority (`key` → `report_date` → `shares_short`) so structural BSON corruption always fails closed with a typed error carrying the absolute byte offset.
- `key`: BSON UTF-8 `String` passed through verbatim (empty/whitespace-only, missing, or wrong type skipped and counted).
- `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)` checked to `i32`), or `Int32` / `Int64` / integral finite `Double` via `te_epoch_i64_to_session_date` (seconds vs. milliseconds UTC). Non-finite or fractional `Double`s skip under `invalid_date`; values overflowing `i64`/`i32` skip under `date_oor`.
- `shares_short`: strict BSON `Double`, `Int32`, or `Int64` (numeric strings are rejected as `wrong_shares_type`). Sign and finiteness validation remains in `build_shorts`.
- `net_change` / `pct_float`: unconfigured, absent, or BSON `Null` → `None`; wrong BSON type → `None` and counted in `nulled_wrong_type` (only on emitted rows).
- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0`, leaving any pre-existing `shorts/part.parquet` untouched.
### Report Counters & Conservation Invariants
On success, `curate-shorts` prints deterministic `key=value` lines to stdout (`ceo_bson`, `builder`, `curate`, `write`, and `timing`):
- **BSON Decode:** `ceo_bson.docs_framed == ceo_bson.docs_in == ceo_bson.rows_out + ceo_bson.skipped`
- **Builder:** `ceo_bson.rows_out == builder.rows_in == builder.rows_out + builder.invalid_shares + builder.dup_collapsed + builder.dup_conflict`
- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.coll_collapsed + curate.coll_dropped`, and `write.rows_written == curate.rows_out`
### `bench-curate-shorts-command`
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing a concatenated-BSON `ceoShorts` file (default `700,000` docs, `12,500` keys across the 218 semi-monthly dates `2017-04-15..=2026-04-30`, mixing `DateTime`/`Int32`/`Int64`/`Double` dates, optional fields with nulls and wrong types, ~0.5% semantically skipped docs, invalid `shares_short`, alias keys, and unmapped keys) plus `provider_mapping.tsv` into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
```bash
cargo run -p curate-etl --release --offline -- bench-curate-shorts-command [rows]
```
Measured locally (`2026-11-29`, Linux `6.8.0-151-generic`, AMD Ryzen 9 9950X3D 16-Core Processor, default `700,000` rows; two back-to-back runs with identical checksum `0xc83dd4cd79c6de64`):
- Input: `rows=700000`, `docs_framed=700000`, `bytes_read=67955103` (`64.81 MiB`), `keys=12500`, `peak_chunk_bytes=8388608` (`8 MiB`)
- Decode counts: `rows_out=696500`, `skipped=3500`, `nulled_net_change=7000`, `nulled_pct_float=5834`
- Output: `rows_out=682500` (`97.50%` retained), `listings_out=12250`, `dropped_unmapped=10500`, `invalid_shares=3500`, `files=1`, `row_groups=1`, `bytes=5891286`, `read_back_rows=682500`
- Run 1: `decode=108.96 ms` (`6,424,653 rows/s`, `594.80 MB/s`), `curate=129.29 ms` (`5,387,095 rows/s`), `write=86.75 ms` (`7,867,006 rows/s`, `64.76 MB/s`), `total=325.00 ms` (`2,153,843 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xc83dd4cd79c6de64`
- Run 2: `decode=108.20 ms` (`6,469,586 rows/s`, `598.96 MB/s`), `curate=129.44 ms` (`5,380,992 rows/s`), `write=83.96 ms` (`8,129,295 rows/s`, `66.92 MB/s`), `total=321.59 ms` (`2,176,676 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xc83dd4cd79c6de64`
### Known Limitations
- **Unverified live `ceoShorts` field names and `timestamp` unit/timezone:** `ceoShorts` value field names (`--shares-short-field`, `--net-change-field`, `--pct-float-field`, `--key-field`) and `timestamp` unit/timezone are unverified against live QA MongoDB data. Confirm them before the first real run with the read-only field-shape probe:
```bash
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections ceoShorts --out <path>
```
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connection, and `pct_float` is passed through as supplied rather than derived from shares outstanding.

View file

@ -9086,6 +9086,399 @@ pub fn run_curate_fx_cmd_benchmark(
Ok(report)
}
/// Default document count for `bench-curate-shorts-command` (~700k `ceoShorts` docs).
pub const DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS: usize = 700_000;
const CURATE_SHORTS_CMD_BENCH_SEED: u64 = 0x570C_4B07_CE05_0A75;
const CURATE_SHORTS_CMD_BENCH_KEYS: usize = 12_500;
/// Errors returned by [`run_curate_shorts_command_benchmark`].
#[derive(Debug)]
pub enum CurateShortsCmdBenchError {
FixtureIo {
path: PathBuf,
source: io::Error,
},
Run(crate::run_curate_shorts::RunCurateShortsError),
Verify(ParquetShortsError),
}
impl std::fmt::Display for CurateShortsCmdBenchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::FixtureIo { path, source } => {
write!(f, "benchmark fixture I/O '{}': {source}", path.display())
}
Self::Run(err) => write!(f, "{err}"),
Self::Verify(err) => write!(f, "Parquet verify failed: {err}"),
}
}
}
impl std::error::Error for CurateShortsCmdBenchError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::FixtureIo { source, .. } => Some(source),
Self::Run(err) => Some(err),
Self::Verify(err) => Some(err),
}
}
}
/// Summary metrics produced by [`run_curate_shorts_command_benchmark`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CurateShortsCmdBenchReport {
pub rows: usize,
pub key_count: usize,
pub docs_framed: u64,
pub bytes_read: u64,
pub peak_chunk_bytes: 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 decode_elapsed_ms: f64,
pub decode_rows_per_sec: f64,
pub input_mb_per_sec: f64,
pub curate_elapsed_ms: f64,
pub curate_rows_per_sec: f64,
pub write_elapsed_ms: f64,
pub write_rows_per_sec: f64,
pub write_mb_per_sec: f64,
pub total_elapsed_ms: f64,
pub total_rows_per_sec: f64,
pub checksum: u64,
pub decode: crate::bson_ceo_shorts::BsonCeoShortsDecodeStats,
pub curate_stats: crate::curate_shorts::CurateShortsStats,
}
fn run_curate_shorts_command_benchmark_tracked(
rows: usize,
) -> Result<(CurateShortsCmdBenchReport, PathBuf), CurateShortsCmdBenchError> {
use std::io::{BufWriter, Write};
use bson::raw::{cstr, RawBson, RawDocumentBuf};
use bson::DateTime as BsonDateTime;
use crate::bson_ceo_shorts::{
BsonCeoShortsDecodeStats, DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD,
};
use crate::curate_shorts::CurateShortsStats;
use crate::run_curate_shorts::{
run_curate_shorts_timed, CurateShortsArgs, DEFAULT_MAPPING_SOURCE,
};
const MIB: f64 = 1024.0 * 1024.0;
let temp = BenchTempDir::new_in_with_prefix(
&std::env::temp_dir(),
"curate-etl-bench-curate-shorts-cmd",
)
.map_err(|(path, source)| CurateShortsCmdBenchError::FixtureIo { path, source })?;
let temp_path = temp.path.clone();
if rows == 0 {
drop(temp);
return Ok((
CurateShortsCmdBenchReport {
rows: 0,
key_count: 0,
docs_framed: 0,
bytes_read: 0,
peak_chunk_bytes: 0,
rows_out: 0,
listings_out: 0,
files_written: 0,
row_groups_written: 0,
bytes_written: 0,
read_back_rows: 0,
decode_elapsed_ms: 0.0,
decode_rows_per_sec: 0.0,
input_mb_per_sec: 0.0,
curate_elapsed_ms: 0.0,
curate_rows_per_sec: 0.0,
write_elapsed_ms: 0.0,
write_rows_per_sec: 0.0,
write_mb_per_sec: 0.0,
total_elapsed_ms: 0.0,
total_rows_per_sec: 0.0,
checksum: 0,
decode: BsonCeoShortsDecodeStats::default(),
curate_stats: CurateShortsStats::default(),
},
temp_path,
));
}
let key_count = CURATE_SHORTS_CMD_BENCH_KEYS;
let all_dates = semi_monthly_report_dates();
let date_count = all_dates.len();
let map_path = temp.path.join("provider_mapping.tsv");
let bson_path = temp.path.join("ceoShorts.bson");
let out_dir = temp.path.join("out");
// 1. Write provider_mapping.tsv:
// - 96% mapped single-range keys
// - 2% reuse-gap keys (2017-01-01..=2020-12-31 -> L, 2022-01-01.. -> L + 50_000)
// - 2% unmapped keys (omitted from TSV)
// - Plus 200 alias keys mapping to listing_ids 1..=200 for cross-key collisions.
{
let f = File::create(&map_path).map_err(|source| CurateShortsCmdBenchError::FixtureIo {
path: map_path.clone(),
source,
})?;
let mut w = BufWriter::with_capacity(256 * 1024, f);
for k in 0..key_count {
let listing_id = (k as i32) + 1;
let bucket = k % 50;
if bucket == 49 {
// Unmapped key
continue;
} else if bucket == 48 {
writeln!(
w,
"{DEFAULT_MAPPING_SOURCE}\tCEO{k:05}\t2017-01-01\t2020-12-31\t{listing_id}"
)
.and_then(|()| {
writeln!(
w,
"{DEFAULT_MAPPING_SOURCE}\tCEO{k:05}\t2022-01-01\t\t{}",
listing_id + 50_000
)
})
.map_err(|source| CurateShortsCmdBenchError::FixtureIo {
path: map_path.clone(),
source,
})?;
} else {
writeln!(
w,
"{DEFAULT_MAPPING_SOURCE}\tCEO{k:05}\t2017-01-01\t\t{listing_id}"
)
.map_err(|source| CurateShortsCmdBenchError::FixtureIo {
path: map_path.clone(),
source,
})?;
}
}
for a in 0..200usize {
let listing_id = (a as i32) + 1;
writeln!(
w,
"{DEFAULT_MAPPING_SOURCE}\tALIAS{a:03}\t2017-01-01\t\t{listing_id}"
)
.map_err(|source| CurateShortsCmdBenchError::FixtureIo {
path: map_path.clone(),
source,
})?;
}
w.flush()
.map_err(|source| CurateShortsCmdBenchError::FixtureIo {
path: map_path.clone(),
source,
})?;
}
// 2. Write synthetic concatenated-BSON ceoShorts file with fixed-seed SplitMix64.
{
let f = File::create(&bson_path).map_err(|source| {
CurateShortsCmdBenchError::FixtureIo {
path: bson_path.clone(),
source,
}
})?;
let mut w = BufWriter::with_capacity(1024 * 1024, f);
let mut rng = SplitMix64::new(CURATE_SHORTS_CMD_BENCH_SEED);
for i in 0..rows {
let r = rng.next_u64();
let key_idx = i % key_count;
let date_idx = (i / key_count) % date_count;
let report_date = all_dates[date_idx];
let epoch_secs = i64::from(report_date) * 86_400;
let epoch_millis = epoch_secs * 1_000;
let mut doc = RawDocumentBuf::new();
// ~0.5% semantically skipped docs (1 in 200)
if i % 200 == 199 {
match (i / 200) % 4 {
0 => {
doc.append(cstr!("symbol"), "");
doc.append(cstr!("timestamp"), epoch_secs);
doc.append(cstr!("sharesShort"), 1_000_i32);
}
1 => {
doc.append(cstr!("symbol"), format!("CEO{key_idx:05}"));
doc.append(cstr!("timestamp"), "2024-03-15");
doc.append(cstr!("sharesShort"), 1_000_i32);
}
2 => {
doc.append(cstr!("symbol"), format!("CEO{key_idx:05}"));
doc.append(cstr!("timestamp"), epoch_secs as f64 + 0.5);
doc.append(cstr!("sharesShort"), 1_000_i32);
}
_ => {
doc.append(cstr!("symbol"), format!("CEO{key_idx:05}"));
doc.append(cstr!("timestamp"), epoch_secs);
doc.append(cstr!("sharesShort"), "bad_num");
}
}
w.write_all(doc.as_bytes()).map_err(|source| {
CurateShortsCmdBenchError::FixtureIo {
path: bson_path.clone(),
source,
}
})?;
continue;
}
// Pick key: occasional alias collision on first 200 keys
let use_alias = key_idx < 200 && i % 40 == 7;
if use_alias {
doc.append(cstr!("symbol"), format!("ALIAS{key_idx:03}"));
} else {
doc.append(cstr!("symbol"), format!("CEO{key_idx:05}"));
}
// Mix report_date BSON encodings: DateTime, Int32 secs, Int64 secs, Int64 millis, integral Double
match i % 5 {
0 => doc.append(cstr!("timestamp"), BsonDateTime::from_millis(epoch_millis)),
1 => doc.append(cstr!("timestamp"), epoch_secs as i32),
2 => doc.append(cstr!("timestamp"), epoch_secs),
3 => doc.append(cstr!("timestamp"), epoch_millis),
_ => doc.append(cstr!("timestamp"), epoch_secs as f64),
}
// ~0.5% invalid shares_short (negative), otherwise deterministic positive count
let shares_short = if i % 200 == 100 {
-50.0
} else {
((r % 5_000_000) as f64) * 1.0
};
doc.append(cstr!("sharesShort"), shares_short);
// Optional netChange: present, null, absent, or occasional wrong type
match i % 10 {
0 => doc.append(cstr!("netChange"), RawBson::Null),
1 => {} // absent
2 if i % 100 == 2 => doc.append(cstr!("netChange"), "n/a"),
_ => {
let delta = ((r >> 16) % 200_000) as f64 - 100_000.0;
doc.append(cstr!("netChange"), delta);
}
}
// Optional pctFloat: present, null, absent, or occasional wrong type
match i % 12 {
0 => doc.append(cstr!("pctFloat"), RawBson::Null),
1 => {} // absent
3 if i % 120 == 3 => doc.append(cstr!("pctFloat"), true),
_ => {
let pct = ((r >> 32) % 2500) as f64 / 100.0;
doc.append(cstr!("pctFloat"), pct);
}
}
w.write_all(doc.as_bytes()).map_err(|source| {
CurateShortsCmdBenchError::FixtureIo {
path: bson_path.clone(),
source,
}
})?;
}
w.flush()
.map_err(|source| CurateShortsCmdBenchError::FixtureIo {
path: bson_path.clone(),
source,
})?;
}
let args = CurateShortsArgs {
ceo_shorts: bson_path,
provider_mapping: map_path,
out_dir: out_dir.clone(),
key_field: DEFAULT_KEY_FIELD.to_string(),
report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(),
shares_short_field: "sharesShort".to_string(),
net_change_field: Some("netChange".to_string()),
pct_float_field: Some("pctFloat".to_string()),
mapping_source: DEFAULT_MAPPING_SOURCE.to_string(),
};
let timed = run_curate_shorts_timed(&args).map_err(CurateShortsCmdBenchError::Run)?;
let read_back_rows =
verify_parquet_shorts_row_count(&out_dir, timed.report.curate_stats.rows_out)
.map_err(CurateShortsCmdBenchError::Verify)?;
let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0;
let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0;
let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0;
let total_elapsed_secs =
timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs;
let total_elapsed_ms = total_elapsed_secs * 1_000.0;
let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs);
let (curate_rows_per_sec, _) =
compute_rates(timed.report.decode.rows_out, timed.curate_elapsed_secs);
let (write_rows_per_sec, _) =
compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs);
let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs);
let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 {
(timed.report.bytes_read 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 = CurateShortsCmdBenchReport {
rows,
key_count,
docs_framed: timed.report.docs_framed,
bytes_read: timed.report.bytes_read,
peak_chunk_bytes: timed.report.peak_chunk_bytes,
rows_out: timed.report.curate_stats.rows_out,
listings_out: timed.report.curate_stats.listings_out,
files_written: timed.report.write_stats.files_written,
row_groups_written: timed.report.write_stats.row_groups_written,
bytes_written: timed.report.write_stats.bytes_written,
read_back_rows,
decode_elapsed_ms,
decode_rows_per_sec,
input_mb_per_sec,
curate_elapsed_ms,
curate_rows_per_sec,
write_elapsed_ms,
write_rows_per_sec,
write_mb_per_sec,
total_elapsed_ms,
total_rows_per_sec,
checksum: timed.checksum,
decode: timed.report.decode,
curate_stats: timed.report.curate_stats,
};
drop(temp);
Ok((report, temp_path))
}
/// Runs the fixed-seed end-to-end `curate-shorts` file -> Parquet benchmark for `rows` synthetic
/// `ceoShorts` BSON documents and `provider_mapping.tsv`.
pub fn run_curate_shorts_command_benchmark(
rows: usize,
) -> Result<CurateShortsCmdBenchReport, CurateShortsCmdBenchError> {
let (report, _) = run_curate_shorts_command_benchmark_tracked(rows)?;
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
@ -10960,4 +11353,50 @@ mod tests {
assert_eq!(report.read_back_rows, 0);
assert_eq!(report.checksum, 0);
}
#[test]
fn curate_shorts_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() {
let (a, dir_a) = run_curate_shorts_command_benchmark_tracked(5_000).unwrap();
let (b, dir_b) = run_curate_shorts_command_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.rows, 5_000);
assert_eq!(a.checksum, b.checksum);
assert_ne!(a.checksum, 0);
assert_eq!(a.rows_out, b.rows_out);
assert!(a.rows_out > 0);
assert_eq!(a.read_back_rows, a.rows_out);
assert_eq!(a.files_written, 1);
assert_eq!(a.bytes_written, b.bytes_written);
assert!(a.peak_chunk_bytes > 0);
assert!(a.decode.skipped_total() > 0);
assert!(a.curate_stats.dropped_unmapped > 0);
// Conservation invariants
assert_eq!(a.docs_framed as usize, a.decode.docs_in);
assert_eq!(a.decode.docs_in, a.decode.rows_out + a.decode.skipped_total());
assert_eq!(a.decode.rows_out, a.curate_stats.builder.rows_in);
assert_eq!(a.curate_stats.rows_in, a.curate_stats.builder.rows_out);
assert_eq!(
a.curate_stats.rows_in,
a.curate_stats.rows_out
+ a.curate_stats.dropped_unmapped
+ a.curate_stats.listing_collision_collapsed
+ a.curate_stats.listing_collision_dropped
);
}
#[test]
fn curate_shorts_cmd_benchmark_zero_rows_handles_cleanly() {
let (report, dir) = run_curate_shorts_command_benchmark_tracked(0).unwrap();
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
assert_eq!(report.rows, 0);
assert_eq!(report.docs_framed, 0);
assert_eq!(report.rows_out, 0);
assert_eq!(report.files_written, 0);
assert_eq!(report.bytes_written, 0);
assert_eq!(report.read_back_rows, 0);
assert_eq!(report.checksum, 0);
}
}

View file

@ -0,0 +1,542 @@
//! Zero-copy raw BSON decoder for MongoDB `ceoShorts` documents (`M1.2ad`).
//!
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
//! allocating a `bson::Document` or per-row `String`s, emitting borrowed [`CeoShortReport<&str>`]
//! rows via a caller-supplied callback.
//!
//! # Unverified Live Schema & Explicit Field Configuration
//!
//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts` stores the upstream
//! `positions[]` payload verbatim, and `design/DATA-CONTRACTS.md` §1 only establishes `timestamp`
//! (the report period date). The value field names are not recorded anywhere in the repository, so
//! callers must supply all field names explicitly via [`CeoShortsFieldNames`] (and the CLI
//! requires `--shares-short-field` with no default).
//!
//! # Decoding & Validation Rules
//! - Every element of each [`RawDocument`] is scanned to completion before applying semantic skip
//! rules so structural BSON corruption always returns `Err(BsonCeoShortsError::CorruptBson)`
//! rather than being masked by an earlier semantic skip.
//! - `key`: BSON UTF-8 `String` passed through verbatim (no trimming, no suffix stripping); empty
//! or whitespace-only strings are skipped (`skipped_empty_key`).
//! - `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)`
//! checked to `i32`), or `Int32` / `Int64` / integral finite `Double` converted via
//! [`crate::bson_te_market_data::te_epoch_i64_to_session_date`] (seconds vs. milliseconds UTC).
//! Non-finite or fractional `Double`s are skipped under `skipped_invalid_report_date`; values
//! outside `i64`/`i32` epoch-day range are skipped under `skipped_report_date_out_of_range`.
//! - `shares_short`: BSON `Double`, `Int32`, or `Int64` (strings are rejected as wrong type per
//! crate convention). Sign and finiteness validation remains in [`crate::shorts::build_shorts`].
//! - `net_change` and `pct_float`: optional; unconfigured, absent, or BSON `Null` yields `None`;
//! wrong BSON type yields `None` and increments `nulled_wrong_type_*` (only on emitted rows).
//! - Deterministic semantic skip priority: `key` → `report_date` → `shares_short`.
//! - Conservation invariant: `docs_in == rows_out + skipped_total()`.
use std::error::Error;
use std::fmt;
use bson::raw::{RawBsonRef, RawDocument};
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
use crate::bson_te_market_data::{te_epoch_i64_to_session_date, MILLIS_PER_DAY};
use crate::shorts::CeoShortReport;
/// Default BSON field name for the `ceoShorts` security key (`--key-field`).
pub const DEFAULT_KEY_FIELD: &str = "symbol";
/// Default BSON field name for the `ceoShorts` report period date (`--report-date-field`).
pub const DEFAULT_REPORT_DATE_FIELD: &str = "timestamp";
/// Borrowed BSON field-name configuration for decoding `ceoShorts` documents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CeoShortsFieldNames<'a> {
pub key: &'a str,
pub report_date: &'a str,
pub shares_short: &'a str,
pub net_change: Option<&'a str>,
pub pct_float: Option<&'a str>,
}
impl<'a> CeoShortsFieldNames<'a> {
/// Validates that every configured field name is non-empty/non-blank and that no two
/// configured roles point to the same BSON field name.
pub fn validate(&self) -> Result<(), BsonCeoShortsError> {
let mut roles: [(&'static str, Option<&str>); 5] = [
("key", Some(self.key)),
("report_date", Some(self.report_date)),
("shares_short", Some(self.shares_short)),
("net_change", self.net_change),
("pct_float", self.pct_float),
];
for &(role, name_opt) in &roles {
if let Some(name) = name_opt {
if name.trim().is_empty() {
return Err(BsonCeoShortsError::InvalidFieldNames {
detail: format!("field name for '{role}' must not be empty or blank"),
});
}
}
}
for i in 0..roles.len() {
let (role_a, Some(name_a)) = roles[i] else {
continue;
};
for &(role_b, name_b_opt) in &roles[i + 1..] {
if let Some(name_b) = name_b_opt {
if name_a == name_b {
return Err(BsonCeoShortsError::InvalidFieldNames {
detail: format!(
"roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'"
),
});
}
}
}
}
// Keep `roles` binding clean without unused_mut warnings.
let _ = &mut roles;
Ok(())
}
}
/// Typed errors returned while validating field configuration or decoding raw `ceoShorts` BSON.
///
/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset;
/// every variant's `Display` output is a single line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BsonCeoShortsError {
/// Invalid [`CeoShortsFieldNames`] configuration (empty/blank name or duplicate role mapping).
InvalidFieldNames { detail: String },
/// Buffer ended before a complete 4-byte length prefix or declared document body.
TruncatedDocument {
offset: u64,
remaining: usize,
declared_len: Option<i32>,
},
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
/// document slice).
CorruptDocumentLength { offset: u64, declared_len: i32 },
/// Underlying BSON framing or element bytes were malformed.
CorruptBson { offset: u64, detail: String },
}
impl fmt::Display for BsonCeoShortsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFieldNames { detail } => {
write!(f, "invalid ceoShorts field configuration: {detail}")
}
Self::TruncatedDocument {
offset,
remaining,
declared_len,
} => match declared_len {
Some(len) => write!(
f,
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
),
None => write!(
f,
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
),
},
Self::CorruptDocumentLength {
offset,
declared_len,
} => write!(
f,
"corrupt BSON document length {declared_len} at byte offset {offset}"
),
Self::CorruptBson { offset, detail } => {
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
}
}
}
}
impl Error for BsonCeoShortsError {}
#[inline]
fn map_framing_error(err: BsonEodPriceError) -> BsonCeoShortsError {
match err {
BsonEodPriceError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonCeoShortsError::TruncatedDocument {
offset: offset as u64,
remaining,
declared_len,
},
BsonEodPriceError::CorruptDocumentLength {
offset,
declared_len,
} => BsonCeoShortsError::CorruptDocumentLength {
offset: offset as u64,
declared_len,
},
BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoShortsError::CorruptBson {
offset: offset as u64,
detail,
},
other => BsonCeoShortsError::CorruptBson {
offset: 0,
detail: other.to_string(),
},
}
}
/// Per-batch decode accounting for `ceoShorts`.
///
/// Conservation invariant:
/// `docs_in == rows_out + skipped_total()`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BsonCeoShortsDecodeStats {
pub docs_in: usize,
pub rows_out: usize,
pub skipped_missing_key: usize,
pub skipped_wrong_key_type: usize,
pub skipped_empty_key: usize,
pub skipped_missing_report_date: usize,
pub skipped_wrong_report_date_type: usize,
pub skipped_invalid_report_date: usize,
pub skipped_report_date_out_of_range: usize,
pub skipped_missing_shares_short: usize,
pub skipped_wrong_shares_short_type: usize,
pub nulled_wrong_type_net_change: usize,
pub nulled_wrong_type_pct_float: usize,
}
impl BsonCeoShortsDecodeStats {
/// Total number of semantically skipped documents across all skip categories.
#[inline]
pub fn skipped_total(&self) -> usize {
self.skipped_missing_key
+ self.skipped_wrong_key_type
+ self.skipped_empty_key
+ self.skipped_missing_report_date
+ self.skipped_wrong_report_date_type
+ self.skipped_invalid_report_date
+ self.skipped_report_date_out_of_range
+ self.skipped_missing_shares_short
+ self.skipped_wrong_shares_short_type
}
/// Accumulates counters from another batch into `self`.
#[inline]
pub fn merge(&mut self, other: &Self) {
self.docs_in += other.docs_in;
self.rows_out += other.rows_out;
self.skipped_missing_key += other.skipped_missing_key;
self.skipped_wrong_key_type += other.skipped_wrong_key_type;
self.skipped_empty_key += other.skipped_empty_key;
self.skipped_missing_report_date += other.skipped_missing_report_date;
self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type;
self.skipped_invalid_report_date += other.skipped_invalid_report_date;
self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range;
self.skipped_missing_shares_short += other.skipped_missing_shares_short;
self.skipped_wrong_shares_short_type += other.skipped_wrong_shares_short_type;
self.nulled_wrong_type_net_change += other.nulled_wrong_type_net_change;
self.nulled_wrong_type_pct_float += other.nulled_wrong_type_pct_float;
}
}
impl std::ops::AddAssign for BsonCeoShortsDecodeStats {
#[inline]
fn add_assign(&mut self, rhs: Self) {
self.merge(&rhs);
}
}
enum KeyState<'a> {
Missing,
WrongType,
Empty,
Valid(&'a str),
}
enum DateState {
Missing,
WrongType,
Invalid,
OutOfRange,
Valid(i32),
}
enum SharesState {
Missing,
WrongType,
Valid(f64),
}
enum OptionalNumState {
None,
WrongType,
Valid(f64),
}
#[inline]
fn decode_report_date_val(val: RawBsonRef<'_>) -> DateState {
match val {
RawBsonRef::DateTime(dt) => {
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
match i32::try_from(days) {
Ok(d) => DateState::Valid(d),
Err(_) => DateState::OutOfRange,
}
}
RawBsonRef::Int32(v) => match te_epoch_i64_to_session_date(i64::from(v)) {
Some(d) => DateState::Valid(d),
None => DateState::OutOfRange,
},
RawBsonRef::Int64(v) => match te_epoch_i64_to_session_date(v) {
Some(d) => DateState::Valid(d),
None => DateState::OutOfRange,
},
RawBsonRef::Double(v) => {
if !v.is_finite() || v.fract() != 0.0 {
return DateState::Invalid;
}
// Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`).
if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) {
return DateState::OutOfRange;
}
match te_epoch_i64_to_session_date(v as i64) {
Some(d) => DateState::Valid(d),
None => DateState::OutOfRange,
}
}
_ => DateState::WrongType,
}
}
#[inline]
fn decode_required_number(val: RawBsonRef<'_>) -> SharesState {
match val {
RawBsonRef::Double(v) => SharesState::Valid(v),
RawBsonRef::Int32(v) => SharesState::Valid(f64::from(v)),
RawBsonRef::Int64(v) => SharesState::Valid(v as f64),
_ => SharesState::WrongType,
}
}
#[inline]
fn decode_optional_number(val: RawBsonRef<'_>) -> OptionalNumState {
match val {
RawBsonRef::Null => OptionalNumState::None,
RawBsonRef::Double(v) => OptionalNumState::Valid(v),
RawBsonRef::Int32(v) => OptionalNumState::Valid(f64::from(v)),
RawBsonRef::Int64(v) => OptionalNumState::Valid(v as f64),
_ => OptionalNumState::WrongType,
}
}
fn decode_ceo_shorts_doc_at<'a, F>(
doc: &'a RawDocument,
doc_offset: u64,
fields: &CeoShortsFieldNames<'_>,
mut on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
where
F: FnMut(CeoShortReport<&'a str>),
{
let mut stats = BsonCeoShortsDecodeStats {
docs_in: 1,
..BsonCeoShortsDecodeStats::default()
};
let mut key_state = KeyState::Missing;
let mut date_state = DateState::Missing;
let mut shares_state = SharesState::Missing;
let mut net_change_state = OptionalNumState::None;
let mut pct_float_state = OptionalNumState::None;
// Scan all elements to completion so structural BSON corruption is never masked by an earlier
// semantic skip.
for elem_res in doc.iter_elements() {
let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson {
offset: doc_offset,
detail: err.to_string(),
})?;
let name = elem.key().as_str();
if name == fields.key {
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{}': {err}", fields.key),
})?;
key_state = match val {
RawBsonRef::String(s) => {
if s.trim().is_empty() {
KeyState::Empty
} else {
KeyState::Valid(s)
}
}
_ => KeyState::WrongType,
};
} else if name == fields.report_date {
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{}': {err}", fields.report_date),
})?;
date_state = decode_report_date_val(val);
} else if name == fields.shares_short {
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{}': {err}", fields.shares_short),
})?;
shares_state = decode_required_number(val);
} else if fields.net_change == Some(name) {
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{name}': {err}"),
})?;
net_change_state = decode_optional_number(val);
} else if fields.pct_float == Some(name) {
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
offset: doc_offset,
detail: format!("field '{name}': {err}"),
})?;
pct_float_state = decode_optional_number(val);
}
}
// Apply deterministic semantic skip priority: key -> report_date -> shares_short.
let key = match key_state {
KeyState::Valid(s) => s,
KeyState::Missing => {
stats.skipped_missing_key += 1;
return Ok(stats);
}
KeyState::WrongType => {
stats.skipped_wrong_key_type += 1;
return Ok(stats);
}
KeyState::Empty => {
stats.skipped_empty_key += 1;
return Ok(stats);
}
};
let report_date = match date_state {
DateState::Valid(d) => d,
DateState::Missing => {
stats.skipped_missing_report_date += 1;
return Ok(stats);
}
DateState::WrongType => {
stats.skipped_wrong_report_date_type += 1;
return Ok(stats);
}
DateState::Invalid => {
stats.skipped_invalid_report_date += 1;
return Ok(stats);
}
DateState::OutOfRange => {
stats.skipped_report_date_out_of_range += 1;
return Ok(stats);
}
};
let shares_short = match shares_state {
SharesState::Valid(v) => v,
SharesState::Missing => {
stats.skipped_missing_shares_short += 1;
return Ok(stats);
}
SharesState::WrongType => {
stats.skipped_wrong_shares_short_type += 1;
return Ok(stats);
}
};
let net_change = match net_change_state {
OptionalNumState::Valid(v) => Some(v),
OptionalNumState::None => None,
OptionalNumState::WrongType => {
stats.nulled_wrong_type_net_change += 1;
None
}
};
let pct_float = match pct_float_state {
OptionalNumState::Valid(v) => Some(v),
OptionalNumState::None => None,
OptionalNumState::WrongType => {
stats.nulled_wrong_type_pct_float += 1;
None
}
};
stats.rows_out += 1;
on_row(CeoShortReport {
key,
report_date,
shares_short,
net_change,
pct_float,
});
Ok(stats)
}
/// Decodes a single `&RawDocument` representing a `ceoShorts` MongoDB document in one forward
/// pass without allocating a `bson::Document` or per-row `String`s.
pub fn decode_ceo_shorts_doc<'a, F>(
doc: &'a RawDocument,
fields: &CeoShortsFieldNames<'_>,
on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
where
F: FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
decode_ceo_shorts_doc_at(doc, 0, fields, on_row)
}
/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoShorts`
/// document.
pub fn decode_ceo_shorts_bytes<'a, F>(
bytes: &'a [u8],
fields: &CeoShortsFieldNames<'_>,
on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
where
F: FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
decode_ceo_shorts_doc_at(doc, 0, fields, on_row)
}
/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_shorts_doc`],
/// emitting every valid [`CeoShortReport<&str>`] to `on_row` and failing closed on any structural
/// BSON framing or element corruption.
///
/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`.
pub fn decode_ceo_shorts_buffer<'a, F>(
buf: &'a [u8],
fields: &CeoShortsFieldNames<'_>,
mut on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
where
F: FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
let mut total = BsonCeoShortsDecodeStats::default();
let mut iter = iter_raw_bson_docs(buf);
while let Some(item) = iter.next_with_offset() {
match item {
Ok((offset, doc)) => {
let doc_stats = decode_ceo_shorts_doc_at(doc, offset as u64, fields, &mut on_row)?;
total += doc_stats;
}
Err((_, err)) => return Err(map_framing_error(err)),
}
}
Ok(total)
}
#[cfg(test)]
#[path = "bson_ceo_shorts_tests.rs"]
mod tests;

View file

@ -0,0 +1,507 @@
use bson::raw::{cstr, RawBson, RawDocumentBuf};
use bson::DateTime as BsonDateTime;
use super::*;
use crate::split::ymd_to_epoch_days;
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn default_fields() -> CeoShortsFieldNames<'static> {
CeoShortsFieldNames {
key: DEFAULT_KEY_FIELD,
report_date: DEFAULT_REPORT_DATE_FIELD,
shares_short: "sharesShort",
net_change: Some("netChange"),
pct_float: Some("pctFloat"),
}
}
fn assert_conservation(stats: &BsonCeoShortsDecodeStats) {
assert_eq!(
stats.docs_in,
stats.rows_out + stats.skipped_total(),
"conservation invariant failed: {stats:?}"
);
}
#[test]
fn validates_field_names_rejecting_empty_blank_and_duplicates() {
assert!(default_fields().validate().is_ok());
let no_opt = CeoShortsFieldNames {
key: "k",
report_date: "d",
shares_short: "s",
net_change: None,
pct_float: None,
};
assert!(no_opt.validate().is_ok());
let bad_configs = [
CeoShortsFieldNames {
key: "",
..default_fields()
},
CeoShortsFieldNames {
key: " \t ",
..default_fields()
},
CeoShortsFieldNames {
report_date: "",
..default_fields()
},
CeoShortsFieldNames {
shares_short: " ",
..default_fields()
},
CeoShortsFieldNames {
net_change: Some(""),
..default_fields()
},
CeoShortsFieldNames {
pct_float: Some(" "),
..default_fields()
},
// Duplicate roles
CeoShortsFieldNames {
key: "same",
report_date: "same",
..default_fields()
},
CeoShortsFieldNames {
key: "symbol",
shares_short: "symbol",
..default_fields()
},
CeoShortsFieldNames {
report_date: "timestamp",
shares_short: "timestamp",
..default_fields()
},
CeoShortsFieldNames {
net_change: Some("sharesShort"),
..default_fields()
},
CeoShortsFieldNames {
pct_float: Some("netChange"),
..default_fields()
},
];
for cfg in bad_configs {
let err = cfg.validate().unwrap_err();
assert!(
matches!(err, BsonCeoShortsError::InvalidFieldNames { .. }),
"expected InvalidFieldNames for {cfg:?}, got {err:?}"
);
let msg = err.to_string();
assert!(!msg.contains('\n'), "single-line display expected: {msg}");
// Entry points also reject invalid config before touching bytes.
assert!(matches!(
decode_ceo_shorts_buffer(&[], &cfg, |_| {}),
Err(BsonCeoShortsError::InvalidFieldNames { .. })
));
}
}
#[test]
fn decodes_report_date_across_datetime_int32_int64_and_integral_double() {
let fields = default_fields();
let d_2024_03_15 = day(2024, 3, 15);
let secs_2024_03_15 = i64::from(d_2024_03_15) * 86_400 + 3_600; // 01:00 UTC
let millis_2024_03_15 = secs_2024_03_15 * 1_000 + 500;
let mut buf = Vec::new();
// 1. BSON DateTime
let mut doc1 = RawDocumentBuf::new();
doc1.append(cstr!("symbol"), "RY");
doc1.append(
cstr!("timestamp"),
BsonDateTime::from_millis(millis_2024_03_15),
);
doc1.append(cstr!("sharesShort"), 100_000_i32);
doc1.append(cstr!("netChange"), -5_000_i32);
doc1.append(cstr!("pctFloat"), 1.25_f64);
buf.extend_from_slice(doc1.as_bytes());
// 2. Int32 seconds
let mut doc2 = RawDocumentBuf::new();
doc2.append(cstr!("symbol"), "TD");
doc2.append(cstr!("timestamp"), secs_2024_03_15 as i32);
doc2.append(cstr!("sharesShort"), 250_000_i64);
doc2.append(cstr!("netChange"), 10_000_i64);
doc2.append(cstr!("pctFloat"), 2_i32);
buf.extend_from_slice(doc2.as_bytes());
// 3. Int64 seconds
let mut doc3 = RawDocumentBuf::new();
doc3.append(cstr!("symbol"), "BNS");
doc3.append(cstr!("timestamp"), secs_2024_03_15);
doc3.append(cstr!("sharesShort"), 300_000.5_f64);
buf.extend_from_slice(doc3.as_bytes());
// 4. Int64 millis
let mut doc4 = RawDocumentBuf::new();
doc4.append(cstr!("symbol"), "BMO");
doc4.append(cstr!("timestamp"), millis_2024_03_15);
doc4.append(cstr!("sharesShort"), 400_000.0_f64);
buf.extend_from_slice(doc4.as_bytes());
// 5. Integral finite Double (seconds)
let mut doc5 = RawDocumentBuf::new();
doc5.append(cstr!("symbol"), "CM");
doc5.append(cstr!("timestamp"), secs_2024_03_15 as f64);
doc5.append(cstr!("sharesShort"), 500_000.0_f64);
buf.extend_from_slice(doc5.as_bytes());
// 6. Integral finite Double (millis)
let mut doc6 = RawDocumentBuf::new();
doc6.append(cstr!("symbol"), "NA");
doc6.append(cstr!("timestamp"), millis_2024_03_15 as f64);
doc6.append(cstr!("sharesShort"), 600_000.0_f64);
buf.extend_from_slice(doc6.as_bytes());
// 7. Pre-1970 negative floor via DateTime (-1 ms -> 1969-12-31 == -1)
let mut doc7 = RawDocumentBuf::new();
doc7.append(cstr!("symbol"), "PRE_DT");
doc7.append(cstr!("timestamp"), BsonDateTime::from_millis(-1));
doc7.append(cstr!("sharesShort"), 700_i32);
buf.extend_from_slice(doc7.as_bytes());
// 8. Pre-1970 negative floor via integral Double (-1.0 sec -> 1969-12-31 == -1)
let mut doc8 = RawDocumentBuf::new();
doc8.append(cstr!("symbol"), "PRE_DBL");
doc8.append(cstr!("timestamp"), -1.0_f64);
doc8.append(cstr!("sharesShort"), 800_i32);
buf.extend_from_slice(doc8.as_bytes());
// 9. -0.0 Double -> epoch day 0 (1970-01-01)
let mut doc9 = RawDocumentBuf::new();
doc9.append(cstr!("symbol"), "NEG_ZERO");
doc9.append(cstr!("timestamp"), -0.0_f64);
doc9.append(cstr!("sharesShort"), 900_i32);
buf.extend_from_slice(doc9.as_bytes());
let mut rows = Vec::new();
let stats = decode_ceo_shorts_buffer(&buf, &fields, |r| {
rows.push(CeoShortReport {
key: r.key.to_string(),
report_date: r.report_date,
shares_short: r.shares_short,
net_change: r.net_change,
pct_float: r.pct_float,
});
})
.expect("decode buffer");
assert_conservation(&stats);
assert_eq!(stats.docs_in, 9);
assert_eq!(stats.rows_out, 9);
assert_eq!(stats.skipped_total(), 0);
for row in &rows[..6] {
assert_eq!(row.report_date, d_2024_03_15);
}
assert_eq!(rows[0].net_change, Some(-5_000.0));
assert_eq!(rows[0].pct_float, Some(1.25));
assert_eq!(rows[1].net_change, Some(10_000.0));
assert_eq!(rows[1].pct_float, Some(2.0));
assert_eq!(rows[2].net_change, None);
assert_eq!(rows[2].pct_float, None);
assert_eq!(rows[6].report_date, -1);
assert_eq!(rows[7].report_date, -1);
assert_eq!(rows[8].report_date, 0);
}
#[test]
fn decodes_custom_field_names_and_preserves_verbatim_key_and_unconfigured_optionals() {
let fields = CeoShortsFieldNames {
key: "tickerCode",
report_date: "asOfDate",
shares_short: "shortPos",
net_change: None,
pct_float: None,
};
let d = day(2024, 6, 30);
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("_id"), "ignored_id");
doc.append(cstr!("tickerCode"), " SHOP.TO "); // verbatim, not trimmed
doc.append(cstr!("asOfDate"), i64::from(d) * 86_400);
doc.append(cstr!("shortPos"), 42_000_i64);
// Even if unrelated fields exist with wrong types, unconfigured optionals stay None without counting.
doc.append(cstr!("netChange"), "not-a-number");
doc.append(cstr!("pctFloat"), true);
let mut rows = Vec::new();
let stats = decode_ceo_shorts_bytes(doc.as_bytes(), &fields, |r| {
rows.push((
r.key.to_string(),
r.report_date,
r.shares_short,
r.net_change,
r.pct_float,
));
})
.expect("decode bytes");
assert_conservation(&stats);
assert_eq!(stats.rows_out, 1);
assert_eq!(stats.nulled_wrong_type_net_change, 0);
assert_eq!(stats.nulled_wrong_type_pct_float, 0);
assert_eq!(rows, vec![(" SHOP.TO ".to_string(), d, 42_000.0, None, None)]);
}
#[test]
fn skips_bad_required_fields_with_exact_counters_and_priority() {
let fields = default_fields();
let d_secs = i64::from(day(2024, 3, 15)) * 86_400;
let mut buf = Vec::new();
// 1. Missing key (also missing date & shares -> key wins priority)
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("extra"), 1_i32);
buf.extend_from_slice(doc.as_bytes());
// 2. Wrong key type (Int32)
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), 123_i32);
doc.append(cstr!("timestamp"), d_secs);
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 3. Empty/blank key (and wrong-typed optionals must NOT increment nulled_wrong_type_*)
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), " ");
doc.append(cstr!("timestamp"), d_secs);
doc.append(cstr!("sharesShort"), 10_i32);
doc.append(cstr!("netChange"), "bad");
doc.append(cstr!("pctFloat"), false);
buf.extend_from_slice(doc.as_bytes());
// 4. Missing report_date (also missing shares -> report_date wins priority)
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
buf.extend_from_slice(doc.as_bytes());
// 5. Wrong report_date type (String)
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), "2024-03-15");
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 6. Invalid report_date: fractional Double
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), 1_710_460_800.5_f64);
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 7. Invalid report_date: NaN Double
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), f64::NAN);
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 8. Invalid report_date: +Inf Double
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), f64::INFINITY);
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 9. Out-of-range report_date: Double > 2^63
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), 1e30_f64);
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 10. Out-of-range report_date: DateTime overflowing i32 days
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), BsonDateTime::from_millis(i64::MAX));
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 11. Out-of-range report_date: Int64 overflowing i32 days
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), i64::MAX);
doc.append(cstr!("sharesShort"), 10_i32);
buf.extend_from_slice(doc.as_bytes());
// 12. Missing shares_short
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), d_secs);
buf.extend_from_slice(doc.as_bytes());
// 13. Wrong shares_short type: numeric string is rejected, not parsed
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "A");
doc.append(cstr!("timestamp"), d_secs);
doc.append(cstr!("sharesShort"), "12345");
buf.extend_from_slice(doc.as_bytes());
let mut emitted = 0usize;
let stats = decode_ceo_shorts_buffer(&buf, &fields, |_| emitted += 1).expect("decode buffer");
assert_conservation(&stats);
assert_eq!(emitted, 0);
assert_eq!(stats.docs_in, 13);
assert_eq!(stats.rows_out, 0);
assert_eq!(stats.skipped_missing_key, 1);
assert_eq!(stats.skipped_wrong_key_type, 1);
assert_eq!(stats.skipped_empty_key, 1);
assert_eq!(stats.skipped_missing_report_date, 1);
assert_eq!(stats.skipped_wrong_report_date_type, 1);
assert_eq!(stats.skipped_invalid_report_date, 3);
assert_eq!(stats.skipped_report_date_out_of_range, 3);
assert_eq!(stats.skipped_missing_shares_short, 1);
assert_eq!(stats.skipped_wrong_shares_short_type, 1);
assert_eq!(stats.nulled_wrong_type_net_change, 0);
assert_eq!(stats.nulled_wrong_type_pct_float, 0);
}
#[test]
fn passes_negative_and_nan_shares_through_and_handles_null_and_wrong_type_optionals() {
let fields = default_fields();
let d_secs = i64::from(day(2024, 3, 15)) * 86_400;
let mut buf = Vec::new();
// 1. Negative shares_short + Null optionals (not counted as wrong type)
let mut doc1 = RawDocumentBuf::new();
doc1.append(cstr!("symbol"), "NEG");
doc1.append(cstr!("timestamp"), d_secs);
doc1.append(cstr!("sharesShort"), -50.0_f64);
doc1.append(cstr!("netChange"), RawBson::Null);
doc1.append(cstr!("pctFloat"), RawBson::Null);
buf.extend_from_slice(doc1.as_bytes());
// 2. NaN shares_short + wrong-type optionals (counted on emitted row)
let mut doc2 = RawDocumentBuf::new();
doc2.append(cstr!("symbol"), "NAN");
doc2.append(cstr!("timestamp"), d_secs);
doc2.append(cstr!("sharesShort"), f64::NAN);
doc2.append(cstr!("netChange"), "123");
doc2.append(cstr!("pctFloat"), true);
buf.extend_from_slice(doc2.as_bytes());
let mut rows = Vec::new();
let stats = decode_ceo_shorts_buffer(&buf, &fields, |r| {
rows.push((
r.key.to_string(),
r.shares_short,
r.net_change,
r.pct_float,
));
})
.expect("decode buffer");
assert_conservation(&stats);
assert_eq!(stats.docs_in, 2);
assert_eq!(stats.rows_out, 2);
assert_eq!(stats.nulled_wrong_type_net_change, 1);
assert_eq!(stats.nulled_wrong_type_pct_float, 1);
assert_eq!(rows[0].0, "NEG");
assert_eq!(rows[0].1, -50.0);
assert_eq!(rows[0].2, None);
assert_eq!(rows[0].3, None);
assert_eq!(rows[1].0, "NAN");
assert!(rows[1].1.is_nan());
assert_eq!(rows[1].2, None);
assert_eq!(rows[1].3, None);
}
#[test]
fn structural_bson_corruption_fails_closed_even_after_semantic_skip() {
let fields = default_fields();
// Build a doc with a bad key (semantic skip) followed by a corrupt trailing element type byte.
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), ""); // would be skipped_empty_key
doc.append(cstr!("z"), 1_i32);
let mut bytes = doc.into_bytes();
// Corrupt the element type byte of "z" (which is 0x10 = Int32) to an invalid BSON type 0x7e.
let z_pos = bytes
.windows(3)
.position(|w| w == [0x10, b'z', 0x00])
.expect("locate z element");
bytes[z_pos] = 0x7e;
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
assert!(
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
"expected CorruptBson at offset 0, got {err:?}"
);
// Also test second document in a buffer has accurate byte offset.
let mut good = RawDocumentBuf::new();
good.append(cstr!("symbol"), "OK");
good.append(cstr!("timestamp"), i64::from(day(2024, 3, 15)) * 86_400);
good.append(cstr!("sharesShort"), 100_i32);
let good_len = good.as_bytes().len() as u64;
let mut combined = Vec::new();
combined.extend_from_slice(good.as_bytes());
combined.extend_from_slice(&bytes);
let err = decode_ceo_shorts_buffer(&combined, &fields, |_| {}).unwrap_err();
assert!(
matches!(err, BsonCeoShortsError::CorruptBson { offset, .. } if offset == good_len),
"expected CorruptBson at offset {good_len}, got {err:?}"
);
}
#[test]
fn framing_errors_return_typed_errors_with_offsets() {
let fields = default_fields();
// Truncated header (< 4 bytes)
let err = decode_ceo_shorts_buffer(&[0x10, 0x00], &fields, |_| {}).unwrap_err();
assert!(matches!(
err,
BsonCeoShortsError::TruncatedDocument {
offset: 0,
remaining: 2,
declared_len: None
}
));
// Truncated body
let err = decode_ceo_shorts_buffer(&[20, 0, 0, 0, 0, 0], &fields, |_| {}).unwrap_err();
assert!(matches!(
err,
BsonCeoShortsError::TruncatedDocument {
offset: 0,
remaining: 6,
declared_len: Some(20)
}
));
// Corrupt length (< 5)
let err = decode_ceo_shorts_buffer(&[3, 0, 0, 0, 0], &fields, |_| {}).unwrap_err();
assert!(matches!(
err,
BsonCeoShortsError::CorruptDocumentLength {
offset: 0,
declared_len: 3
}
));
// Trailing bytes on decode_ceo_shorts_bytes
let mut good = RawDocumentBuf::new();
good.append(cstr!("symbol"), "OK");
let mut extra = good.into_bytes();
extra.push(0x00);
let err = decode_ceo_shorts_bytes(&extra, &fields, |_| {}).unwrap_err();
assert!(matches!(err, BsonCeoShortsError::CorruptDocumentLength { .. }));
}

View file

@ -21,6 +21,9 @@ use std::error::Error;
use std::fmt;
use std::io;
use crate::bson_ceo_shorts::{
decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
};
use crate::bson_eod_prices::{
decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar,
};
@ -32,6 +35,7 @@ use crate::bson_te_market_data::{
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
};
use crate::fx::FxDailyBar;
use crate::shorts::CeoShortReport;
/// Default chunk buffer capacity: 8 MiB.
pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024;
@ -747,6 +751,110 @@ where
decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error)
}
/// Terminal error returned by [`decode_ceo_shorts_chunks`] and [`decode_ceo_shorts_stream`].
#[derive(Debug)]
pub enum BsonCeoShortsStreamError {
Stream(BsonStreamError),
Decode(BsonCeoShortsError),
}
impl fmt::Display for BsonCeoShortsStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stream(err) => write!(f, "{err}"),
Self::Decode(err) => write!(f, "{err}"),
}
}
}
impl Error for BsonCeoShortsStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Stream(err) => Some(err),
Self::Decode(err) => Some(err),
}
}
}
impl From<BsonStreamError> for BsonCeoShortsStreamError {
fn from(err: BsonStreamError) -> Self {
Self::Stream(err)
}
}
impl From<BsonCeoShortsError> for BsonCeoShortsStreamError {
fn from(err: BsonCeoShortsError) -> Self {
Self::Decode(err)
}
}
#[inline]
fn rebase_ceo_shorts_error(base: u64, err: BsonCeoShortsError) -> BsonCeoShortsError {
match err {
BsonCeoShortsError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonCeoShortsError::TruncatedDocument {
offset: base.saturating_add(offset),
remaining,
declared_len,
},
BsonCeoShortsError::CorruptDocumentLength {
offset,
declared_len,
} => BsonCeoShortsError::CorruptDocumentLength {
offset: base.saturating_add(offset),
declared_len,
},
BsonCeoShortsError::CorruptBson { offset, detail } => BsonCeoShortsError::CorruptBson {
offset: base.saturating_add(offset),
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_shorts_buffer`],
/// accumulating [`BsonCeoShortsDecodeStats`] and rebasing structural BSON error offsets to
/// absolute stream byte offsets.
pub fn decode_ceo_shorts_chunks<R, F>(
reader: &mut RawBsonChunkReader<R>,
fields: &CeoShortsFieldNames<'_>,
mut on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsStreamError>
where
R: io::Read,
F: for<'a> FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
let mut total = BsonCeoShortsDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_ceo_shorts_buffer(chunk.bytes, fields, &mut on_row)
.map_err(|err| BsonCeoShortsStreamError::Decode(rebase_ceo_shorts_error(base, err)))?;
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `ceoShorts` [`std::io::Read`] source through
/// [`decode_ceo_shorts_buffer`] with bounded memory.
pub fn decode_ceo_shorts_stream<R, F>(
reader: R,
options: BsonStreamOptions,
fields: &CeoShortsFieldNames<'_>,
on_row: F,
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsStreamError>
where
R: io::Read,
F: for<'a> FnMut(CeoShortReport<&'a str>),
{
fields.validate()?;
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_ceo_shorts_chunks(&mut chunk_reader, fields, on_row)
}
#[cfg(test)]
#[path = "bson_stream_tests.rs"]
mod tests;

View file

@ -1722,3 +1722,152 @@ fn randomized_buffer_and_read_size_sweep_matches_buffer_decoder() {
assert_eq!(got_errs, expected_errs, "case {case} errs mismatch");
}
}
#[test]
fn ceo_shorts_stream_matches_buffer_across_small_chunks_and_preserves_bounded_capacity() {
use super::{decode_ceo_shorts_chunks, BsonStreamOptions, RawBsonChunkReader};
use crate::bson_ceo_shorts::{
decode_ceo_shorts_buffer, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
DEFAULT_REPORT_DATE_FIELD,
};
let fields = CeoShortsFieldNames {
key: DEFAULT_KEY_FIELD,
report_date: DEFAULT_REPORT_DATE_FIELD,
shares_short: "sharesShort",
net_change: Some("netChange"),
pct_float: Some("pctFloat"),
};
let mut fixture = Vec::new();
for i in 0..40_i32 {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), format!("SYM{i}"));
let day_secs = (19_700_i64 + i64::from(i) * 15) * 86_400;
if i % 3 == 0 {
doc.append(
cstr!("timestamp"),
bson::DateTime::from_millis(day_secs * 1_000),
);
} else if i % 3 == 1 {
doc.append(cstr!("timestamp"), day_secs);
} else {
doc.append(cstr!("timestamp"), (day_secs * 1_000) as f64);
}
if i % 10 == 0 {
// semantic skip: wrong shares type
doc.append(cstr!("sharesShort"), "not_a_number");
} else {
doc.append(cstr!("sharesShort"), 10_000 + i * 250);
}
if i % 5 == 0 {
doc.append(cstr!("netChange"), "wrong");
} else {
doc.append(cstr!("netChange"), (i - 10) as f64);
}
doc.append(cstr!("pctFloat"), 0.5 + f64::from(i) * 0.01);
fixture.extend_from_slice(doc.as_bytes());
}
let mut expected_rows = Vec::new();
let expected_stats = decode_ceo_shorts_buffer(&fixture, &fields, |r| {
expected_rows.push((
r.key.to_owned(),
r.report_date,
r.shares_short.to_bits(),
r.net_change.map(f64::to_bits),
r.pct_float.map(f64::to_bits),
));
})
.expect("buffer decode");
for cap in [64usize, 128, 1024] {
let opts = BsonStreamOptions {
chunk_capacity_bytes: cap,
max_doc_bytes: 4096,
};
let mut reader =
RawBsonChunkReader::with_options(FixedStepReader::new(&fixture, 37), opts).unwrap();
let mut got_rows = Vec::new();
let got_stats = decode_ceo_shorts_chunks(&mut reader, &fields, |r| {
got_rows.push((
r.key.to_owned(),
r.report_date,
r.shares_short.to_bits(),
r.net_change.map(f64::to_bits),
r.pct_float.map(f64::to_bits),
));
})
.expect("chunk decode");
assert_eq!(got_stats, expected_stats, "cap={cap}");
assert_eq!(got_rows, expected_rows, "cap={cap}");
assert!(
reader.buffer_capacity() <= 4096,
"capacity {} exceeded max_doc_bytes",
reader.buffer_capacity()
);
}
}
#[test]
fn ceo_shorts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() {
use super::{decode_ceo_shorts_stream, BsonCeoShortsStreamError, BsonStreamOptions};
use crate::bson_ceo_shorts::{BsonCeoShortsError, CeoShortsFieldNames};
let bad_fields = CeoShortsFieldNames {
key: "symbol",
report_date: "symbol",
shares_short: "sharesShort",
net_change: None,
pct_float: None,
};
assert!(matches!(
decode_ceo_shorts_stream(Cursor::new(Vec::<u8>::new()), BsonStreamOptions::default(), &bad_fields, |_| {}),
Err(BsonCeoShortsStreamError::Decode(BsonCeoShortsError::InvalidFieldNames { .. }))
));
let fields = CeoShortsFieldNames {
key: "symbol",
report_date: "timestamp",
shares_short: "sharesShort",
net_change: None,
pct_float: None,
};
let mut good = RawDocumentBuf::new();
good.append(cstr!("symbol"), "RY");
good.append(cstr!("timestamp"), 1_710_460_800_i64);
good.append(cstr!("sharesShort"), 1000_i32);
let good_bytes = good.into_bytes();
let mut corrupt = RawDocumentBuf::new();
corrupt.append(cstr!("symbol"), "TD");
corrupt.append(cstr!("z"), 1_i32);
let mut corrupt_bytes = corrupt.into_bytes();
let z_pos = corrupt_bytes
.windows(3)
.position(|w| w == [0x10, b'z', 0x00])
.expect("locate z");
corrupt_bytes[z_pos] = 0x7e;
let mut combined = Vec::new();
combined.extend_from_slice(&good_bytes);
combined.extend_from_slice(&good_bytes);
let expected_offset = combined.len() as u64;
combined.extend_from_slice(&corrupt_bytes);
let opts = BsonStreamOptions {
chunk_capacity_bytes: good_bytes.len(),
max_doc_bytes: 4096,
};
let err = decode_ceo_shorts_stream(Cursor::new(combined), opts, &fields, |_| {}).unwrap_err();
assert!(
matches!(
err,
BsonCeoShortsStreamError::Decode(BsonCeoShortsError::CorruptBson { offset, .. })
if offset == expected_offset
),
"expected rebased CorruptBson at {expected_offset}, got {err:?}"
);
}

View file

@ -14,16 +14,19 @@ use crate::bench::{
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS,
DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_COMMAND_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::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD};
use crate::run_curate_adj::CurateAdjFactorsArgs;
use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE};
use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL};
use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE};
/// Parsed CLI command to execute.
#[derive(Debug, Clone, PartialEq)]
@ -34,6 +37,7 @@ pub enum CliAction {
CurateAdjFactors(CurateAdjFactorsArgs),
CurateCorporateActions(CurateCorporateActionsArgs),
CurateFx1d(CurateFx1dArgs),
CurateShorts(CurateShortsArgs),
BenchSplit(usize),
BenchAdj(usize),
BenchCorporateActions(usize),
@ -54,6 +58,7 @@ pub enum CliAction {
BenchCurateBars(usize),
BenchCurateBarsCmd(usize),
BenchCurateShorts(usize),
BenchCurateShortsCommand(usize),
BenchCurateEvents(usize),
BenchCurateFx(usize),
BenchCurateFxCmd(usize),
@ -79,6 +84,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
Curate corporate_actions from BSON + TSV files into corporate_actions/part.parquet\n\
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\
{name} curate-shorts --ceo-shorts <path> --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
Curate shorts from ceoShorts BSON + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\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\
@ -99,6 +106,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
{name} bench-curate-bars-cmd [rows] Run fixed-seed end-to-end curate-bars-1d file->Parquet benchmark (default: {DEFAULT_CURATE_BARS_CMD_BENCH_ROWS})\n\
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
{name} bench-curate-shorts-command [rows] Run fixed-seed end-to-end curate-shorts file->Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS})\n\
{name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\
{name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
{name} bench-curate-fx-cmd [rows] Run fixed-seed end-to-end curate-fx-1d file->Parquet benchmark (default: {DEFAULT_CURATE_FX_CMD_BENCH_ROWS})\n\
@ -119,6 +127,7 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> --provider-mapping <path> [--delistings <path>] --out <dir>\n\
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
{name} curate-shorts --ceo-shorts <path> --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
{name} bench-split [rows]\n\
{name} bench-adj [events]\n\
{name} bench-corporate-actions [events]\n\
@ -139,6 +148,7 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} bench-curate-bars [rows]\n\
{name} bench-curate-bars-cmd [rows]\n\
{name} bench-curate-shorts [rows]\n\
{name} bench-curate-shorts-command [rows]\n\
{name} bench-curate-events [rows]\n\
{name} bench-curate-fx [rows]\n\
{name} bench-curate-fx-cmd [rows]\n\
@ -453,6 +463,105 @@ fn parse_curate_fx_1d_args(args: &[&str]) -> Result<CurateFx1dArgs, String> {
})
}
fn parse_curate_shorts_args(args: &[&str]) -> Result<CurateShortsArgs, String> {
let mut ceo_shorts: Option<PathBuf> = None;
let mut provider_mapping: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
let mut key_field: Option<String> = None;
let mut report_date_field: Option<String> = None;
let mut shares_short_field: Option<String> = None;
let mut net_change_field: Option<String> = None;
let mut pct_float_field: Option<String> = None;
let mut mapping_source: Option<String> = 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-shorts"
));
}
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(())
};
let set_name = |slot: &mut Option<String>, flag_name: &str, raw: &str| -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate flag '{flag_name}'"));
}
if raw.trim().is_empty() {
return Err(format!("empty value for flag '{flag_name}'"));
}
*slot = Some(raw.to_string());
Ok(())
};
match flag {
"--ceo-shorts" => set_path(&mut ceo_shorts, "--ceo-shorts", value)?,
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
"--out" => set_path(&mut out_dir, "--out", value)?,
"--key-field" => set_name(&mut key_field, "--key-field", value)?,
"--report-date-field" => {
set_name(&mut report_date_field, "--report-date-field", value)?;
}
"--shares-short-field" => {
set_name(&mut shares_short_field, "--shares-short-field", value)?;
}
"--net-change-field" => set_name(&mut net_change_field, "--net-change-field", value)?,
"--pct-float-field" => set_name(&mut pct_float_field, "--pct-float-field", value)?,
"--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?,
other => return Err(format!("unknown flag '{other}' for curate-shorts")),
}
}
let ceo_shorts =
ceo_shorts.ok_or_else(|| "missing required flag '--ceo-shorts'".to_string())?;
let provider_mapping =
provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
let shares_short_field = shares_short_field
.ok_or_else(|| "missing required flag '--shares-short-field'".to_string())?;
let parsed = CurateShortsArgs {
ceo_shorts,
provider_mapping,
out_dir,
key_field: key_field.unwrap_or_else(|| DEFAULT_KEY_FIELD.to_string()),
report_date_field: report_date_field
.unwrap_or_else(|| DEFAULT_REPORT_DATE_FIELD.to_string()),
shares_short_field,
net_change_field,
pct_float_field,
mapping_source: mapping_source.unwrap_or_else(|| DEFAULT_MAPPING_SOURCE.to_string()),
};
parsed.field_names().validate().map_err(|e| e.to_string())?;
Ok(parsed)
}
/// 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();
@ -472,6 +581,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
parse_curate_corporate_actions_args(rest).map(CliAction::CurateCorporateActions)
}
["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest).map(CliAction::CurateFx1d),
["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest).map(CliAction::CurateShorts),
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
["bench-split", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)),
@ -680,6 +790,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
["bench-curate-shorts", _, ..] => {
Err("too many arguments for bench-curate-shorts".to_string())
}
["bench-curate-shorts-command"] => Ok(CliAction::BenchCurateShortsCommand(
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS,
)),
["bench-curate-shorts-command", raw] => match raw.parse::<usize>() {
Ok(n) if n > 0 => Ok(CliAction::BenchCurateShortsCommand(n)),
_ => Err(format!(
"invalid row count '{raw}' (expected a positive integer)"
)),
},
["bench-curate-shorts-command", _, ..] => {
Err("too many arguments for bench-curate-shorts-command".to_string())
}
["bench-curate-events"] => {
Ok(CliAction::BenchCurateEvents(DEFAULT_CURATE_EVENTS_BENCH_ROWS))
}
@ -1917,4 +2039,176 @@ mod tests {
assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-fx-cmd", "10", "20"])).is_err());
}
#[test]
fn parses_and_validates_curate_shorts_and_bench_curate_shorts_command() {
let usage = format_usage("curate-etl", "0.1.0");
assert!(usage.contains("curate-shorts"));
assert!(usage.contains("bench-curate-shorts-command"));
// Minimal required flags with defaults
assert_eq!(
parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"shorts.bson",
"--provider-mapping",
"map.tsv",
"--out",
"out",
"--shares-short-field",
"sharesShort",
])),
Ok(CliAction::CurateShorts(CurateShortsArgs {
ceo_shorts: PathBuf::from("shorts.bson"),
provider_mapping: PathBuf::from("map.tsv"),
out_dir: PathBuf::from("out"),
key_field: DEFAULT_KEY_FIELD.to_string(),
report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(),
shares_short_field: "sharesShort".to_string(),
net_change_field: None,
pct_float_field: None,
mapping_source: DEFAULT_MAPPING_SOURCE.to_string(),
}))
);
// Full custom flags with = syntax
assert_eq!(
parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts=s.bson",
"--provider-mapping=m.tsv",
"--out=o",
"--shares-short-field=qty",
"--key-field=ticker",
"--report-date-field=asOf",
"--net-change-field=delta",
"--pct-float-field=pct",
"--mapping-source=ceo_alt",
])),
Ok(CliAction::CurateShorts(CurateShortsArgs {
ceo_shorts: PathBuf::from("s.bson"),
provider_mapping: PathBuf::from("m.tsv"),
out_dir: PathBuf::from("o"),
key_field: "ticker".to_string(),
report_date_field: "asOf".to_string(),
shares_short_field: "qty".to_string(),
net_change_field: Some("delta".to_string()),
pct_float_field: Some("pct".to_string()),
mapping_source: "ceo_alt".to_string(),
}))
);
// Missing --shares-short-field
let err = parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
]))
.unwrap_err();
assert!(err.contains("--shares-short-field"), "{err}");
// Duplicate flag
let err = parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--ceo-shorts",
"s2.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shares-short-field",
"qty",
]))
.unwrap_err();
assert!(err.contains("duplicate flag '--ceo-shorts'"), "{err}");
// Unknown flag
let err = parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shares-short-field",
"qty",
"--bogus",
"1",
]))
.unwrap_err();
assert!(err.contains("unknown flag '--bogus'"), "{err}");
// Empty / blank field name
let err = parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shares-short-field",
" ",
]))
.unwrap_err();
assert!(err.contains("empty value for flag '--shares-short-field'"), "{err}");
// Colliding roles with default 'symbol'
let err = parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shares-short-field",
"symbol",
]))
.unwrap_err();
assert!(err.contains("cannot share BSON field 'symbol'"), "{err}");
// Colliding optional roles
let err = parse_args(&to_args(&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"o",
"--shares-short-field",
"qty",
"--net-change-field",
"same",
"--pct-float-field",
"same",
]))
.unwrap_err();
assert!(err.contains("cannot share BSON field 'same'"), "{err}");
// bench-curate-shorts-command
assert_eq!(
parse_args(&to_args(&["bench-curate-shorts-command"])),
Ok(CliAction::BenchCurateShortsCommand(
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS
))
);
assert_eq!(
parse_args(&to_args(&["bench-curate-shorts-command", "2500"])),
Ok(CliAction::BenchCurateShortsCommand(2_500))
);
assert!(parse_args(&to_args(&["bench-curate-shorts-command", "0"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-shorts-command", "-1"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-shorts-command", "abc"])).is_err());
assert!(parse_args(&to_args(&["bench-curate-shorts-command", "1", "2"])).is_err());
}
}

View file

@ -3,6 +3,7 @@
pub mod adj;
pub mod bars;
pub mod bench;
pub mod bson_ceo_shorts;
pub mod bson_eod_prices;
pub mod bson_qm_actions;
pub mod bson_stream;
@ -31,6 +32,11 @@ pub use bars::{
build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume,
VolumeMismatchSample, MAX_MISMATCH_SAMPLES,
};
pub use bson_ceo_shorts::{
decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc,
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
DEFAULT_REPORT_DATE_FIELD,
};
pub use bson_eod_prices::{
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
@ -42,9 +48,10 @@ pub use bson_qm_actions::{
FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
};
pub use bson_stream::{
decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks,
decode_qm_dividend_stream, decode_qm_split_chunks, decode_qm_split_stream,
decode_te_market_data_chunks, decode_te_market_data_stream, BsonStreamError, BsonStreamOptions,
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks,
decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
decode_te_market_data_stream, BsonCeoShortsStreamError, BsonStreamError, BsonStreamOptions,
RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES,
MIN_BSON_DOC_BYTES,
};
@ -186,3 +193,9 @@ pub use run_curate_fx::{
CurateFx1dRunReport, RunCurateFxError, ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL,
EOD_CAD_FOREX_CODE,
};
pub mod run_curate_shorts;
pub use run_curate_shorts::{
format_curate_shorts_report, run_curate_shorts, CurateShortsArgs, CurateShortsRunReport,
RunCurateShortsError, DEFAULT_MAPPING_SOURCE,
};

View file

@ -10,7 +10,7 @@ use curate_etl::bench::{
run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark,
run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark,
run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark,
run_events_benchmark, run_fx_benchmark,
run_curate_shorts_command_benchmark, run_events_benchmark, run_fx_benchmark,
run_parquet_adj_benchmark, run_parquet_bars_benchmark,
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
@ -23,6 +23,7 @@ use curate_etl::run_curate_corporate_actions::{
format_curate_corporate_actions_report, run_curate_corporate_actions,
};
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
const NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");
@ -83,6 +84,16 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateShorts(curate_args)) => match run_curate_shorts(&curate_args) {
Ok(report) => {
println!("{}", format_curate_shorts_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,
@ -1292,6 +1303,70 @@ fn main() -> ExitCode {
);
ExitCode::SUCCESS
}
Ok(CliAction::BenchCurateShortsCommand(rows)) => {
let report = match run_curate_shorts_command_benchmark(rows) {
Ok(report) => report,
Err(err) => {
eprintln!("error: curate-shorts-command benchmark failed: {err}");
return ExitCode::FAILURE;
}
};
let retention_pct = if report.rows > 0 {
(report.rows_out as f64 / report.rows as f64) * 100.0
} else {
0.0
};
println!("curate-etl bench-curate-shorts-command");
println!(
" input: rows={} docs_framed={} bytes_read={} keys={} peak_chunk_bytes={}",
report.rows,
report.docs_framed,
report.bytes_read,
report.key_count,
report.peak_chunk_bytes
);
println!(
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s rows_out={} skipped={} nulled_net_change={} nulled_pct_float={}",
report.decode_elapsed_ms,
report.decode_rows_per_sec,
report.input_mb_per_sec,
report.decode.rows_out,
report.decode.skipped_total(),
report.decode.nulled_wrong_type_net_change,
report.decode.nulled_wrong_type_pct_float
);
println!(
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} dropped_unmapped={} coll_collapsed={} coll_dropped={} invalid_shares={} checksum=0x{:016x}",
report.curate_elapsed_ms,
report.curate_rows_per_sec,
report.rows_out,
retention_pct,
report.listings_out,
report.curate_stats.dropped_unmapped,
report.curate_stats.listing_collision_collapsed,
report.curate_stats.listing_collision_dropped,
report.curate_stats.builder.dropped_invalid_shares_short,
report.checksum
);
println!(
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
report.write_elapsed_ms,
report.write_rows_per_sec,
report.write_mb_per_sec,
report.files_written,
report.row_groups_written,
report.bytes_written,
report.read_back_rows
);
println!(
" total: elapsed={:.2} ms throughput={:.0} rows/s peak_chunk_bytes={} checksum=0x{:016x}",
report.total_elapsed_ms,
report.total_rows_per_sec,
report.peak_chunk_bytes,
report.checksum
);
ExitCode::SUCCESS
}
Err(msg) => {
eprintln!("error: {msg}");
eprintln!("{}", format_usage_stderr(NAME));

View file

@ -0,0 +1,539 @@
//! File-to-file `curate-shorts` command runner (`M1.2ad`).
//!
//! Streams a concatenated raw BSON `ceoShorts` dump file alongside `provider_mapping.tsv` into an
//! atomically published `<out_dir>/shorts/part.parquet` dataset via [`curate_and_write_shorts`].
//!
//! # Contract & Point-in-Time Rules
//! - Field names are supplied explicitly via [`CurateShortsArgs`] (validated via
//! [`CeoShortsFieldNames::validate`] before touching disk) because live MongoDB `ceoShorts`
//! value field names are unverified in the repository.
//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from
//! [`crate::run_curate_bars::load_provider_mapping_tsv`].
//! - All decoded [`CeoShortReport`] rows are passed directly to [`curate_and_write_shorts`] (which
//! resolves `provider_mapping` strictly on `report_date`, not `known_at_date`, stamps
//! `known_at = report_date + 4` Canadian TSX business days at `17:00 America/Toronto`, and
//! counts unmapped keys in [`CurateShortsStats::dropped_unmapped`]).
//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_shorts`] /
//! [`write_shorts_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0`
//! without creating `<out_dir>/shorts` or modifying any pre-existing `part.parquet`.
//! - **Fail-closed safety:** invalid `--out`, invalid field names, empty `--mapping-source`,
//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON
//! framing or element bytes, and out-of-range `report_date` errors return a typed
//! [`RunCurateShortsError`] before touching `args.out_dir`.
//!
//! # Counter Conservation Invariants
//! Every successful [`CurateShortsRunReport`] satisfies:
//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()`
//! - `decode.rows_out == curate_stats.builder.rows_in`
//! - `curate_stats.builder.rows_in == curate_stats.builder.rows_out + curate_stats.builder.dropped_invalid_shares_short + curate_stats.builder.duplicate_collapsed + curate_stats.builder.duplicate_conflict_dropped`
//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped`
//! - `write_stats.rows_written == curate_stats.rows_out`
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use crate::bson_ceo_shorts::{
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
};
use crate::bson_stream::{
decode_ceo_shorts_chunks, BsonCeoShortsStreamError, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader,
};
use crate::curate_shorts::{
curate_and_write_shorts, curate_shorts, CurateShortsStats, CurateShortsWriteError,
};
use crate::parquet_shorts::{
write_shorts_dataset, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats,
};
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
use crate::shorts::CeoShortReport;
/// Default `--mapping-source` passed to `provider_mapping` lookups for `ceoShorts`.
pub const DEFAULT_MAPPING_SOURCE: &str = "ceo";
/// Parsed arguments for the `curate-shorts` CLI command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateShortsArgs {
pub ceo_shorts: PathBuf,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub key_field: String,
pub report_date_field: String,
pub shares_short_field: String,
pub net_change_field: Option<String>,
pub pct_float_field: Option<String>,
pub mapping_source: String,
}
impl CurateShortsArgs {
/// Borrows the configured BSON field names as [`CeoShortsFieldNames`].
#[inline]
pub fn field_names(&self) -> CeoShortsFieldNames<'_> {
CeoShortsFieldNames {
key: self.key_field.as_str(),
report_date: self.report_date_field.as_str(),
shares_short: self.shares_short_field.as_str(),
net_change: self.net_change_field.as_deref(),
pct_float: self.pct_float_field.as_deref(),
}
}
}
/// Full run report produced by [`run_curate_shorts`].
#[derive(Debug, Clone, PartialEq)]
pub struct CurateShortsRunReport {
pub docs_framed: u64,
pub bytes_read: u64,
pub peak_chunk_bytes: usize,
pub decode: BsonCeoShortsDecodeStats,
pub curate_stats: CurateShortsStats,
pub write_stats: ShortsWriteStats,
pub elapsed_secs: f64,
}
/// Stage-timed run output used internally by `bench-curate-shorts-command`.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CurateShortsTimedRun {
pub report: CurateShortsRunReport,
pub decode_elapsed_secs: f64,
pub curate_elapsed_secs: f64,
pub write_elapsed_secs: f64,
pub checksum: u64,
}
/// Typed errors returned by [`run_curate_shorts`].
///
/// Every variant's `Display` output is a single line naming the offending path (and line number or
/// byte offset where applicable).
#[derive(Debug)]
pub enum RunCurateShortsError {
InvalidOutDir {
path: PathBuf,
detail: String,
},
InvalidFieldNames {
source: BsonCeoShortsError,
},
EmptyMappingSource,
OpenInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
ReadInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
TsvParse {
path: PathBuf,
line: usize,
detail: String,
},
ProviderMapping {
path: PathBuf,
source: ProviderMappingError,
},
BsonStream {
path: PathBuf,
source: BsonStreamError,
},
CorruptBson {
path: PathBuf,
offset: u64,
source: BsonCeoShortsError,
},
CurateWrite {
out_dir: PathBuf,
source: CurateShortsWriteError,
},
}
impl fmt::Display for RunCurateShortsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidOutDir { path, detail } => {
write!(f, "invalid --out '{}': {detail}", path.display())
}
Self::InvalidFieldNames { source } => write!(f, "{source}"),
Self::EmptyMappingSource => {
write!(f, "invalid --mapping-source: must not be empty or blank")
}
Self::OpenInput {
label,
path,
source,
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
Self::ReadInput {
label,
path,
source,
} => write!(f, "failed to read {label} '{}': {source}", path.display()),
Self::TsvParse { path, line, detail } => {
write!(f, "{}:{line}: {detail}", path.display())
}
Self::ProviderMapping { path, source } => {
write!(f, "invalid provider_mapping '{}': {source}", path.display())
}
Self::BsonStream { path, source } => {
write!(f, "failed reading ceo-shorts '{}': {source}", path.display())
}
Self::CorruptBson {
path,
offset,
source,
} => write!(
f,
"corrupt ceo-shorts BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CurateWrite { out_dir, source } => {
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
}
}
}
}
impl Error for RunCurateShortsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::InvalidFieldNames { source } => Some(source),
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
Self::ProviderMapping { source, .. } => Some(source),
Self::BsonStream { source, .. } => Some(source),
Self::CorruptBson { source, .. } => Some(source),
Self::CurateWrite { source, .. } => Some(source),
Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None,
}
}
}
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateShortsError> {
if out_dir.exists() && !out_dir.is_dir() {
return Err(RunCurateShortsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
Ok(())
}
fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateShortsError {
match err {
RunCurateBarsError::OpenInput {
label,
path,
source,
} => RunCurateShortsError::OpenInput {
label,
path,
source,
},
RunCurateBarsError::ReadInput {
label,
path,
source,
} => RunCurateShortsError::ReadInput {
label,
path,
source,
},
RunCurateBarsError::TsvParse { path, line, detail } => {
RunCurateShortsError::TsvParse { path, line, detail }
}
RunCurateBarsError::ProviderMapping { path, source } => {
RunCurateShortsError::ProviderMapping { path, source }
}
other => RunCurateShortsError::TsvParse {
path: path.to_path_buf(),
line: 0,
detail: other.to_string(),
},
}
}
fn bson_error_offset(err: &BsonCeoShortsError) -> u64 {
match err {
BsonCeoShortsError::TruncatedDocument { offset, .. }
| BsonCeoShortsError::CorruptDocumentLength { offset, .. }
| BsonCeoShortsError::CorruptBson { offset, .. } => *offset,
BsonCeoShortsError::InvalidFieldNames { .. } => 0,
}
}
struct DecodedShortsInputs {
mapping: ProviderMappingTable,
reports: Vec<CeoShortReport<Arc<str>>>,
docs_framed: u64,
bytes_read: u64,
peak_chunk_bytes: usize,
decode: BsonCeoShortsDecodeStats,
}
fn decode_all_inputs(args: &CurateShortsArgs) -> Result<DecodedShortsInputs, RunCurateShortsError> {
let fields = args.field_names();
fields
.validate()
.map_err(|source| RunCurateShortsError::InvalidFieldNames { source })?;
if args.mapping_source.trim().is_empty() {
return Err(RunCurateShortsError::EmptyMappingSource);
}
let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping)
.map_err(|err| map_tsv_error(&args.provider_mapping, err))?;
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateShortsError::ProviderMapping {
path: args.provider_mapping.clone(),
source,
}
})?;
let file = File::open(&args.ceo_shorts).map_err(|source| RunCurateShortsError::OpenInput {
label: "ceo-shorts",
path: args.ceo_shorts.clone(),
source,
})?;
let mut reader = RawBsonChunkReader::with_options(file, BsonStreamOptions::default()).map_err(
|source| RunCurateShortsError::BsonStream {
path: args.ceo_shorts.clone(),
source,
},
)?;
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
let mut reports: Vec<CeoShortReport<Arc<str>>> = Vec::new();
let decode = decode_ceo_shorts_chunks(&mut reader, &fields, |raw| {
let key = if let Some(existing) = key_interner.get(raw.key) {
Arc::clone(existing)
} else {
let arc: Arc<str> = Arc::from(raw.key);
key_interner.insert(Arc::clone(&arc));
arc
};
reports.push(CeoShortReport {
key,
report_date: raw.report_date,
shares_short: raw.shares_short,
net_change: raw.net_change,
pct_float: raw.pct_float,
});
})
.map_err(|err| match err {
BsonCeoShortsStreamError::Stream(source) => RunCurateShortsError::BsonStream {
path: args.ceo_shorts.clone(),
source,
},
BsonCeoShortsStreamError::Decode(source) => match &source {
BsonCeoShortsError::InvalidFieldNames { .. } => {
RunCurateShortsError::InvalidFieldNames { source }
}
_ => {
let offset = bson_error_offset(&source);
RunCurateShortsError::CorruptBson {
path: args.ceo_shorts.clone(),
offset,
source,
}
}
},
})?;
Ok(DecodedShortsInputs {
mapping,
reports,
docs_framed: reader.docs_framed(),
bytes_read: reader.bytes_read(),
peak_chunk_bytes: reader.buffer_capacity(),
decode,
})
}
/// Runs the end-to-end `curate-shorts` file-to-Parquet pipeline via [`curate_and_write_shorts`].
///
/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before
/// touching `args.out_dir`, leaving any pre-existing `<out_dir>/shorts/part.parquet`
/// byte-identical.
pub fn run_curate_shorts(
args: &CurateShortsArgs,
) -> Result<CurateShortsRunReport, RunCurateShortsError> {
let start = Instant::now();
validate_out_dir(&args.out_dir)?;
let decoded = decode_all_inputs(args)?;
let write_report = curate_and_write_shorts(
&args.out_dir,
decoded.reports,
&args.mapping_source,
&decoded.mapping,
ShortsWriteOptions::default(),
)
.map_err(|source| RunCurateShortsError::CurateWrite {
out_dir: args.out_dir.clone(),
source,
})?;
Ok(CurateShortsRunReport {
docs_framed: decoded.docs_framed,
bytes_read: decoded.bytes_read,
peak_chunk_bytes: decoded.peak_chunk_bytes,
decode: decoded.decode,
curate_stats: write_report.curate_stats,
write_stats: write_report.write_stats,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
fn compute_rows_checksum(rows: &[ShortsParquetRow]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
let mix = |mut h: u64, v: u64| -> u64 {
h ^= v;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
h
};
let mix_str = |mut h: u64, s: &str| -> u64 {
h = mix(h, s.len() as u64);
for &b in s.as_bytes() {
h = mix(h, u64::from(b));
}
h
};
for row in rows {
hash = mix(hash, row.listing_id as u64);
hash = mix(hash, row.report_date as u64);
hash = mix(hash, row.known_at_micros as u64);
hash = mix(hash, row.shares_short.to_bits());
hash = match row.net_change {
Some(v) => mix(mix(hash, 1), v.to_bits()),
None => mix(hash, 0),
};
hash = match row.pct_float {
Some(v) => mix(mix(hash, 1), v.to_bits()),
None => mix(hash, 0),
};
hash = mix_str(hash, row.source.as_ref());
}
hash
}
/// Stage-timed variant of [`run_curate_shorts`] used internally by `bench-curate-shorts-command`.
///
/// Separately times `decode` (TSV load + BSON stream), `curate` (`curate_shorts`), and `write`
/// (`write_shorts_dataset`), and computes a deterministic FNV-1a checksum over all 7 columns of the
/// curated rows.
pub(crate) fn run_curate_shorts_timed(
args: &CurateShortsArgs,
) -> Result<CurateShortsTimedRun, RunCurateShortsError> {
let total_start = Instant::now();
validate_out_dir(&args.out_dir)?;
let decode_start = Instant::now();
let decoded = decode_all_inputs(args)?;
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
let curate_start = Instant::now();
let curated = curate_shorts(decoded.reports, &args.mapping_source, &decoded.mapping).map_err(
|source| RunCurateShortsError::CurateWrite {
out_dir: args.out_dir.clone(),
source: CurateShortsWriteError::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_shorts_dataset(&args.out_dir, &curated.rows, ShortsWriteOptions::default()).map_err(
|source| RunCurateShortsError::CurateWrite {
out_dir: args.out_dir.clone(),
source: CurateShortsWriteError::Parquet(source),
},
)?;
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
let report = CurateShortsRunReport {
docs_framed: decoded.docs_framed,
bytes_read: decoded.bytes_read,
peak_chunk_bytes: decoded.peak_chunk_bytes,
decode: decoded.decode,
curate_stats: curated.stats,
write_stats,
elapsed_secs: total_start.elapsed().as_secs_f64(),
};
Ok(CurateShortsTimedRun {
report,
decode_elapsed_secs,
curate_elapsed_secs,
write_elapsed_secs,
checksum,
})
}
/// Formats [`CurateShortsRunReport`] into a deterministic machine-readable `key=value` summary.
///
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
pub fn format_curate_shorts_report(report: &CurateShortsRunReport) -> String {
let d = &report.decode;
let b = &report.curate_stats.builder;
let c = &report.curate_stats;
let w = &report.write_stats;
format!(
"curate-etl curate-shorts\n\
\x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_date={} wrong_date_type={} invalid_date={} date_oor={} missing_shares={} wrong_shares_type={}) nulled_wrong_type=(net_change={} pct_float={})\n\
\x20 builder: rows_in={} rows_out={} keys_out={} invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict={}\n\
\x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} coll_collapsed={} coll_dropped={}\n\
\x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\
\x20 timing: elapsed_secs={:.6}",
report.docs_framed,
report.bytes_read,
report.peak_chunk_bytes,
d.docs_in,
d.rows_out,
d.skipped_total(),
d.skipped_missing_key,
d.skipped_wrong_key_type,
d.skipped_empty_key,
d.skipped_missing_report_date,
d.skipped_wrong_report_date_type,
d.skipped_invalid_report_date,
d.skipped_report_date_out_of_range,
d.skipped_missing_shares_short,
d.skipped_wrong_shares_short_type,
d.nulled_wrong_type_net_change,
d.nulled_wrong_type_pct_float,
b.rows_in,
b.rows_out,
b.keys_out,
b.dropped_invalid_shares_short,
b.nulled_invalid_net_change,
b.nulled_invalid_pct_float,
b.duplicate_collapsed,
b.duplicate_conflict_dropped,
c.rows_in,
c.rows_out,
c.listings_out,
c.dropped_unmapped,
c.listing_collision_collapsed,
c.listing_collision_dropped,
w.files_written,
w.row_groups_written,
w.rows_written,
w.bytes_written,
report.elapsed_secs,
)
}
#[cfg(test)]
#[path = "run_curate_shorts_tests.rs"]
mod tests;

View file

@ -0,0 +1,395 @@
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 bson::DateTime as BsonDateTime;
use super::*;
use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD};
use crate::split::ymd_to_epoch_days;
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDirGuard {
path: PathBuf,
}
impl TempDirGuard {
fn new(label: &str) -> Self {
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let path =
std::env::temp_dir().join(format!("curate-etl-run-shorts-test-{label}-{pid}-{seq}"));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp dir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDirGuard {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn write_bytes(path: &Path, bytes: &[u8]) {
let mut f = File::create(path).expect("create file");
f.write_all(bytes).expect("write file");
}
fn make_short_doc(
fields: &CeoShortsFieldNames<'_>,
key: &str,
report_date: i32,
shares_short: f64,
net_change: Option<f64>,
pct_float: Option<f64>,
) -> Vec<u8> {
let cstring = |s: &str| bson::raw::CString::try_from(s.to_owned()).expect("valid BSON key");
let mut doc = RawDocumentBuf::new();
doc.append(cstring(fields.key), key);
let millis = i64::from(report_date) * 86_400_000;
doc.append(cstring(fields.report_date), BsonDateTime::from_millis(millis));
doc.append(cstring(fields.shares_short), shares_short);
if let (Some(f), Some(v)) = (fields.net_change, net_change) {
doc.append(cstring(f), v);
}
if let (Some(f), Some(v)) = (fields.pct_float, pct_float) {
doc.append(cstring(f), v);
}
doc.into_bytes()
}
fn default_test_fields() -> CeoShortsFieldNames<'static> {
CeoShortsFieldNames {
key: DEFAULT_KEY_FIELD,
report_date: DEFAULT_REPORT_DATE_FIELD,
shares_short: "sharesShort",
net_change: Some("netChange"),
pct_float: Some("pctFloat"),
}
}
fn assert_report_invariants(report: &CurateShortsRunReport) {
assert_eq!(report.docs_framed as usize, report.decode.docs_in);
assert_eq!(
report.decode.docs_in,
report.decode.rows_out + report.decode.skipped_total()
);
assert_eq!(report.decode.rows_out, report.curate_stats.builder.rows_in);
let b = &report.curate_stats.builder;
assert_eq!(
b.rows_in,
b.rows_out
+ b.dropped_invalid_shares_short
+ b.duplicate_collapsed
+ b.duplicate_conflict_dropped
);
let c = &report.curate_stats;
assert_eq!(c.rows_in, b.rows_out);
assert_eq!(
c.rows_in,
c.rows_out
+ c.dropped_unmapped
+ c.listing_collision_collapsed
+ c.listing_collision_dropped
);
assert_eq!(report.write_stats.rows_written, c.rows_out);
}
#[test]
fn end_to_end_curation_anchors_on_report_date_and_enforces_invariants() {
let dir = TempDirGuard::new("e2e");
let bson_path = dir.path().join("ceoShorts.bson");
let map_path = dir.path().join("provider_mapping.tsv");
let out_a = dir.path().join("out_a");
let out_b = dir.path().join("out_b");
// Listing 101 active on 2024-03-15, ends 2024-03-16 (before known_at_date 2024-03-21).
// Reuse gap on SYM_REUSE: 2020-01-01..=2022-12-31 -> 201, 2024-01-01.. -> 202.
// Alias SYM_ALIAS maps to 101 as well for cross-key collision test.
let mapping_tsv = concat!(
"ceo\tRY\t2020-01-01\t2024-03-16\t101\n",
"ceo\tRY_ALIAS\t2020-01-01\t2024-03-16\t101\n",
"ceo\tREUSE\t2020-01-01\t2022-12-31\t201\n",
"ceo\tREUSE\t2024-01-01\t\t202\n",
);
write_bytes(&map_path, mapping_tsv.as_bytes());
let fields = default_test_fields();
let docs = vec![
// Mapped on report_date 2024-03-15 even though listing ends 2024-03-16 (< known_at 2024-03-21)
make_short_doc(
&fields,
"RY",
day(2024, 3, 15),
100_000.0,
Some(1_000.0),
Some(1.5),
),
// Identical cross-key collision via RY_ALIAS -> collapsed
make_short_doc(
&fields,
"RY_ALIAS",
day(2024, 3, 15),
100_000.0,
Some(1_000.0),
Some(1.5),
),
// Conflicting cross-key collision on 2024-02-29 -> both dropped
make_short_doc(&fields, "RY", day(2024, 2, 29), 90_000.0, None, None),
make_short_doc(&fields, "RY_ALIAS", day(2024, 2, 29), 91_000.0, None, None),
// Reuse gap date 2023-06-15 -> dropped_unmapped
make_short_doc(&fields, "REUSE", day(2023, 6, 15), 50_000.0, None, None),
// Reuse post-gap 2024-03-28 -> listing 202
make_short_doc(&fields, "REUSE", day(2024, 3, 28), 60_000.0, None, None),
// Unmapped key -> dropped_unmapped
make_short_doc(&fields, "UNKNOWN", day(2024, 3, 15), 10_000.0, None, None),
];
let mut forward_bytes = Vec::new();
for d in &docs {
forward_bytes.extend_from_slice(d);
}
write_bytes(&bson_path, &forward_bytes);
let args_a = CurateShortsArgs {
ceo_shorts: bson_path.clone(),
provider_mapping: map_path.clone(),
out_dir: out_a.clone(),
key_field: DEFAULT_KEY_FIELD.to_string(),
report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(),
shares_short_field: "sharesShort".to_string(),
net_change_field: Some("netChange".to_string()),
pct_float_field: Some("pctFloat".to_string()),
mapping_source: DEFAULT_MAPPING_SOURCE.to_string(),
};
let report_a = run_curate_shorts(&args_a).expect("run forward");
assert_report_invariants(&report_a);
assert_eq!(report_a.curate_stats.rows_out, 2); // listing 101 (2024-03-15) and listing 202 (2024-03-28)
assert_eq!(report_a.curate_stats.listings_out, 2);
assert_eq!(report_a.curate_stats.dropped_unmapped, 2);
assert_eq!(report_a.curate_stats.listing_collision_collapsed, 1);
assert_eq!(report_a.curate_stats.listing_collision_dropped, 2);
assert_eq!(report_a.write_stats.files_written, 1);
assert_eq!(report_a.write_stats.rows_written, 2);
// Reversed input order must yield byte-identical shorts/part.parquet.
let bson_rev = dir.path().join("ceoShorts_rev.bson");
let mut rev_bytes = Vec::new();
for d in docs.iter().rev() {
rev_bytes.extend_from_slice(d);
}
write_bytes(&bson_rev, &rev_bytes);
let args_b = CurateShortsArgs {
ceo_shorts: bson_rev,
out_dir: out_b.clone(),
..args_a
};
let report_b = run_curate_shorts(&args_b).expect("run reversed");
assert_report_invariants(&report_b);
assert_eq!(report_a.curate_stats, report_b.curate_stats);
assert_eq!(report_a.write_stats, report_b.write_stats);
let bytes_a = fs::read(out_a.join("shorts/part.parquet")).expect("read a");
let bytes_b = fs::read(out_b.join("shorts/part.parquet")).expect("read b");
assert_eq!(bytes_a, bytes_b, "reversed input must produce byte-identical Parquet");
// Check report formatting determinism (ignoring final timing line).
let text_a = format_curate_shorts_report(&report_a);
let text_b = format_curate_shorts_report(&report_b);
let strip_timing = |s: &str| {
s.lines()
.filter(|l| !l.trim_start().starts_with("timing:"))
.collect::<Vec<_>>()
.join("\n")
};
assert_eq!(strip_timing(&text_a), strip_timing(&text_b));
}
#[test]
fn custom_mapping_source_and_custom_fields_work_end_to_end() {
let dir = TempDirGuard::new("custom");
let bson_path = dir.path().join("custom.bson");
let map_path = dir.path().join("mapping.tsv");
let out_dir = dir.path().join("out");
write_bytes(&map_path, b"ceo_custom\tSHOP\t2020-01-01\t\t777\n");
let custom_fields = CeoShortsFieldNames {
key: "ticker",
report_date: "asOf",
shares_short: "shortQty",
net_change: None,
pct_float: None,
};
let doc = make_short_doc(&custom_fields, "SHOP", day(2024, 7, 15), 12_345.0, None, None);
write_bytes(&bson_path, &doc);
let args = CurateShortsArgs {
ceo_shorts: bson_path,
provider_mapping: map_path,
out_dir,
key_field: "ticker".to_string(),
report_date_field: "asOf".to_string(),
shares_short_field: "shortQty".to_string(),
net_change_field: None,
pct_float_field: None,
mapping_source: "ceo_custom".to_string(),
};
let report = run_curate_shorts(&args).expect("custom run");
assert_report_invariants(&report);
assert_eq!(report.curate_stats.rows_out, 1);
assert_eq!(report.write_stats.rows_written, 1);
}
#[test]
fn failure_modes_and_all_unmapped_preserve_preexisting_output_byte_identically() {
let dir = TempDirGuard::new("failures");
let out_dir = dir.path().join("out");
let shorts_dir = out_dir.join("shorts");
fs::create_dir_all(&shorts_dir).unwrap();
let sentinel_path = shorts_dir.join("part.parquet");
let sentinel_bytes = b"SENTINEL-PREEXISTING-SHORTS-PARQUET".to_vec();
write_bytes(&sentinel_path, &sentinel_bytes);
let valid_map = dir.path().join("valid_map.tsv");
write_bytes(&valid_map, b"ceo\tRY\t2020-01-01\t\t101\n");
let fields = default_test_fields();
let valid_bson = dir.path().join("valid.bson");
write_bytes(
&valid_bson,
&make_short_doc(&fields, "RY", day(2024, 3, 15), 100.0, None, None),
);
let base_args = CurateShortsArgs {
ceo_shorts: valid_bson.clone(),
provider_mapping: valid_map.clone(),
out_dir: out_dir.clone(),
key_field: DEFAULT_KEY_FIELD.to_string(),
report_date_field: DEFAULT_REPORT_DATE_FIELD.to_string(),
shares_short_field: "sharesShort".to_string(),
net_change_field: None,
pct_float_field: None,
mapping_source: DEFAULT_MAPPING_SOURCE.to_string(),
};
// 1. Missing input file
let err = run_curate_shorts(&CurateShortsArgs {
ceo_shorts: dir.path().join("does_not_exist.bson"),
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::OpenInput { .. }));
assert!(!err.to_string().contains('\n'));
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
// 2. Malformed TSV
let bad_tsv = dir.path().join("bad.tsv");
write_bytes(&bad_tsv, b"ceo\tRY\tnot-a-date\t\t101\n");
let err = run_curate_shorts(&CurateShortsArgs {
provider_mapping: bad_tsv,
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::TsvParse { line: 1, .. }));
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
// 3. Overlapping mapping TSV
let overlap_tsv = dir.path().join("overlap.tsv");
write_bytes(
&overlap_tsv,
b"ceo\tRY\t2020-01-01\t2024-06-01\t101\nceo\tRY\t2024-06-01\t\t102\n",
);
let err = run_curate_shorts(&CurateShortsArgs {
provider_mapping: overlap_tsv,
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::ProviderMapping { .. }));
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
// 4. Truncated BSON
let trunc_bson = dir.path().join("trunc.bson");
write_bytes(&trunc_bson, &[20, 0, 0, 0, 1, 2]);
let err = run_curate_shorts(&CurateShortsArgs {
ceo_shorts: trunc_bson,
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::BsonStream { .. }));
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
// 5. Corrupt BSON element
let corrupt_bson = dir.path().join("corrupt.bson");
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), "RY");
doc.append(cstr!("z"), 1_i32);
let mut bytes = doc.into_bytes();
let z_pos = bytes
.windows(3)
.position(|w| w == [0x10, b'z', 0x00])
.unwrap();
bytes[z_pos] = 0x7e;
write_bytes(&corrupt_bson, &bytes);
let err = run_curate_shorts(&CurateShortsArgs {
ceo_shorts: corrupt_bson,
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::CorruptBson { offset: 0, .. }));
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
// 6. Out-of-range report_date (< 2008)
let oor_bson = dir.path().join("oor.bson");
write_bytes(
&oor_bson,
&make_short_doc(&fields, "RY", day(2007, 12, 15), 100.0, None, None),
);
let err = run_curate_shorts(&CurateShortsArgs {
ceo_shorts: oor_bson,
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::CurateWrite { .. }));
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
// 7. Obstructed --out (regular file)
let file_as_out = dir.path().join("file_out");
write_bytes(&file_as_out, b"not-a-dir");
let err = run_curate_shorts(&CurateShortsArgs {
out_dir: file_as_out,
..base_args.clone()
})
.unwrap_err();
assert!(matches!(err, RunCurateShortsError::InvalidOutDir { .. }));
// 8. All-unmapped input succeeds with rows_written == 0 and leaves sentinel untouched
let unmapped_bson = dir.path().join("unmapped.bson");
write_bytes(
&unmapped_bson,
&make_short_doc(&fields, "NO_MATCH", day(2024, 3, 15), 100.0, None, None),
);
let rep = run_curate_shorts(&CurateShortsArgs {
ceo_shorts: unmapped_bson,
..base_args
})
.expect("all-unmapped succeeds");
assert_report_invariants(&rep);
assert_eq!(rep.curate_stats.dropped_unmapped, 1);
assert_eq!(rep.write_stats.rows_written, 0);
assert_eq!(rep.write_stats.files_written, 0);
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
}

View file

@ -33,12 +33,18 @@ fn no_args_and_help_print_usage_and_succeed() {
assert!(text.contains("curate-bars-1d"), "{args:?}: {text}");
assert!(text.contains("curate-adj-factors"), "{args:?}: {text}");
assert!(text.contains("curate-corporate-actions"), "{args:?}: {text}");
assert!(text.contains("curate-fx-1d"), "{args:?}: {text}");
assert!(text.contains("curate-shorts"), "{args:?}: {text}");
assert!(text.contains("bench-curate-bars-cmd"), "{args:?}: {text}");
assert!(text.contains("bench-curate-adj-cmd"), "{args:?}: {text}");
assert!(
text.contains("bench-curate-corporate-actions-cmd"),
"{args:?}: {text}"
);
assert!(
text.contains("bench-curate-shorts-command"),
"{args:?}: {text}"
);
assert!(text.contains("bench-split"), "{args:?}: {text}");
assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}");
assert!(text.contains("bench-fx"), "{args:?}: {text}");
@ -1217,3 +1223,129 @@ fn bench_curate_fx_cmd_small_run_is_deterministic_and_reports_stages() {
assert_eq!(field(&text_a, "checksum="), field(&text_b, "checksum="));
assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out="));
}
#[test]
fn curate_shorts_usage_errors_exit_nonzero_with_usage_on_stderr() {
let cases: &[(&[&str], &str)] = &[
// Missing --shares-short-field
(
&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"out",
],
"--shares-short-field",
),
// Duplicate flag
(
&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--ceo-shorts",
"s2.bson",
"--provider-mapping",
"m.tsv",
"--out",
"out",
"--shares-short-field",
"sharesShort",
],
"duplicate flag",
),
// Unknown flag
(
&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"out",
"--shares-short-field",
"sharesShort",
"--unknown-flag",
"x",
],
"unknown flag",
),
// Empty field name
(
&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"out",
"--shares-short-field=",
],
"empty value",
),
// Two roles sharing one field name (collision with default 'timestamp')
(
&[
"curate-shorts",
"--ceo-shorts",
"s.bson",
"--provider-mapping",
"m.tsv",
"--out",
"out",
"--shares-short-field",
"timestamp",
],
"cannot share BSON field",
),
];
for &(args, expected_substr) in cases {
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(expected_substr), "{args:?}: {err}");
assert!(err.contains("Usage:"), "{args:?}: {err}");
}
}
#[test]
fn bench_curate_shorts_command_small_run_is_deterministic_and_reports_stages() {
let a = run(&["bench-curate-shorts-command", "2000"]);
let b = run(&["bench-curate-shorts-command", "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-shorts-command"),
"{text_a}"
);
assert!(text_a.contains("rows=2000 "), "{text_a}");
assert!(text_a.contains("peak_chunk_bytes="), "{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("rows/s"), "{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="));
}

View file

@ -0,0 +1,403 @@
//! End-to-end binary integration tests for `curate-etl curate-shorts` (`M1.2ad`).
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawDocumentBuf};
use bson::DateTime as BsonDateTime;
use curate_etl::{ymd_to_epoch_days, SHORTS_SOURCE_CEO};
use parquet::basic::{LogicalType, Repetition, TimeUnit, Type as PhysicalType};
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::RowAccessor;
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDir {
path: PathBuf,
}
impl TempDir {
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-it-shorts-{tag}-{pid}-{seq}"));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create integration test temp dir");
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn run(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
.args(args)
.output()
.expect("spawn curate-etl binary")
}
fn stdout(o: &Output) -> String {
String::from_utf8_lossy(&o.stdout).into_owned()
}
fn stderr(o: &Output) -> String {
String::from_utf8_lossy(&o.stderr).into_owned()
}
fn write_bytes(path: &Path, bytes: &[u8]) {
let mut f = File::create(path).expect("create file");
f.write_all(bytes).expect("write file");
}
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 {
let epoch_day = day(y, m, d);
let secs = i64::from(epoch_day) * 86_400
+ i64::from(hour) * 3_600
+ i64::from(minute) * 60
+ i64::from(second);
secs * 1_000_000
}
fn make_doc(
sym: &str,
report_date: i32,
shares_short: f64,
net_change: Option<f64>,
pct_float: Option<f64>,
) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), sym);
doc.append(
cstr!("timestamp"),
BsonDateTime::from_millis(i64::from(report_date) * 86_400_000),
);
doc.append(cstr!("sharesShort"), shares_short);
if let Some(v) = net_change {
doc.append(cstr!("netChange"), v);
}
if let Some(v) = pct_float {
doc.append(cstr!("pctFloat"), v);
}
doc.into_bytes()
}
#[derive(Debug, PartialEq)]
struct ReadRow {
listing_id: i32,
report_date: i32,
known_at: i64,
shares_short: f64,
net_change: Option<f64>,
pct_float: Option<f64>,
source: String,
}
fn read_shorts_parquet(path: &Path) -> Vec<ReadRow> {
let file = File::open(path).expect("open shorts/part.parquet");
let reader = SerializedFileReader::new(file).expect("parse parquet");
let schema = reader.metadata().file_metadata().schema();
let fields = schema.get_fields();
assert_eq!(fields.len(), 7, "expected 7 contract columns");
let expected_cols: [(&str, PhysicalType, Repetition, Option<LogicalType>); 7] = [
("listing_id", PhysicalType::INT32, Repetition::REQUIRED, None),
(
"report_date",
PhysicalType::INT32,
Repetition::REQUIRED,
Some(LogicalType::Date),
),
(
"known_at",
PhysicalType::INT64,
Repetition::REQUIRED,
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
),
(
"shares_short",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
),
(
"net_change",
PhysicalType::DOUBLE,
Repetition::OPTIONAL,
None,
),
(
"pct_float",
PhysicalType::DOUBLE,
Repetition::OPTIONAL,
None,
),
(
"source",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
),
];
for (field, (name, phys, rep, logical)) in fields.iter().zip(expected_cols) {
assert_eq!(field.name(), name);
assert_eq!(field.get_physical_type(), phys);
assert_eq!(field.get_basic_info().repetition(), rep);
assert_eq!(field.get_basic_info().logical_type_ref(), logical.as_ref());
}
let mut out = Vec::new();
let iter = reader.get_row_iter(None).expect("row iter");
for row_res in iter {
let row = row_res.expect("row");
let listing_id = row.get_int(0).expect("listing_id");
let report_date = match row.get_column_iter().nth(1).expect("report_date").1 {
parquet::record::Field::Date(d) => *d,
other => panic!("expected Date for report_date, got {other:?}"),
};
let known_at = row.get_timestamp_micros(2).expect("known_at");
let shares_short = row.get_double(3).expect("shares_short");
let net_change = row.get_double(4).ok();
let pct_float = row.get_double(5).ok();
let source = row.get_string(6).expect("source").to_owned();
out.push(ReadRow {
listing_id,
report_date,
known_at,
shares_short,
net_change,
pct_float,
source,
});
}
out
}
#[test]
fn end_to_end_est_edt_holiday_known_at_sorting_and_determinism() {
let dir = TempDir::new("e2e");
let map_path = dir.path.join("provider_mapping.tsv");
let bson_fwd = dir.path.join("shorts_fwd.bson");
let bson_rev = dir.path.join("shorts_rev.bson");
let out_1 = dir.path.join("out_1");
let out_2 = dir.path.join("out_2");
let out_rev = dir.path.join("out_rev");
write_bytes(
&map_path,
concat!(
"ceo\tRY\t2015-01-01\t\t200\n",
"ceo\tTD\t2015-01-01\t\t100\n",
)
.as_bytes(),
);
// Three cases:
// 1. EST: 2024-01-15 (Mon) + 4 TSX bdays -> 2024-01-19 (Fri) 17:00 EST = 22:00 UTC
// 2. EDT: 2024-07-15 (Mon) + 4 TSX bdays -> 2024-07-19 (Fri) 17:00 EDT = 21:00 UTC
// 3. Holiday crossing (Good Friday 2024-03-29):
// 2024-03-28 (Thu) + 4 TSX bdays -> Mon Apr 1 (1), Tue Apr 2 (2), Wed Apr 3 (3), Thu Apr 4 (4)
// = 2024-04-04 17:00 EDT = 21:00 UTC
// Deliberately emitted unsorted (listing 200 before 100, later dates before earlier) + 1 unmapped key.
let docs = vec![
make_doc("RY", day(2024, 7, 15), 250_000.0, Some(5_000.0), Some(1.2)),
make_doc("TD", day(2024, 3, 28), 300_000.0, Some(-2_500.0), None),
make_doc("TD", day(2024, 1, 15), 180_000.0, None, Some(0.8)),
make_doc("UNMAPPED", day(2024, 1, 15), 10_000.0, None, None),
];
let mut fwd_bytes = Vec::new();
for d in &docs {
fwd_bytes.extend_from_slice(d);
}
write_bytes(&bson_fwd, &fwd_bytes);
let mut rev_bytes = Vec::new();
for d in docs.iter().rev() {
rev_bytes.extend_from_slice(d);
}
write_bytes(&bson_rev, &rev_bytes);
let invoke = |bson: &Path, out: &Path| {
run(&[
"curate-shorts",
"--ceo-shorts",
bson.to_str().unwrap(),
"--provider-mapping",
map_path.to_str().unwrap(),
"--out",
out.to_str().unwrap(),
"--shares-short-field",
"sharesShort",
"--net-change-field",
"netChange",
"--pct-float-field",
"pctFloat",
])
};
let res1 = invoke(&bson_fwd, &out_1);
assert!(res1.status.success(), "{}", stderr(&res1));
assert!(stderr(&res1).is_empty(), "{}", stderr(&res1));
let out_text = stdout(&res1);
assert!(out_text.contains("curate-etl curate-shorts"), "{out_text}");
assert!(out_text.contains("dropped_unmapped=1"), "{out_text}");
assert!(out_text.contains("rows_written=3"), "{out_text}");
let rows = read_shorts_parquet(&out_1.join("shorts/part.parquet"));
assert_eq!(
rows,
vec![
ReadRow {
listing_id: 100,
report_date: day(2024, 1, 15),
known_at: utc_micros(2024, 1, 19, 22, 0, 0), // EST 17:00 = 22:00 UTC
shares_short: 180_000.0,
net_change: None,
pct_float: Some(0.8),
source: SHORTS_SOURCE_CEO.to_string(),
},
ReadRow {
listing_id: 100,
report_date: day(2024, 3, 28),
known_at: utc_micros(2024, 4, 4, 21, 0, 0), // crosses Good Friday -> EDT 17:00 = 21:00 UTC
shares_short: 300_000.0,
net_change: Some(-2_500.0),
pct_float: None,
source: SHORTS_SOURCE_CEO.to_string(),
},
ReadRow {
listing_id: 200,
report_date: day(2024, 7, 15),
known_at: utc_micros(2024, 7, 19, 21, 0, 0), // EDT 17:00 = 21:00 UTC
shares_short: 250_000.0,
net_change: Some(5_000.0),
pct_float: Some(1.2),
source: SHORTS_SOURCE_CEO.to_string(),
},
]
);
// Determinism: repeated run and reversed BSON order must produce byte-identical Parquet.
let res2 = invoke(&bson_fwd, &out_2);
assert!(res2.status.success(), "{}", stderr(&res2));
let res_rev = invoke(&bson_rev, &out_rev);
assert!(res_rev.status.success(), "{}", stderr(&res_rev));
let bytes_1 = fs::read(out_1.join("shorts/part.parquet")).unwrap();
let bytes_2 = fs::read(out_2.join("shorts/part.parquet")).unwrap();
let bytes_rev = fs::read(out_rev.join("shorts/part.parquet")).unwrap();
assert_eq!(bytes_1, bytes_2, "repeated run must be byte-identical");
assert_eq!(bytes_1, bytes_rev, "reversed input must be byte-identical");
}
#[test]
fn failure_modes_exit_nonzero_without_usage_and_preserve_preexisting_parquet() {
let dir = TempDir::new("failures");
let out_dir = dir.path.join("out");
let shorts_dir = out_dir.join("shorts");
fs::create_dir_all(&shorts_dir).unwrap();
let sentinel_path = shorts_dir.join("part.parquet");
let sentinel = b"PREEXISTING-SHORTS-SENTINEL".to_vec();
write_bytes(&sentinel_path, &sentinel);
let valid_map = dir.path.join("valid_map.tsv");
write_bytes(&valid_map, b"ceo\tRY\t2020-01-01\t\t101\n");
let valid_bson = dir.path.join("valid.bson");
write_bytes(&valid_bson, &make_doc("RY", day(2024, 3, 15), 100.0, None, None));
// 1. Missing input file
let missing = dir.path.join("missing.bson");
let res = run(&[
"curate-shorts",
"--ceo-shorts",
missing.to_str().unwrap(),
"--provider-mapping",
valid_map.to_str().unwrap(),
"--out",
out_dir.to_str().unwrap(),
"--shares-short-field",
"sharesShort",
]);
assert!(!res.status.success());
assert!(stdout(&res).is_empty());
let err = stderr(&res);
assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}");
assert!(!err.contains("Usage:"), "{err}");
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel);
// 2. Truncated BSON
let trunc_bson = dir.path.join("trunc.bson");
write_bytes(&trunc_bson, &[25, 0, 0, 0, 0x02, b'a']);
let res = run(&[
"curate-shorts",
"--ceo-shorts",
trunc_bson.to_str().unwrap(),
"--provider-mapping",
valid_map.to_str().unwrap(),
"--out",
out_dir.to_str().unwrap(),
"--shares-short-field",
"sharesShort",
]);
assert!(!res.status.success());
let err = stderr(&res);
assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}");
assert!(!err.contains("Usage:"), "{err}");
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel);
// 3. Malformed mapping TSV
let bad_map = dir.path.join("bad_map.tsv");
write_bytes(&bad_map, b"ceo\tRY\tbad-date\t\t101\n");
let res = run(&[
"curate-shorts",
"--ceo-shorts",
valid_bson.to_str().unwrap(),
"--provider-mapping",
bad_map.to_str().unwrap(),
"--out",
out_dir.to_str().unwrap(),
"--shares-short-field",
"sharesShort",
]);
assert!(!res.status.success());
let err = stderr(&res);
assert_eq!(err.lines().count(), 1, "single-line stderr expected: {err}");
assert!(!err.contains("Usage:"), "{err}");
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel);
// 4. All-unmapped keys -> exits 0, counts dropped_unmapped=1, preserves sentinel
let unmapped_bson = dir.path.join("unmapped.bson");
write_bytes(
&unmapped_bson,
&make_doc("NO_SUCH_KEY", day(2024, 3, 15), 100.0, None, None),
);
let res = run(&[
"curate-shorts",
"--ceo-shorts",
unmapped_bson.to_str().unwrap(),
"--provider-mapping",
valid_map.to_str().unwrap(),
"--out",
out_dir.to_str().unwrap(),
"--shares-short-field",
"sharesShort",
]);
assert!(res.status.success(), "{}", stderr(&res));
let out = stdout(&res);
assert!(out.contains("dropped_unmapped=1"), "{out}");
assert!(out.contains("rows_written=0"), "{out}");
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel);
}