authoravatarclover caruso<git@paperclover.net>2026-11-30 16:13:34-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 16:42:08-08:00
loge44c996f55a67e9dffeed9bfb8bc40dbdf33f6d1
treea845fffb5f89610275c84a5932ef126b5255f34a
parentee926109aac4f87c7ca5d377e6afc1a36e0d778f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add GPU texture pool reuse and per-node --profile telemetry (#25)


4 files changed, 981 insertions(+), 25 deletions(-)

crates/engine/src/bin/render_check.rs+35-2
...@@ -335,7 +335,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -335,7 +335,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
335 }335 }
336 if args.len() < 3 {336 if args.len() < 3 {
337 eprintln!(337 eprintln!(
338 "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check <comp.comp> --export [--saver <name>] [--range <start>..<end>] [--out-dir <dir>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-mp4 <out.mp4> [--node <name>] [--range <start>..<end>] [--crf <u8>] [--max-height <u32>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-prores <out.mov> [--node <name>] [--range <start>..<end>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --roundtrip <out.comp>\n render-check --suite <private/suite.txt> [--fast]"338 "usage:\n render-check <comp.comp> <frame> [--out <out.png>] [--ref <ref.png>] [--node <name>] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check <comp.comp> --render <start>..<end> --out-dir <dir> [--node <name>] [--proxy <1|2|4>]\n render-check <comp.comp> --export [--saver <name>] [--range <start>..<end>] [--out-dir <dir>] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-mp4 <out.mp4> [--node <name>] [--range <start>..<end>] [--crf <u8>] [--max-height <u32>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --export-prores <out.mov> [--node <name>] [--range <start>..<end>] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check <comp.comp> --roundtrip <out.comp>\n render-check --suite <private/suite.txt> [--fast]"
339 );339 );
340 std::process::exit(2);340 std::process::exit(2);
341 }341 }
...@@ -520,6 +520,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -520,6 +520,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
520 let mut vram_budget_mb: Option<u64> = None;520 let mut vram_budget_mb: Option<u64> = None;
521 let mut hiq = true;521 let mut hiq = true;
522 let mut bench = false;522 let mut bench = false;
523 let mut profile = false;
523 let mut i = 3;524 let mut i = 3;
524 while i < args.len() {525 while i < args.len() {
525 match args[i].as_str() {526 match args[i].as_str() {
...@@ -555,8 +556,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -555,8 +556,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
555 bench = true;556 bench = true;
556 i += 1;557 i += 1;
557 }558 }
559 "--profile" => {
560 profile = true;
561 i += 1;
562 }
558 other => {563 other => {
559 eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --proxy-clips, --vram-mb, --fast, --bench)");564 eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --proxy-clips, --vram-mb, --fast, --bench, --profile)");
560 std::process::exit(2);565 std::process::exit(2);
561 }566 }
562 }567 }
...@@ -587,7 +592,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -587,7 +592,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
587 }592 }
588 engine.hiq = hiq;593 engine.hiq = hiq;
589594
595 if profile {
596 engine.cache.begin_frame_profile_with_comp(&comp);
597 }
590 let (tex, cold) = engine.evaluate(&comp, target, frame);598 let (tex, cold) = engine.evaluate(&comp, target, frame);
599 let cold_profile = if profile {
600 engine.cache.take_frame_profile().map(|mut fp| {
601 fp.total_eval_ms = cold.eval_ms;
602 fp
603 })
604 } else {
605 None
606 };
591 eprintln!(607 eprintln!(
592 "[cold] {:.2} ms | eval={} hits={} misses={} loads={} pruned={} vram={:.1}MB unsupported={:?}",608 "[cold] {:.2} ms | eval={} hits={} misses={} loads={} pruned={} vram={:.1}MB unsupported={:?}",
593 cold.eval_ms,609 cold.eval_ms,
...@@ -599,6 +615,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -599,6 +615,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
599 cold.cached_vram_mb,615 cold.cached_vram_mb,
600 cold.unsupported_nodes616 cold.unsupported_nodes
601 );617 );
618 if let Some(fp) = &cold_profile {
619 eprint!("{}", fp.format_top_nodes(15));
620 }
602621
603 if bench {622 if bench {
604 let (_, warm) = engine.evaluate(&comp, target, frame);623 let (_, warm) = engine.evaluate(&comp, target, frame);
...@@ -608,11 +627,25 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -608,11 +627,25 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
608 );627 );
609628
610 engine.bust_gpu_cache();629 engine.bust_gpu_cache();
630 if profile {
631 engine.cache.begin_frame_profile_with_comp(&comp);
632 }
611 let (_, gpu_bust) = engine.evaluate(&comp, target, frame);633 let (_, gpu_bust) = engine.evaluate(&comp, target, frame);
634 let bust_profile = if profile {
635 engine.cache.take_frame_profile().map(|mut fp| {
636 fp.total_eval_ms = gpu_bust.eval_ms;
637 fp
638 })
639 } else {
640 None
641 };
612 eprintln!(642 eprintln!(
613 "[bust] {:.2} ms | eval={} hits={} misses={} loads={}",643 "[bust] {:.2} ms | eval={} hits={} misses={} loads={}",
614 gpu_bust.eval_ms, gpu_bust.nodes_evaluated, gpu_bust.cache_hits, gpu_bust.cache_misses, gpu_bust.source_loads644 gpu_bust.eval_ms, gpu_bust.nodes_evaluated, gpu_bust.cache_hits, gpu_bust.cache_misses, gpu_bust.source_loads
615 );645 );
646 if let Some(fp) = &bust_profile {
647 eprint!("{}", fp.format_top_nodes(15));
648 }
616649
617 engine.set_cache_mode(CacheMode::Bypass);650 engine.set_cache_mode(CacheMode::Bypass);
618 let (_, bypass) = engine.evaluate(&comp, target, frame);651 let (_, bypass) = engine.evaluate(&comp, target, frame);
crates/engine/src/cache.rs+613-22
...@@ -1,9 +1,11 @@...@@ -1,9 +1,11 @@
1//! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction,1//! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction,
2//! and surgical cache-busting modes for profiling and playback verification.2//! VRAM-budgeted texture pooling, per-node profiling hooks, and surgical
3//! cache-busting modes for profiling and playback verification.
34
4use model::{BitDepth, NodeId};5use crate::profile::{FrameProfile, ProfileRecorder};
5use std::collections::{HashMap, HashSet};6use model::{BitDepth, Comp, NodeId};
6use std::sync::Arc;7use std::collections::{HashMap, HashSet, VecDeque};
8use std::sync::{Arc, Mutex};
79
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum CacheMode {11pub enum CacheMode {
...@@ -35,6 +37,28 @@ pub struct CachedTexture {...@@ -35,6 +37,28 @@ pub struct CachedTexture {
35 pub bytes: u64,37 pub bytes: u64,
36}38}
3739
40fn depth_for_format(format: wgpu::TextureFormat) -> BitDepth {
41 match format {
42 wgpu::TextureFormat::Rgba16Float => BitDepth::Float16,
43 wgpu::TextureFormat::Rgba32Float => BitDepth::Float32,
44 _ => BitDepth::Int8,
45 }
46}
47
48fn bytes_per_pixel(format: wgpu::TextureFormat) -> u64 {
49 match format {
50 wgpu::TextureFormat::Rgba32Float => 16,
51 wgpu::TextureFormat::Rgba16Float => 8,
52 _ => u64::from(format.block_copy_size(None).unwrap_or(4)),
53 }
54}
55
56fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 {
57 u64::from(size[0].max(1))
58 .saturating_mul(u64::from(size[1].max(1)))
59 .saturating_mul(bytes_per_pixel(format))
60}
61
38impl CachedTexture {62impl CachedTexture {
39 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self {63 pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self {
40 Self::from_texture_dod(texture, size, [0, 0], size, content_hash)64 Self::from_texture_dod(texture, size, [0, 0], size, content_hash)
...@@ -48,11 +72,7 @@ impl CachedTexture {...@@ -48,11 +72,7 @@ impl CachedTexture {
48 content_hash: u64,72 content_hash: u64,
49 ) -> Self {73 ) -> Self {
50 let format = texture.format();74 let format = texture.format();
51 let depth = match format {75 let depth = depth_for_format(format);
52 wgpu::TextureFormat::Rgba16Float => BitDepth::Float16,
53 wgpu::TextureFormat::Rgba32Float => BitDepth::Float32,
54 _ => BitDepth::Int8,
55 };
56 Self::from_texture_dod_depth(texture, size, origin, canvas_size, depth, content_hash)76 Self::from_texture_dod_depth(texture, size, origin, canvas_size, depth, content_hash)
57 }77 }
5878
...@@ -65,13 +85,8 @@ impl CachedTexture {...@@ -65,13 +85,8 @@ impl CachedTexture {
65 content_hash: u64,85 content_hash: u64,
66 ) -> Self {86 ) -> Self {
67 let format = texture.format();87 let format = texture.format();
68 let bpp = match format {
69 wgpu::TextureFormat::Rgba32Float => 16u64,
70 wgpu::TextureFormat::Rgba16Float => 8u64,
71 _ => 4u64,
72 };
73 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());88 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
74 let bytes = u64::from(size[0]) * u64::from(size[1]) * bpp;89 let bytes = texture_bytes(size, format);
75 Self {90 Self {
76 texture: Arc::new(texture),91 texture: Arc::new(texture),
77 view: Arc::new(view),92 view: Arc::new(view),
...@@ -87,6 +102,33 @@ impl CachedTexture {...@@ -87,6 +102,33 @@ impl CachedTexture {
87 }102 }
88 }103 }
89104
105 #[allow(clippy::too_many_arguments)]
106 pub(crate) fn from_parts(
107 texture: Arc<wgpu::Texture>,
108 view: Arc<wgpu::TextureView>,
109 size: [u32; 2],
110 origin: [i32; 2],
111 canvas_size: [u32; 2],
112 depth: BitDepth,
113 format: wgpu::TextureFormat,
114 content_hash: u64,
115 bytes: u64,
116 ) -> Self {
117 Self {
118 texture,
119 view,
120 size,
121 origin,
122 canvas_size,
123 depth,
124 format,
125 tex_scale: 1.0,
126 edge_mode: None,
127 content_hash,
128 bytes,
129 }
130 }
131
90 pub fn has_dod(&self) -> bool {132 pub fn has_dod(&self) -> bool {
91 self.origin != [0, 0] || self.size != self.canvas_size133 self.origin != [0, 0] || self.size != self.canvas_size
92 }134 }
...@@ -107,6 +149,175 @@ pub struct EvalStats {...@@ -107,6 +149,175 @@ pub struct EvalStats {
107 pub unsupported_nodes: Vec<String>,149 pub unsupported_nodes: Vec<String>,
108}150}
109151
152/// Key identifying compatible GPU textures in `TexturePool`.
153#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
154pub struct TexturePoolKey {
155 pub width: u32,
156 pub height: u32,
157 pub format: wgpu::TextureFormat,
158 pub usage: wgpu::TextureUsages,
159}
160
161/// Snapshot of `TexturePool` counters and resident VRAM.
162#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
163pub struct TexturePoolStats {
164 pub pooled_count: usize,
165 pub pooled_bytes: u64,
166 pub hits: u64,
167 pub misses: u64,
168 pub evictions: u64,
169 pub returns: u64,
170}
171
172struct PooledTexture {
173 texture: Arc<wgpu::Texture>,
174 view: Arc<wgpu::TextureView>,
175 bytes: u64,
176 last_returned: u64,
177}
178
179/// LRU pool of recycled `wgpu::Texture` allocations keyed by `(width, height, format, usage)`.
180pub struct TexturePool {
181 buckets: HashMap<TexturePoolKey, VecDeque<PooledTexture>>,
182 total_bytes: u64,
183 pooled_count: usize,
184 tick: u64,
185 hits: u64,
186 misses: u64,
187 evictions: u64,
188 returns: u64,
189}
190
191impl Default for TexturePool {
192 fn default() -> Self {
193 Self::new()
194 }
195}
196
197impl TexturePool {
198 pub fn new() -> Self {
199 Self {
200 buckets: HashMap::new(),
201 total_bytes: 0,
202 pooled_count: 0,
203 tick: 0,
204 hits: 0,
205 misses: 0,
206 evictions: 0,
207 returns: 0,
208 }
209 }
210
211 pub fn stats(&self) -> TexturePoolStats {
212 TexturePoolStats {
213 pooled_count: self.pooled_count,
214 pooled_bytes: self.total_bytes,
215 hits: self.hits,
216 misses: self.misses,
217 evictions: self.evictions,
218 returns: self.returns,
219 }
220 }
221
222 pub fn pooled_bytes(&self) -> u64 {
223 self.total_bytes
224 }
225
226 pub fn pooled_count(&self) -> usize {
227 self.pooled_count
228 }
229
230 pub fn hits(&self) -> u64 {
231 self.hits
232 }
233
234 pub fn misses(&self) -> u64 {
235 self.misses
236 }
237
238 pub fn evictions(&self) -> u64 {
239 self.evictions
240 }
241
242 pub fn clear(&mut self) {
243 self.buckets.clear();
244 self.total_bytes = 0;
245 self.pooled_count = 0;
246 }
247
248 fn push(&mut self, tex: &CachedTexture) {
249 if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 {
250 return;
251 }
252 let key = TexturePoolKey {
253 width: tex.size[0],
254 height: tex.size[1],
255 format: tex.format,
256 usage: tex.texture.usage(),
257 };
258 self.tick += 1;
259 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);
260 self.pooled_count += 1;
261 self.returns += 1;
262 self.buckets.entry(key).or_default().push_back(PooledTexture {
263 texture: Arc::clone(&tex.texture),
264 view: Arc::clone(&tex.view),
265 bytes: tex.bytes,
266 last_returned: self.tick,
267 });
268 }
269
270 /// Pops an exclusively owned (`Arc::strong_count == 1`) texture matching `key`.
271 /// Entries still referenced elsewhere (e.g. by `output_cache`) are dropped from the pool
272 /// rather than aliased.
273 fn pop(&mut self, key: TexturePoolKey) -> Option<(Arc<wgpu::Texture>, Arc<wgpu::TextureView>, u64)> {
274 let mut found = None;
275 let remove_bucket = if let Some(bucket) = self.buckets.get_mut(&key) {
276 while let Some(item) = bucket.pop_back() {
277 self.total_bytes = self.total_bytes.saturating_sub(item.bytes);
278 self.pooled_count = self.pooled_count.saturating_sub(1);
279 if Arc::strong_count(&item.texture) == 1 && Arc::strong_count(&item.view) == 1 {
280 found = Some((item.texture, item.view, item.bytes));
281 break;
282 }
283 }
284 bucket.is_empty()
285 } else {
286 false
287 };
288 if remove_bucket {
289 self.buckets.remove(&key);
290 }
291 found
292 }
293
294 /// Evicts the globally oldest pooled texture (FIFO/LRU by return order).
295 fn evict_oldest(&mut self) -> bool {
296 let oldest_key = self
297 .buckets
298 .iter()
299 .filter_map(|(&k, q)| q.front().map(|front| (k, front.last_returned)))
300 .min_by_key(|(_, tick)| *tick)
301 .map(|(k, _)| k);
302 let Some(key) = oldest_key else {
303 return false;
304 };
305 let mut remove_bucket = false;
306 if let Some(bucket) = self.buckets.get_mut(&key) {
307 if let Some(item) = bucket.pop_front() {
308 self.total_bytes = self.total_bytes.saturating_sub(item.bytes);
309 self.pooled_count = self.pooled_count.saturating_sub(1);
310 self.evictions += 1;
311 }
312 remove_bucket = bucket.is_empty();
313 }
314 if remove_bucket {
315 self.buckets.remove(&key);
316 }
317 true
318 }
319}
320
110struct Entry {321struct Entry {
111 tex: CachedTexture,322 tex: CachedTexture,
112 last_used: u64,323 last_used: u64,
...@@ -117,6 +328,9 @@ struct Entry {...@@ -117,6 +328,9 @@ struct Entry {
117/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB).328/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB).
118pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768;329pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768;
119330
331/// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`).
332pub type GpuCache = NodeCache;
333
120pub struct NodeCache {334pub struct NodeCache {
121 pub mode: CacheMode,335 pub mode: CacheMode,
122 pub budget_bytes: u64,336 pub budget_bytes: u64,
...@@ -128,6 +342,8 @@ pub struct NodeCache {...@@ -128,6 +342,8 @@ pub struct NodeCache {
128 pub gpu_salt: u64,342 pub gpu_salt: u64,
129 /// Per-node salt bumped when surgically busting a subtree.343 /// Per-node salt bumped when surgically busting a subtree.
130 node_salts: HashMap<NodeId, u64>,344 node_salts: HashMap<NodeId, u64>,
345 pool: Mutex<TexturePool>,
346 profiler: Option<ProfileRecorder>,
131}347}
132348
133impl NodeCache {349impl NodeCache {
...@@ -141,12 +357,25 @@ impl NodeCache {...@@ -141,12 +357,25 @@ impl NodeCache {
141 evictions: 0,357 evictions: 0,
142 gpu_salt: 0,358 gpu_salt: 0,
143 node_salts: HashMap::new(),359 node_salts: HashMap::new(),
360 pool: Mutex::new(TexturePool::new()),
361 profiler: None,
144 }362 }
145 }363 }
146364
365 /// Standard compositor GPU texture usage flags used by `Evaluator`.
366 pub fn default_texture_usage() -> wgpu::TextureUsages {
367 wgpu::TextureUsages::TEXTURE_BINDING
368 | wgpu::TextureUsages::STORAGE_BINDING
369 | wgpu::TextureUsages::COPY_SRC
370 | wgpu::TextureUsages::COPY_DST
371 | wgpu::TextureUsages::RENDER_ATTACHMENT
372 }
373
147 pub fn set_budget_mb(&mut self, budget_mb: u64) {374 pub fn set_budget_mb(&mut self, budget_mb: u64) {
148 self.budget_bytes = budget_mb.saturating_mul(1024 * 1024);375 self.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
376 self.trim_pool_to_budget();
149 self.evict_over_budget();377 self.evict_over_budget();
378 self.trim_pool_to_budget();
150 }379 }
151380
152 pub fn budget_mb(&self) -> u64 {381 pub fn budget_mb(&self) -> u64 {
...@@ -161,6 +390,142 @@ impl NodeCache {...@@ -161,6 +390,142 @@ impl NodeCache {
161 self.node_salts.get(&id).copied().unwrap_or(0)390 self.node_salts.get(&id).copied().unwrap_or(0)
162 }391 }
163392
393 pub fn pool_stats(&self) -> TexturePoolStats {
394 self.pool.lock().expect("texture pool lock").stats()
395 }
396
397 pub fn pooled_bytes(&self) -> u64 {
398 self.pool.lock().expect("texture pool lock").pooled_bytes()
399 }
400
401 pub fn pooled_mb(&self) -> f64 {
402 self.pooled_bytes() as f64 / (1024.0 * 1024.0)
403 }
404
405 pub fn live_bytes(&self) -> u64 {
406 self.total_bytes
407 }
408
409 pub fn live_mb(&self) -> f64 {
410 self.total_bytes as f64 / (1024.0 * 1024.0)
411 }
412
413 pub fn total_vram_bytes(&self) -> u64 {
414 self.total_bytes.saturating_add(self.pooled_bytes())
415 }
416
417 /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an
418 /// exclusively-owned texture is available, otherwise allocates a fresh one on `device`.
419 pub fn acquire_texture(
420 &self,
421 device: &wgpu::Device,
422 width: u32,
423 height: u32,
424 format: wgpu::TextureFormat,
425 usage: wgpu::TextureUsages,
426 ) -> CachedTexture {
427 let clamped = [width.max(1), height.max(1)];
428 let bytes = texture_bytes(clamped, format);
429 let key = TexturePoolKey {
430 width: clamped[0],
431 height: clamped[1],
432 format,
433 usage,
434 };
435 let depth = depth_for_format(format);
436
437 {
438 let mut pool = self.pool.lock().expect("texture pool lock");
439 if let Some((texture, view, pooled_bytes)) = pool.pop(key) {
440 pool.hits += 1;
441 return CachedTexture::from_parts(
442 texture,
443 view,
444 clamped,
445 [0, 0],
446 clamped,
447 depth,
448 format,
449 0,
450 pooled_bytes,
451 );
452 }
453 pool.misses += 1;
454 // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget.
455 while self
456 .total_bytes
457 .saturating_add(pool.total_bytes)
458 .saturating_add(bytes)
459 > self.budget_bytes
460 {
461 if !pool.evict_oldest() {
462 break;
463 }
464 }
465 }
466
467 let texture = device.create_texture(&wgpu::TextureDescriptor {
468 label: Some("comp-tex"),
469 size: wgpu::Extent3d {
470 width: clamped[0],
471 height: clamped[1],
472 depth_or_array_layers: 1,
473 },
474 mip_level_count: 1,
475 sample_count: 1,
476 dimension: wgpu::TextureDimension::D2,
477 format,
478 usage,
479 view_formats: &[],
480 });
481 CachedTexture::from_texture_dod_depth(texture, clamped, [0, 0], clamped, depth, 0)
482 }
483
484 /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics.
485 #[allow(clippy::too_many_arguments)]
486 pub fn acquire_texture_dod_fmt(
487 &self,
488 device: &wgpu::Device,
489 size: [u32; 2],
490 origin: [i32; 2],
491 canvas_size: [u32; 2],
492 depth: BitDepth,
493 format: wgpu::TextureFormat,
494 content_hash: u64,
495 ) -> CachedTexture {
496 let mut tex = self.acquire_texture(
497 device,
498 size[0],
499 size[1],
500 format,
501 Self::default_texture_usage(),
502 );
503 tex.origin = origin;
504 tex.canvas_size = [canvas_size[0].max(1), canvas_size[1].max(1)];
505 tex.depth = depth;
506 tex.content_hash = content_hash;
507 tex
508 }
509
510 /// Starts per-node profiling for the upcoming frame evaluation.
511 pub fn begin_frame_profile(&mut self) {
512 let stats = self.pool_stats();
513 self.profiler = Some(ProfileRecorder::new(stats.hits, stats.misses));
514 }
515
516 /// Starts per-node profiling with node names and kinds pre-populated from `comp`.
517 pub fn begin_frame_profile_with_comp(&mut self, comp: &Comp) {
518 let stats = self.pool_stats();
519 self.profiler = Some(ProfileRecorder::with_comp(comp, stats.hits, stats.misses));
520 }
521
522 /// Stops profiling and returns the collected `FrameProfile`, if active.
523 pub fn take_frame_profile(&mut self) -> Option<FrameProfile> {
524 let rec = self.profiler.take()?;
525 let stats = self.pool_stats();
526 Some(rec.finish(self.total_bytes, stats.pooled_bytes, stats.hits, stats.misses))
527 }
528
164 pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option<CachedTexture> {529 pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option<CachedTexture> {
165 if self.mode == CacheMode::Bypass {530 if self.mode == CacheMode::Bypass {
166 return None;531 return None;
...@@ -170,18 +535,28 @@ impl NodeCache {...@@ -170,18 +535,28 @@ impl NodeCache {
170 e.last_used = self.tick;535 e.last_used = self.tick;
171 e.producers.insert(node);536 e.producers.insert(node);
172 e.frames.insert(frame);537 e.frames.insert(frame);
173 Some(e.tex.clone())538 let tex = e.tex.clone();
539 if let Some(prof) = &mut self.profiler {
540 prof.record(node, true, tex.size, tex.bytes);
541 }
542 Some(tex)
174 }543 }
175544
176 pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) {545 pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) {
546 if let Some(prof) = &mut self.profiler {
547 prof.record(node, false, tex.size, tex.bytes);
548 }
177 if self.mode == CacheMode::Bypass {549 if self.mode == CacheMode::Bypass {
178 return;550 return;
179 }551 }
180 self.tick += 1;552 self.tick += 1;
181 if let Some(old) = self.entries.remove(&key) {553 if let Some(old) = self.entries.remove(&key) {
182 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);554 self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes);
555 if !Arc::ptr_eq(&old.tex.texture, &tex.texture) {
556 self.return_to_pool(&old.tex);
557 }
183 }558 }
184 self.total_bytes += tex.bytes;559 self.total_bytes = self.total_bytes.saturating_add(tex.bytes);
185 let mut producers = HashSet::new();560 let mut producers = HashSet::new();
186 producers.insert(node);561 producers.insert(node);
187 let mut frames = HashSet::new();562 let mut frames = HashSet::new();
...@@ -195,7 +570,32 @@ impl NodeCache {...@@ -195,7 +570,32 @@ impl NodeCache {
195 frames,570 frames,
196 },571 },
197 );572 );
573 // Trim pooled textures before evicting live cached nodes so live working sets stay hot.
574 self.trim_pool_to_budget();
198 self.evict_over_budget();575 self.evict_over_budget();
576 self.trim_pool_to_budget();
577 }
578
579 fn return_to_pool(&self, tex: &CachedTexture) {
580 if tex.bytes == 0 || tex.bytes > self.budget_bytes {
581 return;
582 }
583 let mut pool = self.pool.lock().expect("texture pool lock");
584 pool.push(tex);
585 while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes {
586 if !pool.evict_oldest() {
587 break;
588 }
589 }
590 }
591
592 fn trim_pool_to_budget(&self) {
593 let mut pool = self.pool.lock().expect("texture pool lock");
594 while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes {
595 if !pool.evict_oldest() {
596 break;
597 }
598 }
199 }599 }
200600
201 fn evict_over_budget(&mut self) {601 fn evict_over_budget(&mut self) {
...@@ -207,18 +607,46 @@ impl NodeCache {...@@ -207,18 +607,46 @@ impl NodeCache {
207 if let Some(removed) = self.entries.remove(&oldest_key) {607 if let Some(removed) = self.entries.remove(&oldest_key) {
208 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);608 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
209 self.evictions += 1;609 self.evictions += 1;
610 if self
611 .total_bytes
612 .saturating_add(self.pooled_bytes())
613 .saturating_add(removed.tex.bytes)
614 <= self.budget_bytes
615 {
616 self.return_to_pool(&removed.tex);
617 }
210 }618 }
211 }619 }
212 }620 }
213621
214 /// Wipes every cached GPU node texture and bumps global salt.622 /// Wipes every cached GPU node texture (returning eligible textures to the pool) and bumps global salt.
215 pub fn bust_all(&mut self) {623 pub fn bust_all(&mut self) {
216 self.entries.clear();624 let _ = self.clear_dynamic();
625 }
626
627 /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt.
628 pub fn clear_dynamic(&mut self) -> usize {
629 let count = self.entries.len();
630 let drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();
217 self.total_bytes = 0;631 self.total_bytes = 0;
218 self.gpu_salt += 1;632 self.gpu_salt += 1;
633 if !drained.is_empty() && self.budget_bytes > 0 {
634 let mut pool = self.pool.lock().expect("texture pool lock");
635 for entry in drained {
636 if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes {
637 pool.push(&entry.tex);
638 }
639 }
640 while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes {
641 if !pool.evict_oldest() {
642 break;
643 }
644 }
645 }
646 count
219 }647 }
220648
221 /// Removes cached entries produced for a specific integer frame.649 /// Removes cached entries produced for a specific integer frame, returning them to the pool.
222 pub fn bust_frame(&mut self, frame: i64) -> usize {650 pub fn bust_frame(&mut self, frame: i64) -> usize {
223 let keys: Vec<u64> = self651 let keys: Vec<u64> = self
224 .entries652 .entries
...@@ -230,13 +658,14 @@ impl NodeCache {...@@ -230,13 +658,14 @@ impl NodeCache {
230 for k in keys {658 for k in keys {
231 if let Some(removed) = self.entries.remove(&k) {659 if let Some(removed) = self.entries.remove(&k) {
232 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);660 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
661 self.return_to_pool(&removed.tex);
233 }662 }
234 }663 }
235 count664 count
236 }665 }
237666
238 /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream667 /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream
239 /// via Merkle hashing!) and evicts its existing entries.668 /// via Merkle hashing!) and evicts its existing entries back into the pool.
240 pub fn bust_subtree(&mut self, node: NodeId) -> usize {669 pub fn bust_subtree(&mut self, node: NodeId) -> usize {
241 *self.node_salts.entry(node).or_insert(0) += 1;670 *self.node_salts.entry(node).or_insert(0) += 1;
242 let keys: Vec<u64> = self671 let keys: Vec<u64> = self
...@@ -249,6 +678,7 @@ impl NodeCache {...@@ -249,6 +678,7 @@ impl NodeCache {
249 for k in keys {678 for k in keys {
250 if let Some(removed) = self.entries.remove(&k) {679 if let Some(removed) = self.entries.remove(&k) {
251 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);680 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
681 self.return_to_pool(&removed.tex);
252 }682 }
253 }683 }
254 count684 count
...@@ -259,6 +689,167 @@ impl NodeCache {...@@ -259,6 +689,167 @@ impl NodeCache {
259 }689 }
260690
261 pub fn total_mb(&self) -> f64 {691 pub fn total_mb(&self) -> f64 {
262 self.total_bytes as f64 / (1024.0 * 1024.0)692 self.total_vram_bytes() as f64 / (1024.0 * 1024.0)
693 }
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699 use crate::Engine;
700
701 #[test]
702 fn texture_pool_recycles_after_clear_dynamic_and_bust() {
703 let eng = Engine::new_headless().expect("gpu");
704 let device = eng.device();
705 let usage = NodeCache::default_texture_usage();
706 let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB);
707
708 // Initial acquire misses pool and allocates a 512x512 RGBA8 texture (1 MiB).
709 let t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
710 let ptr1 = Arc::as_ptr(&t1.texture);
711 assert_eq!(t1.bytes, 1024 * 1024);
712 assert_eq!(cache.pool_stats().misses, 1);
713 assert_eq!(cache.pool_stats().hits, 0);
714
715 cache.insert(101, t1, NodeId(1), 0);
716 assert_eq!(cache.live_bytes(), 1024 * 1024);
717 assert_eq!(cache.pooled_bytes(), 0);
718
719 // clear_dynamic returns unshared texture to pool without freeing GPU allocation.
720 let cleared = cache.clear_dynamic();
721 assert_eq!(cleared, 1);
722 assert_eq!(cache.live_bytes(), 0);
723 assert_eq!(cache.pooled_bytes(), 1024 * 1024);
724 assert_eq!(cache.pool_stats().pooled_count, 1);
725
726 // Acquiring same (w, h, format, usage) reuses the exact same wgpu::Texture allocation!
727 let t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
728 assert_eq!(Arc::as_ptr(&t2.texture), ptr1);
729 assert_eq!(cache.pool_stats().hits, 1);
730 assert_eq!(cache.pool_stats().misses, 1);
731 assert_eq!(cache.pooled_bytes(), 0);
732
733 // Different format must miss pool and allocate separately.
734 let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba16Float, usage);
735 assert_ne!(Arc::as_ptr(&t3.texture), ptr1);
736 assert_eq!(cache.pool_stats().misses, 2);
737
738 // Insert both and bust_frame(5) -> returns only frame 5 texture to pool.
739 cache.insert(201, t2, NodeId(1), 5);
740 cache.insert(202, t3, NodeId(2), 6);
741 assert_eq!(cache.bust_frame(5), 1);
742 assert_eq!(cache.pooled_bytes(), 1024 * 1024);
743 assert_eq!(cache.live_bytes(), 2 * 1024 * 1024);
744
745 let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage);
746 assert_eq!(Arc::as_ptr(&t4.texture), ptr1);
747 assert_eq!(cache.pool_stats().hits, 2);
748 }
749
750 #[test]
751 fn texture_pool_never_aliases_shared_arc() {
752 let eng = Engine::new_headless().expect("gpu");
753 let device = eng.device();
754 let usage = NodeCache::default_texture_usage();
755 let mut cache = NodeCache::new(16);
756
757 let t1 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage);
758 let pinned = t1.clone(); // External holder keeps strong_count > 1!
759 let ptr1 = Arc::as_ptr(&t1.texture);
760 cache.insert(1, t1, NodeId(0), 0);
761 cache.bust_all();
762
763 // While `pinned` is still alive, acquire_texture must NOT alias `t1`.
764 let t2 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage);
765 assert_ne!(Arc::as_ptr(&t2.texture), ptr1);
766 assert_eq!(cache.pool_stats().hits, 0);
767 drop(pinned);
768 }
769
770 #[test]
771 fn vram_budget_enforces_live_plus_pooled_cap_and_lru_eviction() {
772 let eng = Engine::new_headless().expect("gpu");
773 let device = eng.device();
774 let usage = NodeCache::default_texture_usage();
775 // 8 MiB budget; each 1024x1024 RGBA8 texture is 4 MiB.
776 let mut cache = NodeCache::new(8);
777 let budget = 8 * 1024 * 1024;
778
779 let a = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage);
780 let b = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage);
781 cache.insert(1, a, NodeId(0), 0);
782 cache.insert(2, b, NodeId(1), 0);
783 assert_eq!(cache.total_vram_bytes(), 8 * 1024 * 1024);
784
785 // Bust both into pool: live=0, pooled=8 MiB <= 8 MiB.
786 cache.bust_all();
787 assert_eq!(cache.live_bytes(), 0);
788 assert_eq!(cache.pooled_bytes(), 8 * 1024 * 1024);
789
790 // Inserting a 1024x1024 RGBA16F (8 MiB) must evict ALL pooled RGBA8 textures so live + pooled <= 8 MiB.
791 let c = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba16Float, usage);
792 assert!(cache.total_vram_bytes() <= budget);
793 cache.insert(3, c, NodeId(2), 1);
794 assert!(cache.total_vram_bytes() <= budget);
795 assert_eq!(cache.pooled_bytes(), 0);
796 assert!(cache.pool_stats().evictions >= 2);
797
798 // Verify deterministic LRU eviction order in pool within 8 MiB.
799 let mut cache3 = NodeCache::new(8);
800 let first = cache3.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 4 MiB
801 let second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 2 MiB
802 let third = cache3.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); // 1 MiB
803 let ptr_second = Arc::as_ptr(&second.texture);
804 cache3.insert(1, first, NodeId(0), 1);
805 cache3.insert(2, second, NodeId(1), 2);
806 cache3.insert(3, third, NodeId(2), 3);
807 assert!(cache3.total_vram_bytes() <= budget);
808
809 // Bust in deterministic order: frame 1 (4 MiB) oldest, then frame 2 (2 MiB), then frame 3 (1 MiB) => 7 MiB pooled.
810 assert_eq!(cache3.bust_frame(1), 1);
811 assert_eq!(cache3.bust_frame(2), 1);
812 assert_eq!(cache3.bust_frame(3), 1);
813 assert_eq!(cache3.pooled_bytes(), 7 * 1024 * 1024);
814
815 // Acquiring a 4 MiB Rgba16Float (512x1024x8 = 4 MiB) misses pool and must evict oldest (frame 1's 4 MiB),
816 // leaving frame 2 (2 MiB) + frame 3 (1 MiB) intact!
817 let _new_f16 = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba16Float, usage);
818 assert_eq!(cache3.pooled_bytes(), 3 * 1024 * 1024);
819 let reused_second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage);
820 assert_eq!(Arc::as_ptr(&reused_second.texture), ptr_second);
821 }
822
823 #[test]
824 fn default_budget_is_768_mb_and_profiler_records_hits_misses() {
825 let eng = Engine::new_headless().expect("gpu");
826 let device = eng.device();
827 let usage = NodeCache::default_texture_usage();
828 let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB);
829 assert_eq!(cache.budget_mb(), 768);
830 assert_eq!(cache.budget_bytes, 768 * 1024 * 1024);
831
832 // Cold profile: 1 miss + insert
833 cache.begin_frame_profile();
834 assert!(cache.get(42, NodeId(7), 10).is_none());
835 let t = cache.acquire_texture(device, 640, 360, wgpu::TextureFormat::Rgba8Unorm, usage);
836 cache.insert(42, t, NodeId(7), 10);
837 let p_cold = cache.take_frame_profile().expect("profile");
838 assert_eq!(p_cold.cache_hits, 0);
839 assert_eq!(p_cold.cache_misses, 1);
840 assert_eq!(p_cold.pool_misses, 1);
841 assert_eq!(p_cold.pool_hits, 0);
842 assert_eq!(p_cold.entries.len(), 1);
843 assert_eq!(p_cold.entries[0].width, 640);
844 assert_eq!(p_cold.entries[0].height, 360);
845
846 // Warm profile: 1 hit
847 cache.begin_frame_profile();
848 assert!(cache.get(42, NodeId(7), 10).is_some());
849 let p_warm = cache.take_frame_profile().expect("profile");
850 assert_eq!(p_warm.cache_hits, 1);
851 assert_eq!(p_warm.cache_misses, 0);
852 assert_eq!(p_warm.entries.len(), 1);
853 assert!(p_warm.entries[0].cache_hit);
263 }854 }
264}855}
crates/engine/src/lib.rs+6-1
...@@ -7,13 +7,18 @@ pub mod export;...@@ -7,13 +7,18 @@ pub mod export;
7pub mod media;7pub mod media;
8pub mod optflow;8pub mod optflow;
9pub mod particles;9pub mod particles;
10pub mod profile;
10pub mod ram_cache;11pub mod ram_cache;
11pub mod scene3d;12pub mod scene3d;
1213
13pub use audio::{AudioPlayer, AudioTrack};14pub use audio::{AudioPlayer, AudioTrack};
14pub use cache::{CacheMode, CachedTexture, DEFAULT_VRAM_BUDGET_MB, EvalStats, NodeCache};15pub use cache::{
16 CacheMode, CachedTexture, DEFAULT_VRAM_BUDGET_MB, EvalStats, GpuCache, NodeCache, TexturePool,
17 TexturePoolKey, TexturePoolStats,
18};
15pub use eval::{DisplaySettings, Engine, create_texture};19pub use eval::{DisplaySettings, Engine, create_texture};
16pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver};20pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver};
21pub use profile::{FrameProfile, NodeProfileEntry};
17pub use ram_cache::{22pub use ram_cache::{
18 DEFAULT_RAM_CACHE_MB, PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher,23 DEFAULT_RAM_CACHE_MB, PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher,
19};24};
crates/engine/src/profile.rs created+327
...@@ -0,0 +1,327 @@
1//! Per-node GPU evaluation profiling and frame telemetry.
2
3use model::{Comp, NodeId};
4use std::collections::HashMap;
5use std::fmt::Write as _;
6use std::time::Instant;
7
8/// Profiling telemetry for a single node lookup or evaluation within a frame.
9#[derive(Clone, Debug, PartialEq)]
10pub struct NodeProfileEntry {
11 pub node_id: NodeId,
12 pub node_name: String,
13 pub kind: String,
14 pub eval_ms: f64,
15 pub cache_hit: bool,
16 pub width: u32,
17 pub height: u32,
18 pub vram_bytes: u64,
19}
20
21/// Aggregated per-frame render telemetry captured across `NodeCache` lookups/inserts.
22#[derive(Clone, Debug, Default)]
23pub struct FrameProfile {
24 pub entries: Vec<NodeProfileEntry>,
25 pub total_eval_ms: f64,
26 pub total_vram_bytes: u64,
27 pub live_vram_bytes: u64,
28 pub pooled_vram_bytes: u64,
29 pub cache_hits: usize,
30 pub cache_misses: usize,
31 pub pool_hits: u64,
32 pub pool_misses: u64,
33}
34
35impl FrameProfile {
36 pub fn new() -> Self {
37 Self::default()
38 }
39
40 /// Resolves `node_name` and `kind` for each entry using `comp.nodes`.
41 pub fn populate_names_from_comp(&mut self, comp: &Comp) {
42 for entry in &mut self.entries {
43 let node_opt = comp
44 .nodes
45 .get(entry.node_id.0)
46 .filter(|n| n.id == entry.node_id)
47 .or_else(|| comp.nodes.iter().find(|n| n.id == entry.node_id));
48 if let Some(node) = node_opt {
49 entry.node_name = node.name.clone();
50 entry.kind = node.kind.clone();
51 }
52 }
53 }
54
55 /// Sum of exclusive `eval_ms` across all profiled node entries.
56 pub fn total_node_eval_ms(&self) -> f64 {
57 self.entries.iter().map(|e| e.eval_ms).sum()
58 }
59
60 /// Texture pool hit ratio in `[0.0, 1.0]`.
61 pub fn pool_reuse_rate(&self) -> f64 {
62 let total = self.pool_hits.saturating_add(self.pool_misses);
63 if total == 0 {
64 0.0
65 } else {
66 self.pool_hits as f64 / total as f64
67 }
68 }
69
70 /// Node cache hit ratio in `[0.0, 1.0]`.
71 pub fn cache_hit_rate(&self) -> f64 {
72 let total = self.cache_hits.saturating_add(self.cache_misses);
73 if total == 0 {
74 0.0
75 } else {
76 self.cache_hits as f64 / total as f64
77 }
78 }
79
80 /// Returns up to `limit` hottest nodes sorted by `eval_ms` descending (tie-broken by VRAM).
81 pub fn hot_nodes(&self, limit: usize) -> Vec<&NodeProfileEntry> {
82 let mut refs: Vec<&NodeProfileEntry> = self.entries.iter().collect();
83 refs.sort_by(|a, b| {
84 b.eval_ms
85 .total_cmp(&a.eval_ms)
86 .then_with(|| b.vram_bytes.cmp(&a.vram_bytes))
87 .then_with(|| a.node_name.cmp(&b.node_name))
88 });
89 refs.truncate(limit);
90 refs
91 }
92
93 /// Returns up to `limit` heaviest nodes sorted by `vram_bytes` descending (tie-broken by `eval_ms`).
94 pub fn hot_nodes_by_vram(&self, limit: usize) -> Vec<&NodeProfileEntry> {
95 let mut refs: Vec<&NodeProfileEntry> = self.entries.iter().collect();
96 refs.sort_by(|a, b| {
97 b.vram_bytes
98 .cmp(&a.vram_bytes)
99 .then_with(|| b.eval_ms.total_cmp(&a.eval_ms))
100 .then_with(|| a.node_name.cmp(&b.node_name))
101 });
102 refs.truncate(limit);
103 refs
104 }
105
106 /// Formats a human-readable summary and top-`limit` hot nodes table.
107 pub fn format_top_nodes(&self, limit: usize) -> String {
108 let mut out = String::new();
109 let total_mb = self.total_vram_bytes as f64 / (1024.0 * 1024.0);
110 let live_mb = self.live_vram_bytes as f64 / (1024.0 * 1024.0);
111 let pool_mb = self.pooled_vram_bytes as f64 / (1024.0 * 1024.0);
112 let _ = writeln!(
113 out,
114 "Profile: eval={:.2}ms (nodes={:.2}ms) | vram={:.1}MB (live={:.1}MB, pool={:.1}MB) | cache={}/{} ({:.1}%) | pool={}/{} (reuse {:.1}%)",
115 self.total_eval_ms,
116 self.total_node_eval_ms(),
117 total_mb,
118 live_mb,
119 pool_mb,
120 self.cache_hits,
121 self.cache_hits + self.cache_misses,
122 self.cache_hit_rate() * 100.0,
123 self.pool_hits,
124 self.pool_hits + self.pool_misses,
125 self.pool_reuse_rate() * 100.0,
126 );
127
128 let top = self.hot_nodes(limit);
129 if top.is_empty() {
130 let _ = writeln!(out, " (no node cache evaluations recorded)");
131 return out;
132 }
133
134 let _ = writeln!(
135 out,
136 "{:<4} {:<24} {:<20} {:<6} {:>11} {:>9} {:>10}",
137 "#", "NODE", "KIND", "CACHE", "RES", "VRAM_MB", "EVAL_MS"
138 );
139 let _ = writeln!(out, "{}", "-".repeat(90));
140 for (idx, e) in top.iter().enumerate() {
141 let res = format!("{}x{}", e.width, e.height);
142 let mb = e.vram_bytes as f64 / (1024.0 * 1024.0);
143 let name = truncate_label(&e.node_name, 24);
144 let kind = truncate_label(&e.kind, 20);
145 let _ = writeln!(
146 out,
147 "{:<4} {:<24} {:<20} {:<6} {:>11} {:>9.2} {:>9.2}ms",
148 idx + 1,
149 name,
150 kind,
151 if e.cache_hit { "HIT" } else { "MISS" },
152 res,
153 mb,
154 e.eval_ms,
155 );
156 }
157 out
158 }
159}
160
161fn truncate_label(s: &str, max_chars: usize) -> String {
162 let count = s.chars().count();
163 if count <= max_chars {
164 s.to_owned()
165 } else if max_chars <= 3 {
166 s.chars().take(max_chars).collect()
167 } else {
168 let mut t: String = s.chars().take(max_chars - 3).collect();
169 t.push_str("...");
170 t
171 }
172}
173
174#[derive(Debug)]
175pub(crate) struct ProfileRecorder {
176 started_at: Instant,
177 last_event: Instant,
178 pool_hits_start: u64,
179 pool_misses_start: u64,
180 node_meta: HashMap<NodeId, (String, String)>,
181 entries: Vec<NodeProfileEntry>,
182}
183
184impl ProfileRecorder {
185 pub(crate) fn new(pool_hits_start: u64, pool_misses_start: u64) -> Self {
186 let now = Instant::now();
187 Self {
188 started_at: now,
189 last_event: now,
190 pool_hits_start,
191 pool_misses_start,
192 node_meta: HashMap::new(),
193 entries: Vec::new(),
194 }
195 }
196
197 pub(crate) fn with_comp(comp: &Comp, pool_hits_start: u64, pool_misses_start: u64) -> Self {
198 let mut rec = Self::new(pool_hits_start, pool_misses_start);
199 rec.node_meta.reserve(comp.nodes.len());
200 for node in &comp.nodes {
201 rec.node_meta
202 .insert(node.id, (node.name.clone(), node.kind.clone()));
203 }
204 rec
205 }
206
207 pub(crate) fn record(
208 &mut self,
209 node_id: NodeId,
210 cache_hit: bool,
211 size: [u32; 2],
212 vram_bytes: u64,
213 ) {
214 let now = Instant::now();
215 let eval_ms = now.duration_since(self.last_event).as_secs_f64() * 1000.0;
216 self.last_event = now;
217 let (node_name, kind) = self
218 .node_meta
219 .get(&node_id)
220 .cloned()
221 .unwrap_or_else(|| (format!("Node#{}", node_id.0), "Unknown".to_owned()));
222 self.entries.push(NodeProfileEntry {
223 node_id,
224 node_name,
225 kind,
226 eval_ms,
227 cache_hit,
228 width: size[0],
229 height: size[1],
230 vram_bytes,
231 });
232 }
233
234 pub(crate) fn finish(
235 self,
236 live_vram_bytes: u64,
237 pooled_vram_bytes: u64,
238 pool_hits_now: u64,
239 pool_misses_now: u64,
240 ) -> FrameProfile {
241 let total_eval_ms = self.started_at.elapsed().as_secs_f64() * 1000.0;
242 let mut cache_hits = 0usize;
243 let mut cache_misses = 0usize;
244 for e in &self.entries {
245 if e.cache_hit {
246 cache_hits += 1;
247 } else {
248 cache_misses += 1;
249 }
250 }
251 FrameProfile {
252 entries: self.entries,
253 total_eval_ms,
254 total_vram_bytes: live_vram_bytes.saturating_add(pooled_vram_bytes),
255 live_vram_bytes,
256 pooled_vram_bytes,
257 cache_hits,
258 cache_misses,
259 pool_hits: pool_hits_now.saturating_sub(self.pool_hits_start),
260 pool_misses: pool_misses_now.saturating_sub(self.pool_misses_start),
261 }
262 }
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 fn entry(id: usize, name: &str, kind: &str, eval_ms: f64, hit: bool, bytes: u64) -> NodeProfileEntry {
270 NodeProfileEntry {
271 node_id: NodeId(id),
272 node_name: name.to_owned(),
273 kind: kind.to_owned(),
274 eval_ms,
275 cache_hit: hit,
276 width: 1920,
277 height: 1080,
278 vram_bytes: bytes,
279 }
280 }
281
282 #[test]
283 fn hot_nodes_sorts_by_duration_and_limits() {
284 let profile = FrameProfile {
285 entries: vec![
286 entry(0, "BG", "Background", 1.2, false, 8 * 1024 * 1024),
287 entry(1, "Blur1", "Blur", 14.5, false, 16 * 1024 * 1024),
288 entry(2, "Loader1", "Loader", 22.0, false, 32 * 1024 * 1024),
289 entry(3, "CC1", "ColorCorrector", 0.05, true, 8 * 1024 * 1024),
290 ],
291 total_eval_ms: 37.75,
292 total_vram_bytes: 64 * 1024 * 1024,
293 live_vram_bytes: 56 * 1024 * 1024,
294 pooled_vram_bytes: 8 * 1024 * 1024,
295 cache_hits: 1,
296 cache_misses: 3,
297 pool_hits: 3,
298 pool_misses: 1,
299 };
300
301 let top2 = profile.hot_nodes(2);
302 assert_eq!(top2.len(), 2);
303 assert_eq!(top2[0].node_name, "Loader1");
304 assert_eq!(top2[1].node_name, "Blur1");
305
306 let top_vram = profile.hot_nodes_by_vram(1);
307 assert_eq!(top_vram[0].node_name, "Loader1");
308 assert!((profile.pool_reuse_rate() - 0.75).abs() < 1e-6);
309 assert!((profile.cache_hit_rate() - 0.25).abs() < 1e-6);
310 assert!((profile.total_node_eval_ms() - 37.75).abs() < 1e-6);
311
312 let table = profile.format_top_nodes(15);
313 assert!(table.contains("Loader1"));
314 assert!(table.contains("Blur1"));
315 assert!(table.contains("reuse 75.0%"));
316 assert!(table.contains("64.0MB"));
317 }
318
319 #[test]
320 fn zero_pool_and_cache_counts_handle_division_by_zero() {
321 let profile = FrameProfile::new();
322 assert_eq!(profile.pool_reuse_rate(), 0.0);
323 assert_eq!(profile.cache_hit_rate(), 0.0);
324 let formatted = profile.format_top_nodes(15);
325 assert!(formatted.contains("no node cache evaluations recorded"));
326 }
327}