Skip to content

perf: cut sender seeks and receiver signature allocations - #8210

Merged
oferchen merged 15 commits into
masterfrom
perf/zero-alloc-reorder-buffer
Oct 20, 2026
Merged

oferchen merged 15 commits into
masterfrom
perf/zero-alloc-reorder-buffer

Conversation

@oferchen

@oferchen oferchen commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Sender seeks: the sender stops seeking between adjacent matched blocks. One CopySource reuses the file position and its BufReader, so a daemon push drops from 80,020 to 2,264 lseek calls and from 86,303 to 42,803 reads on the sender. Wall time drops 12-15% on daemon transfers.
  • Receiver signature buffers: signatures are built from one strided batch or window buffer instead of one Vec per block. Each block is released once it is on the wire, and the basis reader buffer is sized to the file. Pull receiver allocations fall 44% (177,818 to 98,935) and bytes 56% (1,361.5 MB to 600.3 MB).
  • Wire bytes: unchanged. Token framing, CHUNK_SIZE splitting, compressor dictionary bytes and checksum order are identical to master; the golden and parity tests below pin this.

Details

Sender.

  • DeltaToken has one Literal(Cow<'a, [u8]>) variant. Literals are borrowed on the parallel scan and owned on the sequential scan, and WireOp borrows them from the script instead of taking them by value.
  • On --parallel-delta-scan the script is detached with DeltaScript::into_owned() before the map is dropped, so each literal is copied once. Master copied twice, in merge_copy_runs and in the old resegment_literals.
  • Matched blocks for the inline whole-file checksum and the zlib dictionary are re-read through read(2) (CopySource), as on master. There is no mmap-backed checksum.

Receiver.

  • generate_file_signature fills one contiguous batch buffer, and the parallel entry point delegates to the windowed generator. Both produce output identical to master, including the short final block and the trailing-data and EOF checks.
  • FileSignature::release_blocks frees the block list once the request is written; delta reconstruction only reads layout().
  • The basis read buffer is basis_reader_capacity(size): the file size, clamped between 8 KiB and MAX_MAP_SIZE.

Fixed during review:

  • SIGBUS under --parallel-delta-scan. The emit pass borrowed from the source mmap while it could block on the network, so truncating the source mid-send killed the sender (exit 135). The map is now dropped after the scan and literals are owned. The truncate-during-send probe, a 256 MiB push under --bwlimit=16m with truncate -s 1M after 3 s:

    Binary --parallel-delta-scan Without it
    master 23 23
    original PR head 135 (SIGBUS) 23
    this head 23 23
  • Oversized strong-sum width. write_signature_blocks silently clamped s2length to 64. It now refuses any width above MAX_STRONG_SUM_LEN with InvalidInput, as upstream does (io.c:2279), because a truncated sum would desync the peer.

  • Multiplex frames. Oversized frames are back to a single staged write_all (io.c:1088, send_msg()).

  • Citations. The upstream citations deleted by the rewrite are restored: fileio.c:330-336 and match.c:197, 372-373.

Removed from the original PR. None of these carries a measurable share of the gain; see the attribution table.

Item Why removed
Reorder ring, engine ReorderBuffer, parallel-apply and chunk_adapter changes No production caller; reached only from tests and benches
CorkedTcpWriter removal Undid a merged perf feature without evidence; restored with its tests
Effective-id chown skip in ownership.rs Correctness bug: files in setgid directories, or on BSD/macOS, keep the wrong group
Pipeline window 64 to 32 Its rationale cited a nonexistent IOBUF_SIZE
is_new basis skip Overlaps the CVE-2026-53796 receiver work
cleanup.rs DashSet, CLI test locks, keep-dirlinks change, fixture permission tweaks Out of scope
DeltaOp::literal_data, DeltaToken::literal_data No production caller

Measurements.

  • Setup: release builds, a 4-core aarch64 VM and a loopback daemon. The dataset is 2000 x 16 KiB files plus 4 x 64 MiB files. The basis changes one byte in every fourth small file, and in each big file flips one byte per MiB plus a 37-byte insertion every 8 MiB.
  • Method: wall times are medians of 7 interleaved runs, with min-max in parentheses. Syscalls are strace -f -c totals, client + daemon.
  • Integrity: every run exited 0 and was byte-identical.
Cell master wall s this head wall s master syscalls this head syscalls
Daemon push 0.536 (0.507-0.704) 0.472 (0.463-0.670) 177,495 + 104,764 56,069 + 101,905
Daemon pull 0.491 (0.445-0.630) 0.419 (0.403-0.634) 181,588 + 179,078 151,163 + 56,922
Daemon push -z 0.521 (0.502-0.644) 0.490 (0.455-0.654) 177,379 + 174,746 56,092 + 198,800
Daemon push --parallel-delta-scan 0.452 (0.412-0.493) 0.384 (0.365-0.395) 178,294 + 124,986 56,711 + 125,401
Literal-heavy push (256 MiB, half literal) 6.633 (6.406-10.329) 6.383 (6.330-8.198) 20,124 (client) 12,041 (client)

The -z daemon total swings with futex wake-ups alone. Three repeats per binary gave 105,068 / 105,507 / 136,324 on master and 103,168 / 103,340 / 149,119 on this head. The I/O syscalls are equal or lower (read 8,106 to 7,594), and the client side is stable at about 177.5K on master against 56.1K on this head.

Attribution: the original PR head and this head match within noise on every cell. The exception is the parallel scan, where this head re-reads matched blocks through read(2) for SIGBUS safety (+32.8K reads) with wall time within noise.

Cell master wall s original head wall s this head wall s master syscalls original head syscalls this head syscalls
Local copy 0.291 0.289 0.290 49,013 49,015 49,024
Local delta 3.689 3.672 3.658 465,685 363,737 363,610
Daemon push 0.496 0.433 0.440 177,405 55,907 55,952
Daemon pull 0.497 0.457 0.468 241,390 56,830 56,560
Daemon push -z 0.622 0.578 0.572 177,398 55,939 55,951
Daemon push --parallel-delta-scan 0.574 0.491 0.516 177,855 23,681 56,471

Allocations were measured with DHAT on system-allocator builds. The pull receiver drops from 177,818 to 98,935 allocations and from 1,361.5 MB to 600.3 MB. The push sender is unchanged at 193,359, so the sender changes save syscalls, not allocations. Peak RSS is within 3% of master in every cell.

A candidate that folded the whole-file checksum into the scan cut sender syscalls by 77% but slowed the literal-heavy push by 20-30% in 7 of 7 runs, so it is not included.

Test plan

  • CI: fmt + clippy, nextest (stable), Windows, macOS, Linux musl.
  • Formatting: cargo fmt --all -- --check and python3 tools/ci/check_rustfmt_all.py.
  • Lint: cargo clippy -p matching -p transfer -p signature --all-targets --all-features --no-deps -- -D warnings.
  • Doc links: RUSTDOCFLAGS="-D rustdoc::broken_intra_doc_links" cargo doc -p matching --no-deps --document-private-items (it fails on the previous head's link to resegment_literals).
  • cargo nextest run -p matching -p signature --all-features: 607 passed.
  • cargo nextest run -p transfer --all-features -E 'test(/generator::delta|receiver::basis|receiver::wire|transfer_ops|generator::tests|receiver::tests::delta_apply/)': 379 passed.
  • cargo nextest run -p protocol --all-features -E 'test(/golden/)': 421 passed.
  • cargo nextest run -p engine --all-features -E 'binary(delta_reconstruction_tests) | binary(single_byte_transfer_tests)': 55 passed.
  • Placeholders: cargo run --locked -p xtask -- no-placeholders.
  • End-to-end edge matrix over a loopback daemon, plain and -z: every case exits 0 and is byte-identical on this head and on master. The cases are an empty file, a single byte, exactly one block, a short final block, all-literal, all-match, --block-size=131072, --inplace, and batch write plus --read-batch.

Each behaviour change is pinned by a test. Each new test was mutation-checked and goes red under its mutation:

Change Test Mutation
Seek skip on adjacent blocks generator::delta::tests::copy_source_skips_seek_for_adjacent_blocks_and_reseeks_otherwise Always seek: 4 seeks, expected 1. Keep the position after a short read: 2, expected 3.
Batched signature buffers, short final block round_trip::every_block_matches_direct_digests_across_batch_boundaries (36 blocks over 3 batches, 123-byte final block, MD4 and XXH3-128) Slice every block from the buffer start: block 1 strong digest mismatch
release_blocks file::tests::release_blocks_drops_blocks_and_keeps_layout clear() instead of freeing: capacity assertion fails
Basis reader sizing receiver::basis::tests::basis_reader_capacity_tracks_the_file_within_bounds Always MAX_MAP_SIZE: fails
s2length refusal oversized_strong_sum_length_is_refused Remove the bound check: fails
Literals detached before the map drops into_owned_detaches_borrowed_literals Drop literal_bytes in into_owned: fails
Literal(Cow) wire identity protocol golden tests, parallel_delta_wire_parity, zsync_wire_parity -

Removing into_owned() also fails to compile, because the map is moved into the scan arm and dropped there. The truncate-during-send exit 23 is covered by the probe table above rather than by a test, because a test would depend on timing to land the truncation mid-send.

Coordination

  • Related: the follow-ups found while profiling are tracked separately:
    • OpenSSL MD4 falls back to Rust on every call;
    • local delta verifies with MD4 where upstream negotiates xxh128;
    • per-block strong-sum Vec on the push sender;
    • per-file scan, index and window buffers;
    • streaming literal emit.
  • Depends on: none.
  • Blocked by: none.
  • Merge: squash merge recommended. The branch history contains add-then-drop commits from review.

Conventional commit prefix

  • perf: - performance improvement

Pre-merge checklist

  • Conventional commit prefix on PR title matches the change category.
  • cargo fmt --all run locally.
  • CHANGELOG.md updated if user-visible.
  • SECURITY.md updated if security-relevant.
  • No references to internal tooling or non-human authoring aids; hyphens, not em-dashes.

…ctor

Eliminate intermediate staging allocations, payload clones, and per-item
heap churn across the parallel execution and reorder pipeline:

- engine::concurrent_delta::reorder: add ReorderBuffer::try_insert()
  returning Err(item) on capacity overflow so run_bare_loop moves items
  across drain retries and force_insert without cloning DeltaResult.
- engine::concurrent_delta::parallel_apply: compact VerifiedChunk from
  184 B to 32 B (dropping the 68 B ChecksumDigest inside the worker),
  change FileSlot::reorder from ReorderBuffer<DeltaChunk> (112 B/slot)
  to ReorderBuffer<Box<[u8]>> (16 B fat pointer per slot), and stream
  next_in_order() directly to the writer in FileSlot::ingest without
  collecting into an intermediate Vec.
- transfer::reorder_buffer: replace BTreeMap<u64, T> and Vec<T> returns
  in BoundedReorderBuffer<T> with a flat circular ring Vec<Option<T>>
  and stack-inline DrainedItems<T> (Empty | Single | Batch) for zero
  heap allocations on in-order and passthrough items.
- matching::generator: add scan_stripe_runs (emit_literals = false) so
  parallel stripe workers emit only 24 B CopyRun descriptors without
  allocating per-worker literal buffers, and slice gap literals directly
  from source in merge_copy_runs in a single pass.
- signature: replace per-block Vec<Vec<u8>> and per-batch Vec<&[u8]> /
  Vec<RollingDigest> allocations in sequential and parallel signature
  generation with a single contiguous read buffer and stack arrays;
  add FileSignature::release_blocks() and invoke it in
  transfer_ops::request immediately after wire serialization.
- transfer::receiver & writer: lease a pooled BufferGuard in basis.rs
  for small basis files and release it inside the rayon worker before
  entering the reorder stage; use a 68 B stack buffer in wire.rs; use
  IoSlice write_vectored in MultiplexBuffer for oversized frames.
- Wire source_mmap into write_delta_with_inline_checksum so matched blocks read directly from memory rather than re-opening and seeking
- Add DeltaToken::LiteralSlice and lifetime-parameterized DeltaScript to borrow literal bytes without heap allocation
- Use WireOp to stream literals and copy ops to wire format without intermediate vector allocations
- Replace Vec<u8> in DeltaChunk with Box<[u8]> to eliminate capacity reallocations in the parallel delta applier
- Fix test fixture permissions to guarantee umask independence across platforms
@oferchen
oferchen force-pushed the perf/zero-alloc-reorder-buffer branch from 0df1321 to 4b11fd0 Compare October 18, 2026 14:46
@oferchen
oferchen marked this pull request as draft October 18, 2026 14:49
… pipeline window

- crates/core: eliminate CorkedTcpWriter on daemon connections to match
  upstream rsync TCP semantics, removing 40ms delayed-ACK stalls on sub-MSS writes
- crates/transfer: set DEFAULT_PIPELINE_WINDOW to 32, matching upstream rsync's
  IOBUF_SIZE (32 KiB) to prevent socket write buffer saturation
- crates/transfer: propagate is_new (ITEM_IS_NEW) through the transfer pipeline,
  skipping basis file lookup and statx(ENOENT) checks on new destination paths
  matching upstream generator.c:2378
- crates/engine: switch CleanupManager to lock-free DashSet and box LocalCopyMetadata
- crates/metadata: skip redundant chown calls when destination ownership matches
- crates/cli/src/frontend/tests/common.rs: acquire RUN_LOCK in run_with_args
  to serialize top-level reentrant cli::run invocations across test worker threads
- crates/cli/src/frontend/tests/parse_max_alloc.rs: enforce ENV_LOCK guards
  around environment variable mutations and test runs
- crates/cli/src/frontend/tests/clap.rs: route test invocation through run_with_args
- src/bin/client.rs: add TEST_LOCK to serialize client test runs
Restores CorkedTcpWriter, the ownership chown decision, the 64-entry
pipeline window and the pre-existing basis checks, and removes the
cleanup DashSet and CLI test locks. These change behaviour outside the
zero-copy delta and reorder-buffer scope and need their own measured PRs.
Drops the LiteralSlice variant and the two literal_data helpers, restores
master behaviour for the multiplex oversized-frame write, and keeps the
basis reader capacity clamp as the only small-basis change.
The ring was pre-sized to min(window, 2^20) while admission still allowed
any offset below the window, so a release build wrapped a deep gap onto an
occupied slot. Growing by doubling from 16 slots also keeps memory at the
observed reorder depth instead of the configured window. The sender emit
pass now feeds matched blocks through one CopySource helper.
BoundedReorderBuffer, the engine ReorderBuffer and the parallel-apply
consumer have no production caller, so their rewrite can neither carry nor
be gated by a transfer-level measurement. Also refuse an oversized strong
sum width in write_signature_blocks instead of silently clamping it.
With --parallel-delta-scan the emit pass borrowed literals and matched
blocks from the source map while it could block on the network, so a
truncation of the source mid-send killed the sender with SIGBUS (exit 135)
where master reports a read error (exit 23). The script is now detached
with into_owned() and the map dropped before emitting; matched blocks are
re-read through read(2) as on master.
@oferchen oferchen changed the title perf: zero-copy delta pipeline and memory-mapped sender checksumming perf: cut sender seeks and receiver signature allocations Oct 20, 2026
The parallel merge frames gap literals with push_split_literal_slice;
resegment_literals no longer exists, so its doc link was broken.
CopySource is generic over its reader so a counting Seek can show that
adjacent matched blocks share one seek, and that a literal gap or a short
read forces a re-seek. Always seeking still yields correct bytes, so only
a seek count catches that regression.
The sequential generator hashes blocks from one strided batch buffer and
the parallel path delegates to it, so parity between them cannot catch a
slicing slip. Compare each block of a three-batch file with a short final
block against rolling and strong digests computed over its own bytes.
release_blocks must free the block list while keeping the layout and
total bytes. The basis read buffer is now a named function sized to the
file within a floor and the MAX_MAP_SIZE window, with its bounds tested.
@oferchen
oferchen marked this pull request as ready for review October 20, 2026 09:47
@oferchen
oferchen enabled auto-merge (squash) October 20, 2026 11:43
@oferchen
oferchen merged commit ddde389 into master Oct 20, 2026
86 of 87 checks passed
@oferchen
oferchen deleted the perf/zero-alloc-reorder-buffer branch October 20, 2026 11:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant