From 200a55e29f11b3313155dfe3d27ce31e651d749c Mon Sep 17 00:00:00 2001 From: enlight3d <19186686+enlight3d@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:24:48 +0100 Subject: [PATCH 1/2] leonida-gpu: bound the reaper's line (LEONIDA_REAPER_LIMIT) The reaper thread's channel had no bound and nothing slowed its senders. On an RTX 3090 its line grew to hundreds of thousands of things in most runs; the landed host lists waiting there kept their scratch chunks, and the runs that were not stopped ended in a device loss as private memory neared Windows' commit limit, while LEONIDA_REAPER=0 kept memory flat. The lists' scratch was in card memory; it is in PC memory by default since #2819, where the line should stay short. This bound is the safety net for LEONIDA_SCRATCH_CARD=1 and any other cause of a backlog. Once the line (REAPING) holds LEONIDA_REAPER_LIMIT things (4096 by default; 0: no bound, as before; LEONIDA_AB can turn it on and off), what the host is done with is let go of by the thread done with it, as LEONIDA_REAPER=0 does. land(), bury() and fronts_let_go() go through one helper (reap), which counts each batch as the reaper thread takes it off; the check and the count are one atomic step (hand_over), so the line holds fewer than the bound and one batch however many threads send. A batch comes off the line also if letting it go panics. The first time the bound takes hold is logged once; the census memory line counts what was let go in place (REAPED_IN_PLACE) and says the bound. Diagnostics only: host lists and preludes made per frame by the title's threads, the submitting thread and the others, with their time; a SPLIT slot for preludes made and recorded; HostList::reset split into what the list held let go and the allocator and list resets. Claim: D3D12-REAPER-BOUNDED-QUEUE Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/census.rs | 6 +- d3d12/crates/leonida-gpu/src/copystat.rs | 9 +- d3d12/crates/leonida-gpu/src/host.rs | 682 ++++++++++++++++++++--- d3d12/docs/switches.md | 3 +- 4 files changed, 621 insertions(+), 79 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/census.rs b/d3d12/crates/leonida-gpu/src/census.rs index 52ea8adec2..26e085f1de 100644 --- a/d3d12/crates/leonida-gpu/src/census.rs +++ b/d3d12/crates/leonida-gpu/src/census.rs @@ -338,11 +338,13 @@ pub(crate) fn log() { for line in lines(&stands()) { tracing::info!("{line}"); } - let [waiting, handed] = crate::host::waiting_to_go(); + let [waiting, handed, in_place, limit] = crate::host::waiting_to_go(); tracing::info!( "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them (LEONIDA_BURY_LAG), \ {handed} retired objects, landed host lists and lists' fronts handed to the thread that lets them go \ - and not let go yet (LEONIDA_REAPER=0: let go by the submitting thread)" + and not let go yet (LEONIDA_REAPER=0: let go by the submitting thread); \ + {in_place} let go by the thread done with them instead, since the start, the reaper thread's line holding \ + LEONIDA_REAPER_LIMIT={limit} or more (0: no bound)" ); } diff --git a/d3d12/crates/leonida-gpu/src/copystat.rs b/d3d12/crates/leonida-gpu/src/copystat.rs index e041177317..70686d233f 100644 --- a/d3d12/crates/leonida-gpu/src/copystat.rs +++ b/d3d12/crates/leonida-gpu/src/copystat.rs @@ -129,6 +129,11 @@ pub(crate) enum C { WaitsForGroups, WaitsForBuffers, IndirectBounded, + /// Of `ResetNs`: what the lists held let go (their steps, states and + /// scratch), and their allocators and lists reset + /// (`crate::host::HostList::reset`). + ResetLetGoNs, + ResetCommandsNs, } const COUNTERS: usize = 80; /// One of some sets of counters, each in lines of the processor's memory of @@ -1319,7 +1324,7 @@ pub(crate) fn log(frames: f64) { tracing::info!( "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \ until the first submission; {:.1} ms from the last submission to the present call; \ - lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ + lists reset in {:.1} ms (what they held let go {:.1}, allocators and lists reset {:.1}); the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \ putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \ submissions run at the present with their waits not met; waits for memory values: \ @@ -1329,6 +1334,8 @@ pub(crate) fn log(frames: f64) { ms(c[C::UntilSubmitUs as usize]), ms(c[C::TailUs as usize]), c[C::ResetNs as usize] / 1e6, + c[C::ResetLetGoNs as usize] / 1e6, + c[C::ResetCommandsNs as usize] / 1e6, ms(c[C::BackScanUs as usize]), c[C::BackDiffer as usize], ms(c[C::BackSyncUs as usize]), diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 708e12ce5b..36be36ed90 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -595,15 +595,9 @@ fn bury(finished: u64) { if done.is_empty() { return; } - // Let go of on the reaper thread ([`reaper`]), if there is one. - if let Some(tx) = reaper() { - let handed = done.len() as u64; - REAPING.fetch_add(handed, Ordering::Relaxed); - if let Err(std::sync::mpsc::SendError(Reaped::Objects(done))) = tx.send(Reaped::Objects(done)) { - REAPING.fetch_sub(handed, Ordering::Relaxed); - drop(done); - } - } + // Let go of on the reaper thread ([`reaper`]), if there is one and its + // line has room ([`reaper_limit`]); here otherwise, as without one. + reap(Reaped::Objects(done), drop); } /// Takes out of `queues` what waited for submissions up to `finished`: of @@ -687,13 +681,20 @@ mod retired_tests { /// empty line while the lists and fronts behind them held gigabytes. static REAPING: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// What was let go of by the thread done with it instead of the reaper +/// thread, as [`REAPING`] counts it, because that thread's line held +/// [`reaper_limit`] or more ([`hand_over`]), since the start. +static REAPED_IN_PLACE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// For the memory lines: the objects let go that wait for the submissions -/// that may use them ([`retire`], [`bury_lag`]), and those handed to the -/// reaper thread and not dropped yet. +/// that may use them ([`retire`], [`bury_lag`]), those handed to the +/// reaper thread and not dropped yet, what was let go of in place since the +/// start because that thread's line was full ([`REAPED_IN_PLACE`]), and its +/// bound ([`reaper_limit`]). #[cfg(feature = "diagnostics")] -pub(crate) fn waiting_to_go() -> [u64; 2] { +pub(crate) fn waiting_to_go() -> [u64; 4] { let waiting: usize = RETIRED.iter().map(|queue| queue.lock().unwrap_or_else(|e| e.into_inner()).len()).sum(); - [waiting as u64, REAPING.load(Ordering::Relaxed)] + [waiting as u64, REAPING.load(Ordering::Relaxed), REAPED_IN_PLACE.load(Ordering::Relaxed), reaper_limit()] } /// Whether what the host is done with is let go of on a thread of its own @@ -716,7 +717,9 @@ fn reaping() -> bool { /// on the submitting thread at the end of each submission sent ahead: in a /// timeline of the world (Series X, RX 7900 XTX) host lists were reset 250 /// times a frame, 20 ms of threads' time. Only what is already due is -/// sent ([`bury_lag`] and [`land`]'s lag are unchanged). After mgrein's +/// sent ([`bury_lag`] and [`land`]'s lag are unchanged), and nothing when +/// its line is full ([`reaper_limit`]): the thread done with it lets it go +/// then, as without this thread. After mgrein's /// VIctory-7900XTX a2cf68bb (GPL-3.0-or-later, as this), through /// Grimkaaah/Victory-Grimkaaah f2586ef (GPL-3.0), which measured -2.3 to /// -3.8 ms a frame with it on its host. @@ -732,28 +735,9 @@ fn reaper() -> Option<&'static std::sync::mpsc::Sender> { .name("leonida-reaper".into()) .spawn(move || { for reaped in rx { - match reaped { - Reaped::Lists(landed) => { - let _reaping = crate::timeline::span("reaper: landed lists reset and given back"); - let handed = landed_count(&landed); - for (lists, order) in landed { - crate::list::recycle(lists, &order); - } - REAPING.fetch_sub(handed, Ordering::Relaxed); - } - Reaped::Objects(objects) => { - let _reaping = crate::timeline::span("reaper: retired objects dropped"); - let handed = objects.len() as u64; - drop(objects); - REAPING.fetch_sub(handed, Ordering::Relaxed); - } - Reaped::Fronts(fronts) => { - let _reaping = crate::timeline::span("reaper: lists' fronts dropped"); - let handed = fronts.len() as u64; - drop(fronts); - REAPING.fetch_sub(handed, Ordering::Relaxed); - } - } + #[cfg(test)] + let _held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); + reap_one(&REAPING, reaped); } }) .ok() @@ -771,6 +755,17 @@ enum Reaped { Fronts(Vec), } +impl Reaped { + /// How many things it is, as [`REAPING`] counts them. + fn count(&self) -> u64 { + match self { + Reaped::Lists(landed) => landed_count(landed), + Reaped::Objects(objects) => objects.len() as u64, + Reaped::Fronts(fronts) => fronts.len() as u64, + } + } +} + /// The host lists of landed flights, as [`REAPING`] counts them. fn landed_count(landed: &[(Vec, Vec)]) -> u64 { landed.iter().map(|(lists, _)| lists.len() as u64).sum() @@ -782,6 +777,489 @@ fn landed_count(landed: &[(Vec, Vec)]) -> u64 { // staging buffers, which any thread lets go of. unsafe impl Send for Reaped {} +/// Lets go of `what` ([`Reaped::count`] things, as [`REAPING`] counts them) on the +/// reaper thread ([`reaper`]) if there is one and its line has room +/// ([`reaper_limit`], [`hand_over`]); otherwise `in_place` lets go of it +/// here, as with `LEONIDA_REAPER=0`. What [`land`], [`bury`] and +/// [`fronts_let_go`] are done with goes this way. +fn reap(what: Reaped, in_place: impl FnOnce(Reaped)) { + reap_through(reaper(), reaper_limit(), what, in_place); +} + +/// [`reap`] through the reaper thread behind `tx` (none: `in_place` at once, +/// nothing counted), with the bound `limit`. +fn reap_through(tx: Option<&std::sync::mpsc::Sender>, limit: u64, what: Reaped, in_place: impl FnOnce(Reaped)) { + let Some(tx) = tx else { + in_place(what); + return; + }; + // (Counted as the reaper thread takes it off: `Reaped::count`.) + let handed = what.count(); + if let Err(what) = hand_over(tx, &REAPING, &REAPED_IN_PLACE, limit, handed, what) { + in_place(what); + } +} + +/// What the reaper thread does with what it takes ([`reaper`]): lets go of +/// it, and takes it off `line` ([`Off`]). +fn reap_one(line: &std::sync::atomic::AtomicU64, reaped: Reaped) { + // (Off the line once let go of, also if that panics.) + let _off = Off(line, reaped.count()); + match reaped { + Reaped::Lists(landed) => { + let _reaping = crate::timeline::span("reaper: landed lists reset and given back"); + for (lists, order) in landed { + crate::list::recycle(lists, &order); + } + } + Reaped::Objects(objects) => { + let _reaping = crate::timeline::span("reaper: retired objects dropped"); + drop(objects); + } + Reaped::Fronts(fronts) => { + let _reaping = crate::timeline::span("reaper: lists' fronts dropped"); + drop(fronts); + } + } +} + +/// Takes `.1` things off the line `.0` ([`REAPING`]) when dropped: once the +/// reaper thread has let go of a batch, or while it unwinds from one, so a +/// panic does not leave the line counting what is gone. It covers only the +/// batch under way: after such a panic the batches still waiting keep their +/// count in [`REAPING`] (as without the bound), and since nothing can be +/// handed to the thread any more everything is let go of in place, which +/// stays correct. +struct Off<'a>(&'a std::sync::atomic::AtomicU64, u64); + +impl Drop for Off<'_> { + fn drop(&mut self) { + let before = self.0.fetch_sub(self.1, Ordering::Relaxed); + debug_assert!(std::thread::panicking() || before >= self.1, "the reaper's line went below nothing: {before} less {}", self.1); + } +} + +/// For tests: the reaper thread takes nothing off its line while this is +/// held ([`reaper`]). +#[cfg(test)] +static REAPER_HELD: Mutex<()> = Mutex::new(()); + +/// Hands `what`, `handed` things of it as [`REAPING`] counts them, to the +/// reaper thread behind `tx`, counted in `line` until that thread is done +/// with them, if `line` holds fewer than `limit` ([`reaper_limit`]; 0: no +/// bound). Given back otherwise, counted in `in_place`, for the caller to +/// let go of on its own thread as with `LEONIDA_REAPER=0`; and given back, +/// not counted, if the thread is gone. So the line holds fewer than `limit` +/// things and one batch, however many threads send. +/// +/// What is let go of in place may go before what still waits in the line: +/// lists the card has run (a [`crate::list::Detached`] owns its uploads and +/// descriptor state), retired objects already due and lists' fronts, none +/// of which waits for another. The same happens when `LEONIDA_AB` turns +/// `LEONIDA_REAPER` off while the line holds things. +fn hand_over( + tx: &std::sync::mpsc::Sender, + line: &std::sync::atomic::AtomicU64, + in_place: &std::sync::atomic::AtomicU64, + limit: u64, + handed: u64, + what: T, +) -> Result<(), T> { + // Counted before it is sent: the thread takes off only what was put on. + let room = |held: u64| (limit == 0 || held < limit).then_some(held.wrapping_add(handed)); + if let Err(held) = line.fetch_update(Ordering::Relaxed, Ordering::Relaxed, room) { + in_place.fetch_add(handed, Ordering::Relaxed); + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::info!( + "the reaper thread's line holds {held} things, LEONIDA_REAPER_LIMIT={limit} or more: what it cannot take \ + is let go of by the thread done with it from now on (said once; the census memory line counts it)" + ); + }); + return Err(what); + } + tx.send(what).map_err(|std::sync::mpsc::SendError(what)| { + line.fetch_sub(handed, Ordering::Relaxed); + what + }) +} + +/// The bound on the reaper thread's line, as [`REAPING`] counts it +/// (`LEONIDA_REAPER_LIMIT=`, 4,096 by default; `0`: no bound, as +/// before; `LEONIDA_AB` can turn the bound on and off while the title runs). +/// Once the line holds that many things, what the host is done with is let +/// go of by the thread done with it, as with `LEONIDA_REAPER=0` +/// ([`hand_over`]). +/// +/// Measured on 2026-11-30 on an RTX 3090 24 GB (NVIDIA 621.40, i9-13900K; +/// enlight3d's runs of 600 to 900 s into the world): the reaper did not keep +/// up, its line grew to some 250,000-600,000 within 3 to 8 minutes in most +/// runs, the landed host lists waiting there kept their scratch chunks +/// (16.1-16.6 GB mapped at the device losses), and the runs that were not +/// stopped ended in a device loss as the process's private memory neared +/// Windows' commit limit. With +/// `LEONIDA_REAPER=0` memory stayed flat in 4 runs of 4. A thing waiting in +/// the line held some 24-37 KB of mapped scratch and 245-320 KB of private +/// memory on average, so 4,096 of them some 100-150 MB and 1.0-1.3 GB. On an RTX +/// 4060 8 GB (MoonEyes's control, the same day) the line stayed under some +/// 400; on the 3090 the runs without a backlog passed 4,096 for a while +/// (peaks of 12,000-19,000, 3,100-3,700 at their end), so the bound may take +/// hold briefly there, which the runs with `LEONIDA_REAPER=0` say does no +/// harm. Those lists' scratch was in the card's memory; it is in the +/// computer's memory by default now ([`scratch_card`]), where the line should +/// stay short: the bound is a safety net for the card's memory and any other +/// cause of a backlog. +const REAPER_LIMIT: u64 = 4096; + +/// The bound in force ([`REAPER_LIMIT`]), the variable read once; with +/// `LEONIDA_AB` naming it, that bound in the phases that have it on and none +/// in the others. +fn reaper_limit() -> u64 { + static LIMIT: OnceLock = OnceLock::new(); + let set = *LIMIT.get_or_init(reaper_limit_set); + #[cfg(feature = "diagnostics")] + let phase = crate::ab::pick("LEONIDA_REAPER_LIMIT"); + #[cfg(not(feature = "diagnostics"))] + let phase = None; + limit_in_phase(phase, set) +} + +/// The bound in force, from `LEONIDA_AB`'s phase (`None`: it does not name +/// `LEONIDA_REAPER_LIMIT`; off: no bound; on: the bound set, or the default +/// when the variable says none) and the bound the variable sets. +fn limit_in_phase(phase: Option, set: u64) -> u64 { + match (phase, set) { + (None, set) => set, + (Some(false), _) => 0, + (Some(true), 0) => REAPER_LIMIT, + (Some(true), set) => set, + } +} + +/// The bound `LEONIDA_REAPER_LIMIT` sets now ([`reaper_limit`] reads it once). +fn reaper_limit_set() -> u64 { + reaper_limit_from(std::env::var("LEONIDA_REAPER_LIMIT").ok().as_deref()) +} + +/// [`reaper_limit`] from the variable's value: a number of things, or the +/// default when it is unset or not a number. +fn reaper_limit_from(value: Option<&str>) -> u64 { + value.and_then(|v| v.trim().parse().ok()).unwrap_or(REAPER_LIMIT) +} + +#[cfg(test)] +mod reaper_tests { + use super::{REAPER_LIMIT, hand_over, limit_in_phase, reaper_limit_from}; + use super::{ListFront, Off, fronts_let_go, reap_through}; + use super::{REAPED_IN_PLACE, REAPER_HELD, REAPING, Reaped, Retired, reap, reaper_limit, reaper_limit_set}; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::{Arc, Mutex}; + + /// Counts itself when it is dropped. + struct Told(Arc>); + impl Drop for Told { + fn drop(&mut self) { + *self.0.lock().unwrap() += 1; + } + } + + /// A reaper that never takes anything off its line (as on the RTX 3090, + /// where the line grew to hundreds of thousands): the line stays under + /// the bound plus one batch, and every batch over it is given back to the + /// sender, which lets it go where it is. + #[test] + fn a_full_reaper_line_sends_the_rest_back_to_be_let_go_in_place() { + const BATCH: u64 = 7; + const BATCHES: u64 = 200; + // (A bound a batch reaches exactly, and one it overshoots.) + for limit in [98, 100] { + let (tx, rx) = std::sync::mpsc::channel::>(); + let line = AtomicU64::new(0); + let in_place = AtomicU64::new(0); + let dropped = Arc::new(Mutex::new(0u64)); + let mut sent = 0; + for _ in 0..BATCHES { + let batch: Vec = (0..BATCH).map(|_| Told(dropped.clone())).collect(); + match hand_over(&tx, &line, &in_place, limit, BATCH, batch) { + Ok(()) => sent += BATCH, + Err(batch) => drop(batch), + } + let held = line.load(Ordering::Relaxed); + assert!(held < limit + BATCH, "the reaper's line holds {held}, over {limit} and a batch of {BATCH}"); + } + // Batches go while the line holds fewer than the bound, and only then. + assert_eq!(sent, limit.div_ceil(BATCH) * BATCH, "bound {limit}"); + assert_eq!(line.load(Ordering::Relaxed), sent, "the line counts what was handed over, and only that"); + assert_eq!(rx.try_iter().map(|batch| batch.len() as u64).sum::(), sent); + assert_eq!(in_place.load(Ordering::Relaxed), BATCHES * BATCH - sent, "what was let go in place is counted"); + assert_eq!(*dropped.lock().unwrap(), BATCHES * BATCH, "everything was let go, on the line or here"); + } + } + + /// Once the reaper has taken things off its line, batches go to it again; + /// with no bound (0) every batch goes, as before. + #[test] + fn a_reaper_that_keeps_up_gets_every_batch() { + let (tx, rx) = std::sync::mpsc::channel::>(); + let line = AtomicU64::new(0); + let in_place = AtomicU64::new(0); + for _ in 0..50 { + assert!(hand_over(&tx, &line, &in_place, 10, 4, vec![0; 4]).is_ok()); + // The reaper, as it does once a batch is let go. + for batch in rx.try_iter() { + line.fetch_sub(batch.len() as u64, Ordering::Relaxed); + } + } + for _ in 0..1000 { + assert!(hand_over(&tx, &line, &in_place, 0, 4, vec![0; 4]).is_ok()); + } + assert_eq!(line.load(Ordering::Relaxed), 4000); + assert_eq!(in_place.load(Ordering::Relaxed), 0); + // With the thread gone, the batch comes back and nothing stays counted. + drop(rx); + assert!(hand_over(&tx, &line, &in_place, 0, 4, vec![0; 4]).is_err()); + assert_eq!(line.load(Ordering::Relaxed), 4000); + } + + /// Threads that hand things over at the same time, to a reaper that never + /// takes anything off its line: together they never fill it past the + /// bound and one batch (the check and the count are one step). + #[test] + fn threads_together_never_overfill_the_reaper_line() { + const LIMIT: u64 = 64; + const BATCH: u64 = 4; + const THREADS: usize = 8; + const TRIES: usize = 4; + const ROUNDS: usize = 2000; + let (tx, rx) = std::sync::mpsc::channel::(); + let line = AtomicU64::new(0); + let in_place = AtomicU64::new(0); + let start = std::sync::Barrier::new(THREADS + 1); + let end = std::sync::Barrier::new(THREADS + 1); + let (mut most, mut least, mut miscounted) = (0, u64::MAX, 0); + std::thread::scope(|s| { + for _ in 0..THREADS { + s.spawn(|| { + for _ in 0..ROUNDS { + start.wait(); + for _ in 0..TRIES { + let _ = hand_over(&tx, &line, &in_place, LIMIT, BATCH, BATCH); + } + end.wait(); + } + }); + } + // (Kept and checked after the rounds: a panic here would leave the + // threads waiting.) + for _ in 0..ROUNDS { + start.wait(); + end.wait(); + let held = line.swap(0, Ordering::Relaxed); + most = most.max(held); + least = least.min(held); + if rx.try_iter().sum::() != held { + miscounted += 1; + } + } + }); + assert!(most < LIMIT + BATCH, "the reaper's line held {most}, over {LIMIT} and a batch of {BATCH}"); + assert!(least >= LIMIT, "the line was not filled to its bound in a round ({least})"); + assert_eq!(miscounted, 0, "rounds whose line counted other than what was sent"); + let tried = (ROUNDS * THREADS * TRIES) as u64 * BATCH; + assert_eq!(in_place.load(Ordering::Relaxed), tried - ROUNDS as u64 * LIMIT); + } + + /// `LEONIDA_REAPER_LIMIT`: bounded unless it says 0. + #[test] + fn the_reaper_line_is_bounded_unless_asked_not_to_be() { + let default = reaper_limit_from(None); + assert!(default > 0, "the reaper's line has a bound by default"); + assert_eq!(reaper_limit_from(Some("0")), 0); + assert_eq!(reaper_limit_from(Some("5000")), 5000); + assert_eq!(reaper_limit_from(Some("many")), default); + } + + /// The host's own way ([`reap`], as [`super::land`], [`super::bury`] and + /// [`super::fronts_let_go`] take it), with the reaper thread held: what is + /// handed to it stops at the bound, the rest is let go of here at once, and + /// once the thread goes on it lets go of what waited. + #[test] + fn with_the_reaper_thread_held_the_host_lets_go_in_place() { + const BATCH: u64 = 64; + let limit = reaper_limit(); + if super::reaper().is_none() || limit == 0 { + eprintln!("no reaper thread or no bound (LEONIDA_REAPER, LEONIDA_REAPER_LIMIT): not tested"); + return; + } + let held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); + let dropped = Arc::new(Mutex::new(0u64)); + let in_place_before = REAPED_IN_PLACE.load(Ordering::Relaxed); + let batches = limit.div_ceil(BATCH) + 10; + let mut here = 0; + let mut most = 0; + for _ in 0..batches { + let done: Vec<(u64, Retired)> = (0..BATCH).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect(); + reap(Reaped::Objects(done), |what| { + here += BATCH; + drop(what); + }); + most = most.max(REAPING.load(Ordering::Relaxed)); + } + // (Other tests may hand things over meanwhile, in batches as small.) + assert!(most < limit + BATCH, "the reaper's line held {most}, over {limit} and a batch of {BATCH}"); + assert!(here >= 10 * BATCH, "{here} things let go here, of {}", batches * BATCH); + assert_eq!(*dropped.lock().unwrap(), here, "what was let go here went at once"); + assert!(REAPED_IN_PLACE.load(Ordering::Relaxed) - in_place_before >= here); + drop(held); + let all = batches * BATCH; + let started = std::time::Instant::now(); + while *dropped.lock().unwrap() < all && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(*dropped.lock().unwrap(), all, "the reaper thread let go of what waited"); + // And took it off its line. + while REAPING.load(Ordering::Relaxed) >= limit && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let line = REAPING.load(Ordering::Relaxed); + assert!(line < limit, "the reaper's line still holds {line} of a bound of {limit}"); + } + + /// Without a reaper thread (`LEONIDA_REAPER=0`) what the host is done + /// with is let go of where it is, at once, as before. + #[test] + fn without_a_reaper_thread_the_host_lets_go_in_place() { + let dropped = Arc::new(Mutex::new(0u64)); + let done: Vec<(u64, Retired)> = (0..3).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect(); + let mut here = 0; + reap_through(None, 4096, Reaped::Objects(done), |what| { + here += what.count(); + drop(what); + }); + assert_eq!(here, 3, "the batch came back to be let go here"); + assert_eq!(*dropped.lock().unwrap(), 3, "and went at once"); + } + + /// Lists' fronts take the host's way ([`fronts_let_go`]): to the reaper + /// thread, counted in its line, while it has room; let go of here, counted + /// as such, once it is full. + #[test] + fn lists_fronts_go_to_the_reaper_or_here() { + let limit = reaper_limit(); + if super::reaper().is_none() || limit == 0 { + eprintln!("no reaper thread or no bound (LEONIDA_REAPER, LEONIDA_REAPER_LIMIT): not tested"); + return; + } + // (A test before may have left the line full for the thread to empty.) + let started = std::time::Instant::now(); + let held = loop { + let held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); + if REAPING.load(Ordering::Relaxed) + 5 < limit { + break held; + } + drop(held); + let line = REAPING.load(Ordering::Relaxed); + assert!(started.elapsed() < std::time::Duration::from_secs(30), "the reaper's line stayed at {line} of {limit}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + let line = REAPING.load(Ordering::Relaxed); + fronts_let_go((0..5).map(|_| ListFront::default()).collect()); + let handed = REAPING.load(Ordering::Relaxed) - line; + REAPING.fetch_add(limit, Ordering::Relaxed); + let in_place = REAPED_IN_PLACE.load(Ordering::Relaxed); + fronts_let_go((0..7).map(|_| ListFront::default()).collect()); + let kept = REAPED_IN_PLACE.load(Ordering::Relaxed) - in_place; + REAPING.fetch_sub(limit, Ordering::Relaxed); + drop(held); + assert_eq!(handed, 5, "handed to the reaper thread while its line had room"); + assert_eq!(kept, 7, "let go of here once it was full"); + } + + /// What the reaper thread takes is let go of and taken off its line, as + /// many things as each batch counts. + #[test] + fn the_reaper_thread_lets_go_and_takes_off_its_line() { + use super::reap_one; + let line = AtomicU64::new(10); + let dropped = Arc::new(Mutex::new(0u64)); + reap_one(&line, Reaped::Objects((0..3).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect())); + assert_eq!((line.load(Ordering::Relaxed), *dropped.lock().unwrap()), (7, 3), "three retired objects"); + reap_one(&line, Reaped::Fronts((0..2).map(|_| ListFront::default()).collect())); + assert_eq!(line.load(Ordering::Relaxed), 5, "two lists' fronts"); + reap_one(&line, Reaped::Lists(vec![(Vec::new(), Vec::new())])); + assert_eq!(line.load(Ordering::Relaxed), 5, "a flight with no host list counts none"); + } + + /// The reaper thread takes a batch off its line once it has let go of it, + /// and also when letting go of it panics. + #[test] + fn a_batch_comes_off_the_line_even_if_letting_it_go_panics() { + let line = AtomicU64::new(10); + drop(Off(&line, 4)); + assert_eq!(line.load(Ordering::Relaxed), 6); + let caught = std::panic::catch_unwind(|| { + let _off = Off(&line, 6); + panic!("a batch whose letting go panics"); + }); + assert!(caught.is_err()); + assert_eq!(line.load(Ordering::Relaxed), 0); + } + + /// Who makes host objects, by the name of its thread. + #[cfg(feature = "diagnostics")] + #[test] + fn host_objects_are_counted_by_who_made_them() { + use super::{MADE_BY, host, maker}; + assert_eq!(maker(None), 0); + assert_eq!(maker(Some("main")), 0); + assert_eq!(maker(Some("leonida-submit")), 1); + assert_eq!(maker(Some("leonida-reaper")), 2); + let Some(host) = host() else { + eprintln!("no D3D12 device; host objects made not counted"); + return; + }; + let count = |kind: usize| MADE_BY[kind][1].iter().map(|n| n.load(Ordering::Relaxed)).collect::>(); + let (lists, preludes) = (count(0), count(1)); + std::thread::Builder::new() + .name("leonida-submit".into()) + .spawn(move || { + host.new_list().unwrap(); + host.make_prelude().unwrap(); + }) + .unwrap() + .join() + .unwrap(); + let (lists_after, preludes_after) = (count(0), count(1)); + assert!(lists_after[0] > lists[0] && lists_after[1] > lists[1], "a host list by the submitting thread: {lists:?} {lists_after:?}"); + assert!(preludes_after[0] > preludes[0] && preludes_after[1] > preludes[1], "a prelude: {preludes:?} {preludes_after:?}"); + } + + /// `LEONIDA_REAPER_LIMIT` is read from the environment. + #[test] + fn the_reaper_bound_comes_from_its_variable() { + // SAFETY: the system locks the process's environment block; a test + // that reads the bound meanwhile takes 1,234 as it, which it is written + // for. + unsafe { std::env::set_var("LEONIDA_REAPER_LIMIT", "1234") }; + let set = reaper_limit_set(); + unsafe { std::env::remove_var("LEONIDA_REAPER_LIMIT") }; + assert_eq!(set, 1234); + } + + /// With `LEONIDA_AB` naming `LEONIDA_REAPER_LIMIT`: no bound in the phases + /// that have it off, the bound set (or the default) in the others; without + /// it, the bound set. + #[test] + fn the_reaper_bound_in_an_ab_phase() { + assert_eq!(limit_in_phase(None, 4096), 4096); + assert_eq!(limit_in_phase(None, 0), 0); + assert_eq!(limit_in_phase(Some(false), 4096), 0); + assert_eq!(limit_in_phase(Some(false), 0), 0); + assert_eq!(limit_in_phase(Some(true), 5000), 5000); + assert_eq!(limit_in_phase(Some(true), 0), REAPER_LIMIT); + } +} + /// Objects [`retire`] dropped at once (no submission was running) and /// kept until a running submission finished, since the start. static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; @@ -1142,6 +1620,39 @@ pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync: /// makes at its start). pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +/// Leonida (diagnostics): host lists ([`Host::new_list`]) and preludes +/// ([`Host::make_prelude`]: an allocator and a list each) made since the +/// frame-rate line before, by who made them ([`maker`]): how many, and the +/// nanoseconds it took. One is made when the pool of reset lists has none +/// (`crate::list::fresh_list`), and a list made anew makes its prelude at its +/// first submission ([`lazy_prelude`]): on an RTX 3090 whose reaper +/// thread fell behind, 2-6 ms each on the frame's threads (2026-11-30). +#[cfg(feature = "diagnostics")] +static MADE_BY: [[[std::sync::atomic::AtomicU64; 2]; 3]; 2] = + [const { [const { [const { std::sync::atomic::AtomicU64::new(0) }; 2] }; 3] }; 2]; + +/// Who makes host objects, for [`MADE_BY`] by its thread's name: 0 the +/// title's threads (the layer did not start them: no name, or the process's +/// first thread), 1 the submitting thread (`leonida-submit`, with +/// `crate::queue::behind`), 2 the layer's other threads. +#[cfg(feature = "diagnostics")] +fn maker(name: Option<&str>) -> usize { + match name { + None | Some("main") => 0, + Some("leonida-submit") => 1, + Some(_) => 2, + } +} + +/// Counts a host list (`kind` 0) or prelude (1) made since `started`, by +/// the calling thread ([`MADE_BY`]). +#[cfg(feature = "diagnostics")] +fn count_made(kind: usize, started: std::time::Instant) { + let by = &MADE_BY[kind][maker(std::thread::current().name())]; + by[0].fetch_add(1, Ordering::Relaxed); + by[1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); +} + /// The process's private bytes (diagnostics: around the making of lists). #[cfg(feature = "diagnostics")] fn private_bytes() -> u64 { @@ -4895,28 +5406,15 @@ fn land() { return; } // On the reaper thread ([`reaper`]): the lists have run; nothing else - // holds them. - let landed = match reaper() { - Some(tx) => { - let handed = landed_count(&landed); - REAPING.fetch_add(handed, Ordering::Relaxed); - match tx.send(Reaped::Lists(landed)) { - Ok(()) => return, - Err(std::sync::mpsc::SendError(Reaped::Lists(landed))) => { - REAPING.fetch_sub(handed, Ordering::Relaxed); - landed - } - Err(_) => { - REAPING.fetch_sub(handed, Ordering::Relaxed); - return; - } - } + // holds them. Here without one, or with its line full ([`reaper_limit`]). + reap(Reaped::Lists(landed), |reaped| { + let Reaped::Lists(landed) = reaped else { + unreachable!("landed lists come back as they went"); + }; + for (lists, order) in landed { + crate::list::recycle(lists, &order); } - None => landed, - }; - for (lists, order) in landed { - crate::list::recycle(lists, &order); - } + }); } /// The thread that settles the flights once the card has run them all @@ -5825,12 +6323,15 @@ impl Host { use crate::copystat::{C, add}; add(C::HostLists, 1); add(C::HostListNs, started.elapsed().as_nanos() as u64); + count_made(0, started); } list } /// An allocator and a closed list for a prelude. fn make_prelude(&self) -> Option { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: plain object creation. let made: windows::core::Result = unsafe { (|| { @@ -5844,6 +6345,8 @@ impl Host { })() }; LISTS[1].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + count_made(1, started); match made { Ok(prelude) => Some(prelude), Err(e) => { @@ -8597,6 +9100,8 @@ impl HostList { }; give_batches(given); } + #[cfg(feature = "diagnostics")] + let let_go = std::time::Instant::now(); let reset = { let mut allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner()); let (allocator, made) = &mut *allocator; @@ -8611,7 +9116,12 @@ impl HostList { fail(format_args!("a host command list did not reset ({e})")); } #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); + { + use crate::copystat::{C, add}; + add(C::ResetNs, started.elapsed().as_nanos() as u64); + add(C::ResetLetGoNs, (let_go - started).as_nanos() as u64); + add(C::ResetCommandsNs, let_go.elapsed().as_nanos() as u64); + } } /// Something changed in this list that bringing a draw's textures and @@ -9033,6 +9543,9 @@ impl HostList { if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() { return None; } + // (Made, if it is the list's first, and recorded: `SPLIT`.) + #[cfg(feature = "diagnostics")] + let preluding = std::time::Instant::now(); let Some((allocator, list)) = self .prelude .get_or_init(|| host().and_then(|h| h.make_prelude()).map(list_prelude)) @@ -9074,6 +9587,8 @@ impl HostList { if let Err(e) = recorded { fail(format_args!("a host state prelude did not record ({e})")); } + #[cfg(feature = "diagnostics")] + SPLIT[16].fetch_add(preluding.elapsed().as_nanos() as u64, Ordering::Relaxed); list.cast().ok() } @@ -10436,15 +10951,16 @@ mod address_hash_tests { /// copy at a time: nanoseconds, and how many. Ahead of all that: the wait for /// the submission lock, the steps done on the card planned ([`card_steps`]), /// the flights waited for, the heaps' records and what is swept; and, at the -/// end, the wait for the heaps' records. +/// end, the wait for the heaps' records. Among the lists' steps, the +/// preludes made (a list's first) and recorded ([`HostList::prelude`]). #[cfg(feature = "diagnostics")] -static SPLIT: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; +static SPLIT: [std::sync::atomic::AtomicU64; 17] = [const { std::sync::atomic::AtomicU64::new(0) }; 17]; /// What of [`SPLIT`] the frame-rate line took. #[cfg(feature = "diagnostics")] -static SPLIT_TAKEN: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; +static SPLIT_TAKEN: [std::sync::atomic::AtomicU64; 17] = [const { std::sync::atomic::AtomicU64::new(0) }; 17]; /// [`SPLIT`]'s names, for the A/B counters line (`_ns`: nanoseconds; 10 is a count). #[cfg(feature = "diagnostics")] -pub(crate) const SPLIT_NAMES: [&str; 16] = [ +pub(crate) const SPLIT_NAMES: [&str; 17] = [ "ask_watch_ns", "title_bytes_ns", "steps_ns", @@ -10461,11 +10977,12 @@ pub(crate) const SPLIT_NAMES: [&str; 16] = [ "flights_wait_ns", "heap_records_ns", "heap_records_end_ns", + "preludes_ns", ]; /// [`SPLIT`] since the start. #[cfg(feature = "diagnostics")] -pub(crate) fn split_totals() -> [u64; 16] { +pub(crate) fn split_totals() -> [u64; 17] { crate::ab::load(&SPLIT) } @@ -10508,7 +11025,8 @@ fn split_line(frames: f64) { tracing::info!( "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ - several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ + several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them; \ + preludes made and recorded {:.1}), {:.1} snapshots, {:.1} for copies in the \ card's memory, {:.1} sending the lists (LEONIDA_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \ planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \ for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (LEONIDA_ASK_EARLY)", @@ -10524,6 +11042,7 @@ fn split_line(frames: f64) { ms[9], ms[10] * 1e6, ms[7], + ms[16], ms[3], ms[4], ms[5], @@ -10536,6 +11055,25 @@ fn split_line(frames: f64) { e[0], e[1] / 1e3, ); + let made: Vec = MADE_BY.iter().flatten().flatten().map(|n| n.swap(0, Ordering::Relaxed) as f64).collect(); + tracing::info!( + "host objects made per frame (a host list when the pool of reset lists has none): host lists by the title's threads \ + {:.1} in {:.1} ms, by the submitting thread {:.1} in {:.1} ms, by other threads {:.1} in {:.1} ms; preludes (an \ + allocator and a list, LEONIDA_LAZY_PRELUDE) by the title's threads {:.1} in {:.1} ms, by the submitting thread {:.1} \ + in {:.1} ms, by other threads {:.1} in {:.1} ms", + made[0] / frames, + made[1] / 1e6 / frames, + made[2] / frames, + made[3] / 1e6 / frames, + made[4] / frames, + made[5] / 1e6 / frames, + made[6] / frames, + made[7] / 1e6 / frames, + made[8] / frames, + made[9] / 1e6 / frames, + made[10] / frames, + made[11] / 1e6 / frames, + ); let scoped: Vec = SCOPED.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); if copy_scoped() || scoped.iter().any(|&n| n > 0.0) { tracing::info!( @@ -10977,8 +11515,8 @@ pub(crate) fn fronts_line() -> Option { /// address of a copy one of the lists refreshes, which that list's `shadows` /// holds, so the reference is taken from the key. The lists' fronts, as many /// references again, go to the thread that resets landed lists and drops -/// their steps ([`reaper`]; with `LEONIDA_REAPER=0` they are dropped here, as -/// before). +/// their steps ([`reaper`]; with `LEONIDA_REAPER=0`, or when its line is full +/// ([`reaper_limit`]), they are dropped here, as before). /// /// Ported from ReZOnGithub/VIctory-lap 91ca3fd (GPL-3.0-or-later, as this), /// where the table had some 20,000 entries a frame at the boat, each a counted @@ -10992,16 +11530,10 @@ fn fronts_lean() -> bool { } /// Lets go of a submission's lists' fronts once they are joined, on the reaper -/// thread ([`reaper`]; here without one). +/// thread ([`reaper`]; here without one, or with its line full, +/// [`reaper_limit`]). fn fronts_let_go(fronts: Vec) { - if let Some(tx) = reaper() { - let handed = fronts.len() as u64; - REAPING.fetch_add(handed, Ordering::Relaxed); - // (Given back, and dropped here, if the thread is gone.) - if tx.send(Reaped::Fronts(fronts)).is_err() { - REAPING.fetch_sub(handed, Ordering::Relaxed); - } - } + reap(Reaped::Fronts(fronts), drop); } /// Steps of a submission's lists from which [`Batch::refresh_front`] makes diff --git a/d3d12/docs/switches.md b/d3d12/docs/switches.md index aa2ea8648c..098bd2f6c3 100644 --- a/d3d12/docs/switches.md +++ b/d3d12/docs/switches.md @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is ** settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first, and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. -656 names; 616 have a sentence of a comment below, the others no comment or only a bare list. +657 names; 617 have a sentence of a comment below, the others no comment or only a bare list. - **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a switch read some other way; its default is not given here. @@ -442,6 +442,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_READ_BACK_POOL` | on, `0` turns it off | yes | | | `leonida-gpu/host.rs` | Whether a list's read-back buffers are kept, when the list is reset, for the next read backs of their sizes (`LEONIDA_READ_BACK_POOL=0`: each is made for its read back and let go with its list, as before; `LEONIDA_AB` ca... | | `LEONIDA_READ_ZERO_GAPS` | see the code | | | | `leonida-gpu/host.rs` | ...ite over all of a texture's bytes less at each read of it (`LEONIDA_READ_ZERO_GAPS=0`: the whole buffer first, as before).... | | `LEONIDA_REAPER` | see the code | yes | | | `leonida-gpu/host.rs` | Whether what the host is done with is let go of on a thread of its own ([`reaper`]; on by default, `LEONIDA_REAPER=0` turns it off; `LEONIDA_AB` can turn it on and off while the title runs). | +| `LEONIDA_REAPER_LIMIT` | see the code | yes | | | `leonida-gpu/host.rs` | The bound on the reaper thread's line, as [`REAPING`] counts it (`LEONIDA_REAPER_LIMIT=<things>`, 4,096 by default; `0`: no bound, as before; `LEONIDA_AB` can turn the bound on and off while the title runs). | | `LEONIDA_RECHECK_SOON` | see the code | | | | `leonida-gpu/draw.rs` | Whether a texture found changed with nothing to tell of it is looked at again in the next frame (`LEONIDA_RECHECK_SOON=0`: after four, as before). | | `LEONIDA_RECORD_ALWAYS` | see the code | | | | `leonida-gpu/replay/record.rs` | From `LEONIDA_RECORD`, `LEONIDA_RECORD_AT` (seconds, or `f<frame>`), `LEONIDA_RECORD_FRAMES` and `LEONIDA_RECORD_ALWAYS=1`. | | `LEONIDA_RECORD_AT` | see the code | | | | `leonida-gpu/replay/record.rs` | From `LEONIDA_RECORD`, `LEONIDA_RECORD_AT` (seconds, or `f<frame>`), `LEONIDA_RECORD_FRAMES` and `LEONIDA_RECORD_ALWAYS=1`. | From caab7fe29f344f42bfeae4ebf28992dc37b16923 Mon Sep 17 00:00:00 2001 From: enlight3d <19186686+enlight3d@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:03:38 +0100 Subject: [PATCH 2/2] leonida-gpu: the reaper's tests in a file of their own host.rs is past the size the policy allows (cargo test -p xtask), and the reaper's tests were some 15 KB of it. They move as they are into host/reaper_tests.rs, a child module of host like its other files; they reach host's private items through super, as before. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/host.rs | 312 +----------------- .../leonida-gpu/src/host/reaper_tests.rs | 309 +++++++++++++++++ 2 files changed, 310 insertions(+), 311 deletions(-) create mode 100644 d3d12/crates/leonida-gpu/src/host/reaper_tests.rs diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 36be36ed90..0cf7062fd8 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -948,317 +948,7 @@ fn reaper_limit_from(value: Option<&str>) -> u64 { } #[cfg(test)] -mod reaper_tests { - use super::{REAPER_LIMIT, hand_over, limit_in_phase, reaper_limit_from}; - use super::{ListFront, Off, fronts_let_go, reap_through}; - use super::{REAPED_IN_PLACE, REAPER_HELD, REAPING, Reaped, Retired, reap, reaper_limit, reaper_limit_set}; - use std::sync::atomic::{AtomicU64, Ordering}; - use std::sync::{Arc, Mutex}; - - /// Counts itself when it is dropped. - struct Told(Arc>); - impl Drop for Told { - fn drop(&mut self) { - *self.0.lock().unwrap() += 1; - } - } - - /// A reaper that never takes anything off its line (as on the RTX 3090, - /// where the line grew to hundreds of thousands): the line stays under - /// the bound plus one batch, and every batch over it is given back to the - /// sender, which lets it go where it is. - #[test] - fn a_full_reaper_line_sends_the_rest_back_to_be_let_go_in_place() { - const BATCH: u64 = 7; - const BATCHES: u64 = 200; - // (A bound a batch reaches exactly, and one it overshoots.) - for limit in [98, 100] { - let (tx, rx) = std::sync::mpsc::channel::>(); - let line = AtomicU64::new(0); - let in_place = AtomicU64::new(0); - let dropped = Arc::new(Mutex::new(0u64)); - let mut sent = 0; - for _ in 0..BATCHES { - let batch: Vec = (0..BATCH).map(|_| Told(dropped.clone())).collect(); - match hand_over(&tx, &line, &in_place, limit, BATCH, batch) { - Ok(()) => sent += BATCH, - Err(batch) => drop(batch), - } - let held = line.load(Ordering::Relaxed); - assert!(held < limit + BATCH, "the reaper's line holds {held}, over {limit} and a batch of {BATCH}"); - } - // Batches go while the line holds fewer than the bound, and only then. - assert_eq!(sent, limit.div_ceil(BATCH) * BATCH, "bound {limit}"); - assert_eq!(line.load(Ordering::Relaxed), sent, "the line counts what was handed over, and only that"); - assert_eq!(rx.try_iter().map(|batch| batch.len() as u64).sum::(), sent); - assert_eq!(in_place.load(Ordering::Relaxed), BATCHES * BATCH - sent, "what was let go in place is counted"); - assert_eq!(*dropped.lock().unwrap(), BATCHES * BATCH, "everything was let go, on the line or here"); - } - } - - /// Once the reaper has taken things off its line, batches go to it again; - /// with no bound (0) every batch goes, as before. - #[test] - fn a_reaper_that_keeps_up_gets_every_batch() { - let (tx, rx) = std::sync::mpsc::channel::>(); - let line = AtomicU64::new(0); - let in_place = AtomicU64::new(0); - for _ in 0..50 { - assert!(hand_over(&tx, &line, &in_place, 10, 4, vec![0; 4]).is_ok()); - // The reaper, as it does once a batch is let go. - for batch in rx.try_iter() { - line.fetch_sub(batch.len() as u64, Ordering::Relaxed); - } - } - for _ in 0..1000 { - assert!(hand_over(&tx, &line, &in_place, 0, 4, vec![0; 4]).is_ok()); - } - assert_eq!(line.load(Ordering::Relaxed), 4000); - assert_eq!(in_place.load(Ordering::Relaxed), 0); - // With the thread gone, the batch comes back and nothing stays counted. - drop(rx); - assert!(hand_over(&tx, &line, &in_place, 0, 4, vec![0; 4]).is_err()); - assert_eq!(line.load(Ordering::Relaxed), 4000); - } - - /// Threads that hand things over at the same time, to a reaper that never - /// takes anything off its line: together they never fill it past the - /// bound and one batch (the check and the count are one step). - #[test] - fn threads_together_never_overfill_the_reaper_line() { - const LIMIT: u64 = 64; - const BATCH: u64 = 4; - const THREADS: usize = 8; - const TRIES: usize = 4; - const ROUNDS: usize = 2000; - let (tx, rx) = std::sync::mpsc::channel::(); - let line = AtomicU64::new(0); - let in_place = AtomicU64::new(0); - let start = std::sync::Barrier::new(THREADS + 1); - let end = std::sync::Barrier::new(THREADS + 1); - let (mut most, mut least, mut miscounted) = (0, u64::MAX, 0); - std::thread::scope(|s| { - for _ in 0..THREADS { - s.spawn(|| { - for _ in 0..ROUNDS { - start.wait(); - for _ in 0..TRIES { - let _ = hand_over(&tx, &line, &in_place, LIMIT, BATCH, BATCH); - } - end.wait(); - } - }); - } - // (Kept and checked after the rounds: a panic here would leave the - // threads waiting.) - for _ in 0..ROUNDS { - start.wait(); - end.wait(); - let held = line.swap(0, Ordering::Relaxed); - most = most.max(held); - least = least.min(held); - if rx.try_iter().sum::() != held { - miscounted += 1; - } - } - }); - assert!(most < LIMIT + BATCH, "the reaper's line held {most}, over {LIMIT} and a batch of {BATCH}"); - assert!(least >= LIMIT, "the line was not filled to its bound in a round ({least})"); - assert_eq!(miscounted, 0, "rounds whose line counted other than what was sent"); - let tried = (ROUNDS * THREADS * TRIES) as u64 * BATCH; - assert_eq!(in_place.load(Ordering::Relaxed), tried - ROUNDS as u64 * LIMIT); - } - - /// `LEONIDA_REAPER_LIMIT`: bounded unless it says 0. - #[test] - fn the_reaper_line_is_bounded_unless_asked_not_to_be() { - let default = reaper_limit_from(None); - assert!(default > 0, "the reaper's line has a bound by default"); - assert_eq!(reaper_limit_from(Some("0")), 0); - assert_eq!(reaper_limit_from(Some("5000")), 5000); - assert_eq!(reaper_limit_from(Some("many")), default); - } - - /// The host's own way ([`reap`], as [`super::land`], [`super::bury`] and - /// [`super::fronts_let_go`] take it), with the reaper thread held: what is - /// handed to it stops at the bound, the rest is let go of here at once, and - /// once the thread goes on it lets go of what waited. - #[test] - fn with_the_reaper_thread_held_the_host_lets_go_in_place() { - const BATCH: u64 = 64; - let limit = reaper_limit(); - if super::reaper().is_none() || limit == 0 { - eprintln!("no reaper thread or no bound (LEONIDA_REAPER, LEONIDA_REAPER_LIMIT): not tested"); - return; - } - let held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); - let dropped = Arc::new(Mutex::new(0u64)); - let in_place_before = REAPED_IN_PLACE.load(Ordering::Relaxed); - let batches = limit.div_ceil(BATCH) + 10; - let mut here = 0; - let mut most = 0; - for _ in 0..batches { - let done: Vec<(u64, Retired)> = (0..BATCH).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect(); - reap(Reaped::Objects(done), |what| { - here += BATCH; - drop(what); - }); - most = most.max(REAPING.load(Ordering::Relaxed)); - } - // (Other tests may hand things over meanwhile, in batches as small.) - assert!(most < limit + BATCH, "the reaper's line held {most}, over {limit} and a batch of {BATCH}"); - assert!(here >= 10 * BATCH, "{here} things let go here, of {}", batches * BATCH); - assert_eq!(*dropped.lock().unwrap(), here, "what was let go here went at once"); - assert!(REAPED_IN_PLACE.load(Ordering::Relaxed) - in_place_before >= here); - drop(held); - let all = batches * BATCH; - let started = std::time::Instant::now(); - while *dropped.lock().unwrap() < all && started.elapsed() < std::time::Duration::from_secs(30) { - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert_eq!(*dropped.lock().unwrap(), all, "the reaper thread let go of what waited"); - // And took it off its line. - while REAPING.load(Ordering::Relaxed) >= limit && started.elapsed() < std::time::Duration::from_secs(30) { - std::thread::sleep(std::time::Duration::from_millis(10)); - } - let line = REAPING.load(Ordering::Relaxed); - assert!(line < limit, "the reaper's line still holds {line} of a bound of {limit}"); - } - - /// Without a reaper thread (`LEONIDA_REAPER=0`) what the host is done - /// with is let go of where it is, at once, as before. - #[test] - fn without_a_reaper_thread_the_host_lets_go_in_place() { - let dropped = Arc::new(Mutex::new(0u64)); - let done: Vec<(u64, Retired)> = (0..3).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect(); - let mut here = 0; - reap_through(None, 4096, Reaped::Objects(done), |what| { - here += what.count(); - drop(what); - }); - assert_eq!(here, 3, "the batch came back to be let go here"); - assert_eq!(*dropped.lock().unwrap(), 3, "and went at once"); - } - - /// Lists' fronts take the host's way ([`fronts_let_go`]): to the reaper - /// thread, counted in its line, while it has room; let go of here, counted - /// as such, once it is full. - #[test] - fn lists_fronts_go_to_the_reaper_or_here() { - let limit = reaper_limit(); - if super::reaper().is_none() || limit == 0 { - eprintln!("no reaper thread or no bound (LEONIDA_REAPER, LEONIDA_REAPER_LIMIT): not tested"); - return; - } - // (A test before may have left the line full for the thread to empty.) - let started = std::time::Instant::now(); - let held = loop { - let held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); - if REAPING.load(Ordering::Relaxed) + 5 < limit { - break held; - } - drop(held); - let line = REAPING.load(Ordering::Relaxed); - assert!(started.elapsed() < std::time::Duration::from_secs(30), "the reaper's line stayed at {line} of {limit}"); - std::thread::sleep(std::time::Duration::from_millis(10)); - }; - let line = REAPING.load(Ordering::Relaxed); - fronts_let_go((0..5).map(|_| ListFront::default()).collect()); - let handed = REAPING.load(Ordering::Relaxed) - line; - REAPING.fetch_add(limit, Ordering::Relaxed); - let in_place = REAPED_IN_PLACE.load(Ordering::Relaxed); - fronts_let_go((0..7).map(|_| ListFront::default()).collect()); - let kept = REAPED_IN_PLACE.load(Ordering::Relaxed) - in_place; - REAPING.fetch_sub(limit, Ordering::Relaxed); - drop(held); - assert_eq!(handed, 5, "handed to the reaper thread while its line had room"); - assert_eq!(kept, 7, "let go of here once it was full"); - } - - /// What the reaper thread takes is let go of and taken off its line, as - /// many things as each batch counts. - #[test] - fn the_reaper_thread_lets_go_and_takes_off_its_line() { - use super::reap_one; - let line = AtomicU64::new(10); - let dropped = Arc::new(Mutex::new(0u64)); - reap_one(&line, Reaped::Objects((0..3).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect())); - assert_eq!((line.load(Ordering::Relaxed), *dropped.lock().unwrap()), (7, 3), "three retired objects"); - reap_one(&line, Reaped::Fronts((0..2).map(|_| ListFront::default()).collect())); - assert_eq!(line.load(Ordering::Relaxed), 5, "two lists' fronts"); - reap_one(&line, Reaped::Lists(vec![(Vec::new(), Vec::new())])); - assert_eq!(line.load(Ordering::Relaxed), 5, "a flight with no host list counts none"); - } - - /// The reaper thread takes a batch off its line once it has let go of it, - /// and also when letting go of it panics. - #[test] - fn a_batch_comes_off_the_line_even_if_letting_it_go_panics() { - let line = AtomicU64::new(10); - drop(Off(&line, 4)); - assert_eq!(line.load(Ordering::Relaxed), 6); - let caught = std::panic::catch_unwind(|| { - let _off = Off(&line, 6); - panic!("a batch whose letting go panics"); - }); - assert!(caught.is_err()); - assert_eq!(line.load(Ordering::Relaxed), 0); - } - - /// Who makes host objects, by the name of its thread. - #[cfg(feature = "diagnostics")] - #[test] - fn host_objects_are_counted_by_who_made_them() { - use super::{MADE_BY, host, maker}; - assert_eq!(maker(None), 0); - assert_eq!(maker(Some("main")), 0); - assert_eq!(maker(Some("leonida-submit")), 1); - assert_eq!(maker(Some("leonida-reaper")), 2); - let Some(host) = host() else { - eprintln!("no D3D12 device; host objects made not counted"); - return; - }; - let count = |kind: usize| MADE_BY[kind][1].iter().map(|n| n.load(Ordering::Relaxed)).collect::>(); - let (lists, preludes) = (count(0), count(1)); - std::thread::Builder::new() - .name("leonida-submit".into()) - .spawn(move || { - host.new_list().unwrap(); - host.make_prelude().unwrap(); - }) - .unwrap() - .join() - .unwrap(); - let (lists_after, preludes_after) = (count(0), count(1)); - assert!(lists_after[0] > lists[0] && lists_after[1] > lists[1], "a host list by the submitting thread: {lists:?} {lists_after:?}"); - assert!(preludes_after[0] > preludes[0] && preludes_after[1] > preludes[1], "a prelude: {preludes:?} {preludes_after:?}"); - } - - /// `LEONIDA_REAPER_LIMIT` is read from the environment. - #[test] - fn the_reaper_bound_comes_from_its_variable() { - // SAFETY: the system locks the process's environment block; a test - // that reads the bound meanwhile takes 1,234 as it, which it is written - // for. - unsafe { std::env::set_var("LEONIDA_REAPER_LIMIT", "1234") }; - let set = reaper_limit_set(); - unsafe { std::env::remove_var("LEONIDA_REAPER_LIMIT") }; - assert_eq!(set, 1234); - } - - /// With `LEONIDA_AB` naming `LEONIDA_REAPER_LIMIT`: no bound in the phases - /// that have it off, the bound set (or the default) in the others; without - /// it, the bound set. - #[test] - fn the_reaper_bound_in_an_ab_phase() { - assert_eq!(limit_in_phase(None, 4096), 4096); - assert_eq!(limit_in_phase(None, 0), 0); - assert_eq!(limit_in_phase(Some(false), 4096), 0); - assert_eq!(limit_in_phase(Some(false), 0), 0); - assert_eq!(limit_in_phase(Some(true), 5000), 5000); - assert_eq!(limit_in_phase(Some(true), 0), REAPER_LIMIT); - } -} +mod reaper_tests; /// Objects [`retire`] dropped at once (no submission was running) and /// kept until a running submission finished, since the start. diff --git a/d3d12/crates/leonida-gpu/src/host/reaper_tests.rs b/d3d12/crates/leonida-gpu/src/host/reaper_tests.rs new file mode 100644 index 0000000000..afe44d72ab --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/reaper_tests.rs @@ -0,0 +1,309 @@ +use super::{REAPER_LIMIT, hand_over, limit_in_phase, reaper_limit_from}; +use super::{ListFront, Off, fronts_let_go, reap_through}; +use super::{REAPED_IN_PLACE, REAPER_HELD, REAPING, Reaped, Retired, reap, reaper_limit, reaper_limit_set}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// Counts itself when it is dropped. +struct Told(Arc>); +impl Drop for Told { + fn drop(&mut self) { + *self.0.lock().unwrap() += 1; + } +} + +/// A reaper that never takes anything off its line (as on the RTX 3090, +/// where the line grew to hundreds of thousands): the line stays under +/// the bound plus one batch, and every batch over it is given back to the +/// sender, which lets it go where it is. +#[test] +fn a_full_reaper_line_sends_the_rest_back_to_be_let_go_in_place() { + const BATCH: u64 = 7; + const BATCHES: u64 = 200; + // (A bound a batch reaches exactly, and one it overshoots.) + for limit in [98, 100] { + let (tx, rx) = std::sync::mpsc::channel::>(); + let line = AtomicU64::new(0); + let in_place = AtomicU64::new(0); + let dropped = Arc::new(Mutex::new(0u64)); + let mut sent = 0; + for _ in 0..BATCHES { + let batch: Vec = (0..BATCH).map(|_| Told(dropped.clone())).collect(); + match hand_over(&tx, &line, &in_place, limit, BATCH, batch) { + Ok(()) => sent += BATCH, + Err(batch) => drop(batch), + } + let held = line.load(Ordering::Relaxed); + assert!(held < limit + BATCH, "the reaper's line holds {held}, over {limit} and a batch of {BATCH}"); + } + // Batches go while the line holds fewer than the bound, and only then. + assert_eq!(sent, limit.div_ceil(BATCH) * BATCH, "bound {limit}"); + assert_eq!(line.load(Ordering::Relaxed), sent, "the line counts what was handed over, and only that"); + assert_eq!(rx.try_iter().map(|batch| batch.len() as u64).sum::(), sent); + assert_eq!(in_place.load(Ordering::Relaxed), BATCHES * BATCH - sent, "what was let go in place is counted"); + assert_eq!(*dropped.lock().unwrap(), BATCHES * BATCH, "everything was let go, on the line or here"); + } +} + +/// Once the reaper has taken things off its line, batches go to it again; +/// with no bound (0) every batch goes, as before. +#[test] +fn a_reaper_that_keeps_up_gets_every_batch() { + let (tx, rx) = std::sync::mpsc::channel::>(); + let line = AtomicU64::new(0); + let in_place = AtomicU64::new(0); + for _ in 0..50 { + assert!(hand_over(&tx, &line, &in_place, 10, 4, vec![0; 4]).is_ok()); + // The reaper, as it does once a batch is let go. + for batch in rx.try_iter() { + line.fetch_sub(batch.len() as u64, Ordering::Relaxed); + } + } + for _ in 0..1000 { + assert!(hand_over(&tx, &line, &in_place, 0, 4, vec![0; 4]).is_ok()); + } + assert_eq!(line.load(Ordering::Relaxed), 4000); + assert_eq!(in_place.load(Ordering::Relaxed), 0); + // With the thread gone, the batch comes back and nothing stays counted. + drop(rx); + assert!(hand_over(&tx, &line, &in_place, 0, 4, vec![0; 4]).is_err()); + assert_eq!(line.load(Ordering::Relaxed), 4000); +} + +/// Threads that hand things over at the same time, to a reaper that never +/// takes anything off its line: together they never fill it past the +/// bound and one batch (the check and the count are one step). +#[test] +fn threads_together_never_overfill_the_reaper_line() { + const LIMIT: u64 = 64; + const BATCH: u64 = 4; + const THREADS: usize = 8; + const TRIES: usize = 4; + const ROUNDS: usize = 2000; + let (tx, rx) = std::sync::mpsc::channel::(); + let line = AtomicU64::new(0); + let in_place = AtomicU64::new(0); + let start = std::sync::Barrier::new(THREADS + 1); + let end = std::sync::Barrier::new(THREADS + 1); + let (mut most, mut least, mut miscounted) = (0, u64::MAX, 0); + std::thread::scope(|s| { + for _ in 0..THREADS { + s.spawn(|| { + for _ in 0..ROUNDS { + start.wait(); + for _ in 0..TRIES { + let _ = hand_over(&tx, &line, &in_place, LIMIT, BATCH, BATCH); + } + end.wait(); + } + }); + } + // (Kept and checked after the rounds: a panic here would leave the + // threads waiting.) + for _ in 0..ROUNDS { + start.wait(); + end.wait(); + let held = line.swap(0, Ordering::Relaxed); + most = most.max(held); + least = least.min(held); + if rx.try_iter().sum::() != held { + miscounted += 1; + } + } + }); + assert!(most < LIMIT + BATCH, "the reaper's line held {most}, over {LIMIT} and a batch of {BATCH}"); + assert!(least >= LIMIT, "the line was not filled to its bound in a round ({least})"); + assert_eq!(miscounted, 0, "rounds whose line counted other than what was sent"); + let tried = (ROUNDS * THREADS * TRIES) as u64 * BATCH; + assert_eq!(in_place.load(Ordering::Relaxed), tried - ROUNDS as u64 * LIMIT); +} + +/// `LEONIDA_REAPER_LIMIT`: bounded unless it says 0. +#[test] +fn the_reaper_line_is_bounded_unless_asked_not_to_be() { + let default = reaper_limit_from(None); + assert!(default > 0, "the reaper's line has a bound by default"); + assert_eq!(reaper_limit_from(Some("0")), 0); + assert_eq!(reaper_limit_from(Some("5000")), 5000); + assert_eq!(reaper_limit_from(Some("many")), default); +} + +/// The host's own way ([`reap`], as [`super::land`], [`super::bury`] and +/// [`super::fronts_let_go`] take it), with the reaper thread held: what is +/// handed to it stops at the bound, the rest is let go of here at once, and +/// once the thread goes on it lets go of what waited. +#[test] +fn with_the_reaper_thread_held_the_host_lets_go_in_place() { + const BATCH: u64 = 64; + let limit = reaper_limit(); + if super::reaper().is_none() || limit == 0 { + eprintln!("no reaper thread or no bound (LEONIDA_REAPER, LEONIDA_REAPER_LIMIT): not tested"); + return; + } + let held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); + let dropped = Arc::new(Mutex::new(0u64)); + let in_place_before = REAPED_IN_PLACE.load(Ordering::Relaxed); + let batches = limit.div_ceil(BATCH) + 10; + let mut here = 0; + let mut most = 0; + for _ in 0..batches { + let done: Vec<(u64, Retired)> = (0..BATCH).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect(); + reap(Reaped::Objects(done), |what| { + here += BATCH; + drop(what); + }); + most = most.max(REAPING.load(Ordering::Relaxed)); + } + // (Other tests may hand things over meanwhile, in batches as small.) + assert!(most < limit + BATCH, "the reaper's line held {most}, over {limit} and a batch of {BATCH}"); + assert!(here >= 10 * BATCH, "{here} things let go here, of {}", batches * BATCH); + assert_eq!(*dropped.lock().unwrap(), here, "what was let go here went at once"); + assert!(REAPED_IN_PLACE.load(Ordering::Relaxed) - in_place_before >= here); + drop(held); + let all = batches * BATCH; + let started = std::time::Instant::now(); + while *dropped.lock().unwrap() < all && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(*dropped.lock().unwrap(), all, "the reaper thread let go of what waited"); + // And took it off its line. + while REAPING.load(Ordering::Relaxed) >= limit && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let line = REAPING.load(Ordering::Relaxed); + assert!(line < limit, "the reaper's line still holds {line} of a bound of {limit}"); +} + +/// Without a reaper thread (`LEONIDA_REAPER=0`) what the host is done +/// with is let go of where it is, at once, as before. +#[test] +fn without_a_reaper_thread_the_host_lets_go_in_place() { + let dropped = Arc::new(Mutex::new(0u64)); + let done: Vec<(u64, Retired)> = (0..3).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect(); + let mut here = 0; + reap_through(None, 4096, Reaped::Objects(done), |what| { + here += what.count(); + drop(what); + }); + assert_eq!(here, 3, "the batch came back to be let go here"); + assert_eq!(*dropped.lock().unwrap(), 3, "and went at once"); +} + +/// Lists' fronts take the host's way ([`fronts_let_go`]): to the reaper +/// thread, counted in its line, while it has room; let go of here, counted +/// as such, once it is full. +#[test] +fn lists_fronts_go_to_the_reaper_or_here() { + let limit = reaper_limit(); + if super::reaper().is_none() || limit == 0 { + eprintln!("no reaper thread or no bound (LEONIDA_REAPER, LEONIDA_REAPER_LIMIT): not tested"); + return; + } + // (A test before may have left the line full for the thread to empty.) + let started = std::time::Instant::now(); + let held = loop { + let held = REAPER_HELD.lock().unwrap_or_else(|e| e.into_inner()); + if REAPING.load(Ordering::Relaxed) + 5 < limit { + break held; + } + drop(held); + let line = REAPING.load(Ordering::Relaxed); + assert!(started.elapsed() < std::time::Duration::from_secs(30), "the reaper's line stayed at {line} of {limit}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + let line = REAPING.load(Ordering::Relaxed); + fronts_let_go((0..5).map(|_| ListFront::default()).collect()); + let handed = REAPING.load(Ordering::Relaxed) - line; + REAPING.fetch_add(limit, Ordering::Relaxed); + let in_place = REAPED_IN_PLACE.load(Ordering::Relaxed); + fronts_let_go((0..7).map(|_| ListFront::default()).collect()); + let kept = REAPED_IN_PLACE.load(Ordering::Relaxed) - in_place; + REAPING.fetch_sub(limit, Ordering::Relaxed); + drop(held); + assert_eq!(handed, 5, "handed to the reaper thread while its line had room"); + assert_eq!(kept, 7, "let go of here once it was full"); +} + +/// What the reaper thread takes is let go of and taken off its line, as +/// many things as each batch counts. +#[test] +fn the_reaper_thread_lets_go_and_takes_off_its_line() { + use super::reap_one; + let line = AtomicU64::new(10); + let dropped = Arc::new(Mutex::new(0u64)); + reap_one(&line, Reaped::Objects((0..3).map(|_| (0, Retired::Any(Box::new(Told(dropped.clone()))))).collect())); + assert_eq!((line.load(Ordering::Relaxed), *dropped.lock().unwrap()), (7, 3), "three retired objects"); + reap_one(&line, Reaped::Fronts((0..2).map(|_| ListFront::default()).collect())); + assert_eq!(line.load(Ordering::Relaxed), 5, "two lists' fronts"); + reap_one(&line, Reaped::Lists(vec![(Vec::new(), Vec::new())])); + assert_eq!(line.load(Ordering::Relaxed), 5, "a flight with no host list counts none"); +} + +/// The reaper thread takes a batch off its line once it has let go of it, +/// and also when letting go of it panics. +#[test] +fn a_batch_comes_off_the_line_even_if_letting_it_go_panics() { + let line = AtomicU64::new(10); + drop(Off(&line, 4)); + assert_eq!(line.load(Ordering::Relaxed), 6); + let caught = std::panic::catch_unwind(|| { + let _off = Off(&line, 6); + panic!("a batch whose letting go panics"); + }); + assert!(caught.is_err()); + assert_eq!(line.load(Ordering::Relaxed), 0); +} + +/// Who makes host objects, by the name of its thread. +#[cfg(feature = "diagnostics")] +#[test] +fn host_objects_are_counted_by_who_made_them() { + use super::{MADE_BY, host, maker}; + assert_eq!(maker(None), 0); + assert_eq!(maker(Some("main")), 0); + assert_eq!(maker(Some("leonida-submit")), 1); + assert_eq!(maker(Some("leonida-reaper")), 2); + let Some(host) = host() else { + eprintln!("no D3D12 device; host objects made not counted"); + return; + }; + let count = |kind: usize| MADE_BY[kind][1].iter().map(|n| n.load(Ordering::Relaxed)).collect::>(); + let (lists, preludes) = (count(0), count(1)); + std::thread::Builder::new() + .name("leonida-submit".into()) + .spawn(move || { + host.new_list().unwrap(); + host.make_prelude().unwrap(); + }) + .unwrap() + .join() + .unwrap(); + let (lists_after, preludes_after) = (count(0), count(1)); + assert!(lists_after[0] > lists[0] && lists_after[1] > lists[1], "a host list by the submitting thread: {lists:?} {lists_after:?}"); + assert!(preludes_after[0] > preludes[0] && preludes_after[1] > preludes[1], "a prelude: {preludes:?} {preludes_after:?}"); +} + +/// `LEONIDA_REAPER_LIMIT` is read from the environment. +#[test] +fn the_reaper_bound_comes_from_its_variable() { + // SAFETY: the system locks the process's environment block; a test + // that reads the bound meanwhile takes 1,234 as it, which it is written + // for. + unsafe { std::env::set_var("LEONIDA_REAPER_LIMIT", "1234") }; + let set = reaper_limit_set(); + unsafe { std::env::remove_var("LEONIDA_REAPER_LIMIT") }; + assert_eq!(set, 1234); +} + +/// With `LEONIDA_AB` naming `LEONIDA_REAPER_LIMIT`: no bound in the phases +/// that have it off, the bound set (or the default) in the others; without +/// it, the bound set. +#[test] +fn the_reaper_bound_in_an_ab_phase() { + assert_eq!(limit_in_phase(None, 4096), 4096); + assert_eq!(limit_in_phase(None, 0), 0); + assert_eq!(limit_in_phase(Some(false), 4096), 0); + assert_eq!(limit_in_phase(Some(false), 0), 0); + assert_eq!(limit_in_phase(Some(true), 5000), 5000); + assert_eq!(limit_in_phase(Some(true), 0), REAPER_LIMIT); +}