Skip to content

feat(tools): stream-evidence harness for checksum-paged inflate (#112 / #151) - #158

Merged
DrunkOnJava merged 1 commit into
mainfrom
cursor/wave1-stream-evidence-67f9
Aug 29, 2026
Merged

DrunkOnJava merged 1 commit into
mainfrom
cursor/wave1-stream-evidence-67f9

Conversation

@DrunkOnJava

@DrunkOnJava DrunkOnJava commented Aug 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Reusable stream-evidence harness (library + CLI) for Discussion #112 / issue #151 checksum-paged stream probes. Emits machine-readable JSON comparing control (raw stored bytes → inflate) vs experimental (page-stripped → inflate) without changing production decompressors.

Credit

Finding reported by @STE1200 (Steffen) and team in Discussion #112. Tracked as #151. Thank you for the clean-room evidence and gzip-trailer oracles.

Motivation

Wave 1 Worker B deliverable: a probe library Griffin/coordinator and later Finding 1 work can reuse to reproduce or refute silent corruption after the first 65,249-byte stored page — without wiring production inflate yet.

Changes

  • tools/stream_evidence/ — library (experimental_strip_page_checksums, analyze_stored_stream, analyze_file) + stream-evidence binary
  • examples/stream_evidence.rs — discoverability shim using the library
  • docs/recon/stream-evidence-harness.md — usage + JSON field map
  • Workspace member + root dev-dependency registration only (no src/compression.rs edits)

JSON evidence fields

Stream names, stored lengths, suspected page counts/boundaries, payload/tail lengths, decompressed lengths, consumed-byte counts, gzip trailer probes, parser results (Formats/Latest), failure offsets, release, file type, sample SHA-256, provenance/credit.

Testing

  • cargo test -p stream-evidence --release (4 unit tests, including synthetic multi-page divergence)
  • cargo clippy -p stream-evidence --all-targets -- -D warnings
  • cargo fmt --all -- --check
  • Sample runs under /opt/cursor/artifacts/wave1_worker_b_harness/:
    • tier1 + gen-fixture (0 full pages → control == experimental)
    • magnetar 2024_Core_Interior.rvt Formats/Latest (2 full pages → diverge @ 143773; schema class_name_count 9579 vs 8575)
    • same file Global/ElemTable (1 full page → diverge @ 542754)

Audit-honesty checklist

  • Docs state this does not change production inflate
  • External corpus hashes/paths are for local probes only (not redistributed)
  • No emojis; Apache-2.0 / clean-room posture preserved
  • RE finding: reproducible probe under examples/ + docs/recon/ note (full recon addendum left to Finding 1 confirmation PR)

Breaking changes

None.

Related issues

Refs #151 · Discussion #112 · credit @STE1200

Do not merge until Griffin/coordinator review.


Note

Low Risk
New offline probe crate and docs only; no edits to production src/compression.rs or shipped inflate behavior.

Overview
Adds a stream-evidence workspace tool (tools/stream_evidence) for Discussion #112 / issue #151: JSON reports that A/B control (inflate raw stored CFB bytes) vs experimental (strip 65,249-byte page checksum trailers, then inflate), plus page layout, gzip trailer probes, Formats/Latest schema summaries, and a check that harness stripping matches existing rvt::compression::strip_revit_page_checksums.

Production decompressors are unchanged—experimental stripping lives only in the tool crate. Wiring is workspace membership, a root dev-dependency, examples/stream_evidence.rs, and docs/recon/stream-evidence-harness.md. Run via cargo run -p stream-evidence or the example; filters default to Formats/Latest with --all-paged for suspected paged streams.

Reviewed by Cursor Bugbot for commit b9acfa3. Configure here.

Add a reusable control-vs-experimental checksum-page evidence library
and CLI under tools/stream_evidence (plus examples/ shim and docs/recon).
Does not change production inflate; experimental stripping lives in the
harness for probes. Credits @STE1200 (Steffen) for Discussion #112 Finding 1.

Co-authored-by: DrunkOnJava <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Silent fallback analyzes the wrong stream
    • Restricted the first-non-empty-stream fallback to the default no-filter path and return errors when an explicit --stream filter or --all-paged selection matches nothing.

Create PR

Or push these changes by commenting:

@cursor push 9ba53179e0
Preview (9ba53179e0)
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -759,6 +759,7 @@
  "serde-wasm-bindgen",
  "serde_json",
  "sha2",
+ "stream-evidence",
  "thiserror",
  "wasm-bindgen",
 ]
@@ -867,6 +868,20 @@
 checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
 
 [[package]]
+name = "stream-evidence"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "flate2",
+ "hex",
+ "rvt",
+ "serde",
+ "serde_json",
+ "sha2",
+]
+
+[[package]]
 name = "strsim"
 version = "0.11.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"

diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -31,7 +31,7 @@
 # unconditionally — no feature-gated escape hatch. The wheel on
 # PyPI still ships as a single `rvt` distribution; it's built via
 # `maturin build --manifest-path rvt-py/Cargo.toml`.
-members = [".", "rvt-py"]
+members = [".", "rvt-py", "tools/stream_evidence"]
 
 [features]
 # Heap-profiling mode (Q-08). When enabled, binaries built from
@@ -94,6 +94,9 @@
 # synthetic fixtures under corpus/tier1/.
 sha2 = "0.10"
 hex = "0.4"
+# Discussion #112 / #151 stream-evidence harness (library used by
+# `examples/stream_evidence.rs` probes).
+stream-evidence = { path = "tools/stream_evidence" }
 
 # Seven shipped binaries. All depend on the `rvt` library crate.
 

diff --git a/docs/recon/stream-evidence-harness.md b/docs/recon/stream-evidence-harness.md
new file mode 100644
--- /dev/null
+++ b/docs/recon/stream-evidence-harness.md
@@ -1,0 +1,79 @@
+# Stream-evidence harness (Discussion #112 / issue #151)
+
+Reusable **control vs experimental** page-stripping evidence tool for
+checksum-paged Revit CFB streams. Finding reported by
+[@STE1200](https://github.com/STE1200) (Steffen) in
+[Discussion #112](https://github.com/DrunkOnJava/rvt-rs/discussions/112);
+tracked as [#151](https://github.com/DrunkOnJava/rvt-rs/issues/151).
+
+This harness **does not change production inflate**. Experimental stripping
+lives in `tools/stream_evidence` so probes can A/B compare without wiring
+production readers.
+
+## Package
+
+| Path | Role |
+|------|------|
+| `tools/stream_evidence/` | Library + `stream-evidence` CLI |
+| `examples/stream_evidence.rs` | Discoverability shim → same CLI |
+| `docs/recon/stream-evidence-harness.md` | This note |
+
+## Reported layout (hypothesis under test)
+
+Each full stored page = **64,896** payload bytes + **353** checksum/ECC
+trailer (**65,249** total). Short final pages keep all remaining bytes.
+Tails must be removed before RFC 1951 inflate; leaving them in place can
+terminate cleanly while drifting after the first page boundary.
+
+## Run
+
+```bash
+cargo run -p stream-evidence --release -- \
+  --file corpus/tier1/architectural-2024/architectural-2024.rvt \
+  --stream Formats/Latest \
+  -o /tmp/tier1_formats.json
+
+# Project corpus (local only; not redistributed):
+cargo run -p stream-evidence --release -- \
+  --file _project_corpus/Revit/2024_Core_Interior.rvt \
+  --stream Formats/Latest \
+  -o /tmp/core_interior_formats.json
+```
+
+Omit `--stream` to analyze every suspected checksum-paged non-empty stream
+(`Formats/Latest`, `Global/*` table streams, `Partitions/N`).
+
+## JSON fields
+
+Top-level `EvidenceReport`:
+
+- `file`: `release`, `file_type`, `sample_hash_sha256`, `provenance`, `credit`
+- `streams[]`:
+  - `stream_name`, `page_layout` (stored lengths, suspected page counts /
+    boundaries, per-page payload + tail lengths)
+  - `control` / `experimental` arms: prepared lengths, gzip offsets,
+    per-member decompressed lengths, consumed-byte counts, trailer results,
+    parser results (`Formats/Latest` schema summary), failure offsets
+  - `comparison`: equality, length delta, first divergence offset
+  - `production_strip_matches_experimental`: whether
+    `rvt::compression::strip_revit_page_checksums` matches the harness strip
+
+## Library use from probes
+
+```rust
+use stream_evidence::{
+    analyze_file, analyze_stored_stream, experimental_strip_page_checksums,
+};
+
+let report = analyze_file(path, Some(&["Formats/Latest".into()]), false, false)?;
+let stream = analyze_stored_stream("Formats/Latest", &stored_bytes);
+let stripped = experimental_strip_page_checksums(&stored_bytes);
+```
+
+## Provenance / clean-room
+
+- Synthetic tier1 fixtures: license-free `gen-fixture` output under
+  `corpus/tier1/`.
+- External corpora (`_project_corpus/`, `_corpus/`): probe locally only;
+  do not commit Autodesk sample bytes (see `SECURITY.md`).
+- No production `src/compression.rs` behavior is changed by this crate.

diff --git a/examples/stream_evidence.rs b/examples/stream_evidence.rs
new file mode 100644
--- /dev/null
+++ b/examples/stream_evidence.rs
@@ -1,0 +1,52 @@
+//! Example probe: stream-evidence harness (Discussion #112 / issue #151).
+//!
+//! Emits control-vs-experimental page-strip evidence JSON for a Revit file.
+//! Library lives in `tools/stream_evidence` so production inflate is untouched.
+//!
+//! ```text
+//! cargo run --release --example stream_evidence -- \
+//!   --file corpus/tier1/architectural-2024/architectural-2024.rvt \
+//!   -o /tmp/formats.json
+//! ```
+//!
+//! Prefer the workspace binary when scripting:
+//! `cargo run -p stream-evidence --release -- …`
+//!
+//! Credit: [@STE1200](https://github.com/STE1200) (Steffen).
+
+use clap::Parser;
+use std::path::PathBuf;
+use stream_evidence::{analyze_file, stream_names_from_args, write_report};
+
+#[derive(Parser, Debug)]
+#[command(name = "stream_evidence", version)]
+struct Cli {
+    #[arg(long, short = 'f')]
+    file: PathBuf,
+    #[arg(long = "stream", short = 's')]
+    streams: Vec<String>,
+    #[arg(long, default_value_t = false)]
+    all_paged: bool,
+    #[arg(long, default_value_t = false)]
+    include_empty: bool,
+    #[arg(long, short = 'o')]
+    output: Option<PathBuf>,
+}
+
+fn main() -> anyhow::Result<()> {
+    let cli = Cli::parse();
+    let filter = stream_names_from_args(&cli.streams);
+    let report = analyze_file(
+        &cli.file,
+        filter.as_deref(),
+        cli.all_paged,
+        cli.include_empty,
+    )?;
+    if let Some(out) = cli.output.as_ref() {
+        write_report(&report, out)?;
+        eprintln!("wrote {}", out.display());
+    } else {
+        println!("{}", serde_json::to_string_pretty(&report)?);
+    }
+    Ok(())
+}

diff --git a/tools/stream_evidence/Cargo.toml b/tools/stream_evidence/Cargo.toml
new file mode 100644
--- /dev/null
+++ b/tools/stream_evidence/Cargo.toml
@@ -1,0 +1,23 @@
+[package]
+name = "stream-evidence"
+version = "0.1.0"
+edition = "2024"
+rust-version = "1.85"
+license = "Apache-2.0"
+publish = false
+description = "Reusable stream-evidence harness for Discussion #112 / issue #151 checksum-paged inflate probes (control vs experimental page stripping)."
+authors = ["Griffin Long <[email protected]>"]
+
+[[bin]]
+name = "stream-evidence"
+path = "src/main.rs"
+
+[dependencies]
+rvt = { path = "../.." }
+flate2 = "1.0"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+clap = { version = "4", features = ["derive"] }
+sha2 = "0.10"
+hex = "0.4"
+anyhow = "1"

diff --git a/tools/stream_evidence/src/lib.rs b/tools/stream_evidence/src/lib.rs
new file mode 100644
--- /dev/null
+++ b/tools/stream_evidence/src/lib.rs
@@ -1,0 +1,840 @@
+//! Stream-evidence harness for Discussion #112 / issue #151.
+//!
+//! Reports machine-readable JSON for stored CFB streams: page layout,
+//! control (raw) vs experimental (page-stripped) inflate outcomes,
+//! gzip-trailer probes, parser summaries, and file provenance.
+//!
+//! **Does not change production inflate.** Experimental page stripping
+//! lives in this crate so probes can A/B compare without relying on
+//! production `prepare_stream_for_inflate` wiring.
+//!
+//! Credit: finding reported by [@STE1200](https://github.com/STE1200)
+//! (Steffen) in Discussion #112.
+
+#![forbid(unsafe_code)]
+
+use flate2::read::DeflateDecoder;
+use serde::Serialize;
+use sha2::{Digest, Sha256};
+use std::io::Read;
+use std::path::{Path, PathBuf};
+
+/// Stored bytes in a full checksum page (Discussion #112 / reviter).
+pub const REVIT_STORED_PAGE_BYTES: usize = 65_249;
+/// Payload bytes kept from each full page after stripping the trailer.
+pub const REVIT_PAGE_PAYLOAD_BYTES: usize = 64_896;
+/// Checksum/ECC trailer length cut from each full stored page.
+pub const REVIT_PAGE_CHECKSUM_BYTES: usize = REVIT_STORED_PAGE_BYTES - REVIT_PAGE_PAYLOAD_BYTES;
+
+pub const GZIP_MAGIC: [u8; 3] = [0x1F, 0x8B, 0x08];
+
+/// Evidence schema version for consumers / probes.
+pub const EVIDENCE_SCHEMA_VERSION: u32 = 1;
+
+/// Hypothesis-side page strip (experimental arm). Independent copy of the
+/// Discussion #112 layout so probes do not need production wiring.
+pub fn experimental_strip_page_checksums(data: &[u8]) -> Vec<u8> {
+    let full_pages = data.len() / REVIT_STORED_PAGE_BYTES;
+    if full_pages == 0 {
+        return data.to_vec();
+    }
+    let remainder = data.len() - full_pages * REVIT_STORED_PAGE_BYTES;
+    let mut out = Vec::with_capacity(full_pages * REVIT_PAGE_PAYLOAD_BYTES + remainder);
+    for page in 0..full_pages {
+        let start = page * REVIT_STORED_PAGE_BYTES;
+        out.extend_from_slice(&data[start..start + REVIT_PAGE_PAYLOAD_BYTES]);
+    }
+    out.extend_from_slice(&data[full_pages * REVIT_STORED_PAGE_BYTES..]);
+    out
+}
+
+/// Paths suspected to use checksum-paged storage (issue #151).
+pub fn is_suspected_checksum_paged_stream(path: &str) -> bool {
+    let clean = path
+        .trim_start_matches('/')
+        .trim_start_matches("Root Entry/");
+    let clean = clean.trim_start_matches('/');
+    if clean.eq_ignore_ascii_case("Formats/Latest") {
+        return true;
+    }
+    if let Some(rest) = clean
+        .strip_prefix("Partitions/")
+        .or_else(|| clean.strip_prefix("partitions/"))
+    {
+        return !rest.is_empty() && !rest.contains('/');
+    }
+    matches!(
+        clean,
+        "Global/ContentDocuments"
+            | "Global/DocumentIncrementTable"
+            | "Global/ElemTable"
+            | "Global/History"
+            | "Global/Latest"
+            | "Global/PartitionTable"
+    )
+}
+
+/// Describe stored-page boundaries for a raw CFB stream body.
+pub fn analyze_page_layout(stored: &[u8]) -> PageLayoutEvidence {
+    let full_page_count = stored.len() / REVIT_STORED_PAGE_BYTES;
+    let remainder_bytes = stored.len() % REVIT_STORED_PAGE_BYTES;
+    let mut boundaries = Vec::with_capacity(full_page_count + 1);
+    let mut pages = Vec::with_capacity(full_page_count + usize::from(remainder_bytes > 0));
+    for page in 0..full_page_count {
+        let start = page * REVIT_STORED_PAGE_BYTES;
+        boundaries.push(start);
+        pages.push(PageEvidence {
+            index: page,
+            start_offset: start,
+            stored_length: REVIT_STORED_PAGE_BYTES,
+            is_full_page: true,
+            payload_length: REVIT_PAGE_PAYLOAD_BYTES,
+            tail_length: REVIT_PAGE_CHECKSUM_BYTES,
+        });
+    }
+    if remainder_bytes > 0 || full_page_count == 0 {
+        let start = full_page_count * REVIT_STORED_PAGE_BYTES;
+        if full_page_count == 0 {
+            boundaries.push(0);
+        } else {
+            boundaries.push(start);
+        }
+        pages.push(PageEvidence {
+            index: full_page_count,
+            start_offset: start,
+            stored_length: if full_page_count == 0 {
+                stored.len()
+            } else {
+                remainder_bytes
+            },
+            is_full_page: false,
+            payload_length: if full_page_count == 0 {
+                stored.len()
+            } else {
+                remainder_bytes
+            },
+            tail_length: 0,
+        });
+    }
+    let stripped_len = experimental_strip_page_checksums(stored).len();
+    PageLayoutEvidence {
+        stored_length: stored.len(),
+        full_page_count,
+        remainder_bytes,
+        suspected_page_count: pages.len(),
+        suspected_boundaries: boundaries,
+        pages,
+        experimental_stripped_length: stripped_len,
+        bytes_removed_by_strip: stored.len().saturating_sub(stripped_len),
+    }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct PageEvidence {
+    pub index: usize,
+    pub start_offset: usize,
+    pub stored_length: usize,
+    pub is_full_page: bool,
+    pub payload_length: usize,
+    pub tail_length: usize,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct PageLayoutEvidence {
+    pub stored_length: usize,
+    pub full_page_count: usize,
+    pub remainder_bytes: usize,
+    pub suspected_page_count: usize,
+    pub suspected_boundaries: Vec<usize>,
+    pub pages: Vec<PageEvidence>,
+    pub experimental_stripped_length: usize,
+    pub bytes_removed_by_strip: usize,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct GzipTrailerEvidence {
+    /// Absolute offset of the putative CRC32+ISIZE trailer, when known.
+    pub trailer_offset: Option<usize>,
+    pub present: bool,
+    pub isize_matches_output: Option<bool>,
+    pub isize_le: Option<u32>,
+    pub crc32_le: Option<u32>,
+    pub note: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct MemberInflateEvidence {
+    pub gzip_offset: usize,
+    pub ok: bool,
+    pub header_length: Option<usize>,
+    pub decompressed_length: Option<usize>,
+    /// DEFLATE body bytes consumed (excludes gzip header).
+    pub deflate_consumed_bytes: Option<usize>,
+    /// Header + DEFLATE consumed from the prepared buffer.
+    pub total_consumed_bytes: Option<usize>,
+    pub failure_offset: Option<usize>,
+    pub error: Option<String>,
+    pub trailer: GzipTrailerEvidence,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ParserEvidence {
+    pub kind: String,
+    pub ok: bool,
+    pub class_count: Option<usize>,
+    pub field_count: Option<usize>,
+    pub skipped_records: Option<usize>,
+    pub class_name_count: Option<usize>,
+    pub error: Option<String>,
+    pub failure_offset: Option<usize>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ArmEvidence {
+    /// `"control"` = raw stored bytes; `"experimental"` = page-stripped.
+    pub arm: String,
+    pub prepared_length: usize,
+    pub gzip_member_offsets: Vec<usize>,
+    pub members: Vec<MemberInflateEvidence>,
+    pub first_member_decompressed_length: Option<usize>,
+    pub inflate_all_chunks_count: usize,
+    pub inflate_all_chunks_total_bytes: usize,
+    pub first_failure_offset: Option<usize>,
+    pub parser: Option<ParserEvidence>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ComparisonEvidence {
+    pub outputs_equal: bool,
+    pub control_decompressed_length: Option<usize>,
+    pub experimental_decompressed_length: Option<usize>,
+    pub length_delta: Option<i64>,
+    pub first_divergence_offset: Option<usize>,
+    pub note: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct StreamEvidence {
+    pub stream_name: String,
+    pub suspected_checksum_paged: bool,
+    pub page_layout: PageLayoutEvidence,
+    pub control: ArmEvidence,
+    pub experimental: ArmEvidence,
+    pub comparison: ComparisonEvidence,
+    /// Whether production `rvt::compression::strip_revit_page_checksums`
+    /// matches this harness's experimental strip (byte-identical).
+    pub production_strip_matches_experimental: bool,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct FileProvenance {
+    pub path: String,
+    pub file_name: String,
+    pub file_type: String,
+    pub file_size_bytes: u64,
+    pub sample_hash_sha256: String,
+    pub release: Option<u32>,
+    pub build: Option<String>,
+    pub guid: Option<String>,
+    pub provenance: String,
+    pub credit: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct EvidenceReport {
+    pub schema_version: u32,
+    pub harness: String,
+    pub discussion: String,
+    pub issue: String,
+    pub file: FileProvenance,
+    pub streams: Vec<StreamEvidence>,
+}
+
+fn gzip_header_len(data: &[u8], offset: usize) -> Option<usize> {
+    rvt::compression::gzip_header_len(data, offset)
+}
+
+fn find_gzip_offsets(data: &[u8]) -> Vec<usize> {
+    rvt::compression::find_gzip_offsets(data)
+}
+
+/// Inflate one gzip member and record consumed bytes + trailer probe.
+pub fn inflate_member_evidence(data: &[u8], offset: usize) -> MemberInflateEvidence {
+    let Some(header_len) = gzip_header_len(data, offset) else {
+        return MemberInflateEvidence {
+            gzip_offset: offset,
+            ok: false,
+            header_length: None,
+            decompressed_length: None,
+            deflate_consumed_bytes: None,
+            total_consumed_bytes: None,
+            failure_offset: Some(offset),
+            error: Some("no gzip header".into()),
+            trailer: GzipTrailerEvidence {
+                trailer_offset: None,
+                present: false,
+                isize_matches_output: None,
+                isize_le: None,
+                crc32_le: None,
+                note: "no gzip header; trailer not probed".into(),
+            },
+        };
+    };
+    let body_start = match offset.checked_add(header_len) {
+        Some(v) => v,
+        None => {
+            return MemberInflateEvidence {
+                gzip_offset: offset,
+                ok: false,
+                header_length: Some(header_len),
+                decompressed_length: None,
+                deflate_consumed_bytes: None,
+                total_consumed_bytes: None,
+                failure_offset: Some(offset),
+                error: Some("gzip header offset overflow".into()),
+                trailer: GzipTrailerEvidence {
+                    trailer_offset: None,
+                    present: false,
+                    isize_matches_output: None,
+                    isize_le: None,
+                    crc32_le: None,
+                    note: "header overflow".into(),
+                },
+            };
+        }
+    };
+    let body = match data.get(body_start..) {
+        Some(b) => b,
+        None => {
+            return MemberInflateEvidence {
+                gzip_offset: offset,
+                ok: false,
+                header_length: Some(header_len),
+                decompressed_length: None,
+                deflate_consumed_bytes: None,
+                total_consumed_bytes: None,
+                failure_offset: Some(body_start),
+                error: Some("gzip header extends past input".into()),
+                trailer: GzipTrailerEvidence {
+                    trailer_offset: None,
+                    present: false,
+                    isize_matches_output: None,
+                    isize_le: None,
+                    crc32_le: None,
+                    note: "header past input".into(),
+                },
+            };
+        }
+    };
+
+    let limits = rvt::compression::InflateLimits::default();
+    let mut out = Vec::with_capacity(body.len().saturating_mul(4).min(limits.max_output_bytes));
+    let mut decoder = DeflateDecoder::new(body);
+    let mut buf = [0u8; 8192];
+    loop {
+        match decoder.read(&mut buf) {
+            Ok(0) => break,
+            Ok(n) => {
+                let next = out.len().saturating_add(n);
+                if next > limits.max_output_bytes {
+                    let consumed = decoder.total_in() as usize;
+                    return MemberInflateEvidence {
+                        gzip_offset: offset,
+                        ok: false,
+                        header_length: Some(header_len),
+                        decompressed_length: Some(out.len()),
+                        deflate_consumed_bytes: Some(consumed),
+                        total_consumed_bytes: Some(header_len + consumed),
+                        failure_offset: Some(body_start + consumed),
+                        error: Some(format!(
+                            "DEFLATE would exceed {} bytes",
+                            limits.max_output_bytes
+                        )),
+                        trailer: GzipTrailerEvidence {
+                            trailer_offset: None,
+                            present: false,
+                            isize_matches_output: None,
+                            isize_le: None,
+                            crc32_le: None,
+                            note: "inflate aborted on output limit".into(),
+                        },
+                    };
+                }
+                out.extend_from_slice(&buf[..n]);
+            }
+            Err(e) => {
+                let consumed = decoder.total_in() as usize;
+                return MemberInflateEvidence {
+                    gzip_offset: offset,
+                    ok: false,
+                    header_length: Some(header_len),
+                    decompressed_length: Some(out.len()),
+                    deflate_consumed_bytes: Some(consumed),
+                    total_consumed_bytes: Some(header_len + consumed),
+                    failure_offset: Some(body_start + consumed),
+                    error: Some(format!("DEFLATE at offset {offset}: {e}")),
+                    trailer: GzipTrailerEvidence {
+                        trailer_offset: None,
+                        present: false,
+                        isize_matches_output: None,
+                        isize_le: None,
+                        crc32_le: None,
+                        note: "inflate failed before trailer probe".into(),
+                    },
+                };
+            }
+        }
+    }
+
+    let deflate_consumed = decoder.total_in() as usize;
+    let total_consumed = header_len + deflate_consumed;
+    let trailer_offset = body_start + deflate_consumed;
+    let trailer = probe_gzip_trailer(data, trailer_offset, out.len());
+
+    MemberInflateEvidence {
+        gzip_offset: offset,
+        ok: true,
+        header_length: Some(header_len),
+        decompressed_length: Some(out.len()),
+        deflate_consumed_bytes: Some(deflate_consumed),
+        total_consumed_bytes: Some(total_consumed),
+        failure_offset: None,
+        error: None,
+        trailer,
+    }
+}
+
+fn probe_gzip_trailer(
+    data: &[u8],
+    trailer_offset: usize,
+    decompressed_len: usize,
+) -> GzipTrailerEvidence {
+    if trailer_offset.saturating_add(8) > data.len() {
+        return GzipTrailerEvidence {
+            trailer_offset: Some(trailer_offset),
+            present: false,
+            isize_matches_output: None,
+            isize_le: None,
+            crc32_le: None,
+            note: "fewer than 8 bytes remain after DEFLATE (typical Revit truncated-gzip)".into(),
+        };
+    }
+    let t = &data[trailer_offset..trailer_offset + 8];
+    let crc32_le = u32::from_le_bytes([t[0], t[1], t[2], t[3]]);
+    let isize_le = u32::from_le_bytes([t[4], t[5], t[6], t[7]]);
+    let expected_isize = decompressed_len as u32;
+    let isize_matches = isize_le == expected_isize;
+    GzipTrailerEvidence {
+        trailer_offset: Some(trailer_offset),
+        present: true,
+        isize_matches_output: Some(isize_matches),
+        isize_le: Some(isize_le),
+        crc32_le: Some(crc32_le),
+        note: if isize_matches {
+            "8-byte RFC 1952 trailer present; ISIZE matches decompressed length".into()
+        } else {
+            "8 bytes present after DEFLATE but ISIZE does not match output (may be next member / noise)".into()
+        },
+    }
+}
+
+fn first_member_bytes(data: &[u8]) -> Option<Vec<u8>> {
+    let offset = find_gzip_offsets(data).into_iter().next().unwrap_or(0);
+    rvt::compression::inflate_at(data, offset).ok()
+}
+
+fn run_arm(arm: &str, prepared: &[u8], stream_name: &str) -> ArmEvidence {
+    let offsets = find_gzip_offsets(prepared);
+    // Detailed member evidence for the first gzip magic only. Full scans
+    // of every magic hit are expensive on multi-MB streams and include
+    // false positives inside compressed payloads; `inflate_all_chunks`
+    // already covers multi-member aggregation.
+    let probe_offsets: Vec<usize> = if offsets.is_empty() {
+        vec![0]
+    } else {
+        vec![offsets[0]]
+    };
+    let members: Vec<_> = probe_offsets
+        .iter()
+        .copied()
+        .map(|off| inflate_member_evidence(prepared, off))
+        .collect();
+    let first_failure_offset = members.iter().find_map(|m| m.failure_offset);
+    let first_member_decompressed_length = members.first().and_then(|m| m.decompressed_length);
+
+    let chunks = rvt::compression::inflate_all_chunks(prepared);
+    let inflate_all_chunks_total_bytes: usize = chunks.iter().map(|c| c.len()).sum();
+
+    let parser = if stream_name.eq_ignore_ascii_case("Formats/Latest") {
+        Some(parse_formats_latest(prepared))
+    } else {
+        None
+    };
+
+    ArmEvidence {
+        arm: arm.to_string(),
+        prepared_length: prepared.len(),
+        gzip_member_offsets: offsets,
+        members,
+        first_member_decompressed_length,
+        inflate_all_chunks_count: chunks.len(),
+        inflate_all_chunks_total_bytes,
+        first_failure_offset,
+        parser,
+    }
+}
+
+fn parse_formats_latest(prepared: &[u8]) -> ParserEvidence {
+    let decompressed = match first_member_bytes(prepared) {
+        Some(d) => d,
+        None => {
+            return ParserEvidence {
+                kind: "formats_schema".into(),
+                ok: false,
+                class_count: None,
+                field_count: None,
+                skipped_records: None,
+                class_name_count: None,
+                error: Some("inflate failed before schema parse".into()),
+                failure_offset: Some(0),
+            };
+        }
+    };
+    let class_name_count = rvt::class_index::extract_class_names(&decompressed)
+        .ok()
+        .map(|n| n.len());
+    match rvt::formats::parse_schema(&decompressed) {
+        Ok(schema) => {
+            let field_count: usize = schema.classes.iter().map(|c| c.fields.len()).sum();
+            ParserEvidence {
+                kind: "formats_schema".into(),
+                ok: true,
+                class_count: Some(schema.classes.len()),
+                field_count: Some(field_count),
+                skipped_records: Some(schema.skipped_records),
+                class_name_count,
+                error: None,
+                failure_offset: None,
+            }
+        }
+        Err(e) => ParserEvidence {
+            kind: "formats_schema".into(),
+            ok: false,
+            class_count: None,
+            field_count: None,
+            skipped_records: None,
+            class_name_count,
+            error: Some(e.to_string()),
+            failure_offset: None,
+        },
+    }
+}
+
+fn compare_arms(control_prepared: &[u8], experimental_prepared: &[u8]) -> ComparisonEvidence {
+    let control = first_member_bytes(control_prepared);
+    let experimental = first_member_bytes(experimental_prepared);
+    match (control, experimental) {
+        (Some(c), Some(e)) => {
+            let first_divergence_offset = if c == e {
+                None
+            } else {
+                Some(
+                    c.iter()
+                        .zip(e.iter())
+                        .position(|(a, b)| a != b)
+                        .unwrap_or(c.len().min(e.len())),
+                )
+            };
+            ComparisonEvidence {
+                outputs_equal: c == e,
+                control_decompressed_length: Some(c.len()),
+                experimental_decompressed_length: Some(e.len()),
+                length_delta: Some(e.len() as i64 - c.len() as i64),
+                first_divergence_offset,
+                note: if c == e {
+                    "control and experimental first-member outputs are byte-identical".into()
+                } else {
+                    "control and experimental first-member outputs diverge (silent corruption hypothesis when full pages present)".into()
+                },
+            }
+        }
+        (c, e) => ComparisonEvidence {
+            outputs_equal: false,
+            control_decompressed_length: c.as_ref().map(|v| v.len()),
+            experimental_decompressed_length: e.as_ref().map(|v| v.len()),
+            length_delta: match (&c, &e) {
+                (Some(a), Some(b)) => Some(b.len() as i64 - a.len() as i64),
+                _ => None,
... diff truncated: showing 800 of 1144 lines

You can send follow-ups to the cloud agent here.

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit b9acfa3. Configure here.

.collect()
} else {
selected
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Silent fallback analyzes the wrong stream

Medium Severity

When no stream matches the requested filter, analyze_file still succeeds and reports the alphabetically first non-empty CFB stream instead of failing. stream_names() is sorted, so that fallback is almost always BasicFileInfo, which is not checksum-paged. An explicit --stream miss, an empty target, or a missing Formats/Latest therefore emits a successful-looking evidence report for the wrong stream, and the comparison note can still claim a silent-corruption divergence.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b9acfa3. Configure here.

@DrunkOnJava
DrunkOnJava marked this pull request as ready for review August 29, 2026 19:37
@DrunkOnJava
DrunkOnJava merged commit 9f5787c into main Aug 29, 2026
25 of 26 checks passed
@DrunkOnJava
DrunkOnJava deleted the cursor/wave1-stream-evidence-67f9 branch August 29, 2026 19:37
cursor Bot pushed a commit that referenced this pull request Aug 29, 2026
Resolve DISC-112 probe report conflict: keep Worker C chunk-oracle
addendum and the #160 path-gated production note. Refresh framing
contract + Worker C report for judge narrow scope (no universal strip).

Co-authored-by: DrunkOnJava <[email protected]>
DrunkOnJava added a commit that referenced this pull request Aug 31, 2026
## Summary

Reusable **stream-evidence harness** (library + CLI) for Discussion #112
/ issue #151 checksum-paged stream probes. Emits machine-readable JSON
comparing **control** (raw stored bytes → inflate) vs **experimental**
(page-stripped → inflate) without changing production decompressors.

## Credit

Finding reported by [@STE1200](https://github.com/STE1200) (**Steffen**)
and team in [Discussion
#112](#112). Tracked as
[#151](#151). Thank you for
the clean-room evidence and gzip-trailer oracles.

## Motivation

Wave 1 Worker B deliverable: a probe library Griffin/coordinator and
later Finding 1 work can reuse to reproduce or refute silent corruption
after the first 65,249-byte stored page — without wiring production
`inflate` yet.

## Changes

- `tools/stream_evidence/` — library
(`experimental_strip_page_checksums`, `analyze_stored_stream`,
`analyze_file`) + `stream-evidence` binary
- `examples/stream_evidence.rs` — discoverability shim using the library
- `docs/recon/stream-evidence-harness.md` — usage + JSON field map
- Workspace member + root `dev-dependency` registration only (no
`src/compression.rs` edits)

### JSON evidence fields

Stream names, stored lengths, suspected page counts/boundaries,
payload/tail lengths, decompressed lengths, consumed-byte counts, gzip
trailer probes, parser results (`Formats/Latest`), failure offsets,
release, file type, sample SHA-256, provenance/credit.

## Testing

- [x] `cargo test -p stream-evidence --release` (4 unit tests, including
synthetic multi-page divergence)
- [x] `cargo clippy -p stream-evidence --all-targets -- -D warnings`
- [x] `cargo fmt --all -- --check`
- [x] Sample runs under `/opt/cursor/artifacts/wave1_worker_b_harness/`:
  - tier1 + gen-fixture (0 full pages → control == experimental)
- magnetar `2024_Core_Interior.rvt` `Formats/Latest` (2 full pages →
diverge @ 143773; schema class_name_count 9579 vs 8575)
  - same file `Global/ElemTable` (1 full page → diverge @ 542754)

## Audit-honesty checklist

- [x] Docs state this does **not** change production inflate
- [x] External corpus hashes/paths are for local probes only (not
redistributed)
- [x] No emojis; Apache-2.0 / clean-room posture preserved
- [x] RE finding: reproducible probe under `examples/` + `docs/recon/`
note (full recon addendum left to Finding 1 confirmation PR)

## Breaking changes

None.

## Related issues

Refs #151 · Discussion #112 · credit @STE1200

**Do not merge** until Griffin/coordinator review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> New offline probe crate and docs only; no edits to production
`src/compression.rs` or shipped inflate behavior.
> 
> **Overview**
> Adds a **stream-evidence** workspace tool (`tools/stream_evidence`)
for Discussion #112 / issue #151: JSON reports that A/B **control**
(inflate raw stored CFB bytes) vs **experimental** (strip 65,249-byte
page checksum trailers, then inflate), plus page layout, gzip trailer
probes, `Formats/Latest` schema summaries, and a check that harness
stripping matches existing
`rvt::compression::strip_revit_page_checksums`.
> 
> **Production decompressors are unchanged**—experimental stripping
lives only in the tool crate. Wiring is workspace membership, a root
`dev-dependency`, `examples/stream_evidence.rs`, and
`docs/recon/stream-evidence-harness.md`. Run via `cargo run -p
stream-evidence` or the example; filters default to `Formats/Latest`
with `--all-paged` for suspected paged streams.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bab62b7b0ddd5a84e7b3a57b4902c4ed20ec445c. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: DrunkOnJava <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants