cranpose-render-wgpu 0.1.84

WGPU renderer backend for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! The fail-closed command feed and live bypass contract (sol's
//! correctness gates): a bypassed span — empty primitive range, skipped at
//! materialization because the renderer confirmed it holds the slot — must
//! NEVER be silently omitted from drawing. The frame OWNS a pinned handle
//! to the exact fallback recording it was built from, so feed disable,
//! renderer replacement, and even total ambient-registry loss all end in a
//! full same-frame rematerialization; the miss terminal is structurally
//! unreachable and survives only as a loud, counted, self-healing defense
//! against artificially orphaned frames.
//!
//! Same-position-control discipline (documented in `command_feed_parity`):
//! renders are only ever compared against renders taken from equivalent
//! renderer state, and byte-exactness is asserted only between passes whose
//! pipelines are deterministic (feed and flat detector both off, or both
//! at stable slot positions).

mod support;

use cranpose_render_common::graph::{
    CachePolicy, DrawCommandId, DrawRunNode, IsolationReasons, LayerNode, PrimitivePhase,
    ProjectiveTransform, RenderGraph, RenderNode,
};
use cranpose_render_common::raster_cache::LayerRasterCacheHashes;
use cranpose_render_common::style_shared::DrawPlacement;
use cranpose_render_common::Renderer;
use cranpose_ui_graphics::{
    Brush, Color, CommandReplayState, DrawScope, DrawScopeDefault, GraphicsLayer, Point, Rect,
};

const SIZE: u32 = 408;
const CENTER: f32 = 204.0;
const FRAMES: usize = 8;

/// One frame of the synthetic boss through the RECORDING path, identical in
/// structure to `command_feed_parity`: rings rotating at distinct speeds
/// under a breathing scale, churning sparks, recoloring twinkles, movers
/// whose count changes every frame.
fn record_frame(frame: usize) -> DrawScopeDefault {
    let mut scope =
        DrawScopeDefault::new(cranpose_ui_graphics::Size::new(SIZE as f32, SIZE as f32));
    let breathing = 1.0 - 0.0005 * frame as f32;
    scope.draw_rect_at(
        Rect {
            x: 0.0,
            y: 0.0,
            width: SIZE as f32,
            height: SIZE as f32,
        },
        Brush::solid(Color(0.02, 0.02, 0.05, 1.0)),
    );
    for m in 0..(2 + frame % 3) {
        let x = 30.0 + frame as f32 * 7.0 + m as f32 * 15.0;
        scope.draw_circle(
            Brush::solid(Color(1.0, 1.0, 1.0, 1.0)),
            Point::new(x + 4.0, 44.0 + m as f32 * 12.0),
            4.0,
        );
    }
    for (ring, (radius, band, speed)) in [
        (150.0f32, 10.0f32, 0.013f32),
        (120.0, 9.0, -0.008),
        (90.0, 8.0, 0.019),
    ]
    .into_iter()
    .enumerate()
    {
        let radius = radius * breathing;
        let band = band * breathing;
        let count = 420usize;
        let sweep = std::f32::consts::TAU / count as f32 * 0.8;
        for i in 0..count {
            let start = i as f32 * (std::f32::consts::TAU / count as f32) + speed * frame as f32;
            scope.draw_annular_sector(
                Brush::solid(Color(0.3, 0.5 + (i % 5) as f32 * 0.08, 0.8, 1.0)),
                Point::new(CENTER, CENTER),
                radius - band,
                radius,
                start,
                sweep,
            );
        }
        if ring == 1 {
            for s in 0..(30 + (frame * 13) % 25) {
                let a = s as f32 * 0.7 + frame as f32 * 0.31;
                let r = 60.0 + ((s * 17 + frame * 29) % 90) as f32;
                scope.draw_circle(
                    Brush::solid(Color(1.0, 0.6, 0.2, 0.8)),
                    Point::new(CENTER + a.cos() * r, CENTER + a.sin() * r),
                    2.5,
                );
            }
        }
    }
    for d in 0..220 {
        let angle = d as f32 * 0.285;
        let orbit = 55.0 + (d % 7) as f32 * 3.0;
        let alpha = 0.25 + 0.7 * (((d + frame * 3) % 11) as f32 / 10.0);
        scope.draw_annular_sector(
            Brush::solid(Color(0.9, 0.85, 0.4, alpha)),
            Point::new(CENTER, CENTER),
            orbit - 3.0,
            orbit + 3.0,
            angle - 0.02,
            0.04,
        );
    }
    scope
}

fn graph_for(children: Vec<RenderNode>) -> RenderGraph {
    RenderGraph::new(LayerNode {
        node_id: None,
        local_bounds: Rect {
            x: 0.0,
            y: 0.0,
            width: SIZE as f32,
            height: SIZE as f32,
        },
        transform_to_parent: ProjectiveTransform::identity(),
        content_offset: Point::default(),
        motion_context_animated: false,
        translated_content_context: false,
        translated_content_offset: Point::default(),
        scene_children_origin: Point::default(),
        scene_children_layer_translation: Point::default(),
        graphics_layer: GraphicsLayer::default(),
        clip_to_bounds: false,
        shadow_clip: None,
        hit_test: None,
        has_hit_targets: false,
        isolation: IsolationReasons::default(),
        cache_policy: CachePolicy::None,
        cache_hashes: LayerRasterCacheHashes::default(),
        cache_hashes_valid: false,
        children,
    })
}

fn command_for(node_id: usize) -> DrawCommandId {
    DrawCommandId {
        node_id,
        command_index: 0,
        placement: DrawPlacement::Behind,
    }
}

/// Records every frame through one live `CommandReplayState`, exactly as
/// the scene builder's verifier would, returning each frame's graph. Each
/// replay frame owns a pinned handle to the exact recording it was built
/// from (`fallback`), exactly as production attaches the published handle
/// in `draw_nodes` — the frame's ONLY rematerialization source; rendering
/// never consults the ambient registry.
fn build_sequence(node_id: usize, bypass: &mut dyn FnMut(u32) -> bool) -> Vec<RenderGraph> {
    let mut state = CommandReplayState::default();
    let command = command_for(node_id);
    let mut graphs = Vec::with_capacity(FRAMES);
    for frame in 0..FRAMES {
        let scope = record_frame(frame);
        let outcome = state.advance(scope.recorded());
        let center = state.center();
        let (finished, replay) = scope.finish_replay(center, outcome, bypass);
        let fallback = std::rc::Rc::new(finished.recording);
        let replay = replay.map(|mut frame| {
            frame.fallback = Some(fallback);
            Box::new(frame)
        });
        graphs.push(graph_for(vec![RenderNode::DrawRun(
            DrawRunNode::for_command_replayed(
                PrimitivePhase::BeforeChildren,
                Some(command),
                std::rc::Rc::new(finished.primitives),
                replay,
            ),
        )]));
    }
    graphs
}

fn render_sequence(renderer: &mut support::LockedRenderer, graphs: &[RenderGraph]) -> Vec<Vec<u8>> {
    graphs
        .iter()
        .enumerate()
        .map(|(frame, graph)| {
            renderer.scene_mut().graph = Some(graph.clone());
            let captured = renderer
                .capture_frame(SIZE, SIZE)
                .unwrap_or_else(|err| panic!("frame {frame} capture failed: {err:?}"));
            assert_eq!((captured.width, captured.height), (SIZE, SIZE));
            captured.pixels
        })
        .collect()
}

fn run_primitives(graphs: &[RenderGraph]) -> usize {
    graphs
        .iter()
        .map(|graph| match &graph.root.children[0] {
            RenderNode::DrawRun(run) => run.primitives.len(),
            _ => 0,
        })
        .sum()
}

fn differing_bytes(a: &[u8], b: &[u8]) -> usize {
    assert_eq!(a.len(), b.len());
    a.iter().zip(b).filter(|(a, b)| a != b).count()
}

fn channels_differing_over(a: &[u8], b: &[u8], threshold: u8) -> usize {
    assert_eq!(a.len(), b.len());
    a.iter()
        .zip(b)
        .filter(|(a, b)| a.abs_diff(**b) > threshold)
        .count()
}

/// Asserts two frames differ by at most the renderer's pass-position
/// blending noise (≤2/255, documented in `command_feed_parity`): identical
/// CONTENT through different pipeline positions. Missing content would put
/// tens of thousands of channels at diffs near 255.
fn assert_noise_only(label: &str, a: &[Vec<u8>], b: &[Vec<u8>]) {
    for (frame, (a, b)) in a.iter().zip(b).enumerate() {
        let worst = a
            .iter()
            .zip(b)
            .map(|(a, b)| a.abs_diff(*b))
            .max()
            .unwrap_or(0);
        eprintln!("{label} frame {frame}: worst {worst}");
        assert!(
            worst <= 3,
            "{label} frame {frame}: worst channel diff {worst} exceeds blending noise — \
             content differs"
        );
    }
}

fn assert_byte_exact(label: &str, a: &[Vec<u8>], b: &[Vec<u8>]) {
    for (frame, (a, b)) in a.iter().zip(b).enumerate() {
        let differing = differing_bytes(a, b);
        if differing != 0 {
            let mut worst = 0u8;
            let (mut min_x, mut min_y, mut max_x, mut max_y) = (u32::MAX, u32::MAX, 0u32, 0u32);
            for (i, (a, b)) in a.iter().zip(b).enumerate() {
                let diff = a.abs_diff(*b);
                if diff > 0 {
                    worst = worst.max(diff);
                    let pixel = (i / 4) as u32;
                    let (x, y) = (pixel % SIZE, pixel / SIZE);
                    min_x = min_x.min(x);
                    min_y = min_y.min(y);
                    max_x = max_x.max(x);
                    max_y = max_y.max(y);
                }
            }
            eprintln!(
                "{label} frame {frame}: differing {differing} worst {worst} \
                 region x {min_x}..{max_x} y {min_y}..{max_y}"
            );
        } else {
            eprintln!("{label} frame {frame}: differing 0");
        }
        assert_eq!(
            differing, 0,
            "{label} frame {frame}: {differing} bytes differ"
        );
    }
}

/// Declares the current feed generation as the build epoch, exactly as the
/// production pipeline does before every build.
fn declare_current_epoch() {
    cranpose_render_common::scene_builder::set_retained_feed_epoch(Some(
        cranpose_render_wgpu::retained_feed_generation(),
    ));
}

/// Builds the bypassed sequence against live confirmations and asserts the
/// bypass actually engaged (materialization halved), so the fail-closed
/// assertions that follow are not vacuous.
fn build_bypassed_sequence(node_id: usize, full_primitives: usize) -> Vec<RenderGraph> {
    declare_current_epoch();
    let command = command_for(node_id);
    let graphs = build_sequence(node_id, &mut |slot| {
        cranpose_render_common::scene_builder::retained_slot_confirmed(command, slot)
    });
    let bypassed_primitives = run_primitives(&graphs);
    assert!(
        bypassed_primitives < full_primitives / 2,
        "confirmed slots should have bypassed materialization \
         ({bypassed_primitives} of {full_primitives} still materialized)"
    );
    graphs
}

/// T2: graphs built WITH bypass (confirmations live) must render complete
/// after the feed is disabled — the fail-closed walk rebuilds every
/// bypassed span from its recording, byte-identical to a never-bypassed
/// control through the pure ordinary pipeline.
#[test]
fn feed_disabled_after_build_rematerializes_bypassed_spans() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping fail-closed feed-disable: headless WGPU init failed: {err}");
            return;
        }
    };
    std::env::set_var("CRANPOSE_ARC_MESH", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");

    // Warm: captures land and slots are confirmed.
    let graphs = build_sequence(31, &mut |_| false);
    let _ = render_sequence(&mut renderer, &graphs);
    let bypassed_graphs = build_bypassed_sequence(31, run_primitives(&graphs));

    // Flip the feed (and the flat detector) off: from here both passes are
    // deterministic CPU emission with no retention state at all. One warm
    // pass absorbs the pass-position transition (same-position-control
    // discipline, see `command_feed_parity`) before anything is compared.
    std::env::set_var("CRANPOSE_COMMAND_FEED", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "0");
    let _ = render_sequence(&mut renderer, &graphs);
    let control = render_sequence(&mut renderer, &graphs);
    let rematerialized = render_sequence(&mut renderer, &bypassed_graphs);
    std::env::remove_var("CRANPOSE_COMMAND_FEED");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
    std::env::remove_var("CRANPOSE_ARC_MESH");

    let (_, _, remat_misses) = cranpose_render_wgpu::command_feed_live_stats();
    assert_eq!(
        remat_misses, 0,
        "every bypassed span must have rebuilt from its frame's own recording"
    );
    assert_byte_exact("feed-disabled-vs-control", &control, &rematerialized);
}

/// T3: replacing the GPU renderer under live confirmations (surface
/// recreation semantics) must revoke every confirmation and bump the feed
/// generation BEFORE the new renderer exists; in-flight bypassed graphs
/// rematerialize completely, and after one rebuild the fed output is
/// byte-identical to a control render.
#[test]
fn renderer_swap_revokes_confirmations_and_rematerializes() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping fail-closed renderer swap: headless WGPU init failed: {err}");
            return;
        }
    };
    std::env::set_var("CRANPOSE_ARC_MESH", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");
    let command = command_for(32);

    let graphs = build_sequence(32, &mut |_| false);
    let _ = render_sequence(&mut renderer, &graphs);
    let bypassed_graphs = build_bypassed_sequence(32, run_primitives(&graphs));

    // The swap: same replacement path Android's surface recreation takes.
    let generation_before = cranpose_render_wgpu::retained_feed_generation();
    support::reinit_gpu(&mut renderer).expect("GPU reinit failed");
    assert_eq!(
        cranpose_render_wgpu::retained_feed_generation(),
        generation_before + 1,
        "renderer replacement must move the feed to a fresh generation"
    );
    let (feed_slots, _, _) = cranpose_render_wgpu::command_feed_live_stats();
    assert_eq!(feed_slots, 0, "the old renderer's feed slots must be gone");
    declare_current_epoch();
    for slot in 0..32 {
        assert!(
            !cranpose_render_common::scene_builder::retained_slot_confirmed(command, slot),
            "slot {slot} still confirmed after the swap"
        );
    }

    // The in-flight frame: a bypassed graph rendered on the NEW renderer
    // without rebuilding. Every bypassed span must rematerialize from the
    // recording its frame owns — byte-identical to the pure ordinary
    // pipeline.
    let last = FRAMES - 1;
    let remat_frame = render_sequence(&mut renderer, &bypassed_graphs[last..]);
    let (_, _, remat_misses) = cranpose_render_wgpu::command_feed_live_stats();
    assert_eq!(
        remat_misses, 0,
        "the frames own their recordings; no span may terminal-miss"
    );
    // The remat frame is by definition a first-pass-at-position render (the
    // in-flight frame right after the swap), so it is compared under the
    // blending-noise envelope, not byte-exactly; T2 proves byte-exactness
    // of the rematerialization walk from stable positions.
    std::env::set_var("CRANPOSE_COMMAND_FEED", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "0");
    let ordinary_frame = render_sequence(&mut renderer, &graphs[last..]);
    assert_noise_only("swap-remat-vs-ordinary", &ordinary_frame, &remat_frame);

    // Heal: a full fed pass re-earns slots and confirmations on the new
    // renderer, and one rebuild later bypass output is byte-identical to a
    // same-position fed control.
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    let _ = render_sequence(&mut renderer, &bypassed_graphs);
    let (feed_slots, _, remat_misses) = cranpose_render_wgpu::command_feed_live_stats();
    assert!(
        feed_slots >= 4,
        "the new renderer must have re-earned feed slots, got {feed_slots}"
    );
    assert_eq!(remat_misses, 0);
    let rebuilt_graphs = build_bypassed_sequence(32, run_primitives(&graphs));
    // Same-position-control discipline: one warm pass, then the compared
    // control and bypassed passes render from stable renderer state.
    let _ = render_sequence(&mut renderer, &graphs);
    let control = render_sequence(&mut renderer, &graphs);
    let rebuilt = render_sequence(&mut renderer, &rebuilt_graphs);
    std::env::remove_var("CRANPOSE_COMMAND_FEED");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
    std::env::remove_var("CRANPOSE_ARC_MESH");
    assert_byte_exact("post-swap-rebuild-vs-control", &control, &rebuilt);
}

/// T4, reshaped to the categorical property the frame-owned fallback buys:
/// destroying every AMBIENT rematerialization source — all registry
/// recordings cleared AND the renderer (with every retained slot) replaced
/// — no longer causes a miss at all. Every bypassed span rebuilds in the
/// same frame from the recording its frame owns, and the frame renders
/// complete.
#[test]
fn registry_loss_no_longer_reaches_the_miss_terminal() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping fail-closed registry loss: headless WGPU init failed: {err}");
            return;
        }
    };
    std::env::set_var("CRANPOSE_ARC_MESH", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");

    let graphs = build_sequence(33, &mut |_| false);
    let _ = render_sequence(&mut renderer, &graphs);
    let bypassed_graphs = build_bypassed_sequence(33, run_primitives(&graphs));

    // What used to drive the terminal: the ambient recordings and (via the
    // swap) the retained slots are all gone. The frames' own handles are
    // untouched by construction.
    cranpose_render_common::scene_builder::clear_command_recordings_for_tests();
    support::reinit_gpu(&mut renderer).expect("GPU reinit failed");

    let last = FRAMES - 1;
    let remat_frame = render_sequence(&mut renderer, &bypassed_graphs[last..]);
    let (_, _, remat_misses) = cranpose_render_wgpu::command_feed_live_stats();
    assert_eq!(
        remat_misses, 0,
        "the frame-owned fallback must serve every bypassed span; registry \
         loss may no longer reach the terminal"
    );

    // Complete content: the pure ordinary pipeline is the reference. The
    // remat frame is a first-pass-at-position render (right after the
    // swap), so it is compared under the blending-noise envelope; T2 proves
    // byte-exactness of the walk from stable positions.
    std::env::set_var("CRANPOSE_COMMAND_FEED", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "0");
    let ordinary_frame = render_sequence(&mut renderer, &graphs[last..]);
    std::env::remove_var("CRANPOSE_COMMAND_FEED");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
    std::env::remove_var("CRANPOSE_ARC_MESH");
    assert_noise_only("registry-loss-vs-ordinary", &ordinary_frame, &remat_frame);
}

/// T4's defensive remainder: the terminal itself, reachable only by
/// artificially orphaning a frame (stripping the fallback the builder
/// always attaches). It must stay loud, counted, revoking, and
/// self-healing at the next build — the last line of defense behind the
/// structural guarantee.
#[test]
fn orphaned_frame_terminal_counts_revokes_and_self_heals() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping fail-closed orphaned frame: headless WGPU init failed: {err}");
            return;
        }
    };
    std::env::set_var("CRANPOSE_ARC_MESH", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");
    let command = command_for(35);

    let graphs = build_sequence(35, &mut |_| false);
    let _ = render_sequence(&mut renderer, &graphs);
    let bypassed_graphs = build_bypassed_sequence(35, run_primitives(&graphs));

    // The artificial orphan: no frame the builder produces lacks its
    // fallback, so construct the impossible state by hand, then kill the
    // remaining draw sources (registry recordings, and the retained slots
    // via the swap).
    let last = FRAMES - 1;
    let mut orphaned = bypassed_graphs[last].clone();
    {
        let RenderNode::DrawRun(run) = &mut orphaned.root.children[0] else {
            panic!("expected draw run");
        };
        let frame = run
            .replay
            .as_mut()
            .expect("the bypassed graph carries a replay frame");
        assert!(
            frame.fallback.is_some(),
            "the build path must have attached the frame's fallback"
        );
        frame.fallback = None;
    }
    cranpose_render_common::scene_builder::clear_command_recordings_for_tests();
    support::reinit_gpu(&mut renderer).expect("GPU reinit failed");

    renderer.scene_mut().graph = Some(orphaned);
    let missing_frame = renderer
        .capture_frame(SIZE, SIZE)
        .expect("the terminal must not panic or fail the frame");
    let (_, _, remat_misses) = cranpose_render_wgpu::command_feed_live_stats();
    assert!(
        remat_misses > 0,
        "an orphaned frame's bypassed spans must reach the miss terminal"
    );
    declare_current_epoch();
    for slot in 0..32 {
        assert!(
            !cranpose_render_common::scene_builder::retained_slot_confirmed(command, slot),
            "slot {slot} must be revoked after its miss"
        );
    }

    // Non-vacuity + self-heal, both against the pure ordinary pipeline: the
    // miss frame is missing its rings; the next build (nothing confirmed,
    // so nothing bypasses) renders byte-identical to control. One warm
    // pass absorbs the pass-position transition before comparing.
    std::env::set_var("CRANPOSE_COMMAND_FEED", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "0");
    let _ = render_sequence(&mut renderer, &graphs[last..]);
    let control = render_sequence(&mut renderer, &graphs[last..]);
    // Missing rings put many channels far beyond blending noise (≤2/255).
    let missing_differs = channels_differing_over(&control[0], &missing_frame.pixels, 60);
    assert!(
        missing_differs > 10_000,
        "the miss frame should visibly lack the bypassed rings \
         ({missing_differs} channels differ by more than 60)"
    );
    let healed_graphs = build_sequence(35, &mut |slot| {
        cranpose_render_common::scene_builder::retained_slot_confirmed(command, slot)
    });
    assert_eq!(
        run_primitives(&healed_graphs),
        run_primitives(&graphs),
        "with every confirmation revoked the next build must materialize fully"
    );
    let healed = render_sequence(&mut renderer, &healed_graphs[last..]);
    std::env::remove_var("CRANPOSE_COMMAND_FEED");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
    std::env::remove_var("CRANPOSE_ARC_MESH");
    assert_byte_exact("self-heal-vs-control", &control, &healed);
}

/// 5b/7a: a replay-ops batch stamped with a LOWER feed generation than the
/// store's must be dropped whole — empty ack, nothing captured, nothing
/// confirmed, no GPU slot allocated. (A HIGHER generation adopts forward
/// instead; see `higher_generation_replay_ops_adopt_forward`.)
/// Synchronously impossible through the public render path today, so the
/// roundtrip hook skews the batch's stamp below the store's own generation.
#[test]
fn mismatched_generation_replay_ops_drop_whole() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping fail-closed generation mismatch: headless WGPU init failed: {err}");
            return;
        }
    };
    // Move the store's generation off zero (the swap bumps the producer
    // generation and the new store adopts it), so `store - 1` below cannot
    // wrap to u64::MAX and read as a higher generation.
    support::reinit_gpu(&mut renderer).expect("GPU reinit failed");
    let command = command_for(36);
    cranpose_render_wgpu::inject_feed_capture_for_tests(command, 0, 0, 4);
    let confirmed = renderer.replay_ops_roundtrip_for_tests(u64::MAX);
    assert_eq!(
        confirmed, 0,
        "a stale-generation batch must confirm nothing"
    );
    assert_eq!(
        cranpose_render_wgpu::pending_feed_capture_count_for_tests(),
        0,
        "the batch is consumed whole, never requeued"
    );
    let (_, live_slots) = renderer.replay_slot_mesh_stats();
    assert_eq!(
        live_slots, 0,
        "no GPU slot may be captured from a dropped batch"
    );
    let (feed_slots, _, _) = cranpose_render_wgpu::command_feed_live_stats();
    assert_eq!(
        feed_slots, 0,
        "a dropped capture must never become a feed slot"
    );
    declare_current_epoch();
    assert!(
        !cranpose_render_common::scene_builder::retained_slot_confirmed(command, 0),
        "a dropped capture must never confirm its slot"
    );
}

/// 7a §5: a replay-ops batch stamped with a HIGHER generation than the
/// store's is the new universe arriving, not a stale one — a producer-side
/// bump (root-scale change retiring the feed) delivers the retirement
/// releases THROUGH that very batch. The store must adopt the generation
/// and serve the batch: no generation drop, and the feed re-earns slots
/// under the adopted generation on the frames that follow.
#[test]
fn higher_generation_replay_ops_adopt_forward() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping adopt-forward: headless WGPU init failed: {err}");
            return;
        }
    };
    std::env::set_var("CRANPOSE_ARC_MESH", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");

    // Warm at scale 1.0: captures land, slots confirm.
    let graphs = build_sequence(37, &mut |_| false);
    let _ = render_sequence(&mut renderer, &graphs);
    let (feed_slots, _, _) = cranpose_render_wgpu::command_feed_live_stats();
    if feed_slots == 0 {
        eprintln!("skipping adopt-forward: device has no retained replay support");
        std::env::remove_var("CRANPOSE_COMMAND_FEED");
        std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
        std::env::remove_var("CRANPOSE_ARC_MESH");
        return;
    }
    let drops_before = renderer.replay_generation_drops_for_tests();
    let generation_before = cranpose_render_wgpu::retained_feed_generation();

    // The bump: a root-scale change retires the feed at collection start —
    // the producer generation moves to +1 and every retired slot's release
    // travels in the SAME frame's ops batch, which therefore arrives at the
    // store stamped one generation ahead of the store's own.
    renderer.scene_mut().graph = Some(graphs[0].clone());
    renderer
        .capture_frame_with_scale(SIZE, SIZE, 2.0)
        .expect("scale-change frame failed");
    assert_eq!(
        cranpose_render_wgpu::retained_feed_generation(),
        generation_before + 1,
        "the scale change must have retired the feed to a fresh generation"
    );
    assert_eq!(
        renderer.replay_generation_drops_for_tests(),
        drops_before,
        "a higher-generation batch must be adopted and served, never dropped"
    );

    // Served, not just tolerated: under the adopted generation the feed
    // re-earns confirmed slots across the following frames — impossible if
    // the store were dropping every batch of the new generation.
    for graph in &graphs {
        renderer.scene_mut().graph = Some(graph.clone());
        renderer
            .capture_frame_with_scale(SIZE, SIZE, 2.0)
            .expect("post-adopt frame failed");
    }
    let (feed_slots_after, _, _) = cranpose_render_wgpu::command_feed_live_stats();
    std::env::remove_var("CRANPOSE_COMMAND_FEED");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
    std::env::remove_var("CRANPOSE_ARC_MESH");
    assert!(
        feed_slots_after > 0,
        "the feed must re-earn slots under the adopted generation"
    );
    assert_eq!(
        renderer.replay_generation_drops_for_tests(),
        drops_before,
        "no batch of the adopted generation may count a generation drop"
    );
}

/// 7a: a CANCELLED packet whose replay plan carries real feed releases
/// (here: a whole feed retirement from a root-scale change) must hand
/// those releases back to the planner for re-queue — the pool is 128 ids
/// and a dropped batch would leak them forever. The store's slots stay
/// live until a LATER frame's batch actually serves the releases.
#[test]
fn cancelled_packet_requeues_feed_releases() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping cancelled-release requeue: headless WGPU init failed: {err}");
            return;
        }
    };
    std::env::set_var("CRANPOSE_ARC_MESH", "0");
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "1");
    std::env::set_var("CRANPOSE_COMMAND_FEED", "1");

    // Warm at scale 1.0 so the feed holds live, confirmed slots.
    let graphs = build_sequence(38, &mut |_| false);
    let _ = render_sequence(&mut renderer, &graphs);
    let (feed_slots, _, _) = cranpose_render_wgpu::command_feed_live_stats();
    if feed_slots == 0 {
        eprintln!("skipping cancelled-release requeue: device has no retained replay support");
        std::env::remove_var("CRANPOSE_COMMAND_FEED");
        std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
        std::env::remove_var("CRANPOSE_ARC_MESH");
        return;
    }
    let (_, live_before) = renderer.replay_slot_mesh_stats();
    let drops_before = renderer.replay_generation_drops_for_tests();

    // A scale change retires the feed at collection start: every live
    // slot's release rides THIS packet's ops batch.
    renderer.set_root_scale(2.0);
    renderer.scene_mut().graph = Some(graphs[0].clone());
    let packet = renderer
        .build_frame_packet_for_tests(SIZE, SIZE)
        .expect("scale-change packet must build");
    let (queued, _) = cranpose_render_wgpu::planner_replay_queue_stats_for_tests();
    assert_eq!(queued, 0, "the packet's plan must have taken the releases");

    // The packet never reaches the store: cancelled for its surface epoch.
    renderer.note_surface_reconfigured();
    let device = renderer
        .try_device()
        .expect("renderer GPU device was not initialized");
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("Cancelled Release Requeue Target"),
        size: wgpu::Extent3d {
            width: SIZE,
            height: SIZE,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Bgra8UnormSrgb,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        view_formats: &[],
    });
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    let outcome = renderer
        .render_held_packet_for_tests(&view, SIZE, SIZE, packet)
        .expect("a cancel is a protocol outcome, not a draw error");
    assert_eq!(
        outcome,
        cranpose_render_wgpu::PresentOutcome::Cancelled(
            cranpose_render_wgpu::CancelReason::SurfaceEpoch
        )
    );

    // THE slot-leak fix: the cancelled batch's releases are back in the
    // planner queue, and the store still holds every slot (nothing of the
    // cancelled batch reached it).
    let (requeued, _) = cranpose_render_wgpu::planner_replay_queue_stats_for_tests();
    assert!(
        requeued >= feed_slots,
        "the cancelled retirement releases must re-queue whole \
         ({requeued} queued, {feed_slots} retired slots)"
    );
    assert_eq!(
        renderer.replay_slot_mesh_stats().1,
        live_before,
        "a cancelled packet must not free store slots"
    );

    // A later frame's batch serves them: queue drains, no generation drop
    // (the bumped generation adopts forward), and the slot ids return to
    // the pool for reuse rather than leaking.
    renderer.scene_mut().graph = Some(graphs[0].clone());
    renderer
        .capture_frame(SIZE, SIZE)
        .expect("post-cancel frame failed");
    let (queued_after, _) = cranpose_render_wgpu::planner_replay_queue_stats_for_tests();
    assert_eq!(
        queued_after, 0,
        "the next frame's batch must carry the re-queued releases"
    );
    assert_eq!(
        renderer.replay_generation_drops_for_tests(),
        drops_before,
        "serving the re-queued releases must not count a generation drop"
    );
    std::env::remove_var("CRANPOSE_COMMAND_FEED");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");
    std::env::remove_var("CRANPOSE_ARC_MESH");
}

/// T5: a feed capture that outlives the frame it was queued on (aborted
/// collection) must be dropped at the drain — never captured against
/// another frame's shapes, never confirmed. (That `retire_all` also clears
/// the queue is unit-tested in `shape_replay`.)
#[test]
fn stale_feed_captures_are_dropped_at_the_drain() {
    let mut renderer = match support::headless_renderer() {
        Ok(renderer) => renderer,
        Err(err) => {
            eprintln!("skipping fail-closed stale capture: headless WGPU init failed: {err}");
            return;
        }
    };
    // The flat detector stays out so the injected capture is the only
    // replay-adjacent state in play.
    std::env::set_var("CRANPOSE_SIMILARITY_REPLAY", "0");
    let command = command_for(34);

    // A plain (non-replayed) scene with far more shapes than the injected
    // capture asks for: without the frame stamp, the drain WOULD capture
    // shapes 0..64 of the wrong frame and confirm the slot.
    let finished = record_frame(0).finish();
    assert!(finished.primitives.len() > 128);
    let graph = graph_for(vec![RenderNode::DrawRun(
        DrawRunNode::for_command_replayed(
            PrimitivePhase::BeforeChildren,
            Some(command),
            std::rc::Rc::new(finished.primitives),
            None,
        ),
    )]);
    renderer.scene_mut().graph = Some(graph.clone());
    renderer
        .capture_frame(SIZE, SIZE)
        .expect("warm frame failed");

    cranpose_render_wgpu::inject_feed_capture_for_tests(command, 0, 0, 64);
    assert_eq!(
        cranpose_render_wgpu::pending_feed_capture_count_for_tests(),
        1
    );
    renderer
        .capture_frame(SIZE, SIZE)
        .expect("drain frame failed");
    std::env::remove_var("CRANPOSE_SIMILARITY_REPLAY");

    assert_eq!(
        cranpose_render_wgpu::pending_feed_capture_count_for_tests(),
        0,
        "the drain must consume the stale capture"
    );
    let (feed_slots, _, _) = cranpose_render_wgpu::command_feed_live_stats();
    assert_eq!(
        feed_slots, 0,
        "a stale capture must never become a live feed slot"
    );
    declare_current_epoch();
    assert!(
        !cranpose_render_common::scene_builder::retained_slot_confirmed(command, 0),
        "a stale capture must never confirm its slot"
    );
}