Skip to content

docs(design): flush_workers barrier API for ParallelDeltaApplier (FFB-1) - #4659

Merged
oferchen merged 1 commit into
masterfrom
docs/design/ffb-1-applier-barrier-api
May 21, 2026
Merged

oferchen merged 1 commit into
masterfrom
docs/design/ffb-1-applier-barrier-api

Conversation

@oferchen

Copy link
Copy Markdown
Owner

Summary

Design note for the missing barrier primitive on ParallelDeltaApplier. Today finish_file at crates/engine/src/concurrent_delta/parallel_apply.rs:564 returns ApplierStillReferenced whenever a rayon worker still holds an Arc<Mutex<FileSlot>> clone, leaving production callers (PIP-3 wire-up in particular) to either retry-loop or invent their own scope management.

The doc:

  • Inventories the candidate primitives (rayon/crossbeam scopes, channels, per-slot Condvar) and the DashMap-slot lifecycle constraints introduced by BR-3j.c (PR refactor(engine): replace ParallelDeltaApplier outer Mutex with DashMap (BR-3j.c+e) #4634).
  • Evaluates four API shapes:
    • A. flush_workers(ndx) — per-file barrier; blocks until in-flight workers release the slot Arc.
    • B. drain_inflight() — global barrier; blocks until every slot is idle.
    • C. on_file_complete(ndx, cb) — callback-based completion (inverts control flow).
    • D. Bake the barrier into finish_file — single barrier-and-finalise call.
  • Recommends A as the primitive + D as the bundled default + B as a thin loop over A for session shutdown. ApplierStillReferenced stays as a post-barrier invariant assertion (the diagnostic payload is still valuable for "this should never happen" failures).
  • Maps the recommendation to FFB-2 (implementation: add per-slot (Mutex<usize>, Condvar) + guard type, rewrite finish_file to barrier-then-extract), FFB-3 (existing tests stay green because Option D bakes the barrier in), and FFB-4 (PIP-3 receiver picks up the new contract for free; Drop impl calls drain_inflight).

Chosen option

Option A (flush_workers) primitive + Option D (barrier-baked finish_file) default + Option B (drain_inflight) as session-shutdown convenience.

Three public methods, one shared per-slot (Mutex<usize>, Condvar) primitive, zero behaviour change for callers that only ever called finish_file. PIP-3 cutover stops being able to observe ApplierStillReferenced as a transient race.

Follow-up shape

  • FFB-2 (refactor(engine)): add inflight: Arc<(Mutex<usize>, Condvar)> to FileSlot; implement flush_workers / drain_inflight; rewrite finish_file to internally barrier. Keep ApplierStillReferenced as an invariant violation.
  • FFB-3 (refactor(engine)): audit existing tests at parallel_apply.rs:708-829; no edits expected, just verify they still pass with the new bundled barrier and add a #[cfg(test)] accessor for strong-count assertions if needed.
  • FFB-4 (perf(transfer)): wire the PIP-3 receiver site (crates/transfer/src/receiver/mod.rs::enable_parallel_receive_delta); ReceiverContext::Drop calls drain_inflight so workers never outlive the applier.

Test plan

  • Design doc only; no source code changes.
  • CI: docs job (no source changes mean fmt/clippy/nextest are no-ops for this PR).

Design note covering the missing barrier primitive for
`ParallelDeltaApplier::finish_file`. Today the call site at
`parallel_apply.rs:564` returns `ApplierStillReferenced` whenever a
rayon worker still holds an `Arc<Mutex<FileSlot>>` clone, leaving
production callers (PIP-3 in particular) to either retry-loop or
invent their own scope management.

The doc inventories the available primitives (rayon/crossbeam scopes,
channels, per-slot Condvar), evaluates four API shapes
(`flush_workers`, `drain_inflight`, callback, barrier-baked-into
`finish_file`), and recommends Option A (`flush_workers`) as the
primitive plus Option D (barrier inside `finish_file`) as the bundled
default, with Option B (`drain_inflight`) as a thin loop over Option A
for session shutdown.

No source changes. FFB-2 (implementation), FFB-3 (existing caller
migration), and FFB-4 (PIP-3 wire-up) follow in separate PRs.
@oferchen
oferchen force-pushed the docs/design/ffb-1-applier-barrier-api branch from e0b8b6d to 9548d9c Compare May 21, 2026 08:46
@oferchen
oferchen merged commit 8c6d44a into master May 21, 2026
9 checks passed
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label May 21, 2026
oferchen added a commit that referenced this pull request May 21, 2026
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.
oferchen added a commit that referenced this pull request May 21, 2026
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.
@oferchen
oferchen deleted the docs/design/ffb-1-applier-barrier-api branch May 21, 2026 14:09
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 added a commit that referenced this pull request May 21, 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
…-1) (#4659)

Design note covering the missing barrier primitive for
`ParallelDeltaApplier::finish_file`. Today the call site at
`parallel_apply.rs:564` returns `ApplierStillReferenced` whenever a
rayon worker still holds an `Arc<Mutex<FileSlot>>` clone, leaving
production callers (PIP-3 in particular) to either retry-loop or
invent their own scope management.

The doc inventories the available primitives (rayon/crossbeam scopes,
channels, per-slot Condvar), evaluates four API shapes
(`flush_workers`, `drain_inflight`, callback, barrier-baked-into
`finish_file`), and recommends Option A (`flush_workers`) as the
primitive plus Option D (barrier inside `finish_file`) as the bundled
default, with Option B (`drain_inflight`) as a thin loop over Option A
for session shutdown.

No source changes. FFB-2 (implementation), FFB-3 (existing caller
migration), and FFB-4 (PIP-3 wire-up) follow in separate PRs.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant