pub fn run_pass_sink( path: &Path, blobs: &[BlobLoc], spec: PassSpec<'_>, make: F, body: G, sink: H, ) -> Result> where S: Send, F: Fn() -> S + Sync, G: Fn(&mut S, &PrimitiveBlock) -> Result + Sync, H: FnMut(S) -> Result<()> + Send, { let n_chunks = blobs.len().div_ceil(CHUNK_BLOBS).max(1); let shared: Mutex> = Mutex::new(Shared { slots: (0..n_chunks).map(|_| None).collect(), next: 0, waiters: Vec::new(), failed: false, }); let kinds: Vec = (0..blobs.len()).map(|_| AtomicU8::new(0)).collect(); let next_chunk = AtomicUsize::new(0); let done_blobs = AtomicUsize::new(0); let last_pct = AtomicUsize::new(usize::MAX); // Owns the meter's clock: `report` draws the progress.rs standard shape // (`label [pct%] done/total elapsed, ETA`) from it on every redraw. let pass_start = std::time::Instant::now(); let n_threads = crate::par::threads().min(n_chunks); let mut first_err: Option = None; let mut sink_err: Option = None; let mut sink = sink; // How far ahead of the sink the workers may run. // // Without this the reorder buffer is unbounded: a worker deposits and immediately // claims another chunk, so one slow chunk 0 can park every other chunk's // accumulator in `slots` at once. On a planet pass those accumulators are the // largest things in the build, and raising the thread count widens the window, // which is exactly the failure this plan is shaped to avoid. Two chunks per thread // leaves slack for an uneven chunk without letting the buffer grow with the file. // // Note what this does NOT bound. It is a count of chunks, so the bytes it admits are // `window * CHUNK_BLOBS` blobs' worth of accumulator — and on a 64-core box the window // is 128 chunks, which exceeds the chunk count of anything smaller than a continent. // For those the window binds on nothing and the bound is really [`CHUNK_BLOBS`]; see // its doc for the 2.19 GB that cost. Bounding this in bytes would mean measuring `S`, // which is opaque here by design. let window = n_threads.saturating_mul(2).max(2); // Workers still running; the drain stops waiting once it reaches zero, so a // worker that failed (or unwound, in tests) cannot strand it. let alive = AtomicUsize::new(n_threads); // The sink runs HERE, on the calling thread, and never under the lock. // // It used to run inside `deposit`, under the one mutex every worker takes // to deposit and to check the window, and each deposit `notify_all`-ed // every worker parked on the window. At 192 threads with a sink that is the // bottleneck that was a thundering herd: California spent ~400 s of system // time (vs ~110 s user) in futex hash-bucket spinlocks. Now a deposit is a // slot store plus an unpark of the drain thread, the sink overlaps with the // deposits, and a window waiter is woken only when ITS chunk enters the // window. Order is unchanged: the sink still sees chunks strictly in index // order, one at a time, on one thread. let drain_thread = std::thread::current(); std::thread::scope(|scope| { let mut handles = Vec::with_capacity(n_threads); for _ in 0..n_threads { handles.push(scope.spawn(|| -> Result<()> { struct Alive<'a>(&'a AtomicUsize, std::thread::Thread); impl Drop for Alive<'_> { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::AcqRel); self.1.unpark(); } } let _alive = Alive(&alive, drain_thread.clone()); let fail = |e: Error| -> Error { shared.lock().expect("chunk slot mutex").failed = true; e }; let mut file = File::open(path) .map_err(|e| fail(Error(format!("cannot open {}: {e}", path.display()))))?; let mut compressed = Vec::new(); let mut inflated = Vec::new(); loop { let chunk = next_chunk.fetch_add(1, Ordering::Relaxed); if chunk >= n_chunks { return Ok(()); } // Hold off until this chunk is inside the window. The worker that // owns the lowest outstanding chunk always passes this test, so it // always makes progress and the wait cannot deadlock. loop { let mut st = shared.lock().expect("chunk slot mutex"); if chunk < st.next + window || st.failed { st.waiters.retain(|(c, _)| *c != chunk); break; } if !st.waiters.iter().any(|(c, _)| *c == chunk) { st.waiters.push((chunk, std::thread::current())); } drop(st); std::thread::park(); } let start = chunk * CHUNK_BLOBS; let end = ((chunk + 1) * CHUNK_BLOBS).min(blobs.len()); let mut state = make(); for (i, loc) in blobs[start..end].iter().enumerate() { let idx = start + i; match spec.blob_kinds.filter(|k| k[idx] & spec.want == 0) { Some(k) => kinds[idx].store(k[idx], Ordering::Relaxed), None => { read_exact_at(&mut file, loc, &mut compressed).map_err(fail)?; inflate_blob(&compressed, &mut inflated).map_err(fail)?; let block = PrimitiveBlock::decode(&inflated).map_err(fail)?; let seen = body(&mut state, &block).map_err(fail)?; kinds[idx].store(seen, Ordering::Relaxed); } } report(spec.label, &done_blobs, &last_pct, blobs.len(), &pass_start); } shared.lock().expect("chunk slot mutex").slots[chunk] = Some(state); drain_thread.unpark(); } })); } // The in-order drain. let mut next = 0usize; while next < n_chunks { let (ready, failed) = { let mut st = shared.lock().expect("chunk slot mutex"); match st.slots[next].take() { Some(s) => { st.next = next + 1; // Admit exactly the waiters whose chunk just entered the window. let limit = st.next + window; let mut i = 0; while i < st.waiters.len() { if st.waiters[i].0 < limit { st.waiters.swap_remove(i).1.unpark(); } else { i += 1; } } (Some(s), st.failed) } None => (None, st.failed), } }; match ready { Some(s) => { next += 1; // Keep draining after a failure: the pass reports the first error // at the end, and stopping here would strand the remaining chunks. if let Err(e) = sink(s) { if sink_err.is_none() { sink_err = Some(e); } } } None => { if failed || alive.load(Ordering::Acquire) == 0 { // A worker failed (its chunk will never arrive), or every // worker is gone: release anyone parked on the window and // stop; the join below reports the error. let mut st = shared.lock().expect("chunk slot mutex"); st.failed = true; for (_, t) in st.waiters.drain(..) { t.unpark(); } if alive.load(Ordering::Acquire) == 0 { break; } } std::thread::park_timeout(std::time::Duration::from_millis(50)); } } } for h in handles { match h.join() { Ok(Ok(())) => {} Ok(Err(e)) => { if first_err.is_none() { first_err = Some(e); } } Err(_) => { if first_err.is_none() { first_err = Some(Error("a reader thread panicked".into())); } } } } if first_err.is_none() && next < n_chunks { first_err = Some(Error(format!( "pass {}: chunks {next}..{n_chunks} were never produced", spec.label ))); } }); if let Some(e) = first_err { return Err(e); } if let Some(e) = sink_err { return Err(e); } // Snap to 100% in the same standard shape, then a fresh line so the next // stage starts clean instead of on top of the meter. { let n = blobs.len(); eprintln!( "\r{:<28} [100%] {n}/{n} {} elapsed, ETA 0s ", spec.label, crate::progress::hms(pass_start.elapsed().as_secs_f64()), ); } Ok(kinds.iter().map(|k| k.load(Ordering::Relaxed)).collect()) } /// Finished chunks waiting for their turn, plus the window bookkeeping. The /// sink itself lives on the draining thread, outside this lock. struct Shared { slots: Vec>, /// The next chunk the drain will hand to the sink. next: usize, /// Workers parked until their chunk enters the window: `(chunk, thread)`. waiters: Vec<(usize, std::thread::Thread)>, /// A worker failed, so a chunk will never arrive: stop waiting. failed: bool, } /// Run one pass over the file in parallel, returning every chunk's accumulator. /// /// Convenience over [`run_pass_sink`] for passes whose accumulators are small /// enough that holding them all costs nothing. Accumulators come back in chunk /// order, so merging them is deterministic. pub fn run_pass( path: &Path, blobs: &[BlobLoc], blob_kinds: Option<&[u8]>, want: u8, label: &str, make: F, body: G, ) -> Result<(Vec, Vec)> where S: Send, F: Fn() -> S + Sync, G: Fn(&mut S, &PrimitiveBlock) -> Result + Sync, { let mut out: Vec = Vec::new(); let kinds = run_pass_sink(path, blobs, PassSpec { blob_kinds, want, label }, make, body, |s| { out.push(s); Ok(()) })?; Ok((out, kinds)) } pub(crate) fn read_exact_at(file: &mut File, loc: &BlobLoc, out: &mut Vec) -> Result<()> { file.seek(SeekFrom::Start(loc.offset)) .map_err(|e| Error(format!("seek to {} failed: {e}", loc.offset)))?; out.clear(); out.resize(loc.datasize as usize, 0); file.read_exact(out).map_err(|e| Error(format!("short read at {}: {e}", loc.offset))) } /// One redraw of the pass meter, in the single standard shape (`progress.rs`): /// `label [pct%] done/total elapsed, ETA` on one stderr line. fn report( label: &str, done: &AtomicUsize, last_pct: &AtomicUsize, total: usize, start: &std::time::Instant, ) { let n = done.fetch_add(1, Ordering::Relaxed) + 1; if total == 0 { return; } let pct = n * 100 / total; let prev = last_pct.load(Ordering::Relaxed); if pct != prev && last_pct.compare_exchange(prev, pct, Ordering::Relaxed, Ordering::Relaxed).is_ok() { let elapsed = start.elapsed().as_secs_f64(); // ETA extrapolates the average rate so far; meaningless until something is // done, so hold it at zero for the opening frame. let eta = if n == 0 { 0.0 } else { elapsed * (total - n) as f64 / n as f64 }; eprint!( "\r{label:<28} [{pct:>3}%] {n}/{total} {} elapsed, ETA {} ", crate::progress::hms(elapsed), crate::progress::hms(eta), ); let _ = std::io::stderr().flush(); } }