authoravatarclover caruso<git@paperclover.net>2026-12-01 14:22:01-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:35:36-08:00
log181d489f7ee6df2510df91aab084020aeccbf112
tree13289de00752c9ba41b11e501057984f9b2ec627
parenta410bb327c81f2970d3c7e9fa129158d7984c289
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): fix PendingReadback submission index, BindGroup VRAM pinning, uniform ring reset, and default media budget


4 files changed, 427 insertions(+), 98 deletions(-)

crates/engine/src/cache.rs+77-24
...@@ -5,6 +5,7 @@...@@ -5,6 +5,7 @@
5use crate::profile::{FrameProfile, ProfileRecorder};5use crate::profile::{FrameProfile, ProfileRecorder};
6use model::{BitDepth, Comp, NodeId};6use model::{BitDepth, Comp, NodeId};
7use std::collections::{HashMap, VecDeque};7use std::collections::{HashMap, VecDeque};
8use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, Mutex};9use std::sync::{Arc, Mutex};
910
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
...@@ -456,6 +457,9 @@ pub struct NodeCache {...@@ -456,6 +457,9 @@ pub struct NodeCache {
456 total_bytes: u64,457 total_bytes: u64,
457 tick: u64,458 tick: u64,
458 evictions: u64,459 evictions: u64,
460 /// Monotonic counter incremented whenever a texture is dropped without being pooled
461 /// or evicted from `TexturePool`, used to invalidate `BindGroup` caches before they pin VRAM.
462 vram_drops: AtomicU64,
459 /// Monotonic salt bumped when busting GPU cache globally.463 /// Monotonic salt bumped when busting GPU cache globally.
460 pub gpu_salt: u64,464 pub gpu_salt: u64,
461 /// Per-node salt bumped when surgically busting a subtree.465 /// Per-node salt bumped when surgically busting a subtree.
...@@ -479,6 +483,7 @@ impl NodeCache {...@@ -479,6 +483,7 @@ impl NodeCache {
479 total_bytes: 0,483 total_bytes: 0,
480 tick: 0,484 tick: 0,
481 evictions: 0,485 evictions: 0,
486 vram_drops: AtomicU64::new(0),
482 gpu_salt: 0,487 gpu_salt: 0,
483 node_salts: HashMap::new(),488 node_salts: HashMap::new(),
484 pool: Mutex::new(TexturePool::new()),489 pool: Mutex::new(TexturePool::new()),
...@@ -512,6 +517,10 @@ impl NodeCache {...@@ -512,6 +517,10 @@ impl NodeCache {
512 self.evictions517 self.evictions
513 }518 }
514519
520 pub fn vram_drops(&self) -> u64 {
521 self.vram_drops.load(Ordering::Relaxed)
522 }
523
515 pub fn node_salt(&self, id: NodeId) -> u64 {524 pub fn node_salt(&self, id: NodeId) -> u64 {
516 self.node_salts.get(&id).copied().unwrap_or(0)525 self.node_salts.get(&id).copied().unwrap_or(0)
517 }526 }
...@@ -583,16 +592,7 @@ impl NodeCache {...@@ -583,16 +592,7 @@ impl NodeCache {
583 }592 }
584 pool.misses += 1;593 pool.misses += 1;
585 // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget.594 // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget.
586 while self595 self.trim_pool_locked(&mut pool, bytes);
587 .total_bytes
588 .saturating_add(pool.total_bytes)
589 .saturating_add(bytes)
590 > self.budget_bytes
591 {
592 if !pool.evict_oldest() {
593 break;
594 }
595 }
596 }596 }
597597
598 let texture = device.create_texture(&wgpu::TextureDescriptor {598 let texture = device.create_texture(&wgpu::TextureDescriptor {
...@@ -741,6 +741,9 @@ impl NodeCache {...@@ -741,6 +741,9 @@ impl NodeCache {
741741
742 fn defer_to_pool(&mut self, tex: CachedTexture) {742 fn defer_to_pool(&mut self, tex: CachedTexture) {
743 if tex.bytes == 0 || tex.bytes > self.budget_bytes {743 if tex.bytes == 0 || tex.bytes > self.budget_bytes {
744 if tex.bytes > 0 {
745 self.vram_drops.fetch_add(1, Ordering::Relaxed);
746 }
744 return;747 return;
745 }748 }
746 let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum();749 let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum();
...@@ -764,6 +767,7 @@ impl NodeCache {...@@ -764,6 +767,7 @@ impl NodeCache {
764 }767 }
765 pending_bytes = pending_bytes.saturating_sub(dropped.bytes);768 pending_bytes = pending_bytes.saturating_sub(dropped.bytes);
766 self.pending_pool.pop_front();769 self.pending_pool.pop_front();
770 self.vram_drops.fetch_add(1, Ordering::Relaxed);
767 }771 }
768 if self772 if self
769 .total_bytes773 .total_bytes
...@@ -772,6 +776,8 @@ impl NodeCache {...@@ -772,6 +776,8 @@ impl NodeCache {
772 <= self.budget_bytes776 <= self.budget_bytes
773 {777 {
774 self.pending_pool.push_back(tex);778 self.pending_pool.push_back(tex);
779 } else {
780 self.vram_drops.fetch_add(1, Ordering::Relaxed);
775 }781 }
776 }782 }
777 }783 }
...@@ -795,26 +801,35 @@ impl NodeCache {...@@ -795,26 +801,35 @@ impl NodeCache {
795 }801 }
796 }802 }
797803
804 fn trim_pool_locked(&self, pool: &mut TexturePool, reserve_bytes: u64) {
805 while self
806 .total_bytes
807 .saturating_add(pool.total_bytes)
808 .saturating_add(reserve_bytes)
809 > self.budget_bytes
810 {
811 if !pool.evict_oldest() {
812 break;
813 }
814 self.vram_drops.fetch_add(1, Ordering::Relaxed);
815 }
816 }
817
798 fn return_to_pool(&self, tex: &CachedTexture) {818 fn return_to_pool(&self, tex: &CachedTexture) {
799 if tex.bytes == 0 || tex.bytes > self.budget_bytes {819 if tex.bytes == 0 || tex.bytes > self.budget_bytes {
820 if tex.bytes > 0 {
821 self.vram_drops.fetch_add(1, Ordering::Relaxed);
822 }
800 return;823 return;
801 }824 }
802 let mut pool = self.pool.lock().expect("texture pool lock");825 let mut pool = self.pool.lock().expect("texture pool lock");
803 pool.push(tex);826 pool.push(tex);
804 while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes {827 self.trim_pool_locked(&mut pool, 0);
805 if !pool.evict_oldest() {
806 break;
807 }
808 }
809 }828 }
810829
811 fn trim_pool_to_budget(&self) {830 fn trim_pool_to_budget(&self) {
812 let mut pool = self.pool.lock().expect("texture pool lock");831 let mut pool = self.pool.lock().expect("texture pool lock");
813 while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes {832 self.trim_pool_locked(&mut pool, 0);
814 if !pool.evict_oldest() {
815 break;
816 }
817 }
818 }833 }
819834
820 fn evict_over_budget(&mut self) {835 fn evict_over_budget(&mut self) {
...@@ -868,22 +883,31 @@ impl NodeCache {...@@ -868,22 +883,31 @@ impl NodeCache {
868 for tex in recycle_scratch {883 for tex in recycle_scratch {
869 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {884 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {
870 pool.push(&tex);885 pool.push(&tex);
886 } else if tex.bytes > 0 {
887 self.vram_drops.fetch_add(1, Ordering::Relaxed);
871 }888 }
872 }889 }
873 for tex in pending {890 for tex in pending {
874 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {891 if tex.bytes > 0 && tex.bytes <= self.budget_bytes {
875 pool.push(&tex);892 pool.push(&tex);
893 } else if tex.bytes > 0 {
894 self.vram_drops.fetch_add(1, Ordering::Relaxed);
876 }895 }
877 }896 }
878 for entry in drained {897 for entry in drained {
879 if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes {898 if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes {
880 pool.push(&entry.tex);899 pool.push(&entry.tex);
900 } else if entry.tex.bytes > 0 {
901 self.vram_drops.fetch_add(1, Ordering::Relaxed);
881 }902 }
882 }903 }
883 while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes {904 self.trim_pool_locked(&mut pool, 0);
884 if !pool.evict_oldest() {905 } else {
885 break;906 let dropped = drained.iter().filter(|e| e.tex.bytes > 0).count()
886 }907 + pending.iter().filter(|t| t.bytes > 0).count()
908 + recycle_scratch.iter().filter(|t| t.bytes > 0).count();
909 if dropped > 0 {
910 self.vram_drops.fetch_add(dropped as u64, Ordering::Relaxed);
887 }911 }
888 }912 }
889 count913 count
...@@ -1235,4 +1259,33 @@ mod tests {...@@ -1235,4 +1259,33 @@ mod tests {
1235 assert_eq!(Arc::as_ptr(&reused.texture), ptr);1259 assert_eq!(Arc::as_ptr(&reused.texture), ptr);
1236 assert_eq!(cache.pool_stats().hits, 1);1260 assert_eq!(cache.pool_stats().hits, 1);
1237 }1261 }
1262
1263 #[test]
1264 fn vram_drops_increments_on_eviction_overflow_and_pool_trim() {
1265 let eng = Engine::new_headless().expect("gpu");
1266 let device = eng.device();
1267 let usage = NodeCache::default_texture_usage();
1268 // 4 MiB budget: each 512x512 RGBA8 is 1 MiB.
1269 let mut cache = NodeCache::new(4);
1270 assert_eq!(cache.vram_drops(), 0);
1271
1272 // Insert 5 entries -> 1 is evicted to pending_pool; flushing exceeds 4 MiB and drops it.
1273 for i in 0..5u64 {
1274 let t = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
1275 cache.insert(i, t, NodeId(i as usize), 0);
1276 }
1277 cache.flush_pending_pool();
1278 let after_overflow = cache.vram_drops();
1279 assert!(after_overflow >= 1, "expected vram_drops >= 1 after overflow, got {after_overflow}");
1280
1281 // Lowering budget below live bytes evicts & drops entries monotonically.
1282 cache.set_budget_mb(1);
1283 assert!(cache.vram_drops() > after_overflow);
1284
1285 // Busting with 0 budget drops all remaining entries.
1286 let before_bust = cache.vram_drops();
1287 cache.set_budget_mb(0);
1288 cache.bust_all();
1289 assert!(cache.vram_drops() > before_bust);
1290 }
1238}1291}
crates/engine/src/eval/dispatch.rs+132-35
...@@ -36,6 +36,8 @@ pub struct PendingReadback {...@@ -36,6 +36,8 @@ pub struct PendingReadback {
36 #[cfg(not(target_arch = "wasm32"))]36 #[cfg(not(target_arch = "wasm32"))]
37 buf: wgpu::Buffer,37 buf: wgpu::Buffer,
38 #[cfg(not(target_arch = "wasm32"))]38 #[cfg(not(target_arch = "wasm32"))]
39 submission_index: wgpu::SubmissionIndex,
40 #[cfg(not(target_arch = "wasm32"))]
39 rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,41 rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
40 #[cfg(not(target_arch = "wasm32"))]42 #[cfg(not(target_arch = "wasm32"))]
41 width: u32,43 width: u32,
...@@ -60,15 +62,18 @@ impl PendingReadback {...@@ -60,15 +62,18 @@ impl PendingReadback {
60 }62 }
61 #[cfg(not(target_arch = "wasm32"))]63 #[cfg(not(target_arch = "wasm32"))]
62 {64 {
65 // Poll non-blockingly first so already-completed readbacks fire immediately.
66 let _ = engine.device.poll(wgpu::PollType::Poll);
63 let map_res = match self.rx.try_recv() {67 let map_res = match self.rx.try_recv() {
64 Ok(res) => res,68 Ok(res) => res,
65 Err(_) => {69 Err(std::sync::mpsc::TryRecvError::Empty) => {
66 engine.device.poll(wgpu::PollType::Wait {70 engine.device.poll(wgpu::PollType::Wait {
67 submission_index: None,71 submission_index: Some(self.submission_index),
68 timeout: Some(std::time::Duration::from_secs(10)),72 timeout: Some(std::time::Duration::from_secs(10)),
69 })?;73 })?;
70 self.rx.recv()?74 self.rx.recv()?
71 }75 }
76 Err(err @ std::sync::mpsc::TryRecvError::Disconnected) => return Err(err.into()),
72 };77 };
73 map_res?;78 map_res?;
74 let slice = self.buf.slice(..self.required_bytes);79 let slice = self.buf.slice(..self.required_bytes);
...@@ -98,6 +103,16 @@ impl Engine {...@@ -98,6 +103,16 @@ impl Engine {
98 self.pipelines.borrow_mut().prewarm_core(&self.device);103 self.pipelines.borrow_mut().prewarm_core(&self.device);
99 }104 }
100105
106 /// Pre-compiles core WGSL shader modules and compute pipelines for `Int8` (viewer/readback)
107 /// and `depth` when `hiq` is active (e.g. `BitDepth::Float16` for EXR/HiQ comps).
108 pub fn prewarm_for_depth(&self, depth: BitDepth) {
109 self.pipelines.borrow_mut().prewarm_core(&self.device);
110 let eff = self.effective_depth(depth);
111 if eff != BitDepth::Int8 {
112 self.pipelines_for(eff).borrow_mut().prewarm_core(&self.device);
113 }
114 }
115
101 pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture {116 pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture {
102 self.alloc_tex_dod(size, [0, 0], size, depth, content_hash)117 self.alloc_tex_dod(size, [0, 0], size, depth, content_hash)
103 }118 }
...@@ -239,7 +254,7 @@ impl Engine {...@@ -239,7 +254,7 @@ impl Engine {
239 ];254 ];
240 params.p[1] = display.uv_rect;255 params.p[1] = display.uv_rect;
241 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];256 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];
242 self.dispatch_to_view(257 self.dispatch_to_view_uncached(
243 &mut encoder,258 &mut encoder,
244 ShaderOp::DisplayBlit,259 ShaderOp::DisplayBlit,
245 &src.view,260 &src.view,
...@@ -250,6 +265,7 @@ impl Engine {...@@ -250,6 +265,7 @@ impl Engine {
250 &params,265 &params,
251 );266 );
252 self.queue.submit(Some(encoder.finish()));267 self.queue.submit(Some(encoder.finish()));
268 self.reset_uniform_cursors();
253269
254 EvalStats {270 EvalStats {
255 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,271 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,
...@@ -276,30 +292,31 @@ impl Engine {...@@ -276,30 +292,31 @@ impl Engine {
276 }292 }
277 #[cfg(not(target_arch = "wasm32"))]293 #[cfg(not(target_arch = "wasm32"))]
278 {294 {
279 let [w, h] = tex.size;295 let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm;
296 let converted = if needs_conv {
297 let mut reg = self.pipelines.borrow_mut();
298 Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size))
299 } else {
300 None
301 };
302 let src_tex = converted.as_ref().unwrap_or(tex);
303 let [w, h] = src_tex.size;
280 let bpp = 4u32;304 let bpp = 4u32;
281 let unpadded_bpr = w * bpp;305 let unpadded_bpr = w * bpp;
282 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;306 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
283 let padded_bpr = unpadded_bpr.div_ceil(align) * align;307 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
284 let required_bytes = u64::from(padded_bpr) * u64::from(h);308 let required_bytes = u64::from(padded_bpr) * u64::from(h);
285 let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm;309 let buf = self
286310 .pipelines
287 let (buf, converted) = {311 .borrow_mut()
288 let mut reg = self.pipelines.borrow_mut();312 .readback_pool
289 let buf = reg.readback_pool.acquire_buffer(&self.device, required_bytes);313 .acquire_buffer(&self.device, required_bytes);
290 let conv = if needs_conv {
291 Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size))
292 } else {
293 None
294 };
295 (buf, conv)
296 };
297314
298 let mut enc = self.device.create_command_encoder(&Default::default());315 let mut enc = self.device.create_command_encoder(&Default::default());
299 let src_tex = if let Some(conv) = converted.as_ref() {316 if let Some(conv) = converted.as_ref() {
300 let mut params = UniformParams::default();317 let mut params = UniformParams::default();
301 params.p[0] = [1.0, 1.0, 0.0, 0.0];318 params.p[0] = [1.0, 1.0, 0.0, 0.0];
302 self.dispatch_to_view(319 self.dispatch_to_view_uncached(
303 &mut enc,320 &mut enc,
304 ShaderOp::DisplayBlit,321 ShaderOp::DisplayBlit,
305 &tex.view,322 &tex.view,
...@@ -309,10 +326,7 @@ impl Engine {...@@ -309,10 +326,7 @@ impl Engine {
309 conv.size,326 conv.size,
310 &params,327 &params,
311 );328 );
312 conv329 }
313 } else {
314 tex
315 };
316 enc.copy_texture_to_buffer(330 enc.copy_texture_to_buffer(
317 src_tex.texture.as_image_copy(),331 src_tex.texture.as_image_copy(),
318 wgpu::TexelCopyBufferInfo {332 wgpu::TexelCopyBufferInfo {
...@@ -325,7 +339,8 @@ impl Engine {...@@ -325,7 +339,8 @@ impl Engine {
325 },339 },
326 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },340 wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
327 );341 );
328 self.queue.submit(Some(enc.finish()));342 let submission_index = self.queue.submit(Some(enc.finish()));
343 self.reset_uniform_cursors();
329344
330 let slice = buf.slice(..required_bytes);345 let slice = buf.slice(..required_bytes);
331 let (tx, rx) = std::sync::mpsc::channel();346 let (tx, rx) = std::sync::mpsc::channel();
...@@ -334,6 +349,7 @@ impl Engine {...@@ -334,6 +349,7 @@ impl Engine {
334 });349 });
335 Ok(PendingReadback {350 Ok(PendingReadback {
336 buf,351 buf,
352 submission_index,
337 rx,353 rx,
338 width: w,354 width: w,
339 height: h,355 height: h,
...@@ -363,23 +379,40 @@ impl Engine {...@@ -363,23 +379,40 @@ impl Engine {
363 dst_view: &wgpu::TextureView,379 dst_view: &wgpu::TextureView,
364 dst_size: [u32; 2],380 dst_size: [u32; 2],
365 params: &UniformParams,381 params: &UniformParams,
382 cache_bg: bool,
366 ) {383 ) {
367 let (dynamic_offset, bg_hash, bg_idx) = {384 let (dynamic_offset, uncached_bg, cached_key) = {
368 let mut reg = reg_cell.borrow_mut();385 let mut reg = reg_cell.borrow_mut();
369 reg.ensure_pipeline(&self.device, op);386 reg.ensure_pipeline(&self.device, op);
370 let (chunk_idx, dynamic_offset) = reg.alloc_uniform_slot(&self.device, &self.queue, params);387 let (chunk_idx, dynamic_offset) = reg.alloc_uniform_slot(&self.device, &self.queue, params);
371 let (bg_hash, bg_idx) = reg.ensure_bind_group(388 if cache_bg {
372 &self.device,389 let (bg_hash, bg_idx) = reg.ensure_bind_group(
373 src_a,390 &self.device,
374 src_b,391 src_a,
375 mask,392 src_b,
376 dst_view,393 mask,
377 chunk_idx,394 dst_view,
378 );395 chunk_idx,
379 (dynamic_offset, bg_hash, bg_idx)396 );
397 (dynamic_offset, None, Some((bg_hash, bg_idx)))
398 } else {
399 let bg = reg.create_bind_group(
400 &self.device,
401 src_a,
402 src_b,
403 mask,
404 dst_view,
405 chunk_idx,
406 );
407 (dynamic_offset, Some(bg), None)
408 }
380 };409 };
381 let reg = reg_cell.borrow();410 let reg = reg_cell.borrow();
382 let bg = reg.get_bind_group(bg_hash, bg_idx);411 let bg = match (&uncached_bg, cached_key) {
412 (Some(bg), _) => bg,
413 (None, Some((bg_hash, bg_idx))) => reg.get_bind_group(bg_hash, bg_idx),
414 (None, None) => unreachable!(),
415 };
383416
384 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {417 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
385 label: Some("comp-op"),418 label: Some("comp-op"),
...@@ -412,11 +445,14 @@ impl Engine {...@@ -412,11 +445,14 @@ impl Engine {
412 &dst.view,445 &dst.view,
413 dst.size,446 dst.size,
414 params,447 params,
448 true,
415 );449 );
416 }450 }
417451
452 /// Dispatches a compute shader into an ephemeral `TextureView` (e.g. viewer surface or
453 /// one-shot readback conversion) without inserting into `bg_cache`.
418 #[allow(clippy::too_many_arguments)]454 #[allow(clippy::too_many_arguments)]
419 pub(super) fn dispatch_to_view(455 pub(super) fn dispatch_to_view_uncached(
420 &self,456 &self,
421 enc: &mut wgpu::CommandEncoder,457 enc: &mut wgpu::CommandEncoder,
422 op: ShaderOp,458 op: ShaderOp,
...@@ -437,6 +473,7 @@ impl Engine {...@@ -437,6 +473,7 @@ impl Engine {
437 dst_view,473 dst_view,
438 dst_size,474 dst_size,
439 params,475 params,
476 false,
440 );477 );
441 }478 }
442}479}
...@@ -719,4 +756,64 @@ mod tests {...@@ -719,4 +756,64 @@ mod tests {
719 eng.pipelines.borrow_mut().clear_bind_group_cache();756 eng.pipelines.borrow_mut().clear_bind_group_cache();
720 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);757 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);
721 }758 }
759
760 #[test]
761 fn pending_readback_tracks_submission_index_and_bypasses_bg_cache() {
762 let Ok(eng) = Engine::new_headless() else {
763 return;
764 };
765 let fill = |tex: &CachedTexture, rgba: [f32; 4]| {
766 let mut enc = eng.device.create_command_encoder(&Default::default());
767 let mut u = UniformParams::default();
768 u.p[0] = rgba;
769 u.p[1] = rgba;
770 u.p[2] = rgba;
771 u.p[3] = rgba;
772 eng.dispatch_op(
773 &mut enc,
774 ShaderOp::Bg,
775 &eng.dummy.view,
776 &eng.dummy.view,
777 &eng.dummy.view,
778 tex,
779 &u,
780 );
781 eng.queue.submit(Some(enc.finish()));
782 eng.reset_uniform_cursors();
783 };
784
785 let f16_a = eng.alloc_tex([16, 16], BitDepth::Float16, 0);
786 let f16_b = eng.alloc_tex([16, 16], BitDepth::Float16, 0);
787 fill(&f16_a, [0.2, 0.4, 0.8, 1.0]);
788 fill(&f16_b, [0.9, 0.1, 0.5, 1.0]);
789
790 eng.pipelines.borrow_mut().clear_bind_group_cache();
791 let misses_before = eng.pipelines.borrow().bg_misses;
792
793 // Overlapping double-buffered readbacks: finish out of order (b then a) via SubmissionIndex.
794 let pend_a = eng.begin_readback_rgba(&f16_a).expect("begin a");
795 let pend_b = eng.begin_readback_rgba(&f16_b).expect("begin b");
796 assert_ne!(
797 format!("{:?}", pend_a.submission_index),
798 format!("{:?}", pend_b.submission_index)
799 );
800 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);
801 assert_eq!(eng.pipelines.borrow().bg_misses, misses_before);
802
803 let px_b = pend_b.finish(&eng).expect("finish b");
804 let px_a = pend_a.finish(&eng).expect("finish a");
805 assert!((px_a[0] as i32 - 51).abs() <= 2);
806 assert!((px_b[0] as i32 - 230).abs() <= 2);
807
808 // render_ram_frame_into_viewer must also bypass bg_cache and reset uniform cursors.
809 let dst = eng.alloc_tex([16, 16], BitDepth::Int8, 0);
810 let ram_frame = crate::ram_cache::RamFrame {
811 size: [16, 16],
812 rgba: std::sync::Arc::new(vec![128u8; 16 * 16 * 4]),
813 eval_ms: 0.0,
814 };
815 let _ = eng.render_ram_frame_into_viewer(&ram_frame, &dst.texture, DisplaySettings::default());
816 assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0);
817 assert_eq!(eng.pipelines.borrow().bg_misses, misses_before);
818 }
722}819}
crates/engine/src/eval/mod.rs+128-10
...@@ -4,7 +4,7 @@...@@ -4,7 +4,7 @@
4use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache};4use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache};
5use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};5use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};
6use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port};6use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port};
7use std::cell::{OnceCell, RefCell};7use std::cell::{Cell, OnceCell, RefCell};
8use std::collections::{HashMap, HashSet};8use std::collections::{HashMap, HashSet};
9use std::collections::hash_map::DefaultHasher;9use std::collections::hash_map::DefaultHasher;
10use std::hash::{Hash, Hasher};10use std::hash::{Hash, Hasher};
...@@ -76,9 +76,12 @@ pub struct Engine {...@@ -76,9 +76,12 @@ pub struct Engine {
76 ram_upload_tex: RefCell<Option<CachedTexture>>,76 ram_upload_tex: RefCell<Option<CachedTexture>>,
77 dummy: CachedTexture,77 dummy: CachedTexture,
78 vram_budget_bytes: u64,78 vram_budget_bytes: u64,
79 last_bg_vram_drops: Cell<u64>,
79 pub cache: NodeCache,80 pub cache: NodeCache,
80 pub media: MediaCache,81 pub media: MediaCache,
81 pub expr: ExprEngine,82 pub expr: ExprEngine,
83 /// Active evaluation target node (set during `evaluate` / `render_into_viewer`).
84 pub(super) frame_eval_target: Option<NodeId>,
82 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.85 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.
83 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,86 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,
84 /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision.87 /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision.
...@@ -135,9 +138,11 @@ impl Engine {...@@ -135,9 +138,11 @@ impl Engine {
135 ram_upload_tex: RefCell::new(None),138 ram_upload_tex: RefCell::new(None),
136 dummy,139 dummy,
137 vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024),140 vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024),
141 last_bg_vram_drops: Cell::new(0),
138 cache: NodeCache::new(default_vram_mb),142 cache: NodeCache::new(default_vram_mb),
139 media: MediaCache::new(512),143 media: MediaCache::default(),
140 expr: ExprEngine::new(),144 expr: ExprEngine::new(),
145 frame_eval_target: None,
141 frame_memo: HashMap::new(),146 frame_memo: HashMap::new(),
142 frame_consumers: Vec::new(),147 frame_consumers: Vec::new(),
143 frame_consumers_rev: None,148 frame_consumers_rev: None,
...@@ -240,16 +245,36 @@ impl Engine {...@@ -240,16 +245,36 @@ impl Engine {
240 self.media.set_budget_mb(budget_mb);245 self.media.set_budget_mb(budget_mb);
241 }246 }
242247
243 fn clear_bind_group_caches(&self) {248 fn for_each_registry(&self, mut f: impl FnMut(&mut ShaderRegistry)) {
244 self.pipelines.borrow_mut().clear_bind_group_cache();249 f(&mut self.pipelines.borrow_mut());
245 if let Some(r) = self.pipelines_int16.get() {250 if let Some(r) = self.pipelines_int16.get() {
246 r.borrow_mut().clear_bind_group_cache();251 f(&mut r.borrow_mut());
247 }252 }
248 if let Some(r) = self.pipelines_f16.get() {253 if let Some(r) = self.pipelines_f16.get() {
249 r.borrow_mut().clear_bind_group_cache();254 f(&mut r.borrow_mut());
250 }255 }
251 if let Some(r) = self.pipelines_f32.get() {256 if let Some(r) = self.pipelines_f32.get() {
252 r.borrow_mut().clear_bind_group_cache();257 f(&mut r.borrow_mut());
258 }
259 }
260
261 fn clear_bind_group_caches(&self) {
262 self.for_each_registry(|r| r.clear_bind_group_cache());
263 self.last_bg_vram_drops.set(self.cache.vram_drops());
264 }
265
266 pub(super) fn reset_uniform_cursors(&self) {
267 self.for_each_registry(|r| r.reset_uniform_cursor());
268 }
269
270 fn trim_uniform_chunks(&self) {
271 self.for_each_registry(|r| r.trim_uniform_chunks(2));
272 }
273
274 pub(super) fn sync_bg_cache_with_vram_drops(&self) {
275 let drops = self.cache.vram_drops();
276 if drops != self.last_bg_vram_drops.get() {
277 self.clear_bind_group_caches();
253 }278 }
254 }279 }
255280
...@@ -258,6 +283,9 @@ impl Engine {...@@ -258,6 +283,9 @@ impl Engine {
258 self.sync_node_cache_budget();283 self.sync_node_cache_budget();
259 self.cache.bust_all();284 self.cache.bust_all();
260 self.clear_bind_group_caches();285 self.clear_bind_group_caches();
286 self.trim_uniform_chunks();
287 #[cfg(not(target_arch = "wasm32"))]
288 self.pipelines.borrow_mut().readback_pool.clear();
261 self.media.clear();289 self.media.clear();
262 self.particles.clear();290 self.particles.clear();
263 self.sprite_cache.clear();291 self.sprite_cache.clear();
...@@ -273,6 +301,9 @@ impl Engine {...@@ -273,6 +301,9 @@ impl Engine {
273 self.sync_node_cache_budget();301 self.sync_node_cache_budget();
274 self.cache.bust_all();302 self.cache.bust_all();
275 self.clear_bind_group_caches();303 self.clear_bind_group_caches();
304 self.trim_uniform_chunks();
305 #[cfg(not(target_arch = "wasm32"))]
306 self.pipelines.borrow_mut().readback_pool.clear();
276 self.sprite_cache.clear();307 self.sprite_cache.clear();
277 self.scene3d.clear_shadow_targets();308 self.scene3d.clear_shadow_targets();
278 *self.ram_upload_tex.borrow_mut() = None;309 *self.ram_upload_tex.borrow_mut() = None;
...@@ -281,18 +312,21 @@ impl Engine {...@@ -281,18 +312,21 @@ impl Engine {
281 pub fn bust_frame(&mut self, frame: i64) -> usize {312 pub fn bust_frame(&mut self, frame: i64) -> usize {
282 self.output_cache.clear();313 self.output_cache.clear();
283 self.sync_node_cache_budget();314 self.sync_node_cache_budget();
315 let busted = self.cache.bust_frame(frame);
284 self.clear_bind_group_caches();316 self.clear_bind_group_caches();
285 self.cache.bust_frame(frame)317 busted
286 }318 }
287319
288 pub fn bust_subtree(&mut self, node: NodeId) -> usize {320 pub fn bust_subtree(&mut self, node: NodeId) -> usize {
289 self.output_cache.clear();321 self.output_cache.clear();
290 self.sync_node_cache_budget();322 self.sync_node_cache_budget();
323 let busted = self.cache.bust_subtree(node);
291 self.clear_bind_group_caches();324 self.clear_bind_group_caches();
292 self.cache.bust_subtree(node)325 busted
293 }326 }
294327
295 fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> {328 fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> {
329 self.frame_eval_target = None;
296 self.frame_memo.clear();330 self.frame_memo.clear();
297 self.frame_roi_memo.clear();331 self.frame_roi_memo.clear();
298 if self.frame_consumers_rev != Some(comp.revision)332 if self.frame_consumers_rev != Some(comp.revision)
...@@ -307,6 +341,7 @@ impl Engine {...@@ -307,6 +341,7 @@ impl Engine {
307 }341 }
308342
309 fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) {343 fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) {
344 self.frame_eval_target = None;
310 self.frame_memo.clear();345 self.frame_memo.clear();
311 self.frame_roi_memo.clear();346 self.frame_roi_memo.clear();
312 visiting.clear();347 visiting.clear();
...@@ -321,6 +356,7 @@ impl Engine {...@@ -321,6 +356,7 @@ impl Engine {
321 time: f64,356 time: f64,
322 ) -> (CachedTexture, EvalStats) {357 ) -> (CachedTexture, EvalStats) {
323 let t0 = Instant::now();358 let t0 = Instant::now();
359 self.sync_bg_cache_with_vram_drops();
324 let out_key = self.output_cache_key(comp, target, time);360 let out_key = self.output_cache_key(comp, target, time);
325 if let Some((tex, unsupported)) = self.output_cache_get(out_key) {361 if let Some((tex, unsupported)) = self.output_cache_get(out_key) {
326 let stats = EvalStats {362 let stats = EvalStats {
...@@ -339,6 +375,7 @@ impl Engine {...@@ -339,6 +375,7 @@ impl Engine {
339 self.media375 self.media
340 .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips);376 .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips);
341 let mut visiting = self.prepare_frame_scratch(comp);377 let mut visiting = self.prepare_frame_scratch(comp);
378 self.frame_eval_target = Some(target);
342 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {379 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
343 label: Some("comp-eval"),380 label: Some("comp-eval"),
344 });381 });
...@@ -349,11 +386,13 @@ impl Engine {...@@ -349,11 +386,13 @@ impl Engine {
349 tex = self.crop_to_canvas(&mut encoder, tex);386 tex = self.crop_to_canvas(&mut encoder, tex);
350 }387 }
351 self.queue.submit(Some(encoder.finish()));388 self.queue.submit(Some(encoder.finish()));
389 self.reset_uniform_cursors();
352 #[cfg(not(target_arch = "wasm32"))]390 #[cfg(not(target_arch = "wasm32"))]
353 self.media.flush_upload_staging_after_submit(&self.device);391 self.media.flush_upload_staging_after_submit(&self.device);
354 self.finish_frame_scratch(visiting);392 self.finish_frame_scratch(visiting);
355 self.cache.flush_pending_pool();393 self.cache.flush_pending_pool();
356 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());394 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());
395 self.sync_bg_cache_with_vram_drops();
357 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;396 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
358 stats.cached_entries = self.cache.entry_count();397 stats.cached_entries = self.cache.entry_count();
359 stats.cached_vram_mb = self.vram_mb();398 stats.cached_vram_mb = self.vram_mb();
...@@ -372,6 +411,7 @@ impl Engine {...@@ -372,6 +411,7 @@ impl Engine {
372 display: DisplaySettings,411 display: DisplaySettings,
373 ) -> EvalStats {412 ) -> EvalStats {
374 let t0 = Instant::now();413 let t0 = Instant::now();
414 self.sync_bg_cache_with_vram_drops();
375 let out_key = self.output_cache_key(comp, target, time);415 let out_key = self.output_cache_key(comp, target, time);
376 let mut stats = EvalStats::default();416 let mut stats = EvalStats::default();
377 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {417 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
...@@ -386,6 +426,7 @@ impl Engine {...@@ -386,6 +426,7 @@ impl Engine {
386 self.media426 self.media
387 .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips);427 .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips);
388 let mut visiting = self.prepare_frame_scratch(comp);428 let mut visiting = self.prepare_frame_scratch(comp);
429 self.frame_eval_target = Some(target);
389 let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);430 let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);
390 (t, Some(visiting))431 (t, Some(visiting))
391 };432 };
...@@ -409,7 +450,7 @@ impl Engine {...@@ -409,7 +450,7 @@ impl Engine {
409 tex.canvas_size[1] as f32,450 tex.canvas_size[1] as f32,
410 ];451 ];
411 }452 }
412 self.dispatch_to_view(453 self.dispatch_to_view_uncached(
413 &mut encoder,454 &mut encoder,
414 ShaderOp::DisplayBlit,455 ShaderOp::DisplayBlit,
415 &tex.view,456 &tex.view,
...@@ -421,6 +462,7 @@ impl Engine {...@@ -421,6 +462,7 @@ impl Engine {
421 );462 );
422463
423 self.queue.submit(Some(encoder.finish()));464 self.queue.submit(Some(encoder.finish()));
465 self.reset_uniform_cursors();
424 #[cfg(not(target_arch = "wasm32"))]466 #[cfg(not(target_arch = "wasm32"))]
425 self.media.flush_upload_staging_after_submit(&self.device);467 self.media.flush_upload_staging_after_submit(&self.device);
426 if let Some(visiting) = visiting_opt {468 if let Some(visiting) = visiting_opt {
...@@ -428,6 +470,7 @@ impl Engine {...@@ -428,6 +470,7 @@ impl Engine {
428 self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone());470 self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone());
429 }471 }
430 self.cache.flush_pending_pool();472 self.cache.flush_pending_pool();
473 self.sync_bg_cache_with_vram_drops();
431474
432 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;475 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
433 stats.cached_entries = self.cache.entry_count();476 stats.cached_entries = self.cache.entry_count();
...@@ -1472,4 +1515,79 @@ Composition {...@@ -1472,4 +1515,79 @@ Composition {
1472 assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground"));1515 assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground"));
1473 assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground"));1516 assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground"));
1474 }1517 }
1518
1519 #[test]
1520 fn vram_drops_clear_bind_groups_and_viewer_blit_bypasses_bg_cache() {
1521 let Ok(mut eng) = Engine::new_headless() else {
1522 return;
1523 };
1524 // Default Engine::new wires RAM-scaled MediaCache::default().
1525 assert!(crate::media::default_media_cache_budget_mb() >= 512);
1526
1527 // Tight 8 MiB VRAM budget: 1024x1024 RGBA8 = 4 MiB per texture.
1528 eng.set_vram_budget_mb(8);
1529
1530 let src = r#"
1531Composition {
1532 CurrentTime = 0,
1533 RenderRange = { 0, 10 },
1534 GlobalRange = { 0, 10 },
1535 Tools = ordered() {
1536 AnimRed = BezierSpline {
1537 KeyFrames = {
1538 [0] = { 0.1 },
1539 [10] = { 0.9 },
1540 },
1541 },
1542 BG = Background {
1543 Inputs = {
1544 Width = Input { Value = 1024, },
1545 Height = Input { Value = 1024, },
1546 TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", },
1547 TopLeftAlpha = Input { Value = 1.0, },
1548 },
1549 },
1550 BC = BrightnessContrast {
1551 Inputs = {
1552 Input = Input { SourceOp = "BG", Source = "Output", },
1553 Gain = Input { Value = 1.2, },
1554 },
1555 },
1556 },
1557}
1558"#;
1559 let comp = Comp::from_fusion_str(src).expect("parse vram bg test comp");
1560 let bc = comp.find_node("BC").unwrap();
1561
1562 // Evaluate frame 0 -> uniform_cursor resets to 0 after submit, bg_cache populated.
1563 let _ = eng.evaluate(&comp, bc, 0.0);
1564 assert!(eng.frame_eval_target.is_none());
1565 assert_eq!(eng.pipelines.borrow().uniform_chunks.len(), 1);
1566 // Next uniform slot allocated must start at chunk 0, offset 0 (cursor was reset post-submit).
1567 {
1568 let mut reg = eng.pipelines.borrow_mut();
1569 let slot = reg.alloc_uniform_slot(&eng.device, &eng.queue, &UniformParams::default());
1570 assert_eq!(slot, (0, 0));
1571 reg.reset_uniform_cursor();
1572 }
1573 assert!(eng.pipelines.borrow().bg_entry_count() > 0);
1574
1575 // Render into ephemeral viewer textures on frame 0 (output_cache hit): must not grow bg_cache!
1576 let bg_before_viewer = eng.pipelines.borrow().bg_entry_count();
1577 let misses_before_viewer = eng.pipelines.borrow().bg_misses;
1578 let viewer_tex_a = create_texture(&eng.device, [512, 512], 0);
1579 let viewer_tex_b = create_texture(&eng.device, [640, 360], 0);
1580 let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_a.texture, DisplaySettings::default());
1581 let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_b.texture, DisplaySettings::default());
1582 assert_eq!(eng.pipelines.borrow().bg_entry_count(), bg_before_viewer);
1583 assert_eq!(eng.pipelines.borrow().bg_misses, misses_before_viewer);
1584
1585 // Evaluate frames 1..=3 under 8 MiB budget -> organic eviction increments vram_drops
1586 // and sync_bg_cache_with_vram_drops clears bg_cache so evicted textures aren't pinned.
1587 for f in 1..=3 {
1588 let _ = eng.evaluate(&comp, bc, f as f64);
1589 }
1590 assert!(eng.cache.vram_drops() > 0);
1591 assert_eq!(eng.last_bg_vram_drops.get(), eng.cache.vram_drops());
1592 }
1475}1593}
crates/engine/src/eval/registry.rs+90-29
...@@ -238,7 +238,6 @@ impl ShaderOp {...@@ -238,7 +238,6 @@ impl ShaderOp {
238238
239const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl");239const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl");
240const UNIFORM_SLOTS_PER_CHUNK: u32 = 1024;240const UNIFORM_SLOTS_PER_CHUNK: u32 = 1024;
241const MAX_UNIFORM_CHUNKS: usize = 16;
242const LUT_CACHE_CAPACITY: usize = 64;241const LUT_CACHE_CAPACITY: usize = 64;
243#[cfg(not(target_arch = "wasm32"))]242#[cfg(not(target_arch = "wasm32"))]
244const MAX_READBACK_BUFFERS: usize = 3;243const MAX_READBACK_BUFFERS: usize = 3;
...@@ -401,7 +400,6 @@ impl ReadbackPool {...@@ -401,7 +400,6 @@ impl ReadbackPool {
401 tex400 tex
402 }401 }
403402
404 #[allow(dead_code)]
405 pub(super) fn clear(&mut self) {403 pub(super) fn clear(&mut self) {
406 self.buffers.clear();404 self.buffers.clear();
407 self.conv_tex = None;405 self.conv_tex = None;
...@@ -548,9 +546,8 @@ impl ShaderRegistry {...@@ -548,9 +546,8 @@ impl ShaderRegistry {
548 /// Writes `params` into the next aligned slot in the chunked dynamic uniform ring546 /// Writes `params` into the next aligned slot in the chunked dynamic uniform ring
549 /// and returns `(chunk_index, dynamic_byte_offset)`.547 /// and returns `(chunk_index, dynamic_byte_offset)`.
550 ///548 ///
551 /// Lazily allocates 1,024-slot chunks up to `MAX_UNIFORM_CHUNKS` (16,384 slots) so a549 /// Lazily allocates 1,024-slot chunks without wrapping mid-encoder; callers reset the
552 /// single unsubmitted `CommandEncoder` never overwrites earlier slots while long550 /// cursor back to `0` after each `queue.submit` so normal frames stay in chunk `0`.
553 /// multi-frame playback stays memory-bounded.
554 pub(super) fn alloc_uniform_slot(551 pub(super) fn alloc_uniform_slot(
555 &mut self,552 &mut self,
556 device: &wgpu::Device,553 device: &wgpu::Device,
...@@ -560,7 +557,7 @@ impl ShaderRegistry {...@@ -560,7 +557,7 @@ impl ShaderRegistry {
560 let slot_global = self.uniform_cursor;557 let slot_global = self.uniform_cursor;
561 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;558 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;
562 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;559 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;
563 if chunk_idx >= self.uniform_chunks.len() {560 while chunk_idx >= self.uniform_chunks.len() {
564 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);561 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
565 let buf = device.create_buffer(&wgpu::BufferDescriptor {562 let buf = device.create_buffer(&wgpu::BufferDescriptor {
566 label: Some("op-params-ring"),563 label: Some("op-params-ring"),
...@@ -576,12 +573,21 @@ impl ShaderRegistry {...@@ -576,12 +573,21 @@ impl ShaderRegistry {
576 u64::from(offset),573 u64::from(offset),
577 bytemuck::bytes_of(params),574 bytemuck::bytes_of(params),
578 );575 );
579 let next = slot_global + 1;576 self.uniform_cursor = slot_global + 1;
580 let max_slots = (MAX_UNIFORM_CHUNKS as u32) * UNIFORM_SLOTS_PER_CHUNK;
581 self.uniform_cursor = if next >= max_slots { 0 } else { next };
582 (chunk_idx, offset)577 (chunk_idx, offset)
583 }578 }
584579
580 pub(super) fn reset_uniform_cursor(&mut self) {
581 self.uniform_cursor = 0;
582 }
583
584 pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
585 self.uniform_cursor = 0;
586 if self.uniform_chunks.len() > max_chunks {
587 self.uniform_chunks.truncate(max_chunks);
588 }
589 }
590
585 /// Returns a cached tiny LUT/curve texture for `(size, format, bytes)` or uploads and591 /// Returns a cached tiny LUT/curve texture for `(size, format, bytes)` or uploads and
586 /// inserts one into the bounded 64-entry LRU cache.592 /// inserts one into the bounded 64-entry LRU cache.
587 #[allow(clippy::too_many_arguments)]593 #[allow(clippy::too_many_arguments)]
...@@ -657,6 +663,38 @@ impl ShaderRegistry {...@@ -657,6 +663,38 @@ impl ShaderRegistry {
657 tex663 tex
658 }664 }
659665
666 /// Builds a `wgpu::BindGroup` for the four `TextureView` bindings and uniform `chunk_idx`
667 /// without inserting into `bg_cache` (used for ephemeral viewer/readback targets).
668 pub(super) fn create_bind_group(
669 &self,
670 device: &wgpu::Device,
671 src_a: &wgpu::TextureView,
672 src_b: &wgpu::TextureView,
673 mask: &wgpu::TextureView,
674 dst_view: &wgpu::TextureView,
675 chunk_idx: usize,
676 ) -> wgpu::BindGroup {
677 device.create_bind_group(&wgpu::BindGroupDescriptor {
678 label: Some("op-bg"),
679 layout: &self.bgl,
680 entries: &[
681 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
682 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
683 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
684 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) },
685 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
686 wgpu::BindGroupEntry {
687 binding: 5,
688 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
689 buffer: &self.uniform_chunks[chunk_idx],
690 offset: 0,
691 size: NonZeroU64::new(std::mem::size_of::<super::dispatch::UniformParams>() as u64),
692 }),
693 },
694 ],
695 })
696 }
697
660 /// Looks up or creates a cached `wgpu::BindGroup` keyed by the four `TextureView`698 /// Looks up or creates a cached `wgpu::BindGroup` keyed by the four `TextureView`
661 /// handles and dynamic-uniform `chunk_idx`. Holding cloned `TextureView` handles inside699 /// handles and dynamic-uniform `chunk_idx`. Holding cloned `TextureView` handles inside
662 /// cached entries keeps their underlying resources alive while cached, preventing ABA reuse.700 /// cached entries keeps their underlying resources alive while cached, preventing ABA reuse.
...@@ -712,25 +750,7 @@ impl ShaderRegistry {...@@ -712,25 +750,7 @@ impl ShaderRegistry {
712 }750 }
713 }751 }
714752
715 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {753 let bg = self.create_bind_group(device, src_a, src_b, mask, dst_view, chunk_idx);
716 label: Some("op-bg"),
717 layout: &self.bgl,
718 entries: &[
719 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) },
720 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) },
721 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) },
722 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) },
723 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) },
724 wgpu::BindGroupEntry {
725 binding: 5,
726 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
727 buffer: &self.uniform_chunks[chunk_idx],
728 offset: 0,
729 size: NonZeroU64::new(std::mem::size_of::<super::dispatch::UniformParams>() as u64),
730 }),
731 },
732 ],
733 });
734754
735 let bucket = self.bg_cache.entry(hash).or_default();755 let bucket = self.bg_cache.entry(hash).or_default();
736 let idx = bucket.len();756 let idx = bucket.len();
...@@ -753,7 +773,6 @@ impl ShaderRegistry {...@@ -753,7 +773,6 @@ impl ShaderRegistry {
753 &self.bg_cache[&hash][idx].bg773 &self.bg_cache[&hash][idx].bg
754 }774 }
755775
756 #[allow(dead_code)]
757 pub(super) fn clear_bind_group_cache(&mut self) {776 pub(super) fn clear_bind_group_cache(&mut self) {
758 self.bg_cache.clear();777 self.bg_cache.clear();
759 self.bg_count = 0;778 self.bg_count = 0;
...@@ -918,4 +937,46 @@ mod tests {...@@ -918,4 +937,46 @@ mod tests {
918 }937 }
919 let _ = prewarm_ms;938 let _ = prewarm_ms;
920 }939 }
940
941 #[test]
942 fn uniform_ring_grows_past_16_chunks_without_wrapping_and_resets() {
943 let Ok(eng) = Engine::new_headless() else {
944 return;
945 };
946 let params = super::super::dispatch::UniformParams::default();
947 let mut reg = eng.pipelines.borrow_mut();
948
949 let total = 16 * UNIFORM_SLOTS_PER_CHUNK + 5;
950 let mut last = (0usize, 0u32);
951 for _ in 0..total {
952 last = reg.alloc_uniform_slot(&eng.device, &eng.queue, &params);
953 }
954 assert_eq!(last.0, 16, "cursor must grow to chunk 16 instead of wrapping to 0");
955 assert_eq!(last.1, 4 * reg.uniform_stride);
956 assert_eq!(reg.uniform_chunks.len(), 17);
957
958 reg.reset_uniform_cursor();
959 let after_reset = reg.alloc_uniform_slot(&eng.device, &eng.queue, &params);
960 assert_eq!(after_reset, (0, 0));
961
962 reg.trim_uniform_chunks(2);
963 assert_eq!(reg.uniform_chunks.len(), 2);
964 assert_eq!(reg.uniform_cursor, 0);
965 }
966
967 #[test]
968 fn prewarm_for_depth_warms_float16_in_hiq_only() {
969 let Ok(mut eng) = Engine::new_headless() else {
970 return;
971 };
972 eng.hiq = false;
973 eng.prewarm_for_depth(model::BitDepth::Float16);
974 assert_eq!(eng.pipelines.borrow().pipelines.len(), CORE_PREWARM_OPS.len());
975 assert!(eng.pipelines_f16.get().is_none());
976
977 eng.hiq = true;
978 eng.prewarm_for_depth(model::BitDepth::Float16);
979 let f16 = eng.pipelines_f16.get().expect("f16 registry initialized");
980 assert_eq!(f16.borrow().pipelines.len(), CORE_PREWARM_OPS.len());
981 }
921}982}