Skip to content

feat(engine): implement real verify_chunk in ParallelDeltaApplier (BR-3i.c) - #4640

Merged
oferchen merged 1 commit into
masterfrom
feat/engine-real-verify-chunk-br3ic
May 21, 2026
Merged

oferchen merged 1 commit into
masterfrom
feat/engine-real-verify-chunk-br3ic

Conversation

@oferchen

Copy link
Copy Markdown
Owner

Summary

BR-3i.c (#2499) - replace the length-only verify_chunk stub in ParallelDeltaApplier with a real strong-checksum dispatch through the negotiated ChecksumStrategy plumbed in by BR-3i.b (#4616). This is the production-blocker that the README called out as gap (1) for shipping parallel-receive-delta as default; with this change the feature's verify path is real, not a no-op.

Before / after

// before (BR-3i.b)
fn verify_chunk(chunk: DeltaChunk) -> VerifiedChunk {
    let digest_len = chunk.data.len();   // stub: no real verification
    VerifiedChunk { chunk, digest_len }
}

// after (BR-3i.c)
fn verify_chunk(
    strategy: &dyn ChecksumStrategy,
    chunk: DeltaChunk,
) -> Result<VerifiedChunk, ParallelApplyError> {
    let digest = strategy.compute(&chunk.data);
    if let Some(expected) = chunk.expected_strong.as_ref() {
        if expected != &digest {
            return Err(ParallelApplyError::ChecksumMismatch {
                ndx: chunk.ndx,
                chunk_sequence: chunk.chunk_sequence,
                algorithm: strategy.algorithm_kind(),
                expected: hex_lower(expected.as_bytes()),
                actual: hex_lower(digest.as_bytes()),
            });
        }
    }
    Ok(VerifiedChunk { chunk, digest })
}

DeltaChunk gains an optional expected_strong: Option<ChecksumDigest> plus a builder method with_expected_strong(). Existing constructors leave it None so all current callers (the parallel-receive-delta bench, the existing tests) keep compiling unchanged.

Error path

  • New variant ParallelApplyError::ChecksumMismatch { ndx, chunk_sequence, algorithm, expected, actual } carrying both hex digests.
  • The variant flows through the existing From<ParallelApplyError> for io::Error impl, so apply_chunk_parallel and apply_batch_parallel keep their io::Result<()> shape; the receiver can fall back to a phase-2 redo or abort the file without committing corrupt bytes.
  • Verification happens before the per-file mutex is taken; on mismatch the destination writer is never touched (proven by verify_chunk_rejects_mismatched_digest_and_does_not_write).
  • apply_batch_parallel's rayon parallel collect short-circuits on the first error variant, surfaced via Result<Vec<_>, _> collection.

Wire-format invariant

Unchanged. DeltaChunk is purely a receiver-side in-memory staging structure; expected_strong is held in process memory only and never serialised onto the wire. Protocol golden tests stay green.

Coverage

In addition to keeping the existing 13 parallel_apply tests green, this PR adds five regression tests:

  • verify_chunk_accepts_matching_digest_md5 - MD5 happy path (protocol >= 30 default)
  • verify_chunk_accepts_matching_digest_xxh3 - XXH3 happy path, proves dispatch routes through the configured strategy
  • verify_chunk_rejects_mismatched_digest_and_does_not_write - single-chunk mismatch surfaces typed error, writer stays empty
  • verify_batch_rejects_mismatched_digest - batch mismatch short-circuits cleanly
  • parallel_apply_with_real_digests_matches_sequential_byte_for_byte - BR-3i.e parity guarantee with real per-chunk verification under a deterministic permutation
  • checksum_mismatch_error_converts_into_io_error_with_typed_message - typed io::Error round-trip

The obsolete with_strategy_does_not_change_verify_chunk_behaviour test (which asserted the stub behaviour) is replaced by unverified_chunk_preserves_writer_byte_stream, which now documents that chunks with expected_strong = None still compute a digest (stable CPU cost) but skip comparison.

Constraints respected

  • No new dependencies (checksums is already an engine workspace dep).
  • No unsafe added in the engine crate.
  • No #[allow(...)] waivers; clippy -D warnings is clean.
  • Public API of ParallelDeltaApplier is preserved (one new method on DeltaChunk, one new error variant).

Rebase notes

Based on origin/master at 93aed9663. BR-3j.c (#4634) is still open and modifies the files field + slot_for / register_file / finish_file on the same struct (DashMap migration). Those touches do not overlap verify_chunk or DeltaChunk, so the rebase points are minimal: whichever PR merges first, the other will need to rebase, and the conflict should be confined to the strategy / verify path keeping its Mutex<HashMap> vs DashMap access pattern.

README update

The cargo-feature table entry for parallel-receive-delta previously listed two GA-blocking gaps. Gap (1) (verify_chunk scaffold) is closed by this PR; the entry is updated to reflect that and to keep gap (2) (BR-3j outer mutex) tracked as the remaining blocker.

Verification

  • cargo fmt --all -- --check clean
  • cargo clippy --workspace --all-targets --all-features --no-deps -- -D warnings clean
  • cargo nextest run -p engine --features parallel-receive-delta - 4379 passed
  • cargo nextest run -p protocol --all-features -E 'test(golden)' - 407 passed
  • cargo build -p engine --features parallel-receive-delta --benches clean

Test plan

  • CI: fmt + clippy
  • CI: nextest stable, Windows, macOS, Linux musl
  • CI: protocol golden tests
  • CI: interop matrix (no wire change expected)

…-3i.c)

Replace the length-only verify stub with a real strong-checksum
dispatch through the negotiated `ChecksumStrategy` plumbed in BR-3i.b
(#4616). Chunks may opt into per-chunk verification by attaching an
`expected_strong: ChecksumDigest` through the new `with_expected_strong`
builder; the applier computes the digest of `chunk.data` on the rayon
worker and compares byte-for-byte before the per-file write happens.

Mismatches surface as a typed `ParallelApplyError::ChecksumMismatch`
carrying ndx, sequence, algorithm, and both hex digests, then convert
into `io::Error` at the public boundary so the receiver can fall back
to a phase-2 redo or abort the file without committing corrupt bytes.
Chunks with no expected digest still compute the digest (keeping the
parallel-verify CPU cost stable across both shapes) but skip the
comparison, preserving backward compatibility for existing call sites.

The wire format is unchanged - `DeltaChunk` is purely a receiver-side
staging structure and the expected digest is held in-memory only.

This closes the GA-blocking gap on `parallel-receive-delta` that was
called out in the README feature table; the only remaining GA gap is
the outer `Mutex<HashMap<FileNdx, _>>` (BR-3j.a-f, in flight on
#4634).

Adds five regression tests, including BR-3i.e parity:
- happy-path verification for MD5 and XXH3
- single-chunk mismatch surfaces typed error and skips the writer
- batch mismatch short-circuits with typed error
- parallel apply with real digests is byte-identical to sequential
- ChecksumMismatch -> io::Error conversion carries the typed message
@github-actions github-actions Bot added the enhancement New feature or request label May 21, 2026
@oferchen
oferchen merged commit a6058b1 into master May 21, 2026
63 checks passed
@oferchen
oferchen deleted the feat/engine-real-verify-chunk-br3ic branch May 21, 2026 02:25
oferchen added a commit that referenced this pull request May 21, 2026
…ure (BR-3i.d) (#4646)

Add a wire-token to `DeltaChunk` adapter in `delta_pipeline::chunk_builder`
that looks up the basis signature's strong digest for every `BlockRef`
(COPY-equivalent) token and stamps it into `DeltaChunk::expected_strong`
via the builder added on the applier side by BR-3i.c (#4640). Literal
tokens leave the field as `None`: the sender does not embed per-literal
digests, and the applier already skips comparison when nothing is set.

Without this wiring, every basis-match chunk produced for the parallel
receive-delta path slips through `ParallelDeltaApplier::verify_chunk` in
"compute digest, skip comparison" mode, so corrupted basis bytes commit
silently to the destination. With the wiring in place, the receiver-side
verify-chain end-to-end gate added in BR-3i.c finally fires: a basis
whose actual bytes differ from the digest the receiver shipped surfaces
as `ParallelApplyError::ChecksumMismatch` before the per-file mutex is
taken, leaving the destination writer untouched.

The adapter is wire-protocol-free - it never touches the network reader,
the decompressor dictionary, or the disk-commit thread. The caller hands
in already-resolved literal bytes or already-mapped basis bytes, and the
builder produces a `DeltaChunk` with the per-file sequence number bumped
exactly once per emitted chunk. Out-of-bounds block indices and
basis-length disagreements surface as typed `ChunkBuilderError` variants
so the receiver can abort the file without ever feeding mismatched bytes
into the verify step (which would otherwise be reported as a
checksum-mismatch for the wrong reason).

No wire-protocol changes - `DeltaChunk` is purely a receiver-side staging
structure and the expected digest is held in-memory only. Public API of
`ParallelDeltaApplier` is unchanged.

Tests cover the BR-3i.d acceptance criteria:
- copy chunks populate `expected_strong` from the signature
- literal chunks leave `expected_strong = None`
- end-to-end: a corrupted basis surfaces `ChecksumMismatch` and never
  reaches the destination writer
- out-of-bounds block index surfaces typed error without bumping the
  sequence counter
- basis-length mismatch surfaces typed error before verify
- `next_chunk` dispatches each token variant correctly
- `TokenForBuild::from_block_ref` filters non-BlockRef tokens
oferchen added a commit that referenced this pull request May 21, 2026
…roughput (BR-3i.f)

BR-3i.c (PR #4640) replaced the length-only verify stub with a real
strategy.compute(&chunk.data) comparison, so the per-chunk verify path
now has measurable CPU cost. Adds a criterion harness in
crates/engine/benches/parallel_verify_chunk.rs that sweeps:

  - Workload A: 4 files x 256 chunks x 1 MiB (large/few)
  - Workload B: 256 files x 64 chunks x 16 KiB (small/many)
  - Threads: 1, 2, 4, 8, and available_parallelism()
  - Strategies: MD4, MD5, XXH3 (the BR-3i.b supported set)

Each cell pins both the applier concurrency limit and the rayon pool
via ThreadPoolBuilder + pool.install so the dispatch surface is
genuinely thread-bound. Payloads come from a seeded SmallRng keyed by
(workload, file, chunk) for byte-identical reproducibility across
runs. Per-chunk expected_strong digests are pre-computed outside the
timed loop so each iteration exercises the full compute + compare path.

Group throughput reports bytes/sec; chunks/sec is derivable from the
per-cell chunk count and the reported wall time. No new runtime deps;
rand is added to engine dev-dependencies (already a workspace dev-dep).
oferchen added a commit that referenced this pull request May 21, 2026
…roughput (BR-3i.f) (#4653)

BR-3i.c (PR #4640) replaced the length-only verify stub with a real
strategy.compute(&chunk.data) comparison, so the per-chunk verify path
now has measurable CPU cost. Adds a criterion harness in
crates/engine/benches/parallel_verify_chunk.rs that sweeps:

  - Workload A: 4 files x 256 chunks x 1 MiB (large/few)
  - Workload B: 256 files x 64 chunks x 16 KiB (small/many)
  - Threads: 1, 2, 4, 8, and available_parallelism()
  - Strategies: MD4, MD5, XXH3 (the BR-3i.b supported set)

Each cell pins both the applier concurrency limit and the rayon pool
via ThreadPoolBuilder + pool.install so the dispatch surface is
genuinely thread-bound. Payloads come from a seeded SmallRng keyed by
(workload, file, chunk) for byte-identical reproducibility across
runs. Per-chunk expected_strong digests are pre-computed outside the
timed loop so each iteration exercises the full compute + compare path.

Group throughput reports bytes/sec; chunks/sec is derivable from the
per-cell chunk count and the reported wall time. No new runtime deps;
rand is added to engine dev-dependencies (already a workspace dev-dep).
oferchen added a commit that referenced this pull request Aug 24, 2026
…-3i.c) (#4640)

Replace the length-only verify stub with a real strong-checksum
dispatch through the negotiated `ChecksumStrategy` plumbed in BR-3i.b
(#4616). Chunks may opt into per-chunk verification by attaching an
`expected_strong: ChecksumDigest` through the new `with_expected_strong`
builder; the applier computes the digest of `chunk.data` on the rayon
worker and compares byte-for-byte before the per-file write happens.

Mismatches surface as a typed `ParallelApplyError::ChecksumMismatch`
carrying ndx, sequence, algorithm, and both hex digests, then convert
into `io::Error` at the public boundary so the receiver can fall back
to a phase-2 redo or abort the file without committing corrupt bytes.
Chunks with no expected digest still compute the digest (keeping the
parallel-verify CPU cost stable across both shapes) but skip the
comparison, preserving backward compatibility for existing call sites.

The wire format is unchanged - `DeltaChunk` is purely a receiver-side
staging structure and the expected digest is held in-memory only.

This closes the GA-blocking gap on `parallel-receive-delta` that was
called out in the README feature table; the only remaining GA gap is
the outer `Mutex<HashMap<FileNdx, _>>` (BR-3j.a-f, in flight on
#4634).

Adds five regression tests, including BR-3i.e parity:
- happy-path verification for MD5 and XXH3
- single-chunk mismatch surfaces typed error and skips the writer
- batch mismatch short-circuits with typed error
- parallel apply with real digests is byte-identical to sequential
- ChecksumMismatch -> io::Error conversion carries the typed message
oferchen added a commit that referenced this pull request Aug 24, 2026
…ure (BR-3i.d) (#4646)

Add a wire-token to `DeltaChunk` adapter in `delta_pipeline::chunk_builder`
that looks up the basis signature's strong digest for every `BlockRef`
(COPY-equivalent) token and stamps it into `DeltaChunk::expected_strong`
via the builder added on the applier side by BR-3i.c (#4640). Literal
tokens leave the field as `None`: the sender does not embed per-literal
digests, and the applier already skips comparison when nothing is set.

Without this wiring, every basis-match chunk produced for the parallel
receive-delta path slips through `ParallelDeltaApplier::verify_chunk` in
"compute digest, skip comparison" mode, so corrupted basis bytes commit
silently to the destination. With the wiring in place, the receiver-side
verify-chain end-to-end gate added in BR-3i.c finally fires: a basis
whose actual bytes differ from the digest the receiver shipped surfaces
as `ParallelApplyError::ChecksumMismatch` before the per-file mutex is
taken, leaving the destination writer untouched.

The adapter is wire-protocol-free - it never touches the network reader,
the decompressor dictionary, or the disk-commit thread. The caller hands
in already-resolved literal bytes or already-mapped basis bytes, and the
builder produces a `DeltaChunk` with the per-file sequence number bumped
exactly once per emitted chunk. Out-of-bounds block indices and
basis-length disagreements surface as typed `ChunkBuilderError` variants
so the receiver can abort the file without ever feeding mismatched bytes
into the verify step (which would otherwise be reported as a
checksum-mismatch for the wrong reason).

No wire-protocol changes - `DeltaChunk` is purely a receiver-side staging
structure and the expected digest is held in-memory only. Public API of
`ParallelDeltaApplier` is unchanged.

Tests cover the BR-3i.d acceptance criteria:
- copy chunks populate `expected_strong` from the signature
- literal chunks leave `expected_strong = None`
- end-to-end: a corrupted basis surfaces `ChecksumMismatch` and never
  reaches the destination writer
- out-of-bounds block index surfaces typed error without bumping the
  sequence counter
- basis-length mismatch surfaces typed error before verify
- `next_chunk` dispatches each token variant correctly
- `TokenForBuild::from_block_ref` filters non-BlockRef tokens
oferchen added a commit that referenced this pull request Aug 24, 2026
…roughput (BR-3i.f) (#4653)

BR-3i.c (PR #4640) replaced the length-only verify stub with a real
strategy.compute(&chunk.data) comparison, so the per-chunk verify path
now has measurable CPU cost. Adds a criterion harness in
crates/engine/benches/parallel_verify_chunk.rs that sweeps:

  - Workload A: 4 files x 256 chunks x 1 MiB (large/few)
  - Workload B: 256 files x 64 chunks x 16 KiB (small/many)
  - Threads: 1, 2, 4, 8, and available_parallelism()
  - Strategies: MD4, MD5, XXH3 (the BR-3i.b supported set)

Each cell pins both the applier concurrency limit and the rayon pool
via ThreadPoolBuilder + pool.install so the dispatch surface is
genuinely thread-bound. Payloads come from a seeded SmallRng keyed by
(workload, file, chunk) for byte-identical reproducibility across
runs. Per-chunk expected_strong digests are pre-computed outside the
timed loop so each iteration exercises the full compute + compare path.

Group throughput reports bytes/sec; chunks/sec is derivable from the
per-cell chunk count and the reported wall time. No new runtime deps;
rand is added to engine dev-dependencies (already a workspace dev-dep).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant