trg/sched.rs
1//! Bounded worker pool. Concurrency lives at the archive boundary and nowhere
2//! else, because gzip has no index: member N requires inflating 1..N-1.
3//!
4//! # Ordering
5//!
6//! Output stays in argument order by default: these archives are days, and
7//! argument order is chronological order. That is achieved by holding a
8//! completed archive's buffer until every earlier archive has been emitted —
9//! **not** by joining all workers first. A finished job whose predecessors are
10//! already out is written and freed immediately, so nothing waits on the
11//! slowest archive to be handed to `emit`.
12//!
13//! # What actually bounds memory
14//!
15//! Three separate things, and it is worth being precise about which does what,
16//! because `spill_bytes` alone does far less than its name suggests:
17//!
18//! 1. **Buffer recycling.** Output buffers are owned by this module and pooled.
19//! A worker takes one, fills it, and the collector `clear()`s it after
20//! emitting and returns it to the pool. Allocating a fresh buffer per
21//! archive instead makes peak RSS climb with the *archive count*: each one
22//! is grown by a realloc chain to that archive's whole match volume and then
23//! freed, and the allocator does not hand the same span back for the next
24//! one. Measured at `-j1` on six archives of 120k matching lines: 84 MB
25//! per-job vs. 22 MB pooled.
26//!
27//! At `workers == 1` exactly one buffer exists for the whole run, which is
28//! the case that matters most since `-j1` is the default. In the pool path
29//! the *count* of live buffers is not capped, and deliberately so: holding
30//! `k` results in order requires `k` buffers, so a hard cap would be a cap
31//! on the ordering window. It is not needed either — an unwritten
32//! `termcolor::Buffer` is an empty `Vec` that has allocated nothing, and the
33//! ones that did allocate are bounded in *bytes* by `spill_bytes` below.
34//! What the pool guarantees is that a buffer's allocation is reused rather
35//! than rebuilt, which is what the realloc chain cost.
36//! 2. **Per-worker state.** `make_worker` is called once per worker thread, not
37//! once per job, for the same reason — see [`run`].
38//! 3. **`spill_bytes`.** This bounds only the buffers *parked* in `slots`
39//! waiting for their turn in the order. It does **not** bound peak RSS: the
40//! `workers` buffers currently being filled, and the batch the collector has
41//! drained but not yet emitted, are outside the count. Treat it as "how far
42//! out of order are we willing to hold results", not as a memory ceiling. A
43//! real run peaked at 286 MB under a 64 MB cap.
44//!
45//! When parked buffers do exceed `spill_bytes`, they are flushed out of order
46//! with a note on stderr. Holding results in order is worth a lot, but not
47//! unboundedly much when a single slow archive is pinning the rest.
48//!
49//! # Design
50//!
51//! One `Mutex` guards the slot vector, the buffer pool, and a little
52//! bookkeeping; one `Condvar` wakes the collector. Workers only ever *deposit*:
53//! pull the next index with a `fetch_add`, do the work outside the lock, then
54//! take the lock just long enough to move the finished [`Done`] into its slot
55//! and notify. Nothing a worker does can block on another worker.
56//!
57//! The calling thread is the collector. It owns `head` and `emitted`, neither
58//! of which is shared, and it calls `emit` *outside* the lock so a slow stdout
59//! — a pipe into `head(1)`, say — never stalls a worker mid-archive.
60//!
61//! Emission order is correct because a slot is written exactly once (position
62//! `p` is handed to exactly one worker by the atomic counter) and read exactly
63//! once (only the collector takes, and only from a slot it then marks emitted).
64//! In sorted mode the collector walks `order`, so it emits the job with the
65//! next-lowest [`Job::index`] only once every lower index has gone out. The one
66//! deliberate exception is the spill above.
67//!
68//! # Panics and early stop
69//!
70//! A panicking job must not be able to hang the process — during an incident a
71//! hang looks like a slow search and gets waited on, which is strictly worse
72//! than a crash. Four independent mechanisms guarantee it cannot, one per place
73//! a thread can leave unexpectedly:
74//!
75//! - [`catch_unwind`](std::panic::catch_unwind) around the call to `work`,
76//! which turns a panic into an ordinary error on that archive, and a second
77//! one around `make_worker`, which is likewise the caller's closure.
78//! - a `Completion` drop guard that advances the finished count and wakes the
79//! collector even if a worker unwinds anyway, once it has claimed a job.
80//! - a `WorkerLife` drop guard covering the rest of the thread's life —
81//! everything before and between jobs, where `Completion` does not exist yet.
82//! When the last worker goes with jobs still unclaimed, the collector stops
83//! waiting and reports those archives as unread, so the run is a 2.
84//! - a `Teardown` drop guard on the collector, releasing workers parked on
85//! backpressure when it leaves, including by unwinding out of `emit`.
86//!
87//! Each guards a different exit; none of them is redundant with the others, and
88//! the module has hit this failure shape three times, so a new path out of a
89//! thread needs a guard rather than an argument that it cannot be taken.
90//!
91//! `emit` returns `io::Result`, and the first error stops the run: no further
92//! job is started and [`run`] returns the error. That is what makes
93//! `trg ... | head -5` stop searching instead of grinding through a whole
94//! month of archives writing into a closed pipe.
95
96use std::collections::VecDeque;
97use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
98use std::sync::{Condvar, Mutex};
99
100pub struct Job {
101 pub index: usize,
102 pub path: std::path::PathBuf,
103}
104
105pub struct Done {
106 pub index: usize,
107 pub buffer: termcolor::Buffer,
108 pub outcome: crate::archive::Outcome,
109}
110
111/// How the pool runs, as opposed to what it runs.
112pub struct Config {
113 /// Archives searched concurrently. `1` takes a dedicated sequential path.
114 pub workers: usize,
115 /// Emit in [`Job::index`] order rather than completion order.
116 pub sorted: bool,
117 /// How many bytes of *parked* output may wait for their turn before the
118 /// order is abandoned. Not a memory ceiling — see the module docs.
119 pub spill_bytes: usize,
120}
121
122/// Everything the workers and the collector share. The lock is held only for
123/// the moves in and out of `slots` and `pool`.
124struct Shared {
125 /// One slot per job position. `Some` means finished and not yet emitted.
126 slots: Vec<Option<Done>>,
127 /// Positions in completion order, for `--no-sort`.
128 ready: VecDeque<usize>,
129 /// Output buffers not currently in use, kept so their allocations are
130 /// reused instead of being rebuilt per archive.
131 pool: Vec<termcolor::Buffer>,
132 /// Bytes currently parked in `slots`, waiting for their turn in the order.
133 held: usize,
134 /// Bytes the collector has drained out of `slots` but not yet emitted and
135 /// recycled. Counted separately and added to `held` for backpressure,
136 /// because draining moves bytes out of `slots` without freeing anything —
137 /// missing this is what let live buffers track the job count.
138 batch_bytes: usize,
139 /// Jobs finished so far, so the collector knows when to stop waiting.
140 finished: usize,
141 /// Worker threads still running. Decremented by [`WorkerLife`] on every
142 /// exit path, normal or unwinding, so that "nobody is left to finish the
143 /// outstanding jobs" is a state the collector can observe rather than a
144 /// wait it never wakes from.
145 live_workers: usize,
146}
147
148/// Advances the finished count and wakes the collector on drop, so that a
149/// worker which unwinds still counts as having completed its job.
150///
151/// Without this, a panicking worker would leave `finished` short of `n`
152/// forever: the collector would wait on a notification that never comes, and
153/// `thread::scope` would never return. Belt and braces alongside the
154/// `catch_unwind` in [`run_job`], which already stops a panic in `work` itself;
155/// this covers everything else on the path.
156struct Completion<'a> {
157 state: &'a Mutex<Shared>,
158 wake: &'a Condvar,
159 armed: bool,
160}
161
162impl Drop for Completion<'_> {
163 fn drop(&mut self) {
164 if !self.armed {
165 return;
166 }
167 // Never `unwrap` here: panicking inside a `Drop` that is itself running
168 // during an unwind aborts the process. A poisoned lock is handled by
169 // waking the collector anyway, which will then fail on its own lock and
170 // propagate a panic — noisy, but not a hang.
171 if let Ok(mut st) = self.state.lock() {
172 st.finished += 1;
173 }
174 self.wake.notify_all();
175 }
176}
177
178/// Decrements the live-worker count and wakes the collector on drop.
179///
180/// [`Completion`] covers a worker that unwinds *after* it has claimed a job.
181/// This covers the rest of the thread's life, which [`Completion`] cannot: it
182/// is constructed as the thread's first act, before `make_worker()` and before
183/// the first `state.lock()`, so a panic in either — or in `space.wait()` on a
184/// poisoned lock — still tells the collector that this worker is gone.
185///
186/// Without it the collector waits at `wake.wait` for a notification no living
187/// thread will send, and `thread::scope` never returns: a hang, which during an
188/// incident looks like a slow search and gets waited on. This is the third
189/// instance of that shape in this module, after the panicking worker and the
190/// collector unwinding out of `emit`, so it is guarded structurally rather than
191/// by arguing that the current caller does not panic — `run` is public API and
192/// `make_worker` is the caller's closure.
193struct WorkerLife<'a> {
194 state: &'a Mutex<Shared>,
195 wake: &'a Condvar,
196}
197
198impl Drop for WorkerLife<'_> {
199 fn drop(&mut self) {
200 // Never `unwrap`: same discipline as `Completion` — this `Drop` runs
201 // during an unwind, and panicking there aborts the process.
202 if let Ok(mut st) = self.state.lock() {
203 st.live_workers -= 1;
204 }
205 self.wake.notify_all();
206 }
207}
208
209/// Releases every worker parked on backpressure when the collector leaves,
210/// *including* when it leaves by unwinding out of `emit`.
211///
212/// The exact mirror of [`Completion`] at the other end of the pipe. Without it,
213/// a panic in `emit` skips the teardown, workers stay parked on `space`, and
214/// `thread::scope` blocks forever joining them — a hang, which is the one
215/// outcome worse than a crash. Fixing that on the worker side and not the
216/// collector side would not be defensible.
217struct Teardown<'a> {
218 state: &'a Mutex<Shared>,
219 space: &'a Condvar,
220 wake: &'a Condvar,
221 stop: &'a AtomicBool,
222}
223
224impl Drop for Teardown<'_> {
225 fn drop(&mut self) {
226 // Never `unwrap` here: this `Drop` runs during an unwind, and a panic
227 // inside it would abort the process. Same discipline as `Completion`.
228 if let Ok(mut st) = self.state.lock() {
229 // The `Done`s still in the collector's batch are dropped without
230 // passing through `recycle`, so their bytes would be counted
231 // against the backpressure predicate forever. Zeroing here makes
232 // the predicate correct rather than merely short-circuited, so the
233 // wakeup below does not depend on `stop` alone.
234 st.batch_bytes = 0;
235 // Stored while the lock is held so the mutex's release/acquire edge
236 // carries it too; the `Release` ordering covers the lock-free check
237 // at the top of the worker loop.
238 self.stop.store(true, Ordering::Release);
239 } else {
240 self.stop.store(true, Ordering::Release);
241 }
242 self.space.notify_all();
243 self.wake.notify_all();
244 }
245}
246
247/// Call `work`, converting a panic into an error on that archive.
248///
249/// The buffer is cleared on panic: a job that died mid-write may have left a
250/// partial line behind, and half a log line in the middle of ordered output is
251/// worse than none.
252///
253/// This is a no-op under `panic = "abort"`, which the release profile sets. It
254/// is still worth having: an abort is a crash, and a crash is a diagnosable
255/// outcome. The failure mode being prevented is the *hang*, and the
256/// `Completion` guard prevents that on both profiles.
257fn run_job<C, F>(
258 job: &Job,
259 ctx: &mut C,
260 buf: &mut termcolor::Buffer,
261 work: &F,
262) -> crate::archive::Outcome
263where
264 F: Fn(&Job, &mut C, &mut termcolor::Buffer) -> crate::archive::Outcome,
265{
266 // `AssertUnwindSafe` is honest here rather than a silencer: everything
267 // reachable is either this job's own scratch state, which is discarded on
268 // the panic path, or the shared slot vector, which this job has not touched
269 // yet — it deposits only after `work` returns.
270 let called = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(job, ctx, buf)));
271 match called {
272 Ok(o) => o,
273 Err(_) => {
274 buf.clear();
275 let mut o = crate::archive::Outcome::default();
276 o.errors.push(format!(
277 "{}: panicked while searching; skipped",
278 job.path.display()
279 ));
280 o
281 }
282 }
283}
284
285/// Run `work` over `jobs`, emitting each result through `emit`.
286///
287/// `make_worker` is called **once per worker thread**, not once per job. That
288/// is the correct granularity for anything a job needs but cannot share:
289/// `grep_searcher::Searcher` is not `Sync`, so it cannot be hoisted out of the
290/// pool entirely, but building one per *archive* is a real cost — its internal
291/// line buffer grows toward the configured heap limit and is thrown away every
292/// archive. Measured on 60 small archives: 288 MB per-job vs. 30 MB per-worker.
293/// At `workers == 1` this means exactly one is ever built.
294///
295/// `emit` borrows its [`Done`] rather than taking it, so the buffer can be
296/// recycled afterwards. The first `Err` it returns stops the run: no further
297/// job is started, and that error is returned.
298pub fn run<C, F, E>(
299 jobs: Vec<Job>,
300 cfg: Config,
301 make_buffer: impl Fn() -> termcolor::Buffer + Send + Sync,
302 make_worker: impl Fn() -> C + Send + Sync,
303 work: F,
304 emit: E,
305) -> std::io::Result<()>
306where
307 F: Fn(&Job, &mut C, &mut termcolor::Buffer) -> crate::archive::Outcome + Send + Sync,
308 E: FnMut(&Done) -> std::io::Result<()>,
309{
310 run_with_spawn_hook(jobs, cfg, make_buffer, make_worker, work, emit, |_| {})
311}
312
313/// [`run`], with `before_spawn(i)` called just before worker `i` is spawned.
314///
315/// A fault-injection point and nothing else: a panic from it stands in for
316/// `scope.spawn` panicking when the OS refuses a thread, which no test can
317/// provoke for real. `run` passes a no-op, which compiles away.
318fn run_with_spawn_hook<C, F, E>(
319 jobs: Vec<Job>,
320 cfg: Config,
321 make_buffer: impl Fn() -> termcolor::Buffer + Send + Sync,
322 make_worker: impl Fn() -> C + Send + Sync,
323 work: F,
324 mut emit: E,
325 before_spawn: impl Fn(usize),
326) -> std::io::Result<()>
327where
328 F: Fn(&Job, &mut C, &mut termcolor::Buffer) -> crate::archive::Outcome + Send + Sync,
329 E: FnMut(&Done) -> std::io::Result<()>,
330{
331 let Config { workers, sorted, spill_bytes } = cfg;
332 let n = jobs.len();
333 if n == 0 {
334 return Ok(());
335 }
336
337 // The sequential path holds nothing and needs no lock, which is already the
338 // bounded-memory ideal. Kept separate rather than folded into the pool:
339 // `-j1` is the production default and deserves no threads at all. One
340 // worker context and one buffer for the whole run.
341 if workers <= 1 {
342 let mut ctx = make_worker();
343 let mut buf = make_buffer();
344 for job in &jobs {
345 buf.clear();
346 let outcome = run_job(job, &mut ctx, &mut buf, &work);
347 let done = Done { index: job.index, buffer: buf, outcome };
348 let r = emit(&done);
349 buf = done.buffer;
350 r?;
351 // One pathological archive should not leave its whole match volume
352 // reserved for the rest of the run.
353 if buf.as_slice().len() > spill_bytes {
354 buf = make_buffer();
355 }
356 }
357 return Ok(());
358 }
359
360 // Emission order. Sorting by `Job::index` rather than by slot position
361 // means a caller that hands us indices which are not `0..n` still gets the
362 // order it asked for, and that `Done::index` is the one ordering key
363 // everywhere — including the spill loop. Stable, so equal indices keep
364 // argument order. For `main`, where index == position, this is the identity.
365 let mut order: Vec<usize> = (0..n).collect();
366 if sorted {
367 order.sort_by_key(|&p| jobs[p].index);
368 }
369
370 let live = workers.min(n);
371
372 let next = AtomicUsize::new(0);
373 let stop = AtomicBool::new(false);
374 let state = Mutex::new(Shared {
375 slots: (0..n).map(|_| None).collect(),
376 ready: VecDeque::new(),
377 pool: Vec::new(),
378 held: 0,
379 batch_bytes: 0,
380 finished: 0,
381 // Seeded before a single thread is spawned, so it only ever counts
382 // down: the collector cannot mistake "not started yet" for "all gone".
383 live_workers: live,
384 });
385 let wake = Condvar::new();
386 // Workers wait here for the collector to free output bytes. A second
387 // condvar on the *same* mutex, so a worker's check-and-wait is atomic
388 // against the collector's decrement and no wakeup can be missed.
389 let space = Condvar::new();
390
391 let mut write_err: Option<std::io::Error> = None;
392
393 std::thread::scope(|scope| {
394 // Armed before a single worker is spawned, so a panic from
395 // `scope.spawn` itself — the OS refusing a thread — still runs
396 // teardown instead of leaving spawned workers parked on
397 // backpressure forever. The normal exit and the unwinding exit
398 // run identical teardown either way, since this lives until the
399 // end of the same scope regardless of where it's declared.
400 let _teardown = Teardown { state: &state, space: &space, wake: &wake, stop: &stop };
401
402 for i in 0..live {
403 before_spawn(i);
404 let (next, stop, state, wake) = (&next, &stop, &state, &wake);
405 let space = &space;
406 let (jobs, work, make_buffer, make_worker) =
407 (&jobs, &work, &make_buffer, &make_worker);
408 scope.spawn(move || {
409 // First act of the thread, so every later line is covered.
410 let _life = WorkerLife { state, wake };
411 // `make_worker` is the caller's closure and may panic. Catching
412 // it here keeps the panic from propagating out of the scope —
413 // which would turn a per-worker fault into a process-level one
414 // — and lets the surviving workers claim the whole job list.
415 // If none survive, `_life` above is what stops the collector
416 // waiting for them.
417 let mut ctx = match std::panic::catch_unwind(
418 std::panic::AssertUnwindSafe(&make_worker),
419 ) {
420 Ok(c) => c,
421 Err(_) => return,
422 };
423 loop {
424 // Producer-side backpressure. Waiting *before* claiming a
425 // job means a blocked worker holds nothing at all — no
426 // buffer, no slot, no job — which is what makes the wait
427 // deadlock-free. See the module docs.
428 {
429 let mut st = state.lock().unwrap();
430 while !stop.load(Ordering::Acquire)
431 && st.held + st.batch_bytes > spill_bytes
432 {
433 st = space.wait(st).unwrap();
434 }
435 }
436
437 // Checked before claiming work, so a write failure or a
438 // closed pipe stops the sweep at the next archive boundary
439 // instead of at the end of the month.
440 if stop.load(Ordering::Acquire) {
441 return;
442 }
443 let p = next.fetch_add(1, Ordering::Relaxed);
444 if p >= n {
445 return;
446 }
447
448 let mut guard = Completion { state, wake, armed: true };
449
450 let mut buf = {
451 let mut st = state.lock().unwrap();
452 st.pool.pop()
453 }
454 .unwrap_or_else(make_buffer);
455
456 let outcome = run_job(&jobs[p], &mut ctx, &mut buf, work);
457 let bytes = buf.as_slice().len();
458 let done = Done { index: jobs[p].index, buffer: buf, outcome };
459
460 {
461 let mut st = state.lock().unwrap();
462 st.slots[p] = Some(done);
463 st.ready.push_back(p);
464 st.held += bytes;
465 st.finished += 1;
466 guard.armed = false;
467 }
468 wake.notify_all();
469 }
470 });
471 }
472
473 // The collector. Runs on the calling thread so `emit` needs to be
474 // neither `Send` nor `Sync`, and so ordering decisions live in exactly
475 // one place. `head` walks `order`, not raw positions.
476
477 let mut head = 0usize;
478 let mut emitted = vec![false; n];
479 let mut emitted_count = 0usize;
480 let mut batch: Vec<Done> = Vec::new();
481
482 'collect: while emitted_count < n {
483 let mut spill_notices = 0usize;
484 {
485 let mut st = state.lock().unwrap();
486 loop {
487 if sorted {
488 // Drain the in-order prefix: everything from `head`
489 // onwards, in index order, that has landed.
490 while head < n {
491 if emitted[head] {
492 head += 1;
493 continue;
494 }
495 match st.slots[order[head]].take() {
496 Some(d) => {
497 let len = d.buffer.as_slice().len();
498 st.held -= len;
499 st.batch_bytes += len;
500 emitted[head] = true;
501 head += 1;
502 batch.push(d);
503 }
504 None => break,
505 }
506 }
507 // Checked every pass, not only when blocked, so a fast
508 // producer cannot outrun the cap while we are emitting.
509 if st.held > spill_bytes {
510 // Counted here, printed after the lock is dropped.
511 // Writing to stderr under the state mutex stalls
512 // every worker behind a slow terminal, and a failed
513 // stderr write panics *inside* the lock: poisoned
514 // under unwinding, an abort under `panic = "abort"`.
515 // The lock is for moves in and out of `slots` and
516 // `pool`, and nothing else.
517 spill_notices += 1;
518 flush_parked(&mut st, &order, &mut emitted, head, &mut batch);
519 }
520 } else {
521 while let Some(p) = st.ready.pop_front() {
522 if let Some(d) = st.slots[p].take() {
523 let len = d.buffer.as_slice().len();
524 st.held -= len;
525 st.batch_bytes += len;
526 // `order` is the identity here, so position and
527 // order-index coincide. Marked in this mode too
528 // so `emitted` means "taken" on both paths —
529 // the stall sweep below needs to know which
530 // positions are still outstanding.
531 emitted[p] = true;
532 batch.push(d);
533 }
534 }
535 }
536
537 if !batch.is_empty() {
538 break;
539 }
540 // Not a spurious-wakeup hazard: `finished == n` implies
541 // every unemitted slot is `Some`, so the drain above would
542 // have filled `batch`. Reaching here means work is still
543 // outstanding and some worker will notify — the `Completion`
544 // guard makes that true even for a worker that unwinds.
545 debug_assert!(st.finished < n, "collector stalled with all work finished");
546 if st.finished >= n {
547 break;
548 }
549 // Jobs outstanding and not one worker left to claim them.
550 // Only reachable when a worker died on a path neither
551 // `run_job`'s `catch_unwind` nor `Completion` covers — a
552 // poisoned lock, say. Waiting here is the hang; instead,
553 // take whatever landed and report the rest as unread, which
554 // `main` turns into a 2. Never a silent short read.
555 if st.live_workers == 0 {
556 for (h, flag) in emitted.iter_mut().enumerate() {
557 if *flag {
558 continue;
559 }
560 *flag = true;
561 let p = order[h];
562 match st.slots[p].take() {
563 Some(d) => {
564 let len = d.buffer.as_slice().len();
565 st.held -= len;
566 st.batch_bytes += len;
567 batch.push(d);
568 }
569 // `make_buffer` under the lock is safe *here*
570 // and nowhere else: there are no workers left
571 // to stall. The buffer stays empty, so it costs
572 // `recycle` nothing.
573 None => batch.push(Done {
574 index: jobs[p].index,
575 buffer: make_buffer(),
576 outcome: unclaimed(&jobs[p]),
577 }),
578 }
579 }
580 break;
581 }
582 st = wake.wait(st).unwrap();
583 }
584 }
585
586 for _ in 0..spill_notices {
587 eprintln!(
588 "trg: held output exceeded {spill_bytes} bytes; flushing out of order"
589 );
590 }
591
592 // Unreachable per the invariant above; a `break` rather than a spin
593 // so a bug degrades into short output instead of a hung process.
594 if batch.is_empty() {
595 break;
596 }
597
598 // Emit outside the lock: stdout may block, workers must not.
599 for d in batch.drain(..) {
600 emitted_count += 1;
601 let r = emit(&d);
602 recycle(&state, &space, d.buffer, spill_bytes);
603 if let Err(e) = r {
604 stop.store(true, Ordering::Release);
605 write_err = Some(e);
606 break 'collect;
607 }
608 }
609 }
610
611 // Anything still parked is dropped on the way out of the scope; only
612 // reachable on the early-stop path, where it is output nobody wants.
613 // Waking the blocked producers is `Teardown`'s job, on this path and on
614 // the unwinding one alike.
615 });
616
617 match write_err {
618 Some(e) => Err(e),
619 None => Ok(()),
620 }
621}
622
623/// The outcome for a job no worker ever claimed. An `errors` entry is the only
624/// partial-run signal `main` reads, so this is what makes the stalled run a 2
625/// rather than a confident "no matches, everything read".
626fn unclaimed(job: &Job) -> crate::archive::Outcome {
627 let mut o = crate::archive::Outcome::default();
628 o.errors.push(format!(
629 "{}: every worker exited before this archive was searched; not read",
630 job.path.display()
631 ));
632 o
633}
634
635/// Return a buffer to the pool so its allocation is reused, unless it grew past
636/// the spill cap — one pathological archive should not reserve its whole match
637/// volume for the rest of the run. `termcolor::Buffer` exposes no `capacity`,
638/// so the length it reached stands in for it.
639///
640/// This is the only place output bytes are actually freed, so it is also where
641/// backpressure is released. The pool itself needs no size cap: the number of
642/// buffers in existence is now bounded by the backpressure invariant, and
643/// capping it would only throw away the allocations the pool exists to keep.
644fn recycle(
645 state: &Mutex<Shared>,
646 space: &Condvar,
647 mut buffer: termcolor::Buffer,
648 spill_bytes: usize,
649) {
650 let len = buffer.as_slice().len();
651 let oversized = len > spill_bytes;
652 buffer.clear();
653 if let Ok(mut st) = state.lock() {
654 st.batch_bytes -= len;
655 if !oversized {
656 st.pool.push(buffer);
657 }
658 }
659 space.notify_all();
660}
661
662/// Emit everything that has landed but is out of turn, in index order. The
663/// escape valve behind both the byte cap and buffer starvation.
664fn flush_parked(
665 st: &mut Shared,
666 order: &[usize],
667 emitted: &mut [bool],
668 head: usize,
669 batch: &mut Vec<Done>,
670) {
671 for (h, flag) in emitted.iter_mut().enumerate().skip(head) {
672 if let Some(d) = st.slots[order[h]].take() {
673 // Note this does not relieve backpressure: the bytes move from
674 // `held` to `batch_bytes`, and only `recycle` frees them.
675 let len = d.buffer.as_slice().len();
676 st.held -= len;
677 st.batch_bytes += len;
678 *flag = true;
679 batch.push(d);
680 }
681 }
682}
683
684#[cfg(test)]
685mod tests {
686 use super::*;
687 use std::time::Duration;
688
689 /// Deadlock #4: the teardown guard was once armed *after* the spawn loop.
690 /// If `scope.spawn` panics for worker 1 — the OS refusing a thread — while
691 /// worker 0 is parked on backpressure, nothing would wake worker 0, and
692 /// `thread::scope` would wait forever to join it. The hook stands in for
693 /// the refused spawn, since the real one cannot be provoked on demand.
694 ///
695 /// The run happens on its own thread so a regression fails here after
696 /// `PATIENCE` instead of hanging the whole suite.
697 #[test]
698 fn a_spawn_failure_does_not_strand_a_parked_worker() {
699 const PATIENCE: Duration = Duration::from_secs(10);
700 let (tx, rx) = std::sync::mpsc::channel();
701 std::thread::spawn(move || {
702 let jobs = (0..4)
703 .map(|i| Job { index: i, path: std::path::PathBuf::from(format!("j{i}")) })
704 .collect();
705 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
706 run_with_spawn_hook(
707 jobs,
708 // Worker 0's first job overfills the cap, so it parks on
709 // backpressure: no collector is running to drain it.
710 Config { workers: 4, sorted: true, spill_bytes: 8 },
711 termcolor::Buffer::no_color,
712 || (),
713 |_job, _c: &mut (), b| {
714 use std::io::Write;
715 write!(b, "{}", "y".repeat(100)).unwrap();
716 crate::archive::Outcome::default()
717 },
718 |_done: &Done| Ok(()),
719 |i| {
720 if i == 1 {
721 panic!("injected: the OS refused thread {i}");
722 }
723 },
724 )
725 }));
726 let _ = tx.send(r.is_err());
727 });
728 match rx.recv_timeout(PATIENCE) {
729 Ok(panicked) => assert!(panicked, "the injected spawn failure must propagate"),
730 Err(_) => panic!("run hung after a spawn failure: a parked worker was never released"),
731 }
732 }
733}