From e3085812d2762444a22a5bb35376daf831bc8361 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 26 May 2026 00:50:26 +0200 Subject: [PATCH 1/6] feat(bench): land A1 compression-ratio measurement (PR-I2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second implementation slice on RFC 0006. The A1 thesis gate ("Ourios beats ZSTD-alone by ≥ 3× on the compression ratio") now runs end-to-end. C2 remains NotImplemented; A1 and C1 can run individually or together in a single miner pass. Lands: - `src/a1.rs` — `A1Accumulator` streams emitted records into per-partition `ourios_parquet::Writer`s during the harness loop (memory bounded at ~one row group per open partition), captures the miner's audit-event stream into the `audit/...` series, then at finalize closes the writers, sums the on-disk `*.parquet` bytes (data + audit, skipping `*.parquet.tmp`), runs the ZSTD-19 reference codec over each `*.txt` individually, and computes the §3.4.1 ratios. The delta is floored to three significant figures so reported numbers err pessimistic. - `src/harness.rs` — wires a `SharedAuditSink` alongside the record sink and returns the drained audit events (`HarnessResult`). The internal snapshot map is no longer surfaced (no consumer past the loop). - `src/lib.rs` — `run()` restructured to set up whichever gate accumulators are enabled and feed both from one callback; resolves the Parquet output bucket (caller- supplied or a scratch `TempDir`, persisted on `--keep-parquet`). - `crates/ourios-parquet/src/partition.rs` — `PartitionKey` derives `Hash` so the bench can group records / audit events by partition in a `HashMap`. Purely additive. - `tests/a1.rs` — RFC0006.1 un-`#[ignore]`'d; the real `zstd_level_19_bytes` helper (via the `zstd` crate) replaces the stub. The test recomputes every byte count from disk and asserts the bench's reported values match. ZSTD: uses the `zstd` crate (ergonomic safe wrapper over `zstd-safe`, already in the tree via parquet's `zstd` feature) per the RFC §7 resolution — same bundled C library, version pinned by Cargo.lock, no host `zstd` binary needed. Test surface: - `src/a1.rs` unit tests: 3-sigfig floor, the ratio-of-ratios formula, pass/fail threshold, zero-output guard. - `tests/a1.rs`: both RFC0006.1 scenarios now green against the seed corpus (formula legs verified against independent disk recomputation; actual §9 pass/fail numbers are a separate benchmarking session per the RFC). - The lib.rs marker test narrows to `c2_still_returns_not_implemented`. - The harness's snapshot-map test is replaced by `repeated_template_reuses_one_snapshot` (the map is no longer a public output; the reuse contract is what matters). Verification (CLAUDE.md §6.6): - cargo fmt --all --check — clean. - cargo clippy --all-targets --all-features -- -D warnings — clean. - cargo test --all-features — 249 passed / 22 ignored (was 237 / 24; the two RFC0006.1 A1 tests flipped green). Maturity gate: RFC 0006 stays `red` until C2, RFC0006.5, and RFC0006.6 also pass. Co-Authored-By: Claude Opus 4.7 (1M context) --- Cargo.lock | 1 + crates/ourios-bench/Cargo.toml | 21 +- crates/ourios-bench/src/a1.rs | 432 +++++++++++++++++++++++++ crates/ourios-bench/src/harness.rs | 67 ++-- crates/ourios-bench/src/lib.rs | 191 +++++++---- crates/ourios-bench/tests/a1.rs | 55 ++-- crates/ourios-parquet/src/partition.rs | 2 +- 7 files changed, 648 insertions(+), 121 deletions(-) create mode 100644 crates/ourios-bench/src/a1.rs diff --git a/Cargo.lock b/Cargo.lock index c660b3f30..900c916e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -811,6 +811,7 @@ dependencies = [ "serde", "serde_json", "tempfile", + "zstd", ] [[package]] diff --git a/crates/ourios-bench/Cargo.toml b/crates/ourios-bench/Cargo.toml index 6a62fb7c4..297119332 100644 --- a/crates/ourios-bench/Cargo.toml +++ b/crates/ourios-bench/Cargo.toml @@ -28,13 +28,26 @@ ourios-parquet = { path = "../ourios-parquet" } # `derive` gives the struct→JSON path; `std` covers the rest. serde = { version = "1", default-features = false, features = ["derive", "std"] } serde_json = { version = "1", default-features = false, features = ["std"] } +# A1's ZSTD-19 reference codec (RFC 0006 §3.4.1 / §7). `zstd` is +# the ergonomic safe wrapper over `zstd-safe`; both bind the same +# bundled C library and `parquet`'s `zstd` feature already pulls +# it into the tree, so the version is pinned by `Cargo.lock` and +# A1 is reproducible across hosts without a system `zstd` binary. +zstd = "0.13" +# A1 writes the Parquet output bucket somewhere measurable; when +# `BenchConfig.bucket_dir` is `None`, `run` creates a scratch dir +# here and (unless `--keep-parquet`) cleans it up on exit. +tempfile = "3" [dev-dependencies] -# `tempfile` is the standard scratch-directory helper the other -# integration tests in this workspace use (see ourios-parquet's -# dev-dependencies). The bench's red-gate test stubs will need -# it once they run real flows. +# Integration tests reuse `tempfile` for scratch corpora / +# buckets; the RFC0006.1 test also recomputes the ZSTD-19 +# reference byte count, so it needs `zstd` on the test side. tempfile = "3" +# The RFC0006.1 integration test independently recomputes the +# ZSTD-19 reference byte count to check the bench's reported +# value, so it needs `zstd` on the test side too. +zstd = "0.13" [lints] workspace = true diff --git a/crates/ourios-bench/src/a1.rs b/crates/ourios-bench/src/a1.rs new file mode 100644 index 000000000..e7f0cc39c --- /dev/null +++ b/crates/ourios-bench/src/a1.rs @@ -0,0 +1,432 @@ +//! A1 — Compression ratio. +//! +//! Per RFC 0006 §3.4.1: +//! +//! ```text +//! ourios_ratio = bytes(raw_corpus) / bytes(ourios_output) +//! zstd_ratio = bytes(raw_corpus) / bytes(zstd_corpus) +//! A1_delta = ourios_ratio / zstd_ratio +//! ``` +//! +//! - `bytes(raw_corpus)` — sum of `*.txt` file sizes (computed +//! by [`crate::corpus`] during load, passed in here). +//! - `bytes(ourios_output)` — sum of every `*.parquet` file +//! under the bench's output bucket, **including the +//! `audit/...` series**; the pre-rename `*.parquet.tmp` +//! files are skipped (RFC 0005 §7 atomic-publish). +//! - `bytes(zstd_corpus)` — sum of `zstd -19` output over each +//! `*.txt` **individually** (not concatenated — per-file is +//! the honest, stricter comparison the Drain paper uses). +//! - `A1_delta` — the ratio of ratios, rounded *down* to three +//! significant figures so reported numbers err pessimistic. +//! +//! The accumulator streams emitted records into per-partition +//! `ourios_parquet::Writer`s during the harness loop (memory +//! stays at ~one row group per open partition), captures the +//! miner's audit-event stream, then measures the on-disk +//! footprint at finalize time. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use ourios_core::audit::AuditEvent; +use ourios_core::record::MinedRecord; +use ourios_core::tenant::TenantId; +use ourios_parquet::{AuditWriter, PartitionKey, Writer}; + +use crate::A1Result; + +/// RFC 0006 §3.4.1 ZSTD reference level. Level 19 (not 3) +/// matches the Drain paper's published comparison and is the +/// strictest competent byte codec; ZSTD-3 would make A1 +/// trivially pass. +const ZSTD_LEVEL: i32 = 19; + +/// RFC 0006 §3.4.1 pass target — Ourios must beat ZSTD-alone +/// by at least 3×. +const TARGET_DELTA: f64 = 3.0; + +/// Everything [`A1Accumulator::finalize`] hands back: the +/// §3.4.1 ratio result plus the raw byte counts `run` needs to +/// populate the §3.6 `ourios` / `zstd` blocks. Bundled so the +/// measurement is computed once and the caller doesn't +/// re-derive the splits. +pub(crate) struct A1Outcome { + pub result: A1Result, + pub data_parquet_bytes: u64, + pub audit_parquet_bytes: u64, + pub total_parquet_bytes: u64, + pub zstd_bytes: u64, +} + +/// Streaming accumulator for the §3.4.1 A1 measurement. +/// +/// `record` is called once per emitted record by the harness +/// loop and writes it into the partition's data Parquet file. +/// Writes can fail (I/O); since the harness callback can't +/// return a `Result`, the first error is stashed in `error` +/// and surfaced by [`Self::finalize`] — subsequent `record` +/// calls become no-ops so we don't pile errors on a poisoned +/// writer. +pub(crate) struct A1Accumulator { + bucket_root: PathBuf, + data_writers: HashMap, + error: Option, +} + +impl A1Accumulator { + /// Create an accumulator writing under `bucket_root`. The + /// directory is created lazily by the per-partition + /// writers on first record. + pub(crate) fn new(bucket_root: &Path) -> Self { + Self { + bucket_root: bucket_root.to_path_buf(), + data_writers: HashMap::new(), + error: None, + } + } + + /// Stream one emitted record into its partition's data + /// writer. No-op once an earlier write has errored. + pub(crate) fn record(&mut self, emitted: &MinedRecord) { + if self.error.is_some() { + return; + } + if let Err(e) = self.record_inner(emitted) { + self.error = Some(e); + } + } + + fn record_inner(&mut self, emitted: &MinedRecord) -> Result<(), crate::BenchError> { + let partition = PartitionKey::derive(emitted).map_err(|e| crate::BenchError::Pipeline { + detail: format!("partition derive failed: {e}"), + })?; + let writer = match self.data_writers.entry(partition.clone()) { + std::collections::hash_map::Entry::Occupied(w) => w.into_mut(), + std::collections::hash_map::Entry::Vacant(slot) => { + let w = Writer::open(&self.bucket_root, partition).map_err(|e| { + crate::BenchError::Pipeline { + detail: format!("parquet writer open: {e}"), + } + })?; + slot.insert(w) + } + }; + writer + .append_records(std::slice::from_ref(emitted)) + .map_err(|e| crate::BenchError::Pipeline { + detail: format!("parquet append_records: {e}"), + }) + } + + /// Write the miner's audit-event stream into the + /// `audit/...` partition series. Grouped by the same + /// partition key the data records use (derived from a + /// proxy record carrying the event's tenant + timestamp, + /// the established `ourios-parquet` pattern). Called once + /// after the harness loop, before [`Self::finalize`]. + pub(crate) fn write_audit(&mut self, events: &[AuditEvent]) -> Result<(), crate::BenchError> { + if let Some(e) = self.error.take() { + return Err(e); + } + let mut by_partition: HashMap> = HashMap::new(); + for event in events { + let partition = audit_partition(event)?; + by_partition + .entry(partition) + .or_default() + .push(event.clone()); + } + for (partition, events) in by_partition { + let mut writer = AuditWriter::open(&self.bucket_root, partition).map_err(|e| { + crate::BenchError::Pipeline { + detail: format!("audit writer open: {e}"), + } + })?; + writer + .append_events(&events) + .map_err(|e| crate::BenchError::Pipeline { + detail: format!("audit append_events: {e}"), + })?; + writer.close().map_err(|e| crate::BenchError::Pipeline { + detail: format!("audit writer close: {e}"), + })?; + } + Ok(()) + } + + /// Close every data writer, measure the on-disk footprint, + /// run the ZSTD-19 reference codec over `corpus_dir`, and + /// compute the §3.4.1 ratios. + /// + /// `raw_bytes` is `bytes(raw_corpus)` from the corpus load + /// (sum of `*.txt` sizes); `corpus_dir` is re-walked here + /// to feed the reference codec per file. + pub(crate) fn finalize( + mut self, + raw_bytes: u64, + corpus_dir: &Path, + ) -> Result { + if let Some(e) = self.error.take() { + return Err(e); + } + // Close every data writer so the `*.parquet.tmp` files + // are atomically renamed to their final `*.parquet` + // names before we measure. + for (_partition, writer) in self.data_writers.drain() { + writer.close().map_err(|e| crate::BenchError::Pipeline { + detail: format!("parquet writer close: {e}"), + })?; + } + + let data_parquet_bytes = sum_parquet_bytes(&self.bucket_root.join("data"))?; + let audit_parquet_bytes = sum_parquet_bytes(&self.bucket_root.join("audit"))?; + let total_parquet_bytes = data_parquet_bytes + audit_parquet_bytes; + let zstd_bytes = zstd_level_19_bytes(corpus_dir)?; + + Ok(A1Outcome { + result: compute_a1(raw_bytes, total_parquet_bytes, zstd_bytes), + data_parquet_bytes, + audit_parquet_bytes, + total_parquet_bytes, + zstd_bytes, + }) + } +} + +/// Derive the partition key for an audit event from a proxy +/// `MinedRecord` carrying the event's tenant + timestamp — the +/// same approach `ourios-parquet`'s audit round-trip test uses +/// (`PartitionKey::derive` only reads tenant + timestamp). +fn audit_partition(event: &AuditEvent) -> Result { + let nanos = event + .timestamp + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| crate::BenchError::Pipeline { + detail: format!("audit event timestamp before Unix epoch: {e}"), + })? + .as_nanos(); + let time_unix_nano = u64::try_from(nanos).unwrap_or(u64::MAX); + let proxy = MinedRecord { + tenant_id: event.tenant_id.clone(), + time_unix_nano, + ..proxy_record() + }; + PartitionKey::derive(&proxy).map_err(|e| crate::BenchError::Pipeline { + detail: format!("audit partition derive failed: {e}"), + }) +} + +/// A `MinedRecord` with every field at its zero value, used +/// only as a carrier for `(tenant_id, time_unix_nano)` into +/// `PartitionKey::derive`. `MinedRecord` has no `Default`, so +/// the fields are spelled out once here. +fn proxy_record() -> MinedRecord { + use ourios_core::record::BodyKind; + MinedRecord { + tenant_id: TenantId::new(""), + template_id: 0, + template_version: 0, + severity_number: 0, + severity_text: None, + scope_name: None, + scope_version: None, + time_unix_nano: 0, + observed_time_unix_nano: None, + attributes: Vec::new(), + dropped_attributes_count: 0, + resource_attributes: Vec::new(), + trace_id: None, + span_id: None, + flags: 0, + event_name: None, + body_kind: BodyKind::String, + params: Vec::new(), + separators: vec![String::new()], + body: None, + confidence: 0.0, + lossy_flag: false, + } +} + +/// Sum `*.parquet` file sizes under `dir` (recursive), skipping +/// pre-rename `*.parquet.tmp` files per RFC 0005 §7. Returns +/// `Ok(0)` when `dir` doesn't exist (a gate that produced no +/// output for that subtree — e.g. zero audit events). +fn sum_parquet_bytes(dir: &Path) -> Result { + if !dir.exists() { + return Ok(0); + } + let mut total = 0u64; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let entries = std::fs::read_dir(&d).map_err(|e| crate::BenchError::Report { + detail: format!("read_dir({}): {e}", d.display()), + })?; + for entry in entries { + let entry = entry.map_err(|e| crate::BenchError::Report { + detail: format!("read_dir entry under {}: {e}", d.display()), + })?; + let path = entry.path(); + let meta = std::fs::metadata(&path).map_err(|e| crate::BenchError::Report { + detail: format!("metadata({}): {e}", path.display()), + })?; + if meta.is_dir() { + stack.push(path); + } else if path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("parquet")) + { + // `.parquet.tmp` has extension `tmp`, not + // `parquet`, so the suffix check naturally + // skips in-flight writes. + total += meta.len(); + } + } + } + Ok(total) +} + +/// Compute `bytes(zstd_corpus)` — run ZSTD-19 over each `*.txt` +/// file under `dir` individually and sum the compressed +/// lengths. Per-file (not concatenated) per §3.4.1. +fn zstd_level_19_bytes(dir: &Path) -> Result { + let mut total = 0u64; + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let entries = std::fs::read_dir(&d).map_err(|e| crate::BenchError::Corpus { + detail: format!("read_dir({}): {e}", d.display()), + })?; + for entry in entries { + let entry = entry.map_err(|e| crate::BenchError::Corpus { + detail: format!("read_dir entry under {}: {e}", d.display()), + })?; + let path = entry.path(); + let meta = std::fs::metadata(&path).map_err(|e| crate::BenchError::Corpus { + detail: format!("metadata({}): {e}", path.display()), + })?; + if meta.is_dir() { + stack.push(path); + } else if path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("txt")) + { + let bytes = std::fs::read(&path).map_err(|e| crate::BenchError::Corpus { + detail: format!("read({}): {e}", path.display()), + })?; + let compressed = zstd::bulk::compress(&bytes, ZSTD_LEVEL).map_err(|e| { + crate::BenchError::Report { + detail: format!("zstd compress({}): {e}", path.display()), + } + })?; + total += compressed.len() as u64; + } + } + } + Ok(total) +} + +/// Pure §3.4.1 formula given the measured byte counts. Split +/// out so the ratio math + 3-sigfig rounding is unit-testable +/// without touching the filesystem. The data/audit split +/// doesn't enter the formula (A1 operates on the total) — it's +/// carried separately in [`A1Outcome`] for the §3.6 `ourios` +/// block. +#[allow(clippy::cast_precision_loss)] +fn compute_a1(raw_bytes: u64, total_parquet_bytes: u64, zstd_bytes: u64) -> A1Result { + let ourios_ratio = ratio(raw_bytes, total_parquet_bytes); + let zstd_ratio = ratio(raw_bytes, zstd_bytes); + let delta_raw = if zstd_ratio > 0.0 { + ourios_ratio / zstd_ratio + } else { + 0.0 + }; + let delta = round_down_3_sigfigs(delta_raw); + A1Result { + ourios_ratio: round_down_3_sigfigs(ourios_ratio), + zstd_ratio: round_down_3_sigfigs(zstd_ratio), + delta, + target_delta: TARGET_DELTA, + pass: delta >= TARGET_DELTA, + } +} + +/// `numerator / denominator` as `f64`, `0.0` when the +/// denominator is zero (an empty output can't have a ratio). +#[allow(clippy::cast_precision_loss)] +fn ratio(numerator: u64, denominator: u64) -> f64 { + if denominator == 0 { + return 0.0; + } + (numerator as f64) / (denominator as f64) +} + +/// Round `value` *down* to three significant figures, so a +/// reported A1 number never overstates compression (§3.4.1). +fn round_down_3_sigfigs(value: f64) -> f64 { + if value <= 0.0 || !value.is_finite() { + return 0.0; + } + // Number of digits left of the decimal point. + let magnitude = value.abs().log10().floor(); + // Scale so three significant figures sit left of the + // decimal, floor, then scale back. + let scale = 10f64.powf(2.0 - magnitude); + (value * scale).floor() / scale +} + +#[cfg(test)] +mod tests { + // The formula tests compare against exact `f64` literals + // (`0.0`, `3.0`, `4.0`, `20.0`) that the arithmetic + // reproduces bit-exactly — `assert_eq!` is correct here, + // not a tolerance. + #![allow(clippy::float_cmp)] + use super::*; + + /// 3-sigfig floor: `12.49` → `12.4`, `3.456` → `3.45`, + /// `0.98765` → `0.987`. Always rounds toward zero so a + /// reported ratio never overstates compression. + #[test] + fn round_down_3_sigfigs_truncates_to_three_figures() { + assert!((round_down_3_sigfigs(12.49) - 12.4).abs() < 1e-9); + assert!((round_down_3_sigfigs(3.456) - 3.45).abs() < 1e-9); + assert!((round_down_3_sigfigs(0.987_65) - 0.987).abs() < 1e-9); + assert!((round_down_3_sigfigs(100.9) - 100.0).abs() < 1e-9); + assert_eq!(round_down_3_sigfigs(0.0), 0.0); + } + + /// The A1 formula: ratio of ratios, target 3×. + #[test] + fn compute_a1_formula_and_pass_threshold() { + // raw 1000, ourios total 50 → ratio 20; zstd 250 → + // ratio 4. delta = 20 / 4 = 5.0 ≥ 3 → pass. + let a1 = compute_a1(1000, 50, 250); + assert!((a1.ourios_ratio - 20.0).abs() < 1e-9); + assert!((a1.zstd_ratio - 4.0).abs() < 1e-9); + assert!((a1.delta - 5.0).abs() < 1e-9); + assert_eq!(a1.target_delta, 3.0); + assert!(a1.pass); + } + + /// delta just under 3× fails the gate. + #[test] + fn compute_a1_fails_below_target() { + // raw 1000, ourios total 100 → 10; zstd 250 → 4. + // delta = 10 / 4 = 2.5 < 3 → fail. + let a1 = compute_a1(1000, 100, 250); + assert!((a1.delta - 2.5).abs() < 1e-9); + assert!(!a1.pass); + } + + /// Zero-output guard: a denominator of zero yields a `0.0` + /// ratio rather than `inf` / `NaN`, and the gate fails. + #[test] + fn compute_a1_handles_zero_output() { + let a1 = compute_a1(1000, 0, 0); + assert_eq!(a1.ourios_ratio, 0.0); + assert_eq!(a1.zstd_ratio, 0.0); + assert_eq!(a1.delta, 0.0); + assert!(!a1.pass); + } +} diff --git a/crates/ourios-bench/src/harness.rs b/crates/ourios-bench/src/harness.rs index 1dc067fbc..5805bca44 100644 --- a/crates/ourios-bench/src/harness.rs +++ b/crates/ourios-bench/src/harness.rs @@ -27,6 +27,7 @@ use std::collections::HashMap; +use ourios_core::audit::{AuditEvent, SharedAuditSink}; use ourios_core::config::MinerConfig; use ourios_core::otlp::OtlpLogRecord; use ourios_core::record::{MinedRecord, SharedRecordSink}; @@ -37,6 +38,16 @@ use ourios_miner::tree::OwnedToken; use crate::BenchError; use crate::corpus::{BENCH_TENANT, CorpusLoad}; +/// What [`run`] returns after draining the miner: the +/// audit-event stream A1 writes into the `audit/...` partition +/// series for its `bytes(ourios_output)` term. The +/// per-version template snapshots stay local to [`run`] — they +/// feed the per-line callback but have no consumer past the +/// loop, so they aren't surfaced until a gate needs them. +pub(crate) struct HarnessResult { + pub audit_events: Vec, +} + /// Drive the miner over every line in `corpus`, snapshotting /// per-`(template_id, template_version)` template tokens /// once per unique pair, and invoking `on_record` per @@ -70,16 +81,18 @@ use crate::corpus::{BENCH_TENANT, CorpusLoad}; /// cluster's `templates_for()` doesn't return a leaf for /// (impossible by construction; surfaces a future miner /// bug rather than crashing C1's snapshot lookup). -pub(crate) fn run( - corpus: &CorpusLoad, - mut on_record: F, -) -> Result>, BenchError> +pub(crate) fn run(corpus: &CorpusLoad, mut on_record: F) -> Result where F: FnMut(&OtlpLogRecord, &MinedRecord, Option<&[OwnedToken]>), { let sink = SharedRecordSink::new(); + let audit_sink = SharedAuditSink::new(); + // `with_audit_sink` is the constructor that takes the + // audit sink; `with_record_sink` is the chainable setter + // for the record sink. let mut cluster = - MinerCluster::new(MinerConfig::default()).with_record_sink(Box::new(sink.clone())); + MinerCluster::with_audit_sink(MinerConfig::default(), Box::new(audit_sink.clone())) + .with_record_sink(Box::new(sink.clone())); let tenant = TenantId::new(BENCH_TENANT); let mut snapshots: HashMap<(u64, u32), Vec> = HashMap::new(); @@ -117,7 +130,9 @@ where on_record(input, &record, template_snapshot); } - Ok(snapshots) + Ok(HarnessResult { + audit_events: audit_sink.drain(), + }) } /// Take the single record the miner must emit for one @@ -238,28 +253,30 @@ mod tests { ); } - /// Returned snapshot map carries entries keyed by - /// `(template_id, template_version)` for every distinct - /// non-lossy record the harness saw — the C1 path doesn't - /// strictly need this (the streaming callback already had - /// the snapshot), but it's a useful diagnostic + lets - /// future gates inspect the alphabet without re-running. + /// A snapshot is captured at most once per unique + /// `(template_id, template_version)` — re-emitting the + /// same template (the steady-state common case) reuses the + /// stored tokens and the same `&[OwnedToken]` reaches the + /// callback. Two structurally-identical lines share one + /// template, so both callbacks must see byte-identical + /// snapshot slices. #[test] - fn snapshot_map_covers_every_non_lossy_id_version_observed() { - let (_tmp, load) = load_lines(&["user 42 logged in", "user 43 logged in"]); - let mut emitted_keys = std::collections::HashSet::new(); - let snapshots = run(&load, |_input, record, _snap| { - if !record.lossy_flag && record.template_id != NO_TEMPLATE { - emitted_keys.insert((record.template_id, record.template_version)); - } + fn repeated_template_reuses_one_snapshot() { + let (_tmp, load) = load_lines(&["user 42 logged in", "user 99 logged in"]); + let mut snapshots_seen: Vec>> = Vec::new(); + run(&load, |_input, _record, snap| { + snapshots_seen.push(snap.map(<[OwnedToken]>::to_vec)); }) .expect("harness runs"); - for key in emitted_keys { - assert!( - snapshots.contains_key(&key), - "snapshot map missing entry for emitted non-lossy key {key:?}", - ); - } + assert_eq!(snapshots_seen.len(), 2); + assert_eq!( + snapshots_seen[0], snapshots_seen[1], + "two structurally-identical lines share one template snapshot", + ); + assert!( + snapshots_seen[0].as_ref().is_some_and(|s| !s.is_empty()), + "non-lossy lines carry a non-empty template snapshot", + ); } /// `require_single` is the RFC 0001 §6.1 one-record-per- diff --git a/crates/ourios-bench/src/lib.rs b/crates/ourios-bench/src/lib.rs index d0af733d5..8371b8c43 100644 --- a/crates/ourios-bench/src/lib.rs +++ b/crates/ourios-bench/src/lib.rs @@ -26,6 +26,7 @@ use std::fmt; use std::path::PathBuf; +mod a1; mod c1; mod corpus; mod harness; @@ -89,24 +90,30 @@ impl GateSet { /// per `config.update_benchmarks_md` are the binary's /// responsibility (and not yet implemented). /// -/// **Implemented gates**: C1 (PR-I1). A1 and C2 still return -/// [`BenchError::NotImplemented`] — picking them via -/// `config.gates` fails the call. At least one gate must be -/// enabled; an empty `GateSet` returns [`BenchError::Cli`]. +/// **Implemented gates**: A1 (PR-I2) and C1 (PR-I1), in any +/// combination. C2 still returns [`BenchError::NotImplemented`] +/// when selected. At least one gate must be enabled; an empty +/// `GateSet` returns [`BenchError::Cli`]. +/// +/// Both implemented gates share a single miner pass: the +/// harness streams each emitted record to whichever +/// accumulators are active (A1 writes it to its partition's +/// Parquet file, C1 checks its reconstruction), so requesting +/// both does not double the ingest cost. /// /// # Errors /// -/// - [`BenchError::NotImplemented`] when `config.gates.a1` or -/// `config.gates.c2` is set (their implementations land in -/// follow-up PRs). +/// - [`BenchError::NotImplemented`] when `config.gates.c2` is +/// set (its implementation lands in a follow-up PR). /// - [`BenchError::Cli`] when no gates are enabled. /// - [`BenchError::Corpus`] when the corpus directory is /// unreadable, missing, or contributes no non-empty lines. /// - [`BenchError::Pipeline`] when the miner's emit count /// diverges from the input line count (RFC 0001 §6.1 -/// one-record-per-line violation), or when the host clock -/// is set before the Unix epoch (so `timestamp_now` can't -/// produce a §3.6-shaped timestamp). +/// one-record-per-line violation), when the Parquet writer +/// fails, or when the host clock is set before the Unix +/// epoch (so `timestamp_now` can't produce a §3.6-shaped +/// timestamp). /// /// # Panics /// @@ -118,30 +125,17 @@ impl GateSet { /// "surface a real logic bug" behaviour the §3.6 results /// shape needs. pub fn run(config: &BenchConfig) -> Result { - if config.gates.a1 { - return Err(BenchError::NotImplemented { - what: "A1 measurement (lands with the next bench implementation PR)", - }); - } if config.gates.c2 { return Err(BenchError::NotImplemented { what: "C2 measurement (lands with the next bench implementation PR)", }); } - if !config.gates.c1 { + if !config.gates.a1 && !config.gates.c1 { return Err(BenchError::Cli { detail: "no gates enabled; --gates must include at least one of a1, c1, c2".to_string(), }); } - // C1 path. Doesn't write Parquet (A1 isn't enabled), so - // the `ourios.*` byte counts come out zero in this run's - // results JSON. That's the §3.6 nullability rule applied - // to the *gate* fields (`a1: None`), with the per-section - // byte counters left as zero rather than wrapped in - // `Option` — the schema pins them as required `u64` so - // an A1-skipped run still serialises against the same - // shape. let corpus_load = corpus::load(&config.corpus_dir)?; let directory = corpus_load.directory.clone(); let total_files = corpus_load.total_files; @@ -153,11 +147,59 @@ pub fn run(config: &BenchConfig) -> Result { // than surfacing it; `expect` names the assumption. let total_lines = u64::try_from(corpus_load.lines.len()) .expect("usize fits in u64 on every supported Rust target"); - let mut c1_acc = c1::C1Accumulator::new(); - harness::run(&corpus_load, |input, emitted, snap| { - c1_acc.record(input, emitted, snap); + + // Resolve the Parquet output bucket A1 writes into. A + // caller-supplied `bucket_dir` is used as-is; otherwise a + // scratch dir is created and (unless `--keep-parquet`) + // removed when `_bucket_guard` drops at end of scope. + // Held even when A1 is disabled so the branch stays simple + // — an unused empty temp dir costs one inode. + let (bucket_root, _bucket_guard) = resolve_bucket(config)?; + + let mut c1_acc = config.gates.c1.then(c1::C1Accumulator::new); + let mut a1_acc = config + .gates + .a1 + .then(|| a1::A1Accumulator::new(&bucket_root)); + + let harness_result = harness::run(&corpus_load, |input, emitted, snap| { + if let Some(acc) = c1_acc.as_mut() { + acc.record(input, emitted, snap); + } + if let Some(acc) = a1_acc.as_mut() { + acc.record(emitted); + } })?; - let c1_result = c1_acc.finalize(); + + let c1_result = c1_acc.map(|acc| acc.finalize()); + let (a1_result, ourios, zstd) = match a1_acc { + Some(mut acc) => { + acc.write_audit(&harness_result.audit_events)?; + let a1 = acc.finalize(raw_bytes, &config.corpus_dir)?; + let ourios = OuriosStats { + data_parquet_bytes: a1.data_parquet_bytes, + audit_parquet_bytes: a1.audit_parquet_bytes, + total_parquet_bytes: a1.total_parquet_bytes, + }; + let zstd = ZstdStats { + level: 19, + compressed_bytes: a1.zstd_bytes, + }; + (Some(a1.result), ourios, zstd) + } + None => ( + None, + OuriosStats { + data_parquet_bytes: 0, + audit_parquet_bytes: 0, + total_parquet_bytes: 0, + }, + ZstdStats { + level: 19, + compressed_bytes: 0, + }, + ), + }; Ok(ResultsFile { rfc: "RFC 0006".to_string(), @@ -174,21 +216,38 @@ pub fn run(config: &BenchConfig) -> Result { total_files, raw_bytes, }, - ourios: OuriosStats { - data_parquet_bytes: 0, - audit_parquet_bytes: 0, - total_parquet_bytes: 0, - }, - zstd: ZstdStats { - level: 19, - compressed_bytes: 0, - }, - a1: None, - c1: Some(c1_result), + ourios, + zstd, + a1: a1_result, + c1: c1_result, c2: None, }) } +/// Resolve the Parquet output bucket. Returns the directory +/// plus an optional [`tempfile::TempDir`] guard whose `Drop` +/// removes a scratch bucket at end of `run`. When the caller +/// passed an explicit `bucket_dir`, the guard is `None` (the +/// caller owns the directory's lifetime). `--keep-parquet` +/// persists a scratch dir by leaking the guard via +/// `TempDir::keep`. +fn resolve_bucket( + config: &BenchConfig, +) -> Result<(PathBuf, Option), BenchError> { + if let Some(dir) = &config.bucket_dir { + return Ok((dir.clone(), None)); + } + let tmp = tempfile::TempDir::new().map_err(|e| BenchError::Pipeline { + detail: format!("create scratch bucket dir: {e}"), + })?; + if config.keep_parquet { + let path = tmp.keep(); + return Ok((path, None)); + } + let path = tmp.path().to_path_buf(); + Ok((path, Some(tmp))) +} + /// Format `SystemTime::now()` as a §3.6 millisecond-precision /// RFC3339 string (`YYYY-MM-DDTHH:MM:SS.mmmZ`). Computed /// inline (no `chrono` dep) because the bench only needs @@ -458,44 +517,36 @@ mod tests { ); } - /// PR-I1 marker — A1 and C2 still return + /// PR-I2 marker — C2 still returns /// `BenchError::NotImplemented` from `run()`, even though - /// C1 now produces a real `ResultsFile`. This test pins - /// the partial-implementation gate: a future PR that - /// lands A1 (or C2) makes this assertion fail by - /// returning `Ok(...)`, which is the maturity-model - /// marker that the corresponding gate has graduated. The + /// A1 (PR-I2) and C1 (PR-I1) now produce real results. + /// This test pins the partial-implementation gate: the PR + /// that lands C2 makes this assertion fail by returning + /// something other than `NotImplemented`, which is the + /// maturity-model marker that C2 has graduated. The C2 /// implementation PR rewrites this test alongside its - /// code change. + /// code change. C2 is checked before any corpus work, so + /// the bogus `corpus_dir` is never read. #[test] - fn a1_and_c2_still_return_not_implemented() { - for gates in [ - GateSet { - a1: true, - c1: false, - c2: false, - }, - GateSet { + fn c2_still_returns_not_implemented() { + let config = BenchConfig { + corpus_dir: std::path::PathBuf::from("."), + results_dir: std::path::PathBuf::from("."), + bucket_dir: None, + keep_parquet: false, + hardware_kind: None, + update_benchmarks_md: false, + gates: GateSet { a1: false, c1: false, c2: true, }, - ] { - let config = BenchConfig { - corpus_dir: std::path::PathBuf::from("."), - results_dir: std::path::PathBuf::from("."), - bucket_dir: None, - keep_parquet: false, - hardware_kind: None, - update_benchmarks_md: false, - gates, - }; - let err = run(&config).expect_err("A1 / C2 not yet implemented"); - assert!( - matches!(err, BenchError::NotImplemented { .. }), - "expected NotImplemented, got {err:?}", - ); - } + }; + let err = run(&config).expect_err("C2 not yet implemented"); + assert!( + matches!(err, BenchError::NotImplemented { .. }), + "expected NotImplemented, got {err:?}", + ); } /// `ResultsFile` is the §3.6 contract incarnated; its serde diff --git a/crates/ourios-bench/tests/a1.rs b/crates/ourios-bench/tests/a1.rs index e17af0176..03bf4d833 100644 --- a/crates/ourios-bench/tests/a1.rs +++ b/crates/ourios-bench/tests/a1.rs @@ -9,16 +9,18 @@ //! - `bytes(ourios_output)` from the bench's bucket dir //! (`data/...` plus `audit/...`, post-rename `*.parquet` //! files only). -//! - `bytes(zstd_corpus)` from the `zstd_safe` Rust crate at -//! level 19 (per the §7 ZSTD-integration resolution; not a -//! shell-out to the system `zstd` binary). +//! - `bytes(zstd_corpus)` from the `zstd` crate at level 19 +//! (per the §7 ZSTD-integration resolution; not a shell-out +//! to the system `zstd` binary). //! - The reported `delta = ourios_ratio / zstd_ratio` rounded //! down to three significant figures. //! -//! Stubs are tagged `#[ignore]` so the default `cargo test` -//! is unaffected while the RFC is at the `red` maturity stage. -//! The implementation PR that lands the A1 measurement deletes -//! the `#[ignore]` attribute alongside its code change. +//! Un-`#[ignore]`'d in PR-I2 when the A1 measurement landed. +//! The test independently recomputes each byte count from the +//! artifacts on disk (corpus `*.txt`, bucket `*.parquet`, +//! per-file ZSTD-19) and asserts the bench's reported values +//! match — a buggy `run()` whose internal counters drift from +//! disk fails here. use ourios_bench::{BenchConfig, BenchError, GateSet, run}; use std::path::PathBuf; @@ -33,7 +35,6 @@ use std::path::PathBuf; /// §3.4.1 pin; the impl stores it as the exact `f64` /// representation of `3.0`, which is bit-exact. #[test] -#[ignore = "RFC 0006 Red gate — implementation pending"] #[allow(clippy::cast_precision_loss, clippy::float_cmp)] fn rfc0006_1_a1_formula_well_defined_on_seed_corpus() { let bucket = tempfile::TempDir::new().expect("temp dir"); @@ -85,7 +86,7 @@ fn rfc0006_1_a1_formula_well_defined_on_seed_corpus() { ); assert_eq!( results_file.zstd.compressed_bytes, actual_zstd_bytes, - "zstd.compressed_bytes must match `zstd_safe` level-19 output on the same corpus", + "zstd.compressed_bytes must match `zstd` level-19 output on the same corpus", ); assert_eq!(results_file.zstd.level, 19, "§3.4.1 pins ZSTD-19"); @@ -179,17 +180,30 @@ fn sum_parquet_bytes(bucket: &std::path::Path) -> u64 { } /// Compute `bytes(zstd_corpus)` independently by encoding each -/// `*.txt` file with `zstd_safe` at level 19 (per the §7 -/// ZSTD-integration resolution) and summing the resulting -/// byte counts. The implementation under test should produce -/// the identical value. -fn zstd_level_19_bytes(_dir: &std::path::Path) -> u64 { - // The fixture helper lands with the A1 implementation PR - // — it shares the same `zstd_safe` invocation the impl - // uses, so this is mechanical to write once the impl - // exists. Stubbed here so the test compiles and shows - // the intended dependency. - unimplemented!("RFC 0006 Red gate — zstd_safe fixture lands with the A1 implementation PR") +/// `*.txt` file (recursive) with `zstd` at level 19 and +/// summing the compressed lengths. Per-file, not concatenated, +/// per §3.4.1 — the bench under test must produce the +/// identical value. +fn zstd_level_19_bytes(dir: &std::path::Path) -> u64 { + fn walk(dir: &std::path::Path, total: &mut u64) { + for entry in std::fs::read_dir(dir).expect("corpus dir readable") { + let entry = entry.expect("dir entry"); + let path = entry.path(); + if path.is_dir() { + walk(&path, total); + } else if path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("txt")) + { + let bytes = std::fs::read(&path).expect("read txt"); + let compressed = zstd::bulk::compress(&bytes, 19).expect("zstd compress"); + *total += compressed.len() as u64; + } + } + } + let mut total = 0u64; + walk(dir, &mut total); + total } /// Sanity guard against `BenchError::NotImplemented` slipping @@ -199,7 +213,6 @@ fn zstd_level_19_bytes(_dir: &std::path::Path) -> u64 { /// can't make this guard fail for the wrong reason — once A1 /// lands, this guard turns green even before C1/C2 do. #[test] -#[ignore = "RFC 0006 Red gate — implementation pending"] fn rfc0006_1_run_no_longer_returns_not_implemented() { let bucket = tempfile::TempDir::new().expect("temp dir"); let results = tempfile::TempDir::new().expect("temp dir"); diff --git a/crates/ourios-parquet/src/partition.rs b/crates/ourios-parquet/src/partition.rs index 2fef67f84..7f9a40a6c 100644 --- a/crates/ourios-parquet/src/partition.rs +++ b/crates/ourios-parquet/src/partition.rs @@ -22,7 +22,7 @@ use chrono::{DateTime, Datelike, Timelike, Utc}; use ourios_core::record::MinedRecord; /// Partition key for the on-disk Hive-style layout. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PartitionKey { /// Raw (un-encoded) tenant id, as carried on the row. pub tenant_id: String, From bbf50bd7a4f434bf0cd3cc049ee37978662c2395 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 26 May 2026 01:06:43 +0200 Subject: [PATCH 2/6] fixup! feat(bench): land A1 compression-ratio measurement (PR-I2) Co-Authored-By: Claude Opus 4.7 (1M context) --- crates/ourios-bench/Cargo.toml | 16 ++---- crates/ourios-bench/src/a1.rs | 81 +++++++++++++++++++++------- crates/ourios-bench/src/harness.rs | 29 +++++----- crates/ourios-bench/src/lib.rs | 86 +++++++++++++++++++++++++----- crates/ourios-bench/tests/a1.rs | 50 ++++++++++++++++- 5 files changed, 205 insertions(+), 57 deletions(-) diff --git a/crates/ourios-bench/Cargo.toml b/crates/ourios-bench/Cargo.toml index 297119332..36a97d8ea 100644 --- a/crates/ourios-bench/Cargo.toml +++ b/crates/ourios-bench/Cargo.toml @@ -36,18 +36,12 @@ serde_json = { version = "1", default-features = false, features = ["std"] } zstd = "0.13" # A1 writes the Parquet output bucket somewhere measurable; when # `BenchConfig.bucket_dir` is `None`, `run` creates a scratch dir -# here and (unless `--keep-parquet`) cleans it up on exit. +# here and (unless `--keep-parquet`) cleans it up on exit. The +# integration tests reuse both `tempfile` (scratch corpora / +# buckets) and `zstd` (the RFC0006.1 test recomputes the +# reference byte count) — normal dependencies are visible to +# `tests/`, so no separate `[dev-dependencies]` mirror is needed. tempfile = "3" -[dev-dependencies] -# Integration tests reuse `tempfile` for scratch corpora / -# buckets; the RFC0006.1 test also recomputes the ZSTD-19 -# reference byte count, so it needs `zstd` on the test side. -tempfile = "3" -# The RFC0006.1 integration test independently recomputes the -# ZSTD-19 reference byte count to check the bench's reported -# value, so it needs `zstd` on the test side too. -zstd = "0.13" - [lints] workspace = true diff --git a/crates/ourios-bench/src/a1.rs b/crates/ourios-bench/src/a1.rs index e7f0cc39c..5f64c45d4 100644 --- a/crates/ourios-bench/src/a1.rs +++ b/crates/ourios-bench/src/a1.rs @@ -206,7 +206,16 @@ fn audit_partition(event: &AuditEvent) -> Result MinedRecord { } /// Sum `*.parquet` file sizes under `dir` (recursive), skipping -/// pre-rename `*.parquet.tmp` files per RFC 0005 §7. Returns -/// `Ok(0)` when `dir` doesn't exist (a gate that produced no -/// output for that subtree — e.g. zero audit events). +/// pre-rename `*.parquet.tmp` files per RFC 0005 §7. A missing +/// directory yields `Ok(0)` (a gate that produced no output +/// for that subtree — e.g. zero audit events); any *other* I/O +/// error surfaces as [`crate::BenchError::Pipeline`] rather +/// than silently undercounting. Errors here are categorised +/// `Pipeline` (reading writer artifacts is part of the +/// measurement, not JSON/markdown reporting). fn sum_parquet_bytes(dir: &Path) -> Result { - if !dir.exists() { - return Ok(0); - } + // `fs::read_dir` (below) returns `NotFound` for a missing + // directory; we map only that to `Ok(0)` and propagate + // every other error (e.g. permission denied), unlike + // `Path::exists()` which collapses all I/O errors to + // "false" and would undercount. let mut total = 0u64; let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { - let entries = std::fs::read_dir(&d).map_err(|e| crate::BenchError::Report { - detail: format!("read_dir({}): {e}", d.display()), - })?; + let entries = match std::fs::read_dir(&d) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => { + return Err(crate::BenchError::Pipeline { + detail: format!("read_dir({}): {e}", d.display()), + }); + } + }; for entry in entries { - let entry = entry.map_err(|e| crate::BenchError::Report { + let entry = entry.map_err(|e| crate::BenchError::Pipeline { detail: format!("read_dir entry under {}: {e}", d.display()), })?; let path = entry.path(); - let meta = std::fs::metadata(&path).map_err(|e| crate::BenchError::Report { + let meta = std::fs::metadata(&path).map_err(|e| crate::BenchError::Pipeline { detail: format!("metadata({}): {e}", path.display()), })?; if meta.is_dir() { @@ -287,9 +308,32 @@ fn sum_parquet_bytes(dir: &Path) -> Result { Ok(total) } +/// A sink that discards what it's written and only tallies the +/// byte count — lets the ZSTD encoder stream its output past +/// us without us holding the compressed buffer. +struct CountingSink(u64); + +impl std::io::Write for CountingSink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + // `usize → u64` is lossless on every supported target; + // saturating keeps the counter monotone even on the + // hypothetical 128-bit one. + self.0 = self.0.saturating_add(buf.len() as u64); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + /// Compute `bytes(zstd_corpus)` — run ZSTD-19 over each `*.txt` /// file under `dir` individually and sum the compressed -/// lengths. Per-file (not concatenated) per §3.4.1. +/// lengths. Per-file (not concatenated) per §3.4.1. The input +/// is streamed from the file and the compressed output is +/// streamed into a [`CountingSink`], so neither the raw file +/// nor its compressed image is held in memory in full — +/// bounded regardless of corpus file size. +#[allow(clippy::cast_possible_truncation)] fn zstd_level_19_bytes(dir: &Path) -> Result { let mut total = 0u64; let mut stack = vec![dir.to_path_buf()]; @@ -311,15 +355,16 @@ fn zstd_level_19_bytes(dir: &Path) -> Result { .extension() .is_some_and(|e| e.eq_ignore_ascii_case("txt")) { - let bytes = std::fs::read(&path).map_err(|e| crate::BenchError::Corpus { - detail: format!("read({}): {e}", path.display()), + let file = std::fs::File::open(&path).map_err(|e| crate::BenchError::Corpus { + detail: format!("open({}): {e}", path.display()), })?; - let compressed = zstd::bulk::compress(&bytes, ZSTD_LEVEL).map_err(|e| { - crate::BenchError::Report { + let mut sink = CountingSink(0); + zstd::stream::copy_encode(file, &mut sink, ZSTD_LEVEL).map_err(|e| { + crate::BenchError::Pipeline { detail: format!("zstd compress({}): {e}", path.display()), } })?; - total += compressed.len() as u64; + total += sink.0; } } } diff --git a/crates/ourios-bench/src/harness.rs b/crates/ourios-bench/src/harness.rs index 5805bca44..15c6fcea4 100644 --- a/crates/ourios-bench/src/harness.rs +++ b/crates/ourios-bench/src/harness.rs @@ -3,12 +3,11 @@ //! Drives a fresh `MinerCluster` over every line in a loaded //! corpus and yields one `(input, emitted, template)` triple //! per ingested line to a caller-supplied callback. The -//! callback shape lets each gate (C1 today, A1 / C2 in -//! follow-ups) compute its result *while* the loop runs, -//! without the harness buffering every emitted `MinedRecord` -//! in memory — a `Vec` for an RFC-sized 1 M-line -//! corpus is a real OOM risk given each record's `Vec` / -//! `String` payload. +//! callback shape lets each gate compute its result *while* +//! the loop runs, without the harness buffering every emitted +//! `MinedRecord` in memory — a `Vec` for an +//! RFC-sized 1 M-line corpus is a real OOM risk given each +//! record's `Vec` / `String` payload. //! //! Mirrors the H7.1 property test pattern in //! `crates/ourios-miner/tests/hazards.rs` for the snapshot @@ -17,13 +16,19 @@ //! `HashMap::entry(...).Vacant.insert`); the streaming //! surface is the bench-specific shape. //! -//! Future implementation PRs plug additional gate -//! accumulators into the same callback signature: +//! Current consumers (`lib::run` plugs in whichever are +//! enabled): //! -//! - A1: a writer-accumulator that streams `MinedRecord`s -//! into `ourios_parquet::Writer` and sums the bucket bytes. -//! - C2: a counter-accumulator that samples the template -//! count at the §3.4.3 cadence. +//! - C1 (PR-I1): checks each emitted record's reconstruction +//! against the input bytes. +//! - A1 (PR-I2): streams each `MinedRecord` into its +//! partition's `ourios_parquet::Writer` and, after the loop, +//! writes the drained audit events (returned in +//! [`HarnessResult`]) so it can sum the full bucket bytes. +//! +//! C2 (template-count convergence) is the remaining future +//! consumer — a counter-accumulator that samples the template +//! count at the §3.4.3 cadence. use std::collections::HashMap; diff --git a/crates/ourios-bench/src/lib.rs b/crates/ourios-bench/src/lib.rs index 8371b8c43..fc5b86cae 100644 --- a/crates/ourios-bench/src/lib.rs +++ b/crates/ourios-bench/src/lib.rs @@ -2,24 +2,24 @@ //! (A1 compression, C1 reconstruction, C2 template-count //! convergence). //! -//! **Implementation status (PR-I1):** the C1 gate is live — -//! [`run`] computes C1 end-to-end on the corpus directory -//! when `config.gates.c1` is set and returns a populated -//! [`ResultsFile`]. A1 and C2 still return +//! **Implementation status (PR-I2):** the A1 (compression) and +//! C1 (reconstruction) gates are live — [`run`] computes them +//! end-to-end, in any combination, in a single miner pass, and +//! returns a populated [`ResultsFile`]. C2 still returns //! [`BenchError::NotImplemented`] when selected via -//! `config.gates`; their `#[ignore]`'d test stubs in -//! `tests/{a1,c2,reproducibility}.rs` get un-ignored as the -//! respective implementations land. The CLI parser (RFC 0006 -//! §3.7) and the `docs/benchmarks.md` §9 result-file writer -//! ([`ResultsFile`] → disk / markdown) also remain -//! unwritten — `main.rs` is the red-stage scaffold and the -//! binary path doesn't yet drive [`run`]. +//! `config.gates`; its `#[ignore]`'d test stubs in +//! `tests/{c2,reproducibility}.rs` get un-ignored when it +//! lands. The CLI parser (RFC 0006 §3.7) and the +//! `docs/benchmarks.md` §9 result-file writer ([`ResultsFile`] +//! → disk / markdown) also remain unwritten — `main.rs` is the +//! red-stage scaffold and the binary path doesn't yet drive +//! [`run`]. //! //! Per RFC 0006 §3.2 the eventual module layout is `corpus`, //! `harness`, `a1`, `c1`, `c2`, `report`. Those modules land -//! incrementally. PR-I1 extracted `corpus`, `harness`, and -//! `c1`; `a1` / `c2` / `report` remain collapsed (and -//! unwritten) until their respective implementation PRs. +//! incrementally. PR-I1 extracted `corpus`, `harness`, `c1`; +//! PR-I2 added `a1`; `c2` / `report` remain unwritten until +//! their respective implementation PRs. #![deny(unsafe_code)] @@ -156,6 +156,17 @@ pub fn run(config: &BenchConfig) -> Result { // — an unused empty temp dir costs one inode. let (bucket_root, _bucket_guard) = resolve_bucket(config)?; + // A1 measures every `*.parquet` under the bucket; a + // caller-supplied dir that already holds Parquet (e.g. a + // prior `--keep-parquet` run) would inflate + // `bytes(ourios_output)` and skew the ratio. Refuse to + // measure into a dirty bucket. A scratch `TempDir` is + // always empty, so this only ever fires on a reused + // caller dir. + if config.gates.a1 { + ensure_bucket_has_no_parquet(&bucket_root)?; + } + let mut c1_acc = config.gates.c1.then(c1::C1Accumulator::new); let mut a1_acc = config .gates @@ -248,6 +259,53 @@ fn resolve_bucket( Ok((path, Some(tmp))) } +/// Error if the bucket's `data/` or `audit/` subtree already +/// holds a `*.parquet` file. A1 sums every Parquet file under +/// the bucket, so pre-existing artifacts (from a prior +/// `--keep-parquet` run into the same directory) would inflate +/// `bytes(ourios_output)`. Missing subtrees are fine (nothing +/// to collide with). +fn ensure_bucket_has_no_parquet(bucket_root: &std::path::Path) -> Result<(), BenchError> { + for sub in ["data", "audit"] { + let dir = bucket_root.join(sub); + let mut stack = vec![dir]; + while let Some(d) = stack.pop() { + let entries = match std::fs::read_dir(&d) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => { + return Err(BenchError::Pipeline { + detail: format!("scan bucket {}: {e}", d.display()), + }); + } + }; + for entry in entries { + let entry = entry.map_err(|e| BenchError::Pipeline { + detail: format!("scan bucket entry under {}: {e}", d.display()), + })?; + let path = entry.path(); + if path.is_dir() { + stack.push(path); + } else if path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("parquet")) + { + return Err(BenchError::Cli { + detail: format!( + "bucket {} already contains a Parquet file ({}); A1 would \ + count it in bytes(ourios_output). Point --bucket-dir at an \ + empty directory or omit it to use a fresh scratch dir.", + bucket_root.display(), + path.display(), + ), + }); + } + } + } + } + Ok(()) +} + /// Format `SystemTime::now()` as a §3.6 millisecond-precision /// RFC3339 string (`YYYY-MM-DDTHH:MM:SS.mmmZ`). Computed /// inline (no `chrono` dep) because the bench only needs diff --git a/crates/ourios-bench/tests/a1.rs b/crates/ourios-bench/tests/a1.rs index 03bf4d833..08aa00651 100644 --- a/crates/ourios-bench/tests/a1.rs +++ b/crates/ourios-bench/tests/a1.rs @@ -184,6 +184,13 @@ fn sum_parquet_bytes(bucket: &std::path::Path) -> u64 { /// summing the compressed lengths. Per-file, not concatenated, /// per §3.4.1 — the bench under test must produce the /// identical value. +/// +/// Uses the streaming encoder (`zstd::stream::copy_encode`) to +/// match the production path exactly: one-shot +/// `zstd::bulk::compress` can emit a different frame header +/// (it knows the content size up front, streaming doesn't), so +/// the byte counts would diverge by a few header bytes if the +/// two sides used different APIs. fn zstd_level_19_bytes(dir: &std::path::Path) -> u64 { fn walk(dir: &std::path::Path, total: &mut u64) { for entry in std::fs::read_dir(dir).expect("corpus dir readable") { @@ -195,8 +202,9 @@ fn zstd_level_19_bytes(dir: &std::path::Path) -> u64 { .extension() .is_some_and(|e| e.eq_ignore_ascii_case("txt")) { - let bytes = std::fs::read(&path).expect("read txt"); - let compressed = zstd::bulk::compress(&bytes, 19).expect("zstd compress"); + let file = std::fs::File::open(&path).expect("open txt"); + let mut compressed = Vec::new(); + zstd::stream::copy_encode(file, &mut compressed, 19).expect("zstd compress"); *total += compressed.len() as u64; } } @@ -241,3 +249,41 @@ fn rfc0006_1_run_no_longer_returns_not_implemented() { Err(other) => panic!("unexpected error from implemented run(): {other}"), } } + +/// A1 refuses to measure into a `--bucket-dir` that already +/// holds a Parquet file — a prior `--keep-parquet` run's +/// artifacts would otherwise inflate `bytes(ourios_output)` +/// and skew the ratio. The guard fires before the miner runs, +/// so a pre-seeded `data/.../x.parquet` is enough to trip it. +#[test] +fn a1_rejects_a_bucket_that_already_holds_parquet() { + let bucket = tempfile::TempDir::new().expect("temp dir"); + let results = tempfile::TempDir::new().expect("temp dir"); + // Pre-seed a stray Parquet file under the data subtree. + let stale = bucket.path().join("data").join("tenant_id=x"); + std::fs::create_dir_all(&stale).expect("mkdir"); + std::fs::write(stale.join("stale.parquet"), b"not really parquet").expect("seed"); + + let config = BenchConfig { + corpus_dir: PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("workspace root") + .join("testdata/corpus"), + results_dir: results.path().to_path_buf(), + bucket_dir: Some(bucket.path().to_path_buf()), + keep_parquet: false, + hardware_kind: Some("dev-laptop".to_string()), + update_benchmarks_md: false, + gates: GateSet { + a1: true, + c1: false, + c2: false, + }, + }; + let err = run(&config).expect_err("dirty bucket must be rejected"); + assert!( + matches!(&err, BenchError::Cli { detail } if detail.contains("already contains a Parquet file")), + "expected a Cli error about a non-empty bucket, got {err:?}", + ); +} From 398f68e1726f165232400344785d9b8e5e4baaf1 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 26 May 2026 01:23:43 +0200 Subject: [PATCH 3/6] fixup! feat(bench): land A1 compression-ratio measurement (PR-I2) Co-Authored-By: Claude Opus 4.7 (1M context) --- crates/ourios-bench/src/a1.rs | 22 ++++++++++++++-------- crates/ourios-bench/src/lib.rs | 13 +++++++++++-- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/crates/ourios-bench/src/a1.rs b/crates/ourios-bench/src/a1.rs index 5f64c45d4..c59713545 100644 --- a/crates/ourios-bench/src/a1.rs +++ b/crates/ourios-bench/src/a1.rs @@ -125,17 +125,16 @@ impl A1Accumulator { /// proxy record carrying the event's tenant + timestamp, /// the established `ourios-parquet` pattern). Called once /// after the harness loop, before [`Self::finalize`]. - pub(crate) fn write_audit(&mut self, events: &[AuditEvent]) -> Result<(), crate::BenchError> { + pub(crate) fn write_audit(&mut self, events: Vec) -> Result<(), crate::BenchError> { if let Some(e) = self.error.take() { return Err(e); } let mut by_partition: HashMap> = HashMap::new(); for event in events { - let partition = audit_partition(event)?; - by_partition - .entry(partition) - .or_default() - .push(event.clone()); + // Borrow for the partition derive, then move the + // event into the per-partition vec — no clone. + let partition = audit_partition(&event)?; + by_partition.entry(partition).or_default().push(event); } for (partition, events) in by_partition { let mut writer = AuditWriter::open(&self.bucket_root, partition).map_err(|e| { @@ -221,9 +220,16 @@ fn audit_partition(event: &AuditEvent) -> Result Result { let c1_result = c1_acc.map(|acc| acc.finalize()); let (a1_result, ourios, zstd) = match a1_acc { Some(mut acc) => { - acc.write_audit(&harness_result.audit_events)?; + acc.write_audit(harness_result.audit_events)?; let a1 = acc.finalize(raw_bytes, &config.corpus_dir)?; let ourios = OuriosStats { data_parquet_bytes: a1.data_parquet_bytes, @@ -284,7 +284,16 @@ fn ensure_bucket_has_no_parquet(bucket_root: &std::path::Path) -> Result<(), Ben detail: format!("scan bucket entry under {}: {e}", d.display()), })?; let path = entry.path(); - if path.is_dir() { + // `fs::metadata` (fallible) rather than + // `Path::is_dir` (false on metadata errors), + // so an unreadable entry fails the scan + // instead of being silently treated as a + // non-directory and skipped — which could miss + // nested `*.parquet`. + let meta = std::fs::metadata(&path).map_err(|e| BenchError::Pipeline { + detail: format!("scan bucket metadata({}): {e}", path.display()), + })?; + if meta.is_dir() { stack.push(path); } else if path .extension() From 68b1c91299d19acdc184529dfb209aa0a68869ff Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 26 May 2026 08:35:08 +0200 Subject: [PATCH 4/6] fixup! feat(bench): land A1 compression-ratio measurement (PR-I2) Co-Authored-By: Claude Opus 4.7 (1M context) --- crates/ourios-bench/src/a1.rs | 16 +++++++++--- crates/ourios-bench/src/lib.rs | 46 +++++++++++++++++++++++---------- crates/ourios-bench/tests/a1.rs | 31 ++++++++++++++++++++++ 3 files changed, 76 insertions(+), 17 deletions(-) diff --git a/crates/ourios-bench/src/a1.rs b/crates/ourios-bench/src/a1.rs index c59713545..e096f5e93 100644 --- a/crates/ourios-bench/src/a1.rs +++ b/crates/ourios-bench/src/a1.rs @@ -295,9 +295,19 @@ fn sum_parquet_bytes(dir: &Path) -> Result { detail: format!("read_dir entry under {}: {e}", d.display()), })?; let path = entry.path(); - let meta = std::fs::metadata(&path).map_err(|e| crate::BenchError::Pipeline { - detail: format!("metadata({}): {e}", path.display()), - })?; + // `symlink_metadata` (does NOT follow symlinks): + // the bench writes real directories, so a symlink + // in its own output bucket is unexpected. Skip it + // rather than follow it — a symlinked subdir + // pointing at an ancestor would otherwise loop the + // scan forever and hang A1's finalize. + let meta = + std::fs::symlink_metadata(&path).map_err(|e| crate::BenchError::Pipeline { + detail: format!("metadata({}): {e}", path.display()), + })?; + if meta.file_type().is_symlink() { + continue; + } if meta.is_dir() { stack.push(path); } else if path diff --git a/crates/ourios-bench/src/lib.rs b/crates/ourios-bench/src/lib.rs index 1a4539722..113f3b0f5 100644 --- a/crates/ourios-bench/src/lib.rs +++ b/crates/ourios-bench/src/lib.rs @@ -239,22 +239,32 @@ pub fn run(config: &BenchConfig) -> Result { /// plus an optional [`tempfile::TempDir`] guard whose `Drop` /// removes a scratch bucket at end of `run`. When the caller /// passed an explicit `bucket_dir`, the guard is `None` (the -/// caller owns the directory's lifetime). `--keep-parquet` -/// persists a scratch dir by leaking the guard via -/// `TempDir::keep`. +/// caller owns the directory's lifetime); the scratch case +/// returns `Some` so the dir is cleaned up on exit. +/// +/// `keep_parquet` requires an explicit `bucket_dir`: a scratch +/// dir the caller can't locate (paths are deliberately kept +/// out of [`ResultsFile`] per §3.6) would be useless to keep +/// and would just litter the temp filesystem. Requesting +/// `keep_parquet` without `bucket_dir` returns +/// [`BenchError::Cli`]. fn resolve_bucket( config: &BenchConfig, ) -> Result<(PathBuf, Option), BenchError> { if let Some(dir) = &config.bucket_dir { return Ok((dir.clone(), None)); } + if config.keep_parquet { + return Err(BenchError::Cli { + detail: "--keep-parquet requires --bucket-dir: a scratch bucket's path isn't \ + reported (paths are kept out of the results JSON), so keeping it would \ + leave an unfindable directory behind." + .to_string(), + }); + } let tmp = tempfile::TempDir::new().map_err(|e| BenchError::Pipeline { detail: format!("create scratch bucket dir: {e}"), })?; - if config.keep_parquet { - let path = tmp.keep(); - return Ok((path, None)); - } let path = tmp.path().to_path_buf(); Ok((path, Some(tmp))) } @@ -284,15 +294,23 @@ fn ensure_bucket_has_no_parquet(bucket_root: &std::path::Path) -> Result<(), Ben detail: format!("scan bucket entry under {}: {e}", d.display()), })?; let path = entry.path(); - // `fs::metadata` (fallible) rather than - // `Path::is_dir` (false on metadata errors), - // so an unreadable entry fails the scan - // instead of being silently treated as a - // non-directory and skipped — which could miss - // nested `*.parquet`. - let meta = std::fs::metadata(&path).map_err(|e| BenchError::Pipeline { + // `symlink_metadata` (fallible, does NOT + // follow symlinks) rather than `Path::is_dir` + // (false on metadata errors). A symlinked + // entry is skipped, not descended into: the + // bench writes real directories, so a symlink + // in the output bucket is unexpected, and + // following one risks an unbounded scan loop + // (a symlinked subdir pointing at an + // ancestor). Skipping is safe — there are no + // legitimate symlinked Parquet artifacts to + // miss. + let meta = std::fs::symlink_metadata(&path).map_err(|e| BenchError::Pipeline { detail: format!("scan bucket metadata({}): {e}", path.display()), })?; + if meta.file_type().is_symlink() { + continue; + } if meta.is_dir() { stack.push(path); } else if path diff --git a/crates/ourios-bench/tests/a1.rs b/crates/ourios-bench/tests/a1.rs index 08aa00651..4e5789713 100644 --- a/crates/ourios-bench/tests/a1.rs +++ b/crates/ourios-bench/tests/a1.rs @@ -287,3 +287,34 @@ fn a1_rejects_a_bucket_that_already_holds_parquet() { "expected a Cli error about a non-empty bucket, got {err:?}", ); } + +/// `--keep-parquet` without `--bucket-dir` is rejected: a +/// scratch bucket's path isn't reported, so keeping it would +/// leave an unfindable directory behind. The guard fires in +/// bucket resolution, before any corpus work. +#[test] +fn keep_parquet_without_bucket_dir_is_rejected() { + let results = tempfile::TempDir::new().expect("temp dir"); + let config = BenchConfig { + corpus_dir: PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(std::path::Path::parent) + .expect("workspace root") + .join("testdata/corpus"), + results_dir: results.path().to_path_buf(), + bucket_dir: None, + keep_parquet: true, + hardware_kind: Some("dev-laptop".to_string()), + update_benchmarks_md: false, + gates: GateSet { + a1: true, + c1: false, + c2: false, + }, + }; + let err = run(&config).expect_err("keep_parquet without bucket_dir must be rejected"); + assert!( + matches!(&err, BenchError::Cli { detail } if detail.contains("--keep-parquet requires --bucket-dir")), + "expected a Cli error about --keep-parquet, got {err:?}", + ); +} From 3640a12ba4f719693ee38a0a50e3e76938da5fcc Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 26 May 2026 08:52:27 +0200 Subject: [PATCH 5/6] fixup! feat(bench): land A1 compression-ratio measurement (PR-I2) Co-Authored-By: Claude Opus 4.7 (1M context) --- crates/ourios-bench/src/a1.rs | 64 +++++++++++++++++++++++++----- crates/ourios-bench/src/c1.rs | 2 +- crates/ourios-bench/src/harness.rs | 39 +++++++++++++----- crates/ourios-bench/src/lib.rs | 48 ++++++++++++---------- 4 files changed, 108 insertions(+), 45 deletions(-) diff --git a/crates/ourios-bench/src/a1.rs b/crates/ourios-bench/src/a1.rs index e096f5e93..0bb32b9e1 100644 --- a/crates/ourios-bench/src/a1.rs +++ b/crates/ourios-bench/src/a1.rs @@ -101,17 +101,24 @@ impl A1Accumulator { let partition = PartitionKey::derive(emitted).map_err(|e| crate::BenchError::Pipeline { detail: format!("partition derive failed: {e}"), })?; - let writer = match self.data_writers.entry(partition.clone()) { - std::collections::hash_map::Entry::Occupied(w) => w.into_mut(), - std::collections::hash_map::Entry::Vacant(slot) => { - let w = Writer::open(&self.bucket_root, partition).map_err(|e| { - crate::BenchError::Pipeline { - detail: format!("parquet writer open: {e}"), - } - })?; - slot.insert(w) - } - }; + // Hot path: the partition writer almost always already + // exists (a corpus stays in one hour for ~3.6 M lines + // at the §3.3 1 ms/line cadence). `contains_key` + + // `get_mut` keep the common case clone-free; the + // `PartitionKey` (with its `String`) is only cloned on + // the rare first-sight-of-a-partition miss. + if !self.data_writers.contains_key(&partition) { + let writer = Writer::open(&self.bucket_root, partition.clone()).map_err(|e| { + crate::BenchError::Pipeline { + detail: format!("parquet writer open: {e}"), + } + })?; + self.data_writers.insert(partition.clone(), writer); + } + let writer = self + .data_writers + .get_mut(&partition) + .expect("writer inserted above when absent"); writer .append_records(std::slice::from_ref(emitted)) .map_err(|e| crate::BenchError::Pipeline { @@ -445,6 +452,41 @@ mod tests { #![allow(clippy::float_cmp)] use super::*; + /// Day-level audit partitioning: two events on the same + /// calendar day but different hours must collapse to one + /// `PartitionKey` (the `key.hour = 0` normalization), so a + /// multi-hour run writes one audit file per day. Pins the + /// audit layout contract. + #[test] + fn audit_partition_collapses_same_day_hours() { + use ourios_core::audit::AuditEventKind; + use std::time::{Duration, UNIX_EPOCH}; + + let make = |offset_secs: u64| AuditEvent { + kind: AuditEventKind::TemplateWideningRejectedDegenerate { + version: 1, + current_template: "alpha <*>".to_string(), + would_be_template: "<*> <*>".to_string(), + would_be_positions: vec![0], + }, + tenant_id: TenantId::new("bench-tenant"), + template_id: 1, + triggering_line_hash: [0u8; 16], + triggering_line_sample: None, + // §3.3 baseline (2026-04-02T10:58:00Z) + offset. + timestamp: UNIX_EPOCH + Duration::from_secs(1_775_127_480 + offset_secs), + }; + + // Same day, ~2 hours apart (10:58 vs 12:58). + let early = audit_partition(&make(0)).expect("partition"); + let later = audit_partition(&make(2 * 3600)).expect("partition"); + assert_eq!( + early, later, + "same-day events must share one audit partition key (hour normalized to 0)", + ); + assert_eq!(early.hour, 0, "audit key hour is normalized to 0"); + } + /// 3-sigfig floor: `12.49` → `12.4`, `3.456` → `3.45`, /// `0.98765` → `0.987`. Always rounds toward zero so a /// reported ratio never overstates compression. diff --git a/crates/ourios-bench/src/c1.rs b/crates/ourios-bench/src/c1.rs index ef8f2f11c..c50bf133b 100644 --- a/crates/ourios-bench/src/c1.rs +++ b/crates/ourios-bench/src/c1.rs @@ -166,7 +166,7 @@ mod tests { fn c1_is_100_percent_on_seed_corpus() { let load = corpus::load(&seed_corpus_dir()).expect("seed corpus loads"); let mut acc = C1Accumulator::new(); - harness::run(&load, |input, emitted, snap| { + harness::run(&load, false, |input, emitted, snap| { acc.record(input, emitted, snap); }) .expect("harness runs"); diff --git a/crates/ourios-bench/src/harness.rs b/crates/ourios-bench/src/harness.rs index 15c6fcea4..b450fcb8a 100644 --- a/crates/ourios-bench/src/harness.rs +++ b/crates/ourios-bench/src/harness.rs @@ -32,7 +32,7 @@ use std::collections::HashMap; -use ourios_core::audit::{AuditEvent, SharedAuditSink}; +use ourios_core::audit::{AuditEvent, NoOpAuditSink, SharedAuditSink}; use ourios_core::config::MinerConfig; use ourios_core::otlp::OtlpLogRecord; use ourios_core::record::{MinedRecord, SharedRecordSink}; @@ -76,6 +76,14 @@ pub(crate) struct HarnessResult { /// snapshot. Version monotonicity (the miner never unmerges) /// means a `(id, v)` we've already captured stays valid. /// +/// `capture_audit` controls audit-event collection: A1 needs +/// the stream (it writes it into the `audit/...` series), +/// other gates don't. When `false` the cluster gets a +/// [`NoOpAuditSink`] and [`HarnessResult::audit_events`] is +/// empty — important because [`SharedAuditSink`] is unbounded, +/// so buffering it on a C1-only run would retain the whole +/// event stream for nothing. +/// /// # Errors /// /// - [`BenchError::Pipeline`] when the miner's emit count for @@ -86,18 +94,27 @@ pub(crate) struct HarnessResult { /// cluster's `templates_for()` doesn't return a leaf for /// (impossible by construction; surfaces a future miner /// bug rather than crashing C1's snapshot lookup). -pub(crate) fn run(corpus: &CorpusLoad, mut on_record: F) -> Result +pub(crate) fn run( + corpus: &CorpusLoad, + capture_audit: bool, + mut on_record: F, +) -> Result where F: FnMut(&OtlpLogRecord, &MinedRecord, Option<&[OwnedToken]>), { let sink = SharedRecordSink::new(); - let audit_sink = SharedAuditSink::new(); + let audit_sink = capture_audit.then(SharedAuditSink::new); // `with_audit_sink` is the constructor that takes the // audit sink; `with_record_sink` is the chainable setter - // for the record sink. - let mut cluster = - MinerCluster::with_audit_sink(MinerConfig::default(), Box::new(audit_sink.clone())) - .with_record_sink(Box::new(sink.clone())); + // for the record sink. A `NoOpAuditSink` is installed when + // the caller isn't capturing, so the miner's emissions are + // dropped instead of buffered. + let audit_box: Box = match &audit_sink { + Some(s) => Box::new(s.clone()), + None => Box::new(NoOpAuditSink::new()), + }; + let mut cluster = MinerCluster::with_audit_sink(MinerConfig::default(), audit_box) + .with_record_sink(Box::new(sink.clone())); let tenant = TenantId::new(BENCH_TENANT); let mut snapshots: HashMap<(u64, u32), Vec> = HashMap::new(); @@ -136,7 +153,7 @@ where } Ok(HarnessResult { - audit_events: audit_sink.drain(), + audit_events: audit_sink.map(|s| s.drain()).unwrap_or_default(), }) } @@ -221,7 +238,7 @@ mod tests { let (_tmp, load) = load_lines(&["user 42 logged in", "user 43 logged in"]); let line_count = load.lines.len(); let mut count = 0usize; - run(&load, |_input, _record, _snap| count += 1).expect("harness runs"); + run(&load, false, |_input, _record, _snap| count += 1).expect("harness runs"); assert_eq!(count, line_count); } @@ -242,7 +259,7 @@ mod tests { ]); let mut non_lossy_seen = 0usize; let mut non_lossy_with_snapshot = 0usize; - run(&load, |_input, record, snap| { + run(&load, false, |_input, record, snap| { if !record.lossy_flag && record.template_id != NO_TEMPLATE { non_lossy_seen += 1; if snap.is_some() { @@ -269,7 +286,7 @@ mod tests { fn repeated_template_reuses_one_snapshot() { let (_tmp, load) = load_lines(&["user 42 logged in", "user 99 logged in"]); let mut snapshots_seen: Vec>> = Vec::new(); - run(&load, |_input, _record, snap| { + run(&load, false, |_input, _record, snap| { snapshots_seen.push(snap.map(<[OwnedToken]>::to_vec)); }) .expect("harness runs"); diff --git a/crates/ourios-bench/src/lib.rs b/crates/ourios-bench/src/lib.rs index 113f3b0f5..d6905c07b 100644 --- a/crates/ourios-bench/src/lib.rs +++ b/crates/ourios-bench/src/lib.rs @@ -148,32 +148,36 @@ pub fn run(config: &BenchConfig) -> Result { let total_lines = u64::try_from(corpus_load.lines.len()) .expect("usize fits in u64 on every supported Rust target"); - // Resolve the Parquet output bucket A1 writes into. A - // caller-supplied `bucket_dir` is used as-is; otherwise a - // scratch dir is created and (unless `--keep-parquet`) - // removed when `_bucket_guard` drops at end of scope. - // Held even when A1 is disabled so the branch stays simple - // — an unused empty temp dir costs one inode. - let (bucket_root, _bucket_guard) = resolve_bucket(config)?; - - // A1 measures every `*.parquet` under the bucket; a - // caller-supplied dir that already holds Parquet (e.g. a - // prior `--keep-parquet` run) would inflate - // `bytes(ourios_output)` and skew the ratio. Refuse to - // measure into a dirty bucket. A scratch `TempDir` is - // always empty, so this only ever fires on a reused - // caller dir. - if config.gates.a1 { + // Resolve the Parquet output bucket — but only for A1. + // C1 writes no Parquet, so a C1-only run needs no bucket + // and must not be tripped up by bucket concerns (e.g. a + // `--keep-parquet` flag, or an unwritable temp dir). The + // `_bucket_guard` keeps a scratch `TempDir` alive until + // end of scope; it's `None` for a caller-supplied dir or + // when A1 is disabled. + let _bucket_guard: Option; + let mut a1_acc = if config.gates.a1 { + let (bucket_root, guard) = resolve_bucket(config)?; + // A1 measures every `*.parquet` under the bucket; a + // caller-supplied dir already holding Parquet (e.g. a + // prior `--keep-parquet` run) would inflate + // `bytes(ourios_output)`. A scratch `TempDir` is always + // empty, so this only ever fires on a reused caller dir. ensure_bucket_has_no_parquet(&bucket_root)?; - } + _bucket_guard = guard; + Some(a1::A1Accumulator::new(&bucket_root)) + } else { + _bucket_guard = None; + None + }; let mut c1_acc = config.gates.c1.then(c1::C1Accumulator::new); - let mut a1_acc = config - .gates - .a1 - .then(|| a1::A1Accumulator::new(&bucket_root)); - let harness_result = harness::run(&corpus_load, |input, emitted, snap| { + // Capture the audit stream only when A1 needs it + // (`SharedAuditSink` is unbounded — buffering it on a + // C1-only run would retain the full event stream for + // nothing). + let harness_result = harness::run(&corpus_load, config.gates.a1, |input, emitted, snap| { if let Some(acc) = c1_acc.as_mut() { acc.record(input, emitted, snap); } From 4d219eab60e08131ebe80c37a707e5d39097437f Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Tue, 26 May 2026 12:06:25 +0200 Subject: [PATCH 6/6] fixup! feat(bench): land A1 compression-ratio measurement (PR-I2) Co-Authored-By: Claude Opus 4.7 (1M context) --- crates/ourios-bench/src/a1.rs | 37 ++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/crates/ourios-bench/src/a1.rs b/crates/ourios-bench/src/a1.rs index 0bb32b9e1..ed4e8a58a 100644 --- a/crates/ourios-bench/src/a1.rs +++ b/crates/ourios-bench/src/a1.rs @@ -103,27 +103,32 @@ impl A1Accumulator { })?; // Hot path: the partition writer almost always already // exists (a corpus stays in one hour for ~3.6 M lines - // at the §3.3 1 ms/line cadence). `contains_key` + - // `get_mut` keep the common case clone-free; the - // `PartitionKey` (with its `String`) is only cloned on - // the rare first-sight-of-a-partition miss. - if !self.data_writers.contains_key(&partition) { - let writer = Writer::open(&self.bucket_root, partition.clone()).map_err(|e| { - crate::BenchError::Pipeline { - detail: format!("parquet writer open: {e}"), - } - })?; - self.data_writers.insert(partition.clone(), writer); + // at the §3.3 1 ms/line cadence). A single `get_mut` + // serves it — no second lookup, no `PartitionKey` + // clone. + if let Some(writer) = self.data_writers.get_mut(&partition) { + return writer + .append_records(std::slice::from_ref(emitted)) + .map_err(|e| crate::BenchError::Pipeline { + detail: format!("parquet append_records: {e}"), + }); } - let writer = self - .data_writers - .get_mut(&partition) - .expect("writer inserted above when absent"); + // Miss (first record for this partition): open the + // writer, append, then store it. `partition` is cloned + // once for `Writer::open`; the original moves into the + // map as the key. + let mut writer = Writer::open(&self.bucket_root, partition.clone()).map_err(|e| { + crate::BenchError::Pipeline { + detail: format!("parquet writer open: {e}"), + } + })?; writer .append_records(std::slice::from_ref(emitted)) .map_err(|e| crate::BenchError::Pipeline { detail: format!("parquet append_records: {e}"), - }) + })?; + self.data_writers.insert(partition, writer); + Ok(()) } /// Write the miner's audit-event stream into the