T-93: M1.2k — tools/curate-etl: Zstd Parquet writer for events/year=YYYY/part.parquet (contract schema, atomic year-partitioned publish) with round-trip tests and local benchmark (no new crates)

This commit is contained in:
Studio 2026-11-28 14:30:38 -05:00
parent 4e344bcc2e
commit 2babdaba2c
3 changed files with 91 additions and 17 deletions

View file

@ -264,7 +264,7 @@ Rules:
- `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
- `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded)
- `subtype` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
- `subtype` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary disabled)
- `payload_json` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary disabled)
2. **Partition layout, compression & streaming:**
- Writes `<out_dir>/events/year=YYYY/part.parquet` lazily per observed UTC year `partition_year_utc(ts_micros)` (`1900..=2200`).
@ -294,8 +294,8 @@ Rules:
5. **Measured baseline (`2026-11-28`):**
- Command: `cargo run --release -p curate-etl --offline -- bench-parquet-events`
- Input: `rows=500000`, `listings=5000`, `avg_raw_row_bytes=243.6` (11 UTC years `2015..=2025`, ~98.5% filings / ~1.5% linked & lagged earnings)
- Output: `files=11`, `row_groups=11`, `bytes=13348791`, `read_back_rows=500000`
- Perf: `elapsed=549.54 ms`, `throughput=909847 rows/s`, `write=23.17 MB/s`, `size=26.70 bytes/row`, `compression=9.13x`
- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000`
- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x`
## Local Benchmarks
@ -450,8 +450,8 @@ cargo run --release -p curate-etl --offline -- bench-parquet-events [rows]
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-events`
- Input: `rows=500000`, `listings=5000`, `avg_raw_row_bytes=243.6`
- Output: `files=11`, `row_groups=11`, `bytes=13348791`, `read_back_rows=500000`
- Perf: `elapsed=549.54 ms`, `throughput=909847 rows/s`, `write=23.17 MB/s`, `size=26.70 bytes/row`, `compression=9.13x`
- Output: `files=11`, `row_groups=11`, `bytes=13831862`, `read_back_rows=500000`
- Perf: `elapsed=548.08 ms`, `throughput=912273 rows/s`, `write=24.07 MB/s`, `size=27.66 bytes/row`, `compression=8.81x`
## Deferred Follow-Ups (`M1.3+` / `M2`)

View file

@ -363,6 +363,7 @@ fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr {
.set_compression(Compression::ZSTD(zstd_level))
.set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true)
.set_column_dictionary_enabled(ColumnPath::from("kind"), true)
.set_column_dictionary_enabled(ColumnPath::from("subtype"), false)
.set_column_dictionary_enabled(ColumnPath::from("payload_json"), false)
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
.build(),
@ -694,12 +695,37 @@ fn write_events_dataset_with_hooks<P, I, R, F>(
rows: I,
options: EventsWriteOptions,
lock_timeout: Duration,
on_after_backup: F,
) -> Result<EventsWriteStats, ParquetEventsError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<EventsParquetRow>,
F: FnMut(i32, &Path, Option<&Path>),
{
write_events_dataset_with_lock_and_backup_hooks(
out_dir,
rows,
options,
lock_timeout,
|| {},
on_after_backup,
)
}
fn write_events_dataset_with_lock_and_backup_hooks<P, I, R, G, F>(
out_dir: P,
rows: I,
options: EventsWriteOptions,
lock_timeout: Duration,
mut on_lock_contended: G,
mut on_after_backup: F,
) -> Result<EventsWriteStats, ParquetEventsError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<EventsParquetRow>,
G: FnMut(),
F: FnMut(i32, &Path, Option<&Path>),
{
if options.row_group_rows == 0 {
@ -734,7 +760,14 @@ where
// Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held,
// and only after all staging/publication/rollback work has finished.
let dataset_mu = dataset_mutex(&events_dir);
let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner());
let _in_process_guard = match dataset_mu.try_lock() {
Ok(guard) => guard,
Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => {
on_lock_contended();
dataset_mu.lock().unwrap_or_else(|err| err.into_inner())
}
};
let _file_lock = DatasetFileLock::acquire_with_timeout(&events_dir, lock_timeout)?;
let run_id = next_run_id();
@ -1176,6 +1209,14 @@ mod tests {
filing_id: Some("F-2023-8K".to_string()),
url: Some("https://sec.example/2023-8k".to_string()),
},
// Second 2023 8-K so a single row group contains repeated `subtype = "8-k"` values
QmFiling {
key: 10_i32,
timefiled: "2023-05-05T10:00:00 EDT".to_string(),
form_type: "8-K".to_string(),
filing_id: Some("F-2023-8K-2".to_string()),
url: Some("https://sec.example/2023-8k-2".to_string()),
},
// Late-evening ET on 2024-12-31 21:30:00 EST -> 2025-01-01 02:30:00 UTC (year=2025)
QmFiling {
key: 10_i32,
@ -1216,7 +1257,7 @@ mod tests {
];
let built = build_events(filings, earnings);
assert_eq!(built.stats.filings_out, 4);
assert_eq!(built.stats.filings_out, 5);
assert_eq!(built.stats.earnings_linked_to_filing, 1);
assert_eq!(built.stats.earnings_lagged_1605, 1);
@ -1262,10 +1303,10 @@ mod tests {
};
let stats = write_events_dataset(tmp.path(), &rows, opts).expect("write events");
let expected_by_year = BTreeMap::from([(2022, 1), (2023, 3), (2024, 3), (2025, 2)]);
let expected_by_year = BTreeMap::from([(2022, 1), (2023, 4), (2024, 3), (2025, 2)]);
assert_eq!(stats.rows_written, rows.len());
assert_eq!(stats.files_written, 4);
// 2022: 1 row (1 rg), 2023: 3 rows (2 rgs), 2024: 3 rows (2 rgs), 2025: 2 rows (1 rg)
// 2022: 1 row (1 rg), 2023: 4 rows (2 rgs), 2024: 3 rows (2 rgs), 2025: 2 rows (1 rg)
assert_eq!(stats.row_groups_written, 6);
assert_eq!(stats.rows_by_year, expected_by_year);
@ -1300,6 +1341,21 @@ mod tests {
"year {year} column {dict_col} should use dictionary encoding"
);
}
for plain_col in [5usize, 6usize] {
assert!(
!rg.column(plain_col).encodings().any(|e| matches!(
e,
Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY
)),
"year {year} column {plain_col} must not use dictionary encoding"
);
assert!(
rg.column(plain_col)
.encodings()
.any(|e| e == Encoding::PLAIN),
"year {year} column {plain_col} should use PLAIN encoding"
);
}
}
let actual = read_parquet_rows(&path);

View file

@ -14,7 +14,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
use super::tests::{assert_no_transient_files, make_event_row, read_parquet_rows, utc_micros, TempDirGuard};
use super::{
write_events_dataset, write_events_dataset_with_hooks, EventsParquetRow, EventsWriteOptions,
write_events_dataset, write_events_dataset_with_hooks,
write_events_dataset_with_lock_and_backup_hooks, EventsParquetRow, EventsWriteOptions,
EventsWriteStats, ParquetEventsError, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
};
use crate::events::{
@ -730,7 +731,7 @@ fn concurrent_writers_serialize_without_mixed_generations() {
let order = Arc::new(Mutex::new(Vec::<&'static str>::new()));
let (t1_locked_tx, t1_locked_rx) = mpsc::channel::<()>();
let (t2_started_tx, t2_started_rx) = mpsc::channel::<()>();
let (t2_contended_tx, t2_contended_rx) = mpsc::channel::<()>();
let out_1 = out_dir.clone();
let order_1 = Arc::clone(&order);
@ -743,8 +744,10 @@ fn concurrent_writers_serialize_without_mixed_generations() {
on_second: Some(Box::new(move || {
order_1.lock().unwrap().push("t1_row2");
let _ = t1_locked_tx.send(());
let _ = t2_started_rx.recv_timeout(Duration::from_secs(2));
thread::sleep(Duration::from_millis(30));
// Hold the dataset lock until we directly observe writer 2 contend for it.
t2_contended_rx
.recv_timeout(Duration::from_secs(5))
.expect("expected writer 2 to contend on the dataset lock");
})),
on_end: Some(Box::new(move || {
order_1_end.lock().unwrap().push("t1_iter_end");
@ -754,11 +757,11 @@ fn concurrent_writers_serialize_without_mixed_generations() {
});
let out_2 = out_dir.clone();
let order_2_contended = Arc::clone(&order);
let order_2 = Arc::clone(&order);
let rows_b_clone = rows_b.clone();
let h2 = thread::spawn(move || {
t1_locked_rx.recv_timeout(Duration::from_secs(2)).unwrap();
let _ = t2_started_tx.send(());
t1_locked_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let iter = SignalingIter {
rows: rows_b_clone.into_iter(),
seen: 0,
@ -767,16 +770,31 @@ fn concurrent_writers_serialize_without_mixed_generations() {
})),
on_end: None,
};
write_events_dataset(&out_2, iter, EventsWriteOptions::default())
write_events_dataset_with_lock_and_backup_hooks(
&out_2,
iter,
EventsWriteOptions::default(),
DEFAULT_LOCK_TIMEOUT,
|| {
order_2_contended.lock().unwrap().push("t2_contended");
let _ = t2_contended_tx.send(());
},
|_, _, _| {},
)
});
assert_eq!(h1.join().unwrap().unwrap().rows_written, rows_a.len());
assert_eq!(h2.join().unwrap().unwrap().rows_written, rows_b.len());
let recorded = order.lock().unwrap();
let pos_t1_row2 = recorded.iter().position(|&e| e == "t1_row2").unwrap();
let pos_t2_contended = recorded.iter().position(|&e| e == "t2_contended").unwrap();
let pos_t1_end = recorded.iter().position(|&e| e == "t1_iter_end").unwrap();
let pos_t2_row2 = recorded.iter().position(|&e| e == "t2_row2").unwrap();
assert!(pos_t1_end < pos_t2_row2, "expected strict serialization: {recorded:?}");
assert!(
pos_t1_row2 < pos_t2_contended && pos_t2_contended < pos_t1_end && pos_t1_end < pos_t2_row2,
"expected strict serialization with observed lock contention: {recorded:?}"
);
for year in [2023, 2024] {
let actual = read_parquet_rows(&out_dir.join(format!("events/year={year:04}/part.parquet")));