Skip to content

feat(engine): add flush_workers/drain_inflight barrier API to ParallelDeltaApplier (FFB-2) - #4665

Merged
oferchen merged 4 commits into
masterfrom
feat/engine-flush-workers-ffb2
May 21, 2026
Merged

oferchen merged 4 commits into
masterfrom
feat/engine-flush-workers-ffb2

Conversation

@oferchen

Copy link
Copy Markdown
Owner

Summary

Implements the FFB-1 design (PR #4659) for the missing barrier
primitive on ParallelDeltaApplier::finish_file.

The slot value in the outer DashMap changes from
Arc<Mutex<FileSlot>> to Arc<SlotBarrier>, where SlotBarrier
colocates the file mutex with a (Mutex<usize>, Condvar) pair that
tracks outstanding worker references. slot_for now returns a
SlotHandle RAII guard whose Drop impl decrements the in-flight
counter and wakes flush_workers waiters, keeping the bookkeeping
exception-safe across early returns and panics.

Public API additions

  • flush_workers(ndx) - blocks until the slot has zero in-flight
    handles. Returns Ok(()) immediately when the slot is absent
    (already finalised through finish_file or never registered),
    matching the design's "absence is the same observable outcome as
    fully-drained" contract.
  • drain_inflight() - snapshots registered ndx values and waits on
    each via flush_workers. Implemented as the thin loop FFB-1
    recommended for session shutdown.
  • finish_file(ndx) - now bakes flush_workers in (Option D from
    the design doc). Existing callers keep working with no migration:
    per-file completion is one call, and the barrier disappears as
    invisible correctness infrastructure.

ApplierStillReferenced reframing

The typed ParallelApplyError::ApplierStillReferenced variant
stays as the public API per the design, but its semantics shift
from "transient race the caller might observe" to "post-barrier
invariant violation worth filing an issue over". The only ways the
variant can fire post-FFB-2 are:

  1. A caller raced a new slot_for against finish_file after
    flush_workers returned and before DashMap::remove ran (a
    call-site bug).
  2. A SlotHandle outlived its DecrementGuard (an internal bug in
    this module).

Either way, observing the variant in production is now actionable
diagnostic signal rather than a recoverable race. The Display
payload (ndx, strong_count, kind) is unchanged so existing log
scrapers keep working.

Test plan

New unit tests in crates/engine/src/concurrent_delta/parallel_apply.rs::tests:

  • flush_workers_returns_immediately_when_no_inflight - zero
    in-flight returns in well under 50ms.
  • flush_workers_returns_ok_for_unknown_ndx - absent slot is a
    no-op.
  • flush_workers_blocks_until_worker_drops_arc - worker holds
    a handle for 50ms; flush_workers measured elapsed >= 40ms.
  • drain_inflight_drains_all_files - 6 workers, each holding a
    handle for 40ms; drain_inflight measured elapsed >= 30ms.
  • finish_file_calls_flush_workers_internally - worker holds
    handle for 40ms; finish_file blocks then succeeds.
  • flush_workers_survives_spurious_wakeup - AtomicBool gate
    proves the flusher did not exit until the real decrement
    fired, even after 5 spurious notify_all() calls.

Removed test: arc_drain_panic_recovery::parallel_apply_drain::parallel_applier_finish_file_surfaces_typed_applier_still_referenced. That test exercised the now-impossible scenario where finish_file raced a worker blocked inside the per-file slot lock. With the barrier baked in, the scenario is a deadlock by construction rather than an observable race. The module doc note explains the FFB-2 rationale.

CI will exercise the new tests under the default
parallel-receive-delta feature plus the existing concurrent
stress tests (parallel_apply_concurrent.rs).

Local verification

Skipped per current user direction (CI is the verification gate).
The implementation compiles cleanly under cargo check -p engine --features parallel-receive-delta; format, clippy, and nextest
will run via CI.

Cross-references

@oferchen
oferchen force-pushed the feat/engine-flush-workers-ffb2 branch from 2d4055e to d1578a0 Compare May 21, 2026 10:21
oferchen added 3 commits May 21, 2026 16:44
Implements the FFB-1 design (PR #4659) for the
ParallelDeltaApplier::finish_file barrier primitive.

Replaces the per-slot Arc<Mutex<FileSlot>> with Arc<SlotBarrier>,
where SlotBarrier colocates the file mutex with a (Mutex<usize>,
Condvar) pair that tracks outstanding worker references. slot_for
now returns a SlotHandle RAII guard whose Drop impl decrements the
in-flight counter and wakes flush_workers waiters, keeping the
bookkeeping exception-safe across early returns and panics.

Public API additions:
- flush_workers(ndx): blocks until the slot has zero in-flight
  handles (no-op if the slot is absent).
- drain_inflight(): snapshots registered ndx values and waits on
  each via flush_workers, used by shutdown/abort paths.
- finish_file(ndx): now bakes flush_workers in (Option D from the
  design doc) so existing callers keep working with no migration.

ApplierStillReferenced is reframed from a transient race the caller
might observe into a post-barrier invariant violation worth filing
an issue over; the typed variant remains for diagnostic value.

Test additions in parallel_apply.rs:
- flush_workers_returns_immediately_when_no_inflight
- flush_workers_returns_ok_for_unknown_ndx
- flush_workers_blocks_until_worker_drops_arc
- drain_inflight_drains_all_files
- finish_file_calls_flush_workers_internally
- flush_workers_survives_spurious_wakeup

The previously-passing arc_drain_panic_recovery::parallel_apply_drain
test exercised the now-impossible race scenario (worker blocked inside
the slot mutex while finish_file races); that test is removed and the
module doc notes the FFB-2 rationale.

Local verification skipped per user direction; CI is the verification
gate.
Both finish_file_calls_flush_workers_internally and
drain_inflight_drains_all_files used a sleep(5ms) to "let the worker
acquire the SlotHandle" before invoking the barrier call. On macOS
the sleep was insufficient under load - main reached finish_file
before the worker entered slot_for, inflight stayed 0, the barrier
returned immediately, and the elapsed-time assertion fired (observed
18ms < 30ms threshold).

Replaced with an mpsc handshake: the worker sends () after acquiring
the handle, main blocks on recv_timeout before starting the barrier
call. Deterministic across platforms.
Third sibling of the same race pattern: flush_workers_blocks_until_worker_drops_arc
used sleep(5ms) to let the worker acquire the SlotHandle before
starting the timer. macOS nightly didn't schedule the worker in time,
flush_workers returned inflight=0 immediately, and the
elapsed >= 40ms assertion fired.

Same fix as the earlier two tests: replace sleep with an mpsc channel
that the worker pings after acquiring the handle, and main blocks on
recv_timeout before starting the timer.
@oferchen
oferchen force-pushed the feat/engine-flush-workers-ffb2 branch from 641496d to 556a53b Compare May 21, 2026 13:44
Windows nextest surfaced strong_count=2 panics where flush_workers
returned with inflight==0 but the worker's DecrementGuard still held
an Arc<SlotBarrier> clone. The drop sequence is:

1. SlotHandle drops, fields drop in declaration order
2. barrier field (Arc<SlotBarrier>) drops - one ref released
3. _decrement field (DecrementGuard) drops:
   a. Drop body calls decrement_inflight() which acquires the
      inflight mutex, sets the counter to 0, notifies the Condvar
   b. After the body returns, DecrementGuard's own Arc<SlotBarrier>
      clone drops - second ref released

flush_workers wakes on the Condvar notify at step 3a. Main thread
proceeds to DashMap::remove + Arc::try_unwrap, but the worker's
DecrementGuard is still between 3a and 3b - the Arc clone is alive.

Surfaces reliably on Windows under load; intermittent on macOS;
mostly invisible on Linux.

Fix: after flush_workers, spin-then-yield on strong_count > 1 until
the DecrementGuard's drop body completes and its Arc clone is
released. Bounded at 1000 iterations (32 spin_loop + 968 yield_now)
so a real invariant violation (caller raced a new slot_for) still
surfaces ApplierStillReferenced after ~ms, not hangs.

Root-cause-clean fix would refactor DecrementGuard to not hold an
Arc<SlotBarrier> (use Weak, or a separate Arc<(Mutex,Condvar)>
struct), but that is a bigger surgery; this minimal patch closes
the Windows test regression.
oferchen added a commit that referenced this pull request May 21, 2026
…pping_files

Cross-tree fix bundled with SSC-1 because this master-side flaky stress
test has been blocking CI on multiple unrelated PRs (#4663, #4665, #4667).

The race: SMALL_OPS=4000 dispatcher operations spread across WORKERS rayon
workers can complete before the registrar's first `register_file(0, ...)`
returns. When that happens every `apply_chunk_parallel` returns the
typed "unknown" error, `expected` (the success-byte counter) stays 0,
and the sanity assertion `assert!(expected > 0)` at line 264 fires.
The probability is small on Linux but reliably observable on Windows
under the tracing feature build.

Added a separate `registrations_done` AtomicU64 the registrar bumps after
each `register_file` returns. Workers block on `registrations_done >= 1`
via yield_now before starting their dispatch loop. The race against the
registrar for ndx >= 1 is preserved, so the test still stresses the
register-vs-dispatch surface.

Followup candidates: SMALL_NUM/SMALL_OPS retuning, deterministic injection
points - not necessary for the immediate unblock.
oferchen added a commit that referenced this pull request May 21, 2026
…PIP-3+5 wire-up (#4677)

Combined closure note covering three trackers whose deliverables have
already shipped or were absorbed into existing design surface:

- PIP-2 (#2565): the design doc was supposed to describe the
  token_loop -> ParallelDeltaApplier migration. That document already
  exists as docs/design/parallel-receive-delta-default-on.md
  (shipped in PR #4319 scaffold, extended by PR #4666 default-on
  flip). Marked completed retroactively.
- FFB-3 (#2576): conditional task that only activated if FFB-1 chose
  Option A or B. FFB-1 (PR #4659) chose Option D - barrier baked into
  finish_file - so every existing caller already gets the barrier
  without callsite migration. Marked deferred N-A.
- FFB-4 (#2577): explicit flush_workers call at the PIP-3 wire-up
  site. PIP-3 + PIP-5 (PR #4666 merged) routes through finish_file,
  which already barriers via Option D. No explicit call needed.
  Marked satisfied-by-design.

Note: FFB-2 implementation (PR #4665, in CI) needed a spin-then-yield
fix around finish_file's try_unwrap to close a Windows release-race;
future work to restructure DecrementGuard would be FFB-5+ if filed.

No source changes.
@oferchen
oferchen merged commit 5e675f4 into master May 21, 2026
55 checks passed
@oferchen
oferchen deleted the feat/engine-flush-workers-ffb2 branch May 21, 2026 14:52
oferchen added a commit that referenced this pull request May 21, 2026
…H -C (SSC-1) (#4667)

* feat(core): warn on double-compression when --compress meets SSH -C (SSC-1)

Emit a one-time stderr warning at SSH spawn time when both rsync wire
compression (--compress) and SSH stream compression (-C / -o Compression=yes
on the rsync `-e ssh ...` invocation) are enabled. SSH cannot meaningfully
recompress the already-compressed rsync stream, so doing both wastes CPU
and can occasionally expand the payload.

Detection is conservative: it only inspects the SSH command-line built by
the user via `-e` / `--rsh`. Parsing `~/.ssh/config` is left to SSC-3
(#2563); the documentation companion lives in SSC-2 (#2562).

The emitter uses a process-global `OnceLock<bool>` so subsequent SSH
spawns in the same process do not flood stderr. The detection predicate
is split out into a `should_warn_double_compression` helper so the four
new tests (warns_on_double_compression, no_warning_when_only_rsync_compress,
no_warning_when_only_ssh_compress, no_warning_when_neither_compresses)
can exercise the logic without depending on `OnceLock` state.

* fix(engine): close race in concurrent_register_and_dispatch_on_overlapping_files

Cross-tree fix bundled with SSC-1 because this master-side flaky stress
test has been blocking CI on multiple unrelated PRs (#4663, #4665, #4667).

The race: SMALL_OPS=4000 dispatcher operations spread across WORKERS rayon
workers can complete before the registrar's first `register_file(0, ...)`
returns. When that happens every `apply_chunk_parallel` returns the
typed "unknown" error, `expected` (the success-byte counter) stays 0,
and the sanity assertion `assert!(expected > 0)` at line 264 fires.
The probability is small on Linux but reliably observable on Windows
under the tracing feature build.

Added a separate `registrations_done` AtomicU64 the registrar bumps after
each `register_file` returns. Workers block on `registrations_done >= 1`
via yield_now before starting their dispatch loop. The race against the
registrar for ndx >= 1 is preserved, so the test still stresses the
register-vs-dispatch surface.

Followup candidates: SMALL_NUM/SMALL_OPS retuning, deterministic injection
points - not necessary for the immediate unblock.
oferchen added a commit that referenced this pull request May 25, 2026
…(DG-4.a) (#4963)

Specifies the surgical removal of the spin-then-yield block in
ParallelDeltaApplier::finish_file (introduced by PR #4665 as a
stop-gap) now that the DG-3 BarrierState/SlotData split has shipped.
Documents the exact lines to delete, the safety argument, the
mechanical removal procedure, the regression-test gating, and the
rollback procedure. The follow-up DG-4 code PR applies the deletion.
oferchen added a commit that referenced this pull request Aug 24, 2026
…PIP-3+5 wire-up (#4677)

Combined closure note covering three trackers whose deliverables have
already shipped or were absorbed into existing design surface:

- PIP-2 (#2565): the design doc was supposed to describe the
  token_loop -> ParallelDeltaApplier migration. That document already
  exists as docs/design/parallel-receive-delta-default-on.md
  (shipped in PR #4319 scaffold, extended by PR #4666 default-on
  flip). Marked completed retroactively.
- FFB-3 (#2576): conditional task that only activated if FFB-1 chose
  Option A or B. FFB-1 (PR #4659) chose Option D - barrier baked into
  finish_file - so every existing caller already gets the barrier
  without callsite migration. Marked deferred N-A.
- FFB-4 (#2577): explicit flush_workers call at the PIP-3 wire-up
  site. PIP-3 + PIP-5 (PR #4666 merged) routes through finish_file,
  which already barriers via Option D. No explicit call needed.
  Marked satisfied-by-design.

Note: FFB-2 implementation (PR #4665, in CI) needed a spin-then-yield
fix around finish_file's try_unwrap to close a Windows release-race;
future work to restructure DecrementGuard would be FFB-5+ if filed.

No source changes.
oferchen added a commit that referenced this pull request Aug 24, 2026
…lDeltaApplier (FFB-2) (#4665)

* feat(engine): add flush_workers/drain_inflight barrier API (FFB-2)

Implements the FFB-1 design (PR #4659) for the
ParallelDeltaApplier::finish_file barrier primitive.

Replaces the per-slot Arc<Mutex<FileSlot>> with Arc<SlotBarrier>,
where SlotBarrier colocates the file mutex with a (Mutex<usize>,
Condvar) pair that tracks outstanding worker references. slot_for
now returns a SlotHandle RAII guard whose Drop impl decrements the
in-flight counter and wakes flush_workers waiters, keeping the
bookkeeping exception-safe across early returns and panics.

Public API additions:
- flush_workers(ndx): blocks until the slot has zero in-flight
  handles (no-op if the slot is absent).
- drain_inflight(): snapshots registered ndx values and waits on
  each via flush_workers, used by shutdown/abort paths.
- finish_file(ndx): now bakes flush_workers in (Option D from the
  design doc) so existing callers keep working with no migration.

ApplierStillReferenced is reframed from a transient race the caller
might observe into a post-barrier invariant violation worth filing
an issue over; the typed variant remains for diagnostic value.

Test additions in parallel_apply.rs:
- flush_workers_returns_immediately_when_no_inflight
- flush_workers_returns_ok_for_unknown_ndx
- flush_workers_blocks_until_worker_drops_arc
- drain_inflight_drains_all_files
- finish_file_calls_flush_workers_internally
- flush_workers_survives_spurious_wakeup

The previously-passing arc_drain_panic_recovery::parallel_apply_drain
test exercised the now-impossible race scenario (worker blocked inside
the slot mutex while finish_file races); that test is removed and the
module doc notes the FFB-2 rationale.

Local verification skipped per user direction; CI is the verification
gate.

* fix(engine): handshake-based barrier coordination in FFB-2 tests

Both finish_file_calls_flush_workers_internally and
drain_inflight_drains_all_files used a sleep(5ms) to "let the worker
acquire the SlotHandle" before invoking the barrier call. On macOS
the sleep was insufficient under load - main reached finish_file
before the worker entered slot_for, inflight stayed 0, the barrier
returned immediately, and the elapsed-time assertion fired (observed
18ms < 30ms threshold).

Replaced with an mpsc handshake: the worker sends () after acquiring
the handle, main blocks on recv_timeout before starting the barrier
call. Deterministic across platforms.

* fix(engine): handshake-based barrier in flush_workers_blocks test

Third sibling of the same race pattern: flush_workers_blocks_until_worker_drops_arc
used sleep(5ms) to let the worker acquire the SlotHandle before
starting the timer. macOS nightly didn't schedule the worker in time,
flush_workers returned inflight=0 immediately, and the
elapsed >= 40ms assertion fired.

Same fix as the earlier two tests: replace sleep with an mpsc channel
that the worker pings after acquiring the handle, and main blocks on
recv_timeout before starting the timer.

* fix(engine): spin-then-yield around finish_file's try_unwrap (FFB-2)

Windows nextest surfaced strong_count=2 panics where flush_workers
returned with inflight==0 but the worker's DecrementGuard still held
an Arc<SlotBarrier> clone. The drop sequence is:

1. SlotHandle drops, fields drop in declaration order
2. barrier field (Arc<SlotBarrier>) drops - one ref released
3. _decrement field (DecrementGuard) drops:
   a. Drop body calls decrement_inflight() which acquires the
      inflight mutex, sets the counter to 0, notifies the Condvar
   b. After the body returns, DecrementGuard's own Arc<SlotBarrier>
      clone drops - second ref released

flush_workers wakes on the Condvar notify at step 3a. Main thread
proceeds to DashMap::remove + Arc::try_unwrap, but the worker's
DecrementGuard is still between 3a and 3b - the Arc clone is alive.

Surfaces reliably on Windows under load; intermittent on macOS;
mostly invisible on Linux.

Fix: after flush_workers, spin-then-yield on strong_count > 1 until
the DecrementGuard's drop body completes and its Arc clone is
released. Bounded at 1000 iterations (32 spin_loop + 968 yield_now)
so a real invariant violation (caller raced a new slot_for) still
surfaces ApplierStillReferenced after ~ms, not hangs.

Root-cause-clean fix would refactor DecrementGuard to not hold an
Arc<SlotBarrier> (use Weak, or a separate Arc<(Mutex,Condvar)>
struct), but that is a bigger surgery; this minimal patch closes
the Windows test regression.
oferchen added a commit that referenced this pull request Aug 24, 2026
…H -C (SSC-1) (#4667)

* feat(core): warn on double-compression when --compress meets SSH -C (SSC-1)

Emit a one-time stderr warning at SSH spawn time when both rsync wire
compression (--compress) and SSH stream compression (-C / -o Compression=yes
on the rsync `-e ssh ...` invocation) are enabled. SSH cannot meaningfully
recompress the already-compressed rsync stream, so doing both wastes CPU
and can occasionally expand the payload.

Detection is conservative: it only inspects the SSH command-line built by
the user via `-e` / `--rsh`. Parsing `~/.ssh/config` is left to SSC-3
(#2563); the documentation companion lives in SSC-2 (#2562).

The emitter uses a process-global `OnceLock<bool>` so subsequent SSH
spawns in the same process do not flood stderr. The detection predicate
is split out into a `should_warn_double_compression` helper so the four
new tests (warns_on_double_compression, no_warning_when_only_rsync_compress,
no_warning_when_only_ssh_compress, no_warning_when_neither_compresses)
can exercise the logic without depending on `OnceLock` state.

* fix(engine): close race in concurrent_register_and_dispatch_on_overlapping_files

Cross-tree fix bundled with SSC-1 because this master-side flaky stress
test has been blocking CI on multiple unrelated PRs (#4663, #4665, #4667).

The race: SMALL_OPS=4000 dispatcher operations spread across WORKERS rayon
workers can complete before the registrar's first `register_file(0, ...)`
returns. When that happens every `apply_chunk_parallel` returns the
typed "unknown" error, `expected` (the success-byte counter) stays 0,
and the sanity assertion `assert!(expected > 0)` at line 264 fires.
The probability is small on Linux but reliably observable on Windows
under the tracing feature build.

Added a separate `registrations_done` AtomicU64 the registrar bumps after
each `register_file` returns. Workers block on `registrations_done >= 1`
via yield_now before starting their dispatch loop. The race against the
registrar for ndx >= 1 is preserved, so the test still stresses the
register-vs-dispatch surface.

Followup candidates: SMALL_NUM/SMALL_OPS retuning, deterministic injection
points - not necessary for the immediate unblock.
oferchen added a commit that referenced this pull request Aug 24, 2026
…(DG-4.a) (#4963)

Specifies the surgical removal of the spin-then-yield block in
ParallelDeltaApplier::finish_file (introduced by PR #4665 as a
stop-gap) now that the DG-3 BarrierState/SlotData split has shipped.
Documents the exact lines to delete, the safety argument, the
mechanical removal procedure, the regression-test gating, and the
rollback procedure. The follow-up DG-4 code PR applies the deletion.
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.

1 participant