From e616abe9539afe32bd065761935c5d79feee8e05 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 17:37:13 +0100 Subject: [PATCH 1/9] GPU: size the upload cache from the card's memory (EFFECTCRAFT_GPU_UPLOAD_MB), so 300 large layers upload once Refs #3731 --- Cargo.lock | 1 + crates/gpu/Cargo.toml | 3 + crates/gpu/src/context.rs | 19 +++-- crates/gpu/src/memcap.rs | 175 ++++++++++++++++++++++++++++++++++++-- crates/gpu/src/tests.rs | 49 +++++++++++ docs/preferences.md | 5 +- 6 files changed, 234 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7af09affa..8d088d167 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1788,6 +1788,7 @@ dependencies = [ "wasm-bindgen", "web-time", "wgpu", + "windows-registry", ] [[package]] diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 01154dd9f..84baae720 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -27,6 +27,9 @@ web-time = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = { workspace = true } +[target.'cfg(windows)'.dependencies] +windows-registry = "=0.6.1" + [dev-dependencies] effectcraft-text = { workspace = true } diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index d074fe213..85b172625 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -112,9 +112,6 @@ type EffectPipelines = HashMap<&'static str, (usize, std::sync::OnceLock usize { + self.memcap.upload_budget() + } + #[cfg(test)] pub(crate) fn memcap_waits(&self) -> u64 { self.memcap.waits() @@ -1580,7 +1582,7 @@ impl GpuContext { uploads: Mutex::new(Uploads::default()), pictures: Default::default(), upload_staging: Default::default(), - upload_budget: std::sync::atomic::AtomicUsize::new(UPLOAD_BUDGET), + upload_budget: std::sync::atomic::AtomicUsize::new(self.upload_budget()), upload_full_warned: Default::default(), pool: self.pool.clone(), staging: Default::default(), @@ -1658,9 +1660,10 @@ impl GpuContext { (GpuImage { texture, width: w, height: h, _lease: Some(lease), levels: None }, was_reused) } - /// Bytes of uploaded layer textures the context keeps (default 1536 MB). An application that - /// knows the device's memory can raise it (static layers of a big frame upload once) or lower - /// it (a small GPU); the least recently used textures go first. + /// Bytes of uploaded layer textures the context keeps (by default 3/8 of the card's memory + /// when known, 1536 MB otherwise; `EFFECTCRAFT_GPU_UPLOAD_MB`, see `memcap`). An application + /// can raise it (static layers of a big frame upload once) or lower it (a small GPU); the + /// least recently used textures go first. pub fn set_upload_budget(&self, bytes: usize) { self.upload_budget.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed); } diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 25194a7c2..289063e12 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -12,9 +12,16 @@ //! wgpu has no safe query for the adapter's memory size (`max_buffer_size` is capped at `i32::MAX` //! on Direct3D 12 and Linux/Mesa Vulkan), so the default cap is conservative per device type, //! and lower on a discrete card whose memory the OS reports without `unsafe` (Linux's amdgpu -//! driver, in sysfs: a 2–4 GB card ran out of memory and took the system down, #1487); +//! driver, in sysfs, and the display class key of the registry on Windows: a 2–4 GB card ran +//! out of memory and took the system down, #1487); //! `EFFECTCRAFT_GPU_MEMCAP_MB` overrides it (0 = off). Backends without an allocator report //! (Metal, WebGPU, GL) are never gated. +//! +//! The upload cache (textures of layers already uploaded) has a budget of its own, three eighths +//! of the card's memory when that is known and 1.5 GiB otherwise (`EFFECTCRAFT_GPU_UPLOAD_MB` +//! overrides it): a comp whose layers are larger than the budget re-uploads all of them every +//! frame (#3731). The cache counts against the cap, so the default cap grows with the budget +//! (never above three quarters of the card) and frames in flight are not starved by it. use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; @@ -30,8 +37,16 @@ const MIB: u64 = 1 << 20; /// Overrides the default cap: whole MiB, 0 turns the gate off. const MEMCAP_ENV: &str = "EFFECTCRAFT_GPU_MEMCAP_MB"; +/// Overrides the default upload cache budget: whole MiB, 0 = the default. +const UPLOAD_ENV: &str = "EFFECTCRAFT_GPU_UPLOAD_MB"; + +/// The upload cache budget when the card's memory is not known (the default cap leaves room for it). +const UPLOAD_DEFAULT: u64 = GIB + GIB / 2; + pub(crate) struct MemCap { cap: u64, + /// Bytes of uploaded layer textures to keep (see [`upload_budget`]). + upload: usize, hysteresis: u64, calls: AtomicU64, waits: AtomicU64, @@ -49,13 +64,32 @@ pub(crate) struct MemCap { impl MemCap { pub(crate) fn new(info: &wgpu::AdapterInfo) -> MemCap { let env = std::env::var(MEMCAP_ENV).ok(); - Self::from_env(env.as_deref(), info.device_type, vram(info)) + let upload = std::env::var(UPLOAD_ENV).ok(); + Self::from_envs(env.as_deref(), upload.as_deref(), info.device_type, vram(info)) } + #[cfg(test)] fn from_env(var: Option<&str>, device_type: wgpu::DeviceType, vram: Option) -> MemCap { - let cap = cap_from_env(var, device_type, vram); + Self::from_envs(var, None, device_type, vram) + } + + fn from_envs(cap_var: Option<&str>, upload_var: Option<&str>, device_type: wgpu::DeviceType, vram: Option) -> MemCap { + let mut upload = upload_budget(upload_var, vram); + // An explicit cap is the user's: it does not grow with the cache, so a default budget + // is lowered to half of it (never below the former fixed 1.5 GiB); an explicit one stays. + let cap = match cap_var { + Some(_) => { + let cap = cap_from_env(cap_var, device_type, vram); + if cap > 0 && explicit_upload(upload_var).is_none() { + upload = upload.min((cap / 2).max(UPLOAD_DEFAULT)); + } + cap + } + None => default_cap_for(device_type, vram, upload), + }; MemCap { cap, + upload: usize::try_from(upload).unwrap_or(usize::MAX), hysteresis: default_hysteresis(cap), calls: AtomicU64::new(0), waits: AtomicU64::new(0), @@ -72,6 +106,7 @@ impl MemCap { pub(crate) fn fresh(&self) -> MemCap { MemCap { cap: self.cap, + upload: self.upload, hysteresis: self.hysteresis, calls: AtomicU64::new(0), waits: AtomicU64::new(0), @@ -86,6 +121,11 @@ impl MemCap { self.cap } + /// Bytes of uploaded layer textures the context keeps. + pub(crate) fn upload_budget(&self) -> usize { + self.upload + } + /// Remember an allocator sample: the peak only grows. pub(crate) fn note(&self, allocated: u64) { self.peak.fetch_max(allocated, Relaxed); @@ -179,9 +219,39 @@ fn cap_from_env(var: Option<&str>, device_type: wgpu::DeviceType, vram: Option, vram: Option) -> u64 { + let default = vram.map_or(UPLOAD_DEFAULT, |v| v / 8 * 3); + if let Some(v) = var + && explicit_upload(var).is_none() + && v.trim() != "0" + { + log::warn!(target: "effectcraft_gpu", "{UPLOAD_ENV}={v:?} is not a whole number of MiB that fits in 64 bits: using {} MiB", default / MIB); + } + explicit_upload(var).unwrap_or(default) +} + +/// The budget the user set: whole MiB above 0. +fn explicit_upload(var: Option<&str>) -> Option { + var?.trim().parse::().ok().and_then(|mb| mb.checked_mul(MIB)).filter(|&b| b > 0) +} + +/// The default cap plus what the upload cache holds beyond the 1.5 GiB the default cap already +/// leaves room for, never above three quarters of the card's memory when that is known. +fn default_cap_for(t: wgpu::DeviceType, vram: Option, upload: u64) -> u64 { + let base = default_cap(t, vram); + let cap = base.saturating_add(upload.saturating_sub(UPLOAD_DEFAULT)); + match vram { + Some(v) if t == wgpu::DeviceType::DiscreteGpu => cap.min((v / 4).saturating_mul(3)).max(base), + _ => cap, + } +} + /// Discrete cards: 3 GiB, low enough to fire on 4–8 GB cards with headroom for the driver and -/// desktop while leaving ~1 GiB above the default 1.5 GiB upload cache + 256 MB pool (larger -/// cards can raise it with `EFFECTCRAFT_GPU_MEMCAP_MB`), and at most three quarters of the card's +/// desktop while leaving ~1 GiB above the default 1.5 GiB upload cache + 256 MB pool (a bigger +/// upload cache raises it, see [`default_cap_for`]; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), and at most three quarters of the card's /// memory when it is known (`vram`), so a 2 GB card gets 1.5 GiB (#1487). Integrated and software /// adapters share system memory: 2 GiB, whatever their carve-out. fn default_cap(t: wgpu::DeviceType, vram: Option) -> u64 { @@ -191,22 +261,55 @@ fn default_cap(t: wgpu::DeviceType, vram: Option) -> u64 { } } -/// The adapter's dedicated memory in bytes, where the OS reports it without `unsafe`. +/// The adapter's dedicated memory in bytes, where the OS reports it without `unsafe`: Linux's +/// amdgpu driver in sysfs, the display class key of the registry on Windows. fn vram(info: &wgpu::AdapterInfo) -> Option { - if !cfg!(target_os = "linux") || info.device_type != wgpu::DeviceType::DiscreteGpu { + if info.device_type != wgpu::DeviceType::DiscreteGpu { return None; } - let bytes = vram_in_sysfs(Path::new("/sys/class/drm"), info.vendor, info.device, &info.device_pci_bus_id); + #[cfg(target_os = "linux")] + let (bytes, source) = (vram_in_sysfs(Path::new("/sys/class/drm"), info.vendor, info.device, &info.device_pci_bus_id), "sysfs"); + #[cfg(windows)] + let (bytes, source) = (vram_in_registry(info.vendor, info.device), "registry"); + #[cfg(not(any(target_os = "linux", windows)))] + let (bytes, source) = (None::, ""); if let Some(b) = bytes { - log::info!(target: "effectcraft_gpu", "gpu {}: {} MiB of video memory (sysfs)", info.name, b >> 20); + log::info!(target: "effectcraft_gpu", "gpu {}: {} MiB of video memory ({source})", info.name, b >> 20); } bytes } +/// `HardwareInformation.qwMemorySize` of the display adapters under the display class key whose +/// `MatchingDeviceId` names the PCI vendor and device (drivers write it as a 64-bit value, so a +/// 32 GB card reads right). Variants of one model share the ids: the smallest wins. +#[cfg(windows)] +fn vram_in_registry(vendor: u32, device: u32) -> Option { + use windows_registry::LOCAL_MACHINE; + let class = LOCAL_MACHINE.open(r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}").ok()?; + let entries: Vec<(String, u64)> = class + .keys() + .ok()? + .filter_map(|name| { + let key = class.open(&name).ok()?; + Some((key.get_string("MatchingDeviceId").ok()?, key.get_u64("HardwareInformation.qwMemorySize").ok()?)) + }) + .collect(); + vram_from_entries(&entries, vendor, device) +} + +/// The smallest nonzero memory among `(MatchingDeviceId, bytes)` entries of the PCI device +/// `vendor`:`device` (ids look like `pci\ven_10de&dev_2b85&subsys_...`). +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +fn vram_from_entries(entries: &[(String, u64)], vendor: u32, device: u32) -> Option { + let want = format!("ven_{vendor:04x}&dev_{device:04x}"); + entries.iter().filter(|(id, bytes)| *bytes > 0 && id.to_ascii_lowercase().contains(&want)).map(|&(_, b)| b).min() +} + /// `mem_info_vram_total` (amdgpu) of the DRM card under `drm` whose PCI vendor and device ids are /// `vendor` and `device`. Connector entries (`card1-DP-1`) are skipped. Variants of one model share /// those ids (the RX 550 ships with 2 and 4 GB), so the card at PCI address `bus` (`uevent`'s /// `PCI_SLOT_NAME`, wgpu's `device_pci_bus_id`) wins; without one, the smallest matching card. +#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))] fn vram_in_sysfs(drm: &Path, vendor: u32, device: u32, bus: &str) -> Option { let id = |path: &Path| std::fs::read_to_string(path).ok().and_then(|s| u32::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok()); let slot = |dev: &Path| { @@ -314,6 +417,60 @@ mod tests { assert_eq!(cap_from_env(Some("4096"), d, Some(2 * GIB)), 4 * GIB, "the override still wins"); } + #[test] + fn video_memory_is_matched_by_pci_ids_in_registry_entries() { + let e = |id: &str, gb: u64| (id.to_string(), gb * GIB); + let entries = [e(r"PCI\VEN_10DE&DEV_2B85&SUBSYS_1", 32), e(r"PCI\VEN_8086&DEV_46A6&SUBSYS_2", 0), e(r"PCI\VEN_10DE&DEV_2204", 24)]; + assert_eq!(vram_from_entries(&entries, 0x10de, 0x2b85), Some(32 * GIB)); + assert_eq!(vram_from_entries(&entries, 0x8086, 0x46a6), None, "a zero size is not known"); + assert_eq!(vram_from_entries(&entries, 0x1002, 0x73bf), None); + let twins = [e(r"PCI\VEN_1002&DEV_699F", 4), e(r"PCI\VEN_1002&DEV_699F&SUBSYS_9", 2)]; + assert_eq!(vram_from_entries(&twins, 0x1002, 0x699f), Some(2 * GIB), "the smaller variant"); + } + + /// #3731: the upload budget follows the card (3/8 of its memory), the environment overrides + /// it, and the default cap leaves room for it. + #[test] + fn upload_budget_follows_the_card_and_the_cap_leaves_room() { + let d = wgpu::DeviceType::DiscreteGpu; + assert_eq!(upload_budget(None, None), 3 * GIB / 2, "unknown memory: the former fixed budget"); + assert_eq!(upload_budget(None, Some(4 * GIB)), 3 * GIB / 2); + assert_eq!(upload_budget(None, Some(32 * GIB)), 12 * GIB); + assert_eq!(upload_budget(None, Some(2 * GIB)), 768 * MIB); + assert_eq!(upload_budget(Some("24000"), Some(2 * GIB)), 24000 * MIB, "the override wins"); + assert_eq!(upload_budget(Some("0"), Some(32 * GIB)), 12 * GIB, "0 is the default"); + for bad in ["", "lots", "-1", "99999999999999999999"] { + assert_eq!(upload_budget(Some(bad), None), 3 * GIB / 2, "{bad:?}"); + } + // The cap grows with the budget, never above three quarters of a known card. + assert_eq!(default_cap_for(d, None, 3 * GIB / 2), 3 * GIB); + assert_eq!(default_cap_for(d, Some(32 * GIB), 12 * GIB), 3 * GIB + 21 * GIB / 2); + assert_eq!(default_cap_for(d, Some(32 * GIB), 40 * GIB), 24 * GIB); + assert_eq!(default_cap_for(d, Some(2 * GIB), 768 * MIB), 3 * GIB / 2); + assert_eq!(default_cap_for(wgpu::DeviceType::IntegratedGpu, None, 3 * GIB / 2), 2 * GIB); + // A card of any size: the default budget and cap leave a quarter of the memory free. + for gb in [4, 6, 8, 12, 16, 24, 32] { + let v = gb * GIB; + assert!(default_cap_for(d, Some(v), upload_budget(None, Some(v))) <= v / 4 * 3, "{gb} GB"); + } + // An explicit cap is not changed by the budget; the context takes both. + let m = MemCap::from_envs(Some("4096"), Some("9000"), d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (4 * GIB, 9000 * MIB as usize)); + // A default budget is lowered to half an explicit cap (not below 1.5 GiB), an explicit one + // is kept, and a cap of 0 (gate off) changes nothing. + let m = MemCap::from_envs(Some("8192"), None, d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (8 * GIB, 4 * GIB as usize)); + let m = MemCap::from_envs(Some("4096"), None, d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (4 * GIB, 2 * GIB as usize)); + let m = MemCap::from_envs(Some("8"), None, d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (8 * MIB, 3 * GIB as usize / 2)); + let m = MemCap::from_envs(Some("0"), None, d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (0, 12 * GIB as usize)); + let m = MemCap::from_envs(None, Some("9000"), d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (3 * GIB + 9000 * MIB - 3 * GIB / 2, 9000 * MIB as usize)); + assert_eq!(MemCap::from_env(None, d, None).upload_budget(), 3 * GIB as usize / 2); + } + #[test] fn video_memory_is_read_from_the_matching_drm_card() { let dir = std::env::temp_dir().join(format!("effectcraft-memcap-{}", std::process::id())); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 1d2782262..2e52f6737 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1486,6 +1486,55 @@ fn upload_budget_bounds_the_layer_textures_kept() { assert!(a == b && b == c, "the upload budget changed the frame"); } +/// #3731: layers of footage at 8 bpc (a layer buffer each, uploaded through the upload cache) +/// upload once while they fit the budget and again every frame when they do not. The budget comes +/// from the memory rule, so a child process sets `EFFECTCRAFT_GPU_UPLOAD_MB=1` (smaller than the +/// layers) and must see the uploads repeat, the default must not. (At 32 bpc the layers share +/// the footage picture, which the budget does not bound.) +#[test] +fn upload_budget_comes_from_the_memory_rule() { + const ENV: &str = "EFFECTCRAFT_GPU_UPLOAD_TEST_CHILD"; + let tight = std::env::var_os(ENV).is_some(); + if !tight && std::env::var_os("EFFECTCRAFT_GPU_UPLOAD_MB").is_some() { + return; // the caller set a budget of their own + } + if !tight { + let exe = std::env::current_exe().expect("test binary path"); + let out = std::process::Command::new(exe) + .env(ENV, "1") + .env("EFFECTCRAFT_GPU_UPLOAD_MB", "1") + .args(["--exact", "tests::upload_budget_comes_from_the_memory_rule", "--nocapture"]) + .output() + .expect("spawn child test process"); + assert!(out.status.success(), "child test failed:\n{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + } + let Some(g) = gpu() else { return }; + let mut s = Scene::new(BitDepth::Bpc8); + for i in 0..3 { + let mut l = s.footage(600, 400); // 3.8 MB as RGBA f32 each + set(&mut l, "transform/position", v3(30.0 + 10.0 * i as f64, 30.0)); + s.push(l); + } + let cache = effectcraft_render::cache::LayerCache::new(256 << 20); + let frame = |k: u64| { + let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, ..opts() }); + r.accel = Some(g); + r.cache = Some(&cache); + let before = g.ctx.transfer_stats().upload_bytes; + g.render(&r, s.cid, Tick::from_seconds_f64(k as f64 / 30.0)).expect("the GPU renders the frame"); + g.ctx.transfer_stats().upload_bytes - before + }; + let _ = frame(0); + let up = frame(1); + if tight { + assert_eq!(g.ctx.upload_budget(), 1 << 20, "EFFECTCRAFT_GPU_UPLOAD_MB=1"); + assert!(up > 0, "layers over the budget must upload again"); + } else { + assert_eq!(g.ctx.upload_budget(), g.ctx.upload_budget_from_rule()); + assert_eq!(up, 0, "layers within the budget re-uploaded"); + } +} + /// Layers with effect stacks run them resident on the GPU (`walk::draw_resident_fx`): GPU /// effects, a CPU-only effect in the middle (read back, run, upload), opacity and a blend mode, /// a shape layer whose effects run in effect space from its bounds' corner; 8 and 32 bpc, full diff --git a/docs/preferences.md b/docs/preferences.md index c35d2c793..ec2ff9c32 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -97,7 +97,10 @@ Commands (CLI, MCP, control channel): frames the Render Queue renders on the GPU at once. Auto measures the GPU memory after the job's first GPU frame and fits up to 3 frames into the GPU memory cap (by default a conservative 3 GiB on a discrete card, less when its memory is known, 2 GiB on an integrated - one; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), keeping room for the upload cache to fill. It + one; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), keeping room for the upload cache to fill (the + textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where the OS + reports it, on Linux with amdgpu and on Windows; the default cap grows with it, never above + three quarters of the card; `EFFECTCRAFT_GPU_UPLOAD_MB` sets it in whole MiB, 0 = default). It renders one frame at a time where the memory can't be measured (Metal, WebGPU, GL, or the cap turned off) and once frames have had to wait for memory. The render log names the count. `EFFECTCRAFT_GPU_INFLIGHT` overrides it. CPU renders have no such setting. A job on GPU From 559bf802511440e97cd20c3b0a485d1a76bdf862 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:18:30 +0100 Subject: [PATCH 2/9] GPU tests: take the GPU lock before the upload-budget test starts its child process (#3737 review) --- crates/gpu/src/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 2e52f6737..42cccf9b1 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1499,6 +1499,8 @@ fn upload_budget_comes_from_the_memory_rule() { return; // the caller set a budget of their own } if !tight { + // The child uses the GPU: tests of this process wait until it is done (#3737 review). + hold_gpu_lock(); let exe = std::env::current_exe().expect("test binary path"); let out = std::process::Command::new(exe) .env(ENV, "1") From a987ed12161e2cfc26b717e77bbadcc977b59af7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 15:29:51 +0100 Subject: [PATCH 3/9] Read NVIDIA video memory with nvidia-smi when the OS does not report it The proprietary NVIDIA driver on Linux has no sysfs file for the card's memory, so the upload budget stayed at 1.5 GiB there. When the adapter is NVIDIA and nothing else reported its memory, run nvidia-smi once (no console window, 3 s timeout, cached) and take the line of the adapter's PCI address, else of its device id, else the smallest card. --- crates/gpu/src/memcap.rs | 164 ++++++++++++++++++++++++++++++++++++++- docs/preferences.md | 5 +- 2 files changed, 164 insertions(+), 5 deletions(-) diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 289063e12..c0c1e6579 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -12,8 +12,9 @@ //! wgpu has no safe query for the adapter's memory size (`max_buffer_size` is capped at `i32::MAX` //! on Direct3D 12 and Linux/Mesa Vulkan), so the default cap is conservative per device type, //! and lower on a discrete card whose memory the OS reports without `unsafe` (Linux's amdgpu -//! driver, in sysfs, and the display class key of the registry on Windows: a 2–4 GB card ran -//! out of memory and took the system down, #1487); +//! driver, in sysfs, the display class key of the registry on Windows, and for NVIDIA cards +//! neither reports the driver's `nvidia-smi`: a 2–4 GB card ran out of memory and took the +//! system down, #1487); //! `EFFECTCRAFT_GPU_MEMCAP_MB` overrides it (0 = off). Backends without an allocator report //! (Metal, WebGPU, GL) are never gated. //! @@ -261,8 +262,13 @@ fn default_cap(t: wgpu::DeviceType, vram: Option) -> u64 { } } +/// The PCI vendor id of NVIDIA. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +const NVIDIA: u32 = 0x10de; + /// The adapter's dedicated memory in bytes, where the OS reports it without `unsafe`: Linux's -/// amdgpu driver in sysfs, the display class key of the registry on Windows. +/// amdgpu driver in sysfs, the display class key of the registry on Windows, and for an NVIDIA +/// card neither reports (the proprietary Linux driver has no sysfs file) the driver's `nvidia-smi`. fn vram(info: &wgpu::AdapterInfo) -> Option { if info.device_type != wgpu::DeviceType::DiscreteGpu { return None; @@ -273,6 +279,12 @@ fn vram(info: &wgpu::AdapterInfo) -> Option { let (bytes, source) = (vram_in_registry(info.vendor, info.device), "registry"); #[cfg(not(any(target_os = "linux", windows)))] let (bytes, source) = (None::, ""); + #[cfg(not(target_arch = "wasm32"))] + let (bytes, source) = if bytes.is_none() && info.vendor == NVIDIA { + (nvidia_smi_output().and_then(|out| vram_from_nvidia_smi(out, info.device, &info.device_pci_bus_id)), "nvidia-smi") + } else { + (bytes, source) + }; if let Some(b) = bytes { log::info!(target: "effectcraft_gpu", "gpu {}: {} MiB of video memory ({source})", info.name, b >> 20); } @@ -337,6 +349,89 @@ fn vram_in_sysfs(drm: &Path, vendor: u32, device: u32, bus: &str) -> Option found.iter().find(|(s, _)| !bus.is_empty() && s.as_deref() == Some(bus.as_str())).map(|&(_, b)| b).or_else(|| found.iter().map(|&(_, b)| b).min()) } +/// What `nvidia-smi` is asked for: one line per GPU, `bus id, device id, memory in MiB`. +#[cfg(not(target_arch = "wasm32"))] +const NVIDIA_SMI_ARGS: [&str; 2] = ["--query-gpu=pci.bus_id,pci.device_id,memory.total", "--format=csv,noheader,nounits"]; + +/// How long `nvidia-smi` may take. It answers in well under a second, but it can stall on a +/// driver that is busy or broken, and the context must not wait for that. +#[cfg(not(target_arch = "wasm32"))] +const NVIDIA_SMI_TIMEOUT: Duration = Duration::from_secs(3); + +/// The output of `nvidia-smi` (see [`NVIDIA_SMI_ARGS`]), run once per process and kept: `None` when +/// it is missing, fails, or takes too long. +#[cfg(not(target_arch = "wasm32"))] +fn nvidia_smi_output() -> Option<&'static str> { + static OUTPUT: std::sync::OnceLock> = std::sync::OnceLock::new(); + OUTPUT.get_or_init(|| run_with_timeout(std::ffi::OsStr::new("nvidia-smi"), &NVIDIA_SMI_ARGS, NVIDIA_SMI_TIMEOUT)).as_deref() +} + +/// Runs `program` with `args` and returns its standard output when it exits successfully within +/// `timeout`, without a console window on Windows. A program still running at the timeout is +/// killed and not waited for (a process stuck in the driver may not die at once). +#[cfg(not(target_arch = "wasm32"))] +fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) -> Option { + use std::io::Read; + use std::process::{Command, Stdio}; + let mut cmd = Command::new(program); + cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().ok()?; + let start = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) if status.success() => break, + Ok(None) if start.elapsed() < timeout => std::thread::sleep(Duration::from_millis(10)), + Ok(Some(_)) => return None, + _ => { + let _ = child.kill(); + return None; + } + } + } + // The output is a few short lines, so the pipe never fills before the program exits. + let mut out = String::new(); + child.stdout.take()?.read_to_string(&mut out).ok()?; + Some(out) +} + +/// The memory in bytes of the NVIDIA GPU in `nvidia-smi` output (lines of `bus id, device id, +/// memory in MiB`, like `00000000:01:00.0, 0x250310DE, 12288`) that is the adapter: the line at +/// PCI address `bus` (wgpu's `device_pci_bus_id`, `0000:01:00.0`), otherwise the smallest among +/// the lines of PCI device `device`, otherwise the smallest of all. Smaller is the safe guess, as +/// the budget and the cap are fractions of it. Lines that do not parse (`[N/A]`, a zero, a size +/// that overflows) are skipped. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn vram_from_nvidia_smi(output: &str, device: u32, bus: &str) -> Option { + // A PCI address as (domain, rest): nvidia-smi writes eight digits of domain, wgpu four. + let address = |s: &str| { + let s = s.trim().to_ascii_lowercase(); + let (domain, rest) = s.split_once(':')?; + Some((u32::from_str_radix(domain, 16).ok()?, rest.to_string())).filter(|(_, rest)| !rest.is_empty()) + }; + let gpus: Vec<(Option<(u32, String)>, Option, u64)> = output + .lines() + .filter_map(|line| { + let mut fields = line.split(','); + let (addr, id, mib) = (fields.next()?, fields.next()?, fields.next()?); + let bytes = mib.trim().parse::().ok()?.checked_mul(MIB).filter(|&b| b > 0)?; + let id = id.trim().to_ascii_lowercase(); + let pci_device = u32::from_str_radix(id.strip_prefix("0x").unwrap_or(&id), 16).ok().map(|id| id >> 16); + Some((address(addr), pci_device, bytes)) + }) + .collect(); + let want = address(bus); + if let Some(&(_, _, bytes)) = gpus.iter().find(|(a, _, _)| want.is_some() && *a == want) { + return Some(bytes); + } + gpus.iter().filter(|(_, d, _)| *d == Some(device)).map(|&(_, _, b)| b).min().or_else(|| gpus.iter().map(|&(_, _, b)| b).min()) +} + /// Minimum reclaimable bytes before a wait is worth draining an encoder (1/8 of the cap, /// clamped between 1 MiB and 256 MiB, or 1/4 of caps smaller than 4 MiB). fn default_hysteresis(cap: u64) -> u64 { @@ -501,4 +596,67 @@ mod tests { assert_eq!(vram_in_sysfs(&dir, 0x1002, 0x699f, "0000:09:00.0"), Some(2 * GIB), "no such address: the smaller card"); let _ = std::fs::remove_dir_all(&dir); } + + /// #3731: NVIDIA's Linux driver has no sysfs file, so the memory comes from `nvidia-smi`. + #[test] + fn video_memory_is_read_from_nvidia_smi_output() { + let one = "00000000:01:00.0, 0x250310DE, 12288\n"; + assert_eq!(vram_from_nvidia_smi(one, 0x2503, "0000:01:00.0"), Some(12 * GIB)); + assert_eq!(vram_from_nvidia_smi(one, 0x2503, ""), Some(12 * GIB), "no address: the device id"); + assert_eq!(vram_from_nvidia_smi("00000000:01:00.0, 0x250310de, 12288", 0x2503, ""), Some(12 * GIB), "lower case, no newline"); + // Two cards: the adapter's address wins, then its device id, then the smallest card. + let two = "00000000:01:00.0, 0x2B8510DE, 32607\r\n00000000:02:00.0, 0x250310DE, 12288\r\n"; + assert_eq!(vram_from_nvidia_smi(two, 0x2b85, "0000:01:00.0"), Some(32607 * MIB)); + assert_eq!(vram_from_nvidia_smi(two, 0x2b85, "0000:02:00.0"), Some(12 * GIB), "the address over the device id"); + assert_eq!(vram_from_nvidia_smi(two, 0x2b85, ""), Some(32607 * MIB)); + assert_eq!(vram_from_nvidia_smi(two, 0x2b85, "0000:09:00.0"), Some(32607 * MIB), "no such address: the device id"); + assert_eq!(vram_from_nvidia_smi(two, 0x1234, ""), Some(12 * GIB), "no such device: the smallest card"); + let twins = "00000000:01:00.0, 0x250310DE, 12288\n00000000:02:00.0, 0x250310DE, 8192\n"; + assert_eq!(vram_from_nvidia_smi(twins, 0x2503, ""), Some(8 * GIB), "same device, no address: the smaller one"); + // Nothing usable: no output, an error text, missing or unknown sizes, overflow. + for bad in [ + "", + "\n", + "NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver.", + "00000000:01:00.0, 0x250310DE", + "00000000:01:00.0, 0x250310DE, [N/A]", + "00000000:01:00.0, 0x250310DE, 0", + "00000000:01:00.0, 0x250310DE, -1", + "00000000:01:00.0, 0x250310DE, 12288 MiB", + "00000000:01:00.0, 0x250310DE, 99999999999999999999", + "00000000:01:00.0, 0x250310DE, 18446744073709551615", + ] { + assert_eq!(vram_from_nvidia_smi(bad, 0x2503, "0000:01:00.0"), None, "{bad:?}"); + } + // A bad line next to a good one leaves the good one. + let mixed = "00000000:01:00.0, 0x250310DE, [N/A]\n00000000:02:00.0, garbage, 6144\n"; + assert_eq!(vram_from_nvidia_smi(mixed, 0x2503, "0000:01:00.0"), Some(6 * GIB)); + } + + /// Stands in for an `nvidia-smi` that hangs: only run (through `--ignored`) as a child of + /// `a_program_that_fails_or_hangs_gives_no_output`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "the child process of a_program_that_fails_or_hangs_gives_no_output"] + fn stand_in_for_a_hanging_program() { + std::thread::sleep(Duration::from_secs(20)); + } + + /// `nvidia-smi` missing, failing or hanging gives no memory, and never holds the caller long. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_program_that_fails_or_hangs_gives_no_output() { + let missing = std::ffi::OsStr::new("effectcraft-no-such-program-3731"); + assert_eq!(run_with_timeout(missing, &NVIDIA_SMI_ARGS, Duration::from_secs(5)), None); + let me = std::env::current_exe().unwrap(); + // This test binary stands in for the program: listing tests succeeds and prints them, + // an unknown flag exits with an error, and the sleeping test outlasts the timeout. + let listed = run_with_timeout(me.as_os_str(), &["--list", "--exact", "memcap::tests::stand_in_for_a_hanging_program"], Duration::from_secs(20)); + assert!(listed.is_some_and(|out| out.contains("stand_in_for_a_hanging_program"))); + assert_eq!(run_with_timeout(me.as_os_str(), &["--no-such-flag-3731"], Duration::from_secs(20)), None); + let start = std::time::Instant::now(); + let hung = run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"], Duration::from_millis(500)); + assert_eq!(hung, None); + assert!(start.elapsed() < Duration::from_secs(10), "waited {:?}", start.elapsed()); + } } diff --git a/docs/preferences.md b/docs/preferences.md index ec2ff9c32..7a2cbead2 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -98,8 +98,9 @@ Commands (CLI, MCP, control channel): job's first GPU frame and fits up to 3 frames into the GPU memory cap (by default a conservative 3 GiB on a discrete card, less when its memory is known, 2 GiB on an integrated one; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), keeping room for the upload cache to fill (the - textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where the OS - reports it, on Linux with amdgpu and on Windows; the default cap grows with it, never above + textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where it is + known: on Linux with amdgpu, on Windows, and on NVIDIA cards through `nvidia-smi`; the + default cap grows with it, never above three quarters of the card; `EFFECTCRAFT_GPU_UPLOAD_MB` sets it in whole MiB, 0 = default). It renders one frame at a time where the memory can't be measured (Metal, WebGPU, GL, or the cap turned off) and once frames have had to wait for memory. The render log names the count. From ef6ba0ef8ae18c60aff2f0b57df16a43af5043bc Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 15:32:36 +0100 Subject: [PATCH 4/9] Log when nvidia-smi gives no answer; shorten the stand-in sleep --- crates/gpu/src/memcap.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index c0c1e6579..8cd30b161 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -363,7 +363,15 @@ const NVIDIA_SMI_TIMEOUT: Duration = Duration::from_secs(3); #[cfg(not(target_arch = "wasm32"))] fn nvidia_smi_output() -> Option<&'static str> { static OUTPUT: std::sync::OnceLock> = std::sync::OnceLock::new(); - OUTPUT.get_or_init(|| run_with_timeout(std::ffi::OsStr::new("nvidia-smi"), &NVIDIA_SMI_ARGS, NVIDIA_SMI_TIMEOUT)).as_deref() + OUTPUT + .get_or_init(|| { + let out = run_with_timeout(std::ffi::OsStr::new("nvidia-smi"), &NVIDIA_SMI_ARGS, NVIDIA_SMI_TIMEOUT); + if out.is_none() { + log::debug!(target: "effectcraft_gpu", "nvidia-smi is missing, failed or took longer than {NVIDIA_SMI_TIMEOUT:?}: video memory unknown"); + } + out + }) + .as_deref() } /// Runs `program` with `args` and returns its standard output when it exits successfully within @@ -639,7 +647,7 @@ mod tests { #[test] #[ignore = "the child process of a_program_that_fails_or_hangs_gives_no_output"] fn stand_in_for_a_hanging_program() { - std::thread::sleep(Duration::from_secs(20)); + std::thread::sleep(Duration::from_secs(5)); } /// `nvidia-smi` missing, failing or hanging gives no memory, and never holds the caller long. From ec3116f04da205354232fea58d78f61f4bc71775 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 16:24:46 +0100 Subject: [PATCH 5/9] Keep nvidia-smi from holding the caller; never take another card's memory Read nvidia-smi's output on a thread of its own and stop at the same timeout, so a process it leaves behind holding the pipe cannot block. Reap a program killed at the timeout, waiting at most 200 ms. When the adapter's own nvidia-smi line (or a line of its device id) has no size, the memory is unknown instead of another card's. A memory cap override that is not a number now behaves like no override for both the cap and the upload budget. The upload-budget test sets a budget that fits before its first phase, and the docs say how a set cap lowers the default upload budget. --- crates/gpu/src/context.rs | 4 +- crates/gpu/src/memcap.rs | 180 ++++++++++++++++++++++++++++++-------- crates/gpu/src/tests.rs | 10 ++- docs/preferences.md | 3 +- 4 files changed, 154 insertions(+), 43 deletions(-) diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 5721fbcee..aec859ac0 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -1679,7 +1679,9 @@ impl GpuContext { } /// Bytes of uploaded layer textures the context keeps (by default 3/8 of the card's memory - /// when known, 1536 MB otherwise; `EFFECTCRAFT_GPU_UPLOAD_MB`, see `memcap`). An application + /// when known, 1536 MiB otherwise; a positive `EFFECTCRAFT_GPU_MEMCAP_MB` lowers that default to + /// half the cap, not below 1536 MiB; a positive `EFFECTCRAFT_GPU_UPLOAD_MB` sets it and is not + /// lowered by the cap; see `memcap`). An application /// can raise it (static layers of a big frame upload once) or lower it (a small GPU); the /// least recently used textures go first. pub fn set_upload_budget(&self, bytes: usize) { diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 8cd30b161..3b11ce165 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -78,15 +78,21 @@ impl MemCap { let mut upload = upload_budget(upload_var, vram); // An explicit cap is the user's: it does not grow with the cache, so a default budget // is lowered to half of it (never below the former fixed 1.5 GiB); an explicit one stays. - let cap = match cap_var { - Some(_) => { - let cap = cap_from_env(cap_var, device_type, vram); + // A value that is not a number is treated as unset (with a warning), not as a cap. + let cap = match explicit_cap(cap_var) { + Some(cap) => { if cap > 0 && explicit_upload(upload_var).is_none() { upload = upload.min((cap / 2).max(UPLOAD_DEFAULT)); } cap } - None => default_cap_for(device_type, vram, upload), + None => { + let cap = default_cap_for(device_type, vram, upload); + if let Some(v) = cap_var { + log::warn!(target: "effectcraft_gpu", "{MEMCAP_ENV}={v:?} is not a whole number of MiB that fits in 64 bits: using {} MiB", cap / MIB); + } + cap + } }; MemCap { cap, @@ -206,18 +212,10 @@ impl MemCap { } } -/// The cap from the `EFFECTCRAFT_GPU_MEMCAP_MB` value: whole MiB (0 turns the gate off), or the -/// default for `device_type` when unset, or (with a warning) when not a number or too large. -fn cap_from_env(var: Option<&str>, device_type: wgpu::DeviceType, vram: Option) -> u64 { - let Some(v) = var else { return default_cap(device_type, vram) }; - match v.trim().parse::().ok().and_then(|mb| mb.checked_mul(MIB)) { - Some(cap) => cap, - None => { - let cap = default_cap(device_type, vram); - log::warn!(target: "effectcraft_gpu", "{MEMCAP_ENV}={v:?} is not a whole number of MiB that fits in 64 bits: using {} MiB", cap / MIB); - cap - } - } +/// The cap the user set in `EFFECTCRAFT_GPU_MEMCAP_MB`: whole MiB (0 turns the gate off); `None` +/// when unset, not a number or too large. +fn explicit_cap(var: Option<&str>) -> Option { + var?.trim().parse::().ok()?.checked_mul(MIB) } /// The upload cache budget from the `EFFECTCRAFT_GPU_UPLOAD_MB` value: whole MiB, or (0, unset, or @@ -374,9 +372,14 @@ fn nvidia_smi_output() -> Option<&'static str> { .as_deref() } -/// Runs `program` with `args` and returns its standard output when it exits successfully within -/// `timeout`, without a console window on Windows. A program still running at the timeout is -/// killed and not waited for (a process stuck in the driver may not die at once). +/// How long a killed program may take to exit before it is left behind unreaped. +#[cfg(not(target_arch = "wasm32"))] +const REAP_TIMEOUT: Duration = Duration::from_millis(200); + +/// Runs `program` with `args` and returns its standard output when it exits successfully and its +/// output ends within `timeout`, without a console window on Windows. The output is read on a +/// thread of its own, so a process the program left behind holding the pipe open cannot hold the +/// caller past the timeout. A program still running at the timeout is killed (see [`stop`]). #[cfg(not(target_arch = "wasm32"))] fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) -> Option { use std::io::Read; @@ -389,31 +392,60 @@ fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) const CREATE_NO_WINDOW: u32 = 0x0800_0000; cmd.creation_flags(CREATE_NO_WINDOW); } - let mut child = cmd.spawn().ok()?; let start = std::time::Instant::now(); + let mut child = cmd.spawn().ok()?; + let (tx, rx) = std::sync::mpsc::channel(); + let reader = child.stdout.take().and_then(|mut stdout| { + std::thread::Builder::new() + .name("nvidia-smi output".into()) + .spawn(move || { + let mut out = String::new(); + let _ = tx.send(stdout.read_to_string(&mut out).ok().map(|_| out)); + }) + .ok() + }); + if reader.is_none() { + stop(&mut child); + return None; + } loop { match child.try_wait() { Ok(Some(status)) if status.success() => break, Ok(None) if start.elapsed() < timeout => std::thread::sleep(Duration::from_millis(10)), Ok(Some(_)) => return None, _ => { - let _ = child.kill(); + stop(&mut child); return None; } } } - // The output is a few short lines, so the pipe never fills before the program exits. - let mut out = String::new(); - child.stdout.take()?.read_to_string(&mut out).ok()?; - Some(out) + rx.recv_timeout(timeout.saturating_sub(start.elapsed())).ok().flatten() +} + +/// Kills `child` and collects its exit status, waiting at most [`REAP_TIMEOUT`] for it to exit +/// (a process stuck in the driver may not die at once, and the caller must not wait for that). +/// The exit status, or `None` when the program has not exited by then. +#[cfg(not(target_arch = "wasm32"))] +fn stop(child: &mut std::process::Child) -> Option { + let _ = child.kill(); + let start = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => return Some(status), + Ok(None) if start.elapsed() < REAP_TIMEOUT => std::thread::sleep(Duration::from_millis(5)), + _ => return None, + } + } } /// The memory in bytes of the NVIDIA GPU in `nvidia-smi` output (lines of `bus id, device id, /// memory in MiB`, like `00000000:01:00.0, 0x250310DE, 12288`) that is the adapter: the line at /// PCI address `bus` (wgpu's `device_pci_bus_id`, `0000:01:00.0`), otherwise the smallest among /// the lines of PCI device `device`, otherwise the smallest of all. Smaller is the safe guess, as -/// the budget and the cap are fractions of it. Lines that do not parse (`[N/A]`, a zero, a size -/// that overflows) are skipped. +/// the budget and the cap are fractions of it. A size that does not parse (`[N/A]`, a zero, a +/// size that overflows) is unknown: on the adapter's own line, or on any line of its device id +/// when no line has its address, the memory is unknown, never another card's. Lines without three +/// fields are skipped. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] fn vram_from_nvidia_smi(output: &str, device: u32, bus: &str) -> Option { // A PCI address as (domain, rest): nvidia-smi writes eight digits of domain, wgpu four. @@ -422,12 +454,13 @@ fn vram_from_nvidia_smi(output: &str, device: u32, bus: &str) -> Option { let (domain, rest) = s.split_once(':')?; Some((u32::from_str_radix(domain, 16).ok()?, rest.to_string())).filter(|(_, rest)| !rest.is_empty()) }; - let gpus: Vec<(Option<(u32, String)>, Option, u64)> = output + type Gpu = (Option<(u32, String)>, Option, Option); + let gpus: Vec = output .lines() .filter_map(|line| { let mut fields = line.split(','); let (addr, id, mib) = (fields.next()?, fields.next()?, fields.next()?); - let bytes = mib.trim().parse::().ok()?.checked_mul(MIB).filter(|&b| b > 0)?; + let bytes = mib.trim().parse::().ok().and_then(|mib| mib.checked_mul(MIB)).filter(|&b| b > 0); let id = id.trim().to_ascii_lowercase(); let pci_device = u32::from_str_radix(id.strip_prefix("0x").unwrap_or(&id), 16).ok().map(|id| id >> 16); Some((address(addr), pci_device, bytes)) @@ -435,9 +468,14 @@ fn vram_from_nvidia_smi(output: &str, device: u32, bus: &str) -> Option { .collect(); let want = address(bus); if let Some(&(_, _, bytes)) = gpus.iter().find(|(a, _, _)| want.is_some() && *a == want) { - return Some(bytes); + return bytes; } - gpus.iter().filter(|(_, d, _)| *d == Some(device)).map(|&(_, _, b)| b).min().or_else(|| gpus.iter().map(|&(_, _, b)| b).min()) + let same: Vec> = gpus.iter().filter(|(_, d, _)| *d == Some(device)).map(|&(_, _, b)| b).collect(); + if !same.is_empty() { + // Any of them may be the adapter: one of unknown size makes the adapter's size unknown. + return same.iter().copied().collect::>>()?.into_iter().min(); + } + gpus.iter().filter_map(|&(_, _, b)| b).min() } /// Minimum reclaimable bytes before a wait is worth draining an encoder (1/8 of the cap, @@ -515,9 +553,23 @@ mod tests { assert_eq!(default_cap(d, Some(4 * GIB)), 3 * GIB); assert_eq!(default_cap(d, Some(16 * GIB)), 3 * GIB, "never above the default"); assert_eq!(default_cap(wgpu::DeviceType::IntegratedGpu, Some(GIB / 2)), 2 * GIB); - assert_eq!(cap_from_env(None, d, Some(2 * GIB)), 3 * GIB / 2); - assert_eq!(cap_from_env(Some("lots"), d, Some(2 * GIB)), 3 * GIB / 2, "a bad override falls back to it"); - assert_eq!(cap_from_env(Some("4096"), d, Some(2 * GIB)), 4 * GIB, "the override still wins"); + let cap = |v| MemCap::from_env(v, d, Some(2 * GIB)).cap(); + assert_eq!(cap(None), 3 * GIB / 2); + assert_eq!(cap(Some("lots")), 3 * GIB / 2, "a bad override falls back to it"); + assert_eq!(cap(Some("4096")), 4 * GIB, "the override still wins"); + } + + /// A cap override that is not a number is ignored as a whole: the cap and the upload budget + /// are those of no override, not the 3 GiB base cap and a budget lowered to half of it. + #[test] + fn a_bad_cap_override_keeps_the_default_cap_and_budget() { + let d = wgpu::DeviceType::DiscreteGpu; + let unset = MemCap::from_envs(None, None, d, Some(32 * GIB)); + assert_eq!((unset.cap(), unset.upload_budget()), (3 * GIB + 21 * GIB / 2, 12 * GIB as usize)); + for bad in ["", "lots", "-1", "1.5", "17592186044416"] { + let m = MemCap::from_envs(Some(bad), None, d, Some(32 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (unset.cap(), unset.upload_budget()), "{bad:?}"); + } } #[test] @@ -636,9 +688,23 @@ mod tests { ] { assert_eq!(vram_from_nvidia_smi(bad, 0x2503, "0000:01:00.0"), None, "{bad:?}"); } - // A bad line next to a good one leaves the good one. + // A line that is not a card next to a good one leaves the good one. + let noise = "NVIDIA-SMI warning\n00000000:02:00.0, garbage, 6144\n"; + assert_eq!(vram_from_nvidia_smi(noise, 0x2503, "0000:01:00.0"), Some(6 * GIB)); + } + + /// The adapter's own line without a size gives unknown memory (the 1.5 GiB fallback), never + /// the size of another card: a 4 GB card next to a 24 GB one must not get the larger budget. + #[test] + fn an_unknown_size_on_the_adapters_line_is_not_taken_from_another_card() { let mixed = "00000000:01:00.0, 0x250310DE, [N/A]\n00000000:02:00.0, garbage, 6144\n"; - assert_eq!(vram_from_nvidia_smi(mixed, 0x2503, "0000:01:00.0"), Some(6 * GIB)); + assert_eq!(vram_from_nvidia_smi(mixed, 0x2503, "0000:01:00.0"), None, "the adapter's address"); + assert_eq!(vram_from_nvidia_smi(mixed, 0x2503, ""), None, "the adapter's device id"); + let twins = "00000000:01:00.0, 0x250310DE, [N/A]\n00000000:02:00.0, 0x250310DE, 8192\n00000000:03:00.0, 0x2B8510DE, 24576\n"; + assert_eq!(vram_from_nvidia_smi(twins, 0x2503, ""), None, "either twin may be the adapter"); + assert_eq!(vram_from_nvidia_smi(twins, 0x2503, "0000:09:00.0"), None, "no such address: either twin"); + assert_eq!(vram_from_nvidia_smi(twins, 0x2503, "0000:02:00.0"), Some(8 * GIB), "the known twin by its address"); + assert_eq!(vram_from_nvidia_smi(twins, 0x1234, ""), Some(8 * GIB), "no such device: the smallest known card"); } /// Stands in for an `nvidia-smi` that hangs: only run (through `--ignored`) as a child of @@ -665,6 +731,46 @@ mod tests { let start = std::time::Instant::now(); let hung = run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"], Duration::from_millis(500)); assert_eq!(hung, None); - assert!(start.elapsed() < Duration::from_secs(10), "waited {:?}", start.elapsed()); + // Well under the stand-in's 5 s: the caller did not wait for it to finish. + assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); + } + + /// Stands in for an `nvidia-smi` that exits at once but leaves a process behind that holds its + /// output open (the hanging stand-in, which inherits it): only run (through `--ignored`) as a + /// child of `output_held_open_by_a_left_process_does_not_hold_the_caller`. + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "the child process of output_held_open_by_a_left_process_does_not_hold_the_caller"] + fn stand_in_that_leaves_its_output_open() { + let me = std::env::current_exe().unwrap(); + let _left = std::process::Command::new(me).args(["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"]).spawn().unwrap(); + } + + /// The output is read within the same timeout: a program that exits but leaves a process + /// holding its output open gives no output, and the caller does not wait for that process. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn output_held_open_by_a_left_process_does_not_hold_the_caller() { + let me = std::env::current_exe().unwrap(); + let start = std::time::Instant::now(); + let out = run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_that_leaves_its_output_open"], Duration::from_secs(1)); + assert_eq!(out, None); + assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); + } + + /// A program killed at the timeout is reaped (its exit status collected), within a bounded wait. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_killed_program_is_reaped() { + let me = std::env::current_exe().unwrap(); + let mut child = std::process::Command::new(me) + .args(["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"]) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap(); + let start = std::time::Instant::now(); + let status = stop(&mut child); + assert!(status.is_some_and(|s| !s.success()), "{status:?}"); + assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 2aa251356..681793091 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1533,17 +1533,19 @@ fn upload_budget_bounds_the_layer_textures_kept() { let img = g.render(&r, s.cid, Tick::from_seconds_f64(k as f64 / 30.0)).expect("the GPU renders the frame"); (img.data, g.ctx.transfer_stats().upload_bytes - before) }; + // A budget that holds both 640 KB footprints, whatever EFFECTCRAFT_GPU_UPLOAD_MB says. + let inherited = g.ctx.upload_budget(); + g.ctx.set_upload_budget(64 << 20); let fits = effectcraft_render::cache::LayerCache::new(64 << 20); let (a, _) = frame(&fits, 0); - let (b, up) = frame(&fits, 1); - assert_eq!(up, 0, "static layers re-uploaded within the default budget"); + let (b, up_fits) = frame(&fits, 1); // A budget smaller than the two 640 KB footprints: each upload evicts the other. - let default = g.ctx.upload_budget(); g.ctx.set_upload_budget(1 << 20); let tight = effectcraft_render::cache::LayerCache::new(64 << 20); let _ = frame(&tight, 0); let (c, up) = frame(&tight, 1); - g.ctx.set_upload_budget(default); + g.ctx.set_upload_budget(inherited); + assert_eq!(up_fits, 0, "static layers re-uploaded within a budget that fits them"); assert!(up > 0, "over budget, the footprints must upload again"); assert!(a == b && b == c, "the upload budget changed the frame"); } diff --git a/docs/preferences.md b/docs/preferences.md index 7a2cbead2..558aacf2f 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -101,7 +101,8 @@ Commands (CLI, MCP, control channel): textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where it is known: on Linux with amdgpu, on Windows, and on NVIDIA cards through `nvidia-smi`; the default cap grows with it, never above - three quarters of the card; `EFFECTCRAFT_GPU_UPLOAD_MB` sets it in whole MiB, 0 = default). It + three quarters of the card, and a cap set with `EFFECTCRAFT_GPU_MEMCAP_MB` lowers it to half + that cap, not below 1.5 GiB; `EFFECTCRAFT_GPU_UPLOAD_MB` sets it in whole MiB, 0 = default). It renders one frame at a time where the memory can't be measured (Metal, WebGPU, GL, or the cap turned off) and once frames have had to wait for memory. The render log names the count. `EFFECTCRAFT_GPU_INFLIGHT` overrides it. CPU renders have no such setting. A job on GPU From 3d3abd95619a11fa438d6276bb1399726a502c86 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 16:31:12 +0100 Subject: [PATCH 6/9] Give the held-output test room to start, retry reaping on a loaded machine, clearer budget docs --- crates/gpu/src/memcap.rs | 13 ++++++++++--- docs/preferences.md | 5 +++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 3b11ce165..258732e0f 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -741,6 +741,7 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] #[ignore = "the child process of output_held_open_by_a_left_process_does_not_hold_the_caller"] + #[allow(clippy::zombie_processes, reason = "the process is left running on purpose; this process exits at once")] fn stand_in_that_leaves_its_output_open() { let me = std::env::current_exe().unwrap(); let _left = std::process::Command::new(me).args(["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"]).spawn().unwrap(); @@ -753,9 +754,11 @@ mod tests { fn output_held_open_by_a_left_process_does_not_hold_the_caller() { let me = std::env::current_exe().unwrap(); let start = std::time::Instant::now(); - let out = run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_that_leaves_its_output_open"], Duration::from_secs(1)); + // The timeout leaves the stand-in time to start and exit; the left process sleeps 5 s. + let out = + run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_that_leaves_its_output_open"], Duration::from_millis(2500)); assert_eq!(out, None); - assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); + assert!(start.elapsed() < Duration::from_millis(4500), "waited {:?}", start.elapsed()); } /// A program killed at the timeout is reaped (its exit status collected), within a bounded wait. @@ -769,7 +772,11 @@ mod tests { .spawn() .unwrap(); let start = std::time::Instant::now(); - let status = stop(&mut child); + // A loaded machine may take longer than one `REAP_TIMEOUT` to end the process. + let mut status = stop(&mut child); + while status.is_none() && start.elapsed() < Duration::from_secs(3) { + status = stop(&mut child); + } assert!(status.is_some_and(|s| !s.success()), "{status:?}"); assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); } diff --git a/docs/preferences.md b/docs/preferences.md index 558aacf2f..2c023e936 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -101,8 +101,9 @@ Commands (CLI, MCP, control channel): textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where it is known: on Linux with amdgpu, on Windows, and on NVIDIA cards through `nvidia-smi`; the default cap grows with it, never above - three quarters of the card, and a cap set with `EFFECTCRAFT_GPU_MEMCAP_MB` lowers it to half - that cap, not below 1.5 GiB; `EFFECTCRAFT_GPU_UPLOAD_MB` sets it in whole MiB, 0 = default). It + three quarters of the card, and a cap above 0 set with `EFFECTCRAFT_GPU_MEMCAP_MB` lowers the + default budget to half that cap, not below 1.5 GiB; `EFFECTCRAFT_GPU_UPLOAD_MB` sets the budget + in whole MiB, 0 = default, and a budget set there is kept). It renders one frame at a time where the memory can't be measured (Metal, WebGPU, GL, or the cap turned off) and once frames have had to wait for memory. The render log names the count. `EFFECTCRAFT_GPU_INFLIGHT` overrides it. CPU renders have no such setting. A job on GPU From 34a1c8893018fbccd4672ec12dfa9eba6b8ffcee Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 17:38:13 +0100 Subject: [PATCH 7/9] Reap a killed nvidia-smi on a thread of its own, tell why it gave no output, restore the test budget on failure, clearer cap docs --- crates/gpu/src/context.rs | 5 +- crates/gpu/src/memcap.rs | 128 +++++++++++++++++++++++++++----------- crates/gpu/src/tests.rs | 23 ++++++- docs/preferences.md | 5 +- 4 files changed, 118 insertions(+), 43 deletions(-) diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index aec859ac0..7125ea526 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -1679,8 +1679,9 @@ impl GpuContext { } /// Bytes of uploaded layer textures the context keeps (by default 3/8 of the card's memory - /// when known, 1536 MiB otherwise; a positive `EFFECTCRAFT_GPU_MEMCAP_MB` lowers that default to - /// half the cap, not below 1536 MiB; a positive `EFFECTCRAFT_GPU_UPLOAD_MB` sets it and is not + /// when known, 1536 MiB otherwise; a positive `EFFECTCRAFT_GPU_MEMCAP_MB` can only lower that + /// default: to at most the larger of half the cap and 1536 MiB, so a smaller default, like the + /// 768 MiB of a 2 GiB card, stays; a positive `EFFECTCRAFT_GPU_UPLOAD_MB` sets it and is not /// lowered by the cap; see `memcap`). An application /// can raise it (static layers of a big frame upload once) or lower it (a small GPU); the /// least recently used textures go first. diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 258732e0f..2b92ed28c 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -76,8 +76,9 @@ impl MemCap { fn from_envs(cap_var: Option<&str>, upload_var: Option<&str>, device_type: wgpu::DeviceType, vram: Option) -> MemCap { let mut upload = upload_budget(upload_var, vram); - // An explicit cap is the user's: it does not grow with the cache, so a default budget - // is lowered to half of it (never below the former fixed 1.5 GiB); an explicit one stays. + // An explicit cap is the user's: it does not grow with the cache, so a default budget is + // kept at most at the larger of half the cap and the former fixed 1.5 GiB (it is never + // raised, and a smaller default stays as it is); an explicit budget stays. // A value that is not a number is treated as unset (with a warning), not as a cap. let cap = match explicit_cap(cap_var) { Some(cap) => { @@ -364,24 +365,37 @@ fn nvidia_smi_output() -> Option<&'static str> { OUTPUT .get_or_init(|| { let out = run_with_timeout(std::ffi::OsStr::new("nvidia-smi"), &NVIDIA_SMI_ARGS, NVIDIA_SMI_TIMEOUT); - if out.is_none() { - log::debug!(target: "effectcraft_gpu", "nvidia-smi is missing, failed or took longer than {NVIDIA_SMI_TIMEOUT:?}: video memory unknown"); + if let Err(why) = &out { + log::debug!(target: "effectcraft_gpu", "nvidia-smi gave no answer ({why:?}, timeout {NVIDIA_SMI_TIMEOUT:?}): video memory unknown"); } - out + out.ok() }) .as_deref() } -/// How long a killed program may take to exit before it is left behind unreaped. +/// How long the caller waits for a killed program to exit before a thread of its own reaps it. #[cfg(not(target_arch = "wasm32"))] const REAP_TIMEOUT: Duration = Duration::from_millis(200); +/// Why [`run_with_timeout`] has no output. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug, PartialEq, Eq)] +enum NoOutput { + /// The program could not start, exited with an error, or its output could not be read. + Failed, + /// The program was still running at the timeout (it is killed). + TimedOut, + /// The program exited successfully, but its output was still open at the timeout (a process + /// it left behind holds it). + OutputOpen, +} + /// Runs `program` with `args` and returns its standard output when it exits successfully and its /// output ends within `timeout`, without a console window on Windows. The output is read on a /// thread of its own, so a process the program left behind holding the pipe open cannot hold the /// caller past the timeout. A program still running at the timeout is killed (see [`stop`]). #[cfg(not(target_arch = "wasm32"))] -fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) -> Option { +fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) -> Result { use std::io::Read; use std::process::{Command, Stdio}; let mut cmd = Command::new(program); @@ -393,7 +407,7 @@ fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) cmd.creation_flags(CREATE_NO_WINDOW); } let start = std::time::Instant::now(); - let mut child = cmd.spawn().ok()?; + let mut child = cmd.spawn().map_err(|_| NoOutput::Failed)?; let (tx, rx) = std::sync::mpsc::channel(); let reader = child.stdout.take().and_then(|mut stdout| { std::thread::Builder::new() @@ -405,39 +419,59 @@ fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) .ok() }); if reader.is_none() { - stop(&mut child); - return None; + let _ = stop(child); + return Err(NoOutput::Failed); } loop { match child.try_wait() { Ok(Some(status)) if status.success() => break, Ok(None) if start.elapsed() < timeout => std::thread::sleep(Duration::from_millis(10)), - Ok(Some(_)) => return None, - _ => { - stop(&mut child); - return None; + Ok(Some(_)) => return Err(NoOutput::Failed), + Ok(None) => { + let _ = stop(child); + return Err(NoOutput::TimedOut); + } + Err(_) => { + let _ = stop(child); + return Err(NoOutput::Failed); } } } - rx.recv_timeout(timeout.saturating_sub(start.elapsed())).ok().flatten() + match rx.recv_timeout(timeout.saturating_sub(start.elapsed())) { + Ok(Some(out)) => Ok(out), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(NoOutput::OutputOpen), + Ok(None) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(NoOutput::Failed), + } } -/// Kills `child` and collects its exit status, waiting at most [`REAP_TIMEOUT`] for it to exit -/// (a process stuck in the driver may not die at once, and the caller must not wait for that). -/// The exit status, or `None` when the program has not exited by then. +/// Kills `child` and collects its exit status, so it is not left behind as a zombie. The caller +/// waits at most [`REAP_TIMEOUT`] for that (a process stuck in the driver may not die at once); +/// after that a thread of its own waits for the program (see [`reap_later`]). The exit status +/// when the program exited within [`REAP_TIMEOUT`], otherwise the reaping thread. #[cfg(not(target_arch = "wasm32"))] -fn stop(child: &mut std::process::Child) -> Option { +fn stop(mut child: std::process::Child) -> Result> { let _ = child.kill(); let start = std::time::Instant::now(); loop { match child.try_wait() { - Ok(Some(status)) => return Some(status), + Ok(Some(status)) => return Ok(status), Ok(None) if start.elapsed() < REAP_TIMEOUT => std::thread::sleep(Duration::from_millis(5)), - _ => return None, + _ => return Err(reap_later(child)), } } } +/// A thread that waits for a program to exit; it gives the exit status. +#[cfg(not(target_arch = "wasm32"))] +type Reaper = std::thread::JoinHandle>; + +/// Waits for `child` to exit on a thread of its own, which collects its exit status. `None` when +/// the thread cannot start: the child is then dropped (left unreaped, as it cannot be helped). +#[cfg(not(target_arch = "wasm32"))] +fn reap_later(mut child: std::process::Child) -> Option { + std::thread::Builder::new().name("nvidia-smi reaper".into()).spawn(move || child.wait().ok()).ok() +} + /// The memory in bytes of the NVIDIA GPU in `nvidia-smi` output (lines of `bus id, device id, /// memory in MiB`, like `00000000:01:00.0, 0x250310DE, 12288`) that is the adapter: the line at /// PCI address `bus` (wgpu's `device_pci_bus_id`, `0000:01:00.0`), otherwise the smallest among @@ -619,6 +653,9 @@ mod tests { assert_eq!((m.cap(), m.upload_budget()), (4 * GIB, 2 * GIB as usize)); let m = MemCap::from_envs(Some("8"), None, d, Some(32 * GIB)); assert_eq!((m.cap(), m.upload_budget()), (8 * MIB, 3 * GIB as usize / 2)); + // The cap only lowers: a 2 GiB card's 768 MiB default stays under a 2 GiB cap. + let m = MemCap::from_envs(Some("2048"), None, d, Some(2 * GIB)); + assert_eq!((m.cap(), m.upload_budget()), (2 * GIB, 768 * MIB as usize)); let m = MemCap::from_envs(Some("0"), None, d, Some(32 * GIB)); assert_eq!((m.cap(), m.upload_budget()), (0, 12 * GIB as usize)); let m = MemCap::from_envs(None, Some("9000"), d, Some(32 * GIB)); @@ -721,16 +758,16 @@ mod tests { #[test] fn a_program_that_fails_or_hangs_gives_no_output() { let missing = std::ffi::OsStr::new("effectcraft-no-such-program-3731"); - assert_eq!(run_with_timeout(missing, &NVIDIA_SMI_ARGS, Duration::from_secs(5)), None); + assert_eq!(run_with_timeout(missing, &NVIDIA_SMI_ARGS, Duration::from_secs(5)), Err(NoOutput::Failed)); let me = std::env::current_exe().unwrap(); // This test binary stands in for the program: listing tests succeeds and prints them, // an unknown flag exits with an error, and the sleeping test outlasts the timeout. let listed = run_with_timeout(me.as_os_str(), &["--list", "--exact", "memcap::tests::stand_in_for_a_hanging_program"], Duration::from_secs(20)); - assert!(listed.is_some_and(|out| out.contains("stand_in_for_a_hanging_program"))); - assert_eq!(run_with_timeout(me.as_os_str(), &["--no-such-flag-3731"], Duration::from_secs(20)), None); + assert!(listed.is_ok_and(|out| out.contains("stand_in_for_a_hanging_program"))); + assert_eq!(run_with_timeout(me.as_os_str(), &["--no-such-flag-3731"], Duration::from_secs(20)), Err(NoOutput::Failed)); let start = std::time::Instant::now(); let hung = run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"], Duration::from_millis(500)); - assert_eq!(hung, None); + assert_eq!(hung, Err(NoOutput::TimedOut)); // Well under the stand-in's 5 s: the caller did not wait for it to finish. assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); } @@ -757,26 +794,45 @@ mod tests { // The timeout leaves the stand-in time to start and exit; the left process sleeps 5 s. let out = run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_that_leaves_its_output_open"], Duration::from_millis(2500)); - assert_eq!(out, None); + // Not a stand-in that failed to start its left process (that exits with an error). + assert_eq!(out, Err(NoOutput::OutputOpen)); assert!(start.elapsed() < Duration::from_millis(4500), "waited {:?}", start.elapsed()); } - /// A program killed at the timeout is reaped (its exit status collected), within a bounded wait. + /// The hanging stand-in, its output discarded. #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_killed_program_is_reaped() { + fn hanging_stand_in() -> std::process::Child { let me = std::env::current_exe().unwrap(); - let mut child = std::process::Command::new(me) + std::process::Command::new(me) .args(["--exact", "--ignored", "memcap::tests::stand_in_for_a_hanging_program"]) .stdout(std::process::Stdio::null()) .spawn() - .unwrap(); + .unwrap() + } + + /// A program killed at the timeout is reaped (its exit status collected): by the caller within + /// `REAP_TIMEOUT`, or else by a thread of its own, never left behind. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_killed_program_is_reaped() { let start = std::time::Instant::now(); - // A loaded machine may take longer than one `REAP_TIMEOUT` to end the process. - let mut status = stop(&mut child); - while status.is_none() && start.elapsed() < Duration::from_secs(3) { - status = stop(&mut child); - } + let status = match stop(hanging_stand_in()) { + Ok(status) => Some(status), + Err(reaper) => reaper.expect("the reaper thread starts").join().unwrap(), + }; + assert!(status.is_some_and(|s| !s.success()), "{status:?}"); + assert!(start.elapsed() < Duration::from_secs(4), "waited {:?}", start.elapsed()); + } + + /// A killed program that has not exited when the caller stops waiting is reaped by a thread of + /// its own, which collects its exit status (#3737 review). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_program_that_exits_late_is_reaped_by_a_thread() { + let mut child = hanging_stand_in(); + let _ = child.kill(); + let start = std::time::Instant::now(); + let status = reap_later(child).expect("the reaper thread starts").join().unwrap(); assert!(status.is_some_and(|s| !s.success()), "{status:?}"); assert!(start.elapsed() < Duration::from_secs(3), "waited {:?}", start.elapsed()); } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 681793091..b6f0a1343 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1533,8 +1533,16 @@ fn upload_budget_bounds_the_layer_textures_kept() { let img = g.render(&r, s.cid, Tick::from_seconds_f64(k as f64 / 30.0)).expect("the GPU renders the frame"); (img.data, g.ctx.transfer_stats().upload_bytes - before) }; + // The shared context's budget comes back when the test ends, also when a frame fails (#3737 + // review): the GPU lock is held until this thread ends, so no other test sees the change. + struct Restore<'a>(&'a crate::GpuContext, usize); + impl Drop for Restore<'_> { + fn drop(&mut self) { + self.0.set_upload_budget(self.1); + } + } + let _restore = Restore(&g.ctx, g.ctx.upload_budget()); // A budget that holds both 640 KB footprints, whatever EFFECTCRAFT_GPU_UPLOAD_MB says. - let inherited = g.ctx.upload_budget(); g.ctx.set_upload_budget(64 << 20); let fits = effectcraft_render::cache::LayerCache::new(64 << 20); let (a, _) = frame(&fits, 0); @@ -1544,7 +1552,6 @@ fn upload_budget_bounds_the_layer_textures_kept() { let tight = effectcraft_render::cache::LayerCache::new(64 << 20); let _ = frame(&tight, 0); let (c, up) = frame(&tight, 1); - g.ctx.set_upload_budget(inherited); assert_eq!(up_fits, 0, "static layers re-uploaded within a budget that fits them"); assert!(up > 0, "over budget, the footprints must upload again"); assert!(a == b && b == c, "the upload budget changed the frame"); @@ -1558,10 +1565,13 @@ fn upload_budget_bounds_the_layer_textures_kept() { #[test] fn upload_budget_comes_from_the_memory_rule() { const ENV: &str = "EFFECTCRAFT_GPU_UPLOAD_TEST_CHILD"; + // What the child prints once its checks passed: a child without a GPU exits successfully too. + const CHECKED: &str = "upload budget child: checked"; let tight = std::env::var_os(ENV).is_some(); if !tight && std::env::var_os("EFFECTCRAFT_GPU_UPLOAD_MB").is_some() { return; // the caller set a budget of their own } + let mut child_checked = None; if !tight { // The child uses the GPU: tests of this process wait until it is done (#3737 review). hold_gpu_lock(); @@ -1572,9 +1582,15 @@ fn upload_budget_comes_from_the_memory_rule() { .args(["--exact", "tests::upload_budget_comes_from_the_memory_rule", "--nocapture"]) .output() .expect("spawn child test process"); - assert!(out.status.success(), "child test failed:\n{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "child test failed:\n{stdout}\n{stderr}"); + child_checked = Some((stdout.contains(CHECKED), format!("{stdout}\n{stderr}"))); } let Some(g) = gpu() else { return }; + // This process has a GPU, so the child must have run its checks, not skipped them. + if let Some((checked, output)) = child_checked { + assert!(checked, "the child did not run its checks:\n{output}"); + } let mut s = Scene::new(BitDepth::Bpc8); for i in 0..3 { let mut l = s.footage(600, 400); // 3.8 MB as RGBA f32 each @@ -1595,6 +1611,7 @@ fn upload_budget_comes_from_the_memory_rule() { if tight { assert_eq!(g.ctx.upload_budget(), 1 << 20, "EFFECTCRAFT_GPU_UPLOAD_MB=1"); assert!(up > 0, "layers over the budget must upload again"); + println!("{CHECKED}"); } else { assert_eq!(g.ctx.upload_budget(), g.ctx.upload_budget_from_rule()); assert_eq!(up, 0, "layers within the budget re-uploaded"); diff --git a/docs/preferences.md b/docs/preferences.md index 2c023e936..486eac4c3 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -101,8 +101,9 @@ Commands (CLI, MCP, control channel): textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where it is known: on Linux with amdgpu, on Windows, and on NVIDIA cards through `nvidia-smi`; the default cap grows with it, never above - three quarters of the card, and a cap above 0 set with `EFFECTCRAFT_GPU_MEMCAP_MB` lowers the - default budget to half that cap, not below 1.5 GiB; `EFFECTCRAFT_GPU_UPLOAD_MB` sets the budget + three quarters of the card, and a cap above 0 set with `EFFECTCRAFT_GPU_MEMCAP_MB` can only + lower the default budget: to at most the larger of half that cap and 1.5 GiB, so a smaller + default, like the 768 MiB of a 2 GiB card, stays; `EFFECTCRAFT_GPU_UPLOAD_MB` sets the budget in whole MiB, 0 = default, and a budget set there is kept). It renders one frame at a time where the memory can't be measured (Metal, WebGPU, GL, or the cap turned off) and once frames have had to wait for memory. The render log names the count. From 83e06a587a45c0b1435198d5287c22857d768a42 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 17:47:45 +0100 Subject: [PATCH 8/9] Give the held-output test more start-up room; name the reaper test for what it checks --- crates/gpu/src/memcap.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 2b92ed28c..73b3ce29b 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -793,7 +793,7 @@ mod tests { let start = std::time::Instant::now(); // The timeout leaves the stand-in time to start and exit; the left process sleeps 5 s. let out = - run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_that_leaves_its_output_open"], Duration::from_millis(2500)); + run_with_timeout(me.as_os_str(), &["--exact", "--ignored", "memcap::tests::stand_in_that_leaves_its_output_open"], Duration::from_millis(3000)); // Not a stand-in that failed to start its left process (that exits with an error). assert_eq!(out, Err(NoOutput::OutputOpen)); assert!(start.elapsed() < Duration::from_millis(4500), "waited {:?}", start.elapsed()); @@ -824,11 +824,11 @@ mod tests { assert!(start.elapsed() < Duration::from_secs(4), "waited {:?}", start.elapsed()); } - /// A killed program that has not exited when the caller stops waiting is reaped by a thread of - /// its own, which collects its exit status (#3737 review). + /// The thread that reaps a killed program the caller stopped waiting for collects its exit + /// status (#3737 review). #[cfg(not(target_arch = "wasm32"))] #[test] - fn a_program_that_exits_late_is_reaped_by_a_thread() { + fn a_killed_program_is_reaped_by_a_thread_of_its_own() { let mut child = hanging_stand_in(); let _ = child.kill(); let start = std::time::Instant::now(); From 1c5960bb7dc6208d54c03fa87e9111117f7a9b77 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 15:27:07 +0100 Subject: [PATCH 9/9] fix(gpu): cap NVIDIA diagnostic output --- crates/gpu/src/memcap.rs | 45 +++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/gpu/src/memcap.rs b/crates/gpu/src/memcap.rs index 73b3ce29b..5b1e62fde 100644 --- a/crates/gpu/src/memcap.rs +++ b/crates/gpu/src/memcap.rs @@ -357,8 +357,12 @@ const NVIDIA_SMI_ARGS: [&str; 2] = ["--query-gpu=pci.bus_id,pci.device_id,memory #[cfg(not(target_arch = "wasm32"))] const NVIDIA_SMI_TIMEOUT: Duration = Duration::from_secs(3); +/// Allow hundreds of short CSV rows while bounding the reader even after a caller timeout. +#[cfg(not(target_arch = "wasm32"))] +const NVIDIA_SMI_MAX_STDOUT: usize = 16 * 1024; + /// The output of `nvidia-smi` (see [`NVIDIA_SMI_ARGS`]), run once per process and kept: `None` when -/// it is missing, fails, or takes too long. +/// it is missing, fails, takes too long, or exceeds its output budget. #[cfg(not(target_arch = "wasm32"))] fn nvidia_smi_output() -> Option<&'static str> { static OUTPUT: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -383,6 +387,8 @@ const REAP_TIMEOUT: Duration = Duration::from_millis(200); enum NoOutput { /// The program could not start, exited with an error, or its output could not be read. Failed, + /// The diagnostic exceeded its stdout budget. + TooLarge, /// The program was still running at the timeout (it is killed). TimedOut, /// The program exited successfully, but its output was still open at the timeout (a process @@ -390,13 +396,23 @@ enum NoOutput { OutputOpen, } +#[cfg(not(target_arch = "wasm32"))] +fn read_probe_stdout(stdout: impl std::io::Read) -> Result { + use std::io::Read; + let mut out = Vec::new(); + stdout.take(NVIDIA_SMI_MAX_STDOUT as u64 + 1).read_to_end(&mut out).map_err(|_| NoOutput::Failed)?; + if out.len() > NVIDIA_SMI_MAX_STDOUT { + return Err(NoOutput::TooLarge); + } + String::from_utf8(out).map_err(|_| NoOutput::Failed) +} + /// Runs `program` with `args` and returns its standard output when it exits successfully and its -/// output ends within `timeout`, without a console window on Windows. The output is read on a +/// output ends within `timeout` and fits the byte budget, without a console window on Windows. The output is read on a /// thread of its own, so a process the program left behind holding the pipe open cannot hold the /// caller past the timeout. A program still running at the timeout is killed (see [`stop`]). #[cfg(not(target_arch = "wasm32"))] fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) -> Result { - use std::io::Read; use std::process::{Command, Stdio}; let mut cmd = Command::new(program); cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); @@ -409,12 +425,11 @@ fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) let start = std::time::Instant::now(); let mut child = cmd.spawn().map_err(|_| NoOutput::Failed)?; let (tx, rx) = std::sync::mpsc::channel(); - let reader = child.stdout.take().and_then(|mut stdout| { + let reader = child.stdout.take().and_then(|stdout| { std::thread::Builder::new() .name("nvidia-smi output".into()) .spawn(move || { - let mut out = String::new(); - let _ = tx.send(stdout.read_to_string(&mut out).ok().map(|_| out)); + let _ = tx.send(read_probe_stdout(stdout)); }) .ok() }); @@ -438,9 +453,9 @@ fn run_with_timeout(program: &std::ffi::OsStr, args: &[&str], timeout: Duration) } } match rx.recv_timeout(timeout.saturating_sub(start.elapsed())) { - Ok(Some(out)) => Ok(out), + Ok(out) => out, Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(NoOutput::OutputOpen), - Ok(None) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(NoOutput::Failed), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(NoOutput::Failed), } } @@ -744,6 +759,20 @@ mod tests { assert_eq!(vram_from_nvidia_smi(twins, 0x1234, ""), Some(8 * GIB), "no such device: the smallest known card"); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn oversized_probe_output_leaves_video_memory_unknown() { + let mut csv = b"00000000:01:00.0, 0x250310de, 12288\n".to_vec(); + csv.resize(NVIDIA_SMI_MAX_STDOUT, b' '); + let vram = |out: Result| out.ok().and_then(|out| vram_from_nvidia_smi(&out, 0x2503, "0000:01:00.0")); + assert_eq!(vram(read_probe_stdout(csv.as_slice())), Some(12 * GIB)); + + csv.extend_from_slice(b" "); + let mut stdout = std::io::Cursor::new(csv); + assert_eq!(vram(read_probe_stdout(&mut stdout)), None); + assert_eq!(stdout.position(), NVIDIA_SMI_MAX_STDOUT as u64 + 1, "stop reading as soon as the budget is exceeded"); + } + /// Stands in for an `nvidia-smi` that hangs: only run (through `--ignored`) as a child of /// `a_program_that_fails_or_hangs_gives_no_output`. #[cfg(not(target_arch = "wasm32"))]