impl RangeQueues { fn new(ranges: usize) -> std::sync::Arc { std::sync::Arc::new(RangeQueues { state: Mutex::new(RangeState { queues: (0..ranges).map(|_| std::collections::VecDeque::new()).collect(), finished: vec![false; ranges], current: 0, ahead: 0, abandoned: false, coordinator_waiting: false, workers_waiting: 0, }), cv: std::sync::Condvar::new(), }) } /// Whether the coordinator has stopped reading (an earlier range failed). fn abandoned(&self) -> bool { self.state.lock().expect("the merge's range queues").abandoned } /// Range `r`'s sending half, for its worker. Dropping it marks the range finished. fn sender(self: &std::sync::Arc, r: usize) -> RangeTx { RangeTx { queues: std::sync::Arc::clone(self), r, local: Default::default() } } } /// One range worker's end of [`RangeQueues`]: `send` in the shape of the channel it replaced. struct RangeTx { queues: std::sync::Arc, r: usize, /// Tiles merged but not yet queued, and their byte estimate: handed over /// [`SEND_BATCH`] at a time, so 48 workers take the shared lock once per batch rather than /// once per tile (per-tile sends had most range workers parked on that lock). local: std::cell::RefCell<(Vec<(RangeOut, u64)>, u64)>, } /// Tiles a range worker hands over per lock acquisition (or fewer, once [`SEND_BATCH_BYTES`] of /// them are held). const SEND_BATCH: usize = 64; const SEND_BATCH_BYTES: u64 = 4 << 20; impl RangeTx { /// Queue one tile (or error) for range `r`. `Err` when the coordinator is gone, which ends the /// worker exactly as a dropped receiver did. fn send(&self, item: RangeOut) -> std::result::Result<(), ()> { let bytes = match &item { Ok((_, layers)) => tile_bytes(layers), Err(_) => 0, }; let failed = item.is_err(); let full = { let mut local = self.local.borrow_mut(); local.0.push((item, bytes)); local.1 += bytes; failed || local.0.len() >= SEND_BATCH || local.1 >= SEND_BATCH_BYTES }; if full { self.flush() } else { Ok(()) } } /// Hand the held tiles to the queue, waiting while the range is over its bound: the count /// bound when it is the range being drained, the shared run-ahead allowance otherwise. fn flush(&self) -> std::result::Result<(), ()> { let (batch, bytes) = std::mem::take(&mut *self.local.borrow_mut()); if batch.is_empty() { return Ok(()); } let q = &self.queues; let mut s = q.state.lock().expect("the merge's range queues"); loop { if s.abandoned { return Err(()); } let wait = if self.r == s.current { s.queues[self.r].len() >= RANGE_QUEUE_BOUND } else { // Always let a range queue its first batch, so a range is never blocked behind // its own empty queue; past that, the shared allowance decides. !s.queues[self.r].is_empty() && s.ahead + bytes > RANGE_AHEAD_BYTES }; if !wait { break; } s.workers_waiting += 1; s = q.cv.wait(s).expect("the merge's range queues"); s.workers_waiting -= 1; } if self.r != s.current { s.ahead += bytes; } s.queues[self.r].extend(batch); let wake = self.r == s.current && s.coordinator_waiting; drop(s); if wake { q.cv.notify_all(); } Ok(()) } } impl Drop for RangeTx { fn drop(&mut self) { // Whatever is still held goes out first; then the range is finished. A coordinator that // has gone away refuses the flush, which is fine: nobody is reading. let _ = self.flush(); let q = &self.queues; q.state.lock().expect("the merge's range queues").finished[self.r] = true; q.cv.notify_all(); } } /// Ordered coordinator over range workers: an iterator yielding the serial /// tile sequence. /// /// Ranges drain strictly in order (range 0 to exhaustion, then range 1, ...), /// so the yielded sequence is tile-ascending regardless of completion order. /// A range's error aborts the drain with the lowest-indexed failure: ranges /// before it drained cleanly, so it is the earliest tile-ordered failure — /// deterministic, like serial. struct ParallelMerge { queues: std::sync::Arc, ranges: usize, done: bool, /// Tiles taken off the current range's queue in one go, handed out one per `next`. local: std::collections::VecDeque, } impl ParallelMerge { fn new(queues: std::sync::Arc) -> ParallelMerge { let ranges = queues.state.lock().expect("the merge's range queues").queues.len(); ParallelMerge { queues, ranges, done: false, local: std::collections::VecDeque::new() } } /// Move everything queued for the current range into `local`, advancing past finished /// ranges, waiting only when the current range has nothing yet. `false` once every range /// has drained. fn refill(&mut self) -> bool { let q = &self.queues; let mut s = q.state.lock().expect("the merge's range queues"); loop { if s.current >= self.ranges { return false; } let current = s.current; if !s.queues[current].is_empty() { self.local.extend(s.queues[current].drain(..).map(|(item, _)| item)); let wake = s.workers_waiting > 0; drop(s); if wake { q.cv.notify_all(); } return true; } if s.finished[current] { // Range drained cleanly: advance. Its successor's queued bytes stop counting // against the run-ahead allowance now that it is the one being drained. s.current += 1; if s.current < self.ranges { let next = s.current; let queued: u64 = s.queues[next].iter().map(|(_, b)| *b).sum(); s.ahead -= queued; } if s.workers_waiting > 0 { q.cv.notify_all(); } continue; } s.coordinator_waiting = true; s = q.cv.wait(s).expect("the merge's range queues"); s.coordinator_waiting = false; } } } impl Drop for ParallelMerge { /// Release any worker still parked on its queue: whatever ended the drain, nobody reads /// further, and the workers' scope is waiting to join them. fn drop(&mut self) { self.queues.state.lock().expect("the merge's range queues").abandoned = true; self.queues.cv.notify_all(); } } impl Iterator for ParallelMerge { type Item = Result<(u64, Vec)>; fn next(&mut self) -> Option)>> { if self.done { return None; } if self.local.is_empty() && !self.refill() { self.done = true; return None; } let item = self.local.pop_front().expect("refilled above"); if item.is_err() { // Lowest-indexed failure wins because lower ranges already drained clean; nothing // further is read. self.done = true; self.local.clear(); self.queues.state.lock().expect("the merge's range queues").abandoned = true; self.queues.cv.notify_all(); } Some(item) } } enum MergeStream<'a> { Serial(Merged<'a>), Parallel(ParallelMerge), } impl Iterator for MergeStream<'_> { type Item = Result<(u64, Vec)>; fn next(&mut self) -> Option)>> { match self { MergeStream::Serial(m) => m.next(), MergeStream::Parallel(m) => m.next(), } } }