euv-performance 0.51.0

Reproducible CPU, layout, rasterization, and allocation benchmarks for the cross-platform euv runtime.
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
use super::*;

/// Evaluates `AdaptiveExecutionRouter` across `AB_ROUTER_WARMUP_STEPS` steady frames and returns the settled `ExecutionLane`.
///
/// # Arguments
///
/// - `ExecutionWorkloadFeatures` - Workload descriptor fed to the online cost model.
///
/// # Returns
///
/// - `ExecutionLane` - Active lane settled after streak and dwell thresholds.
#[must_use]
fn evaluate_router_lane(workload: ExecutionWorkloadFeatures) -> ExecutionLane {
    let mut router: AdaptiveExecutionRouter = AdaptiveExecutionRouter::default();
    let mut active_lane: ExecutionLane = router.get_active_lane();
    for step_idx in 0..AB_ROUTER_WARMUP_STEPS {
        let now_ms: u64 = ((step_idx as u64).saturating_add(1)).saturating_mul(AB_ROUTER_STEP_MS);
        let decision: ExecutionRouterDecision = router.evaluate(workload, now_ms);
        active_lane = decision.get_active_lane();
    }
    active_lane
}

/// Builds a flat BFS `GpuComputeSceneInput` with `child_count` items under one root container for `mode`.
///
/// # Arguments
///
/// - `GpuLayoutMode` - Root layout algorithm (`Grid`, `FlexRow`, `FlexColumn`, `DataViz`, or `Spring`).
/// - `usize` - Number of direct child nodes under the root container.
/// - `f32` - Grid column count when `mode == GpuLayoutMode::Grid`.
/// - `f32` - Physical viewport width in pixels.
/// - `f32` - Physical viewport height in pixels.
///
/// # Returns
///
/// - `GpuComputeSceneInput` - Populated compute layout input scene ready for Metal hardware dispatch.
#[must_use]
fn build_parallel_ab_compute_scene(
    mode: GpuLayoutMode,
    child_count: usize,
    grid_cols: f32,
    viewport_width: f32,
    viewport_height: f32,
) -> GpuComputeSceneInput {
    let total_nodes: usize = child_count.saturating_add(1);
    let mut nodes: Vec<GpuLayoutNodeInput> = Vec::with_capacity(total_nodes);
    let mut visuals: Vec<GpuVisualStyleInput> = Vec::with_capacity(total_nodes);
    let root_flags: u32 = pack_gpu_layout_flags(
        mode,
        GpuJustifyMode::Start,
        GpuAlignMode::Start,
        true,
        true,
        true,
    );
    let mut root_node: GpuLayoutNodeInput = GpuLayoutNodeInput::default();
    root_node
        .set_parent_bfs(GPU_LAYOUT_NO_PARENT)
        .set_first_child(1)
        .set_child_count(child_count as u32)
        .set_flags_kind(root_flags)
        .set_pref_min_size([viewport_width, viewport_height, 0.0, 0.0])
        .set_pad_gap_flex([8.0, 8.0, 4.0, 4.0])
        .set_extra_or_intrinsic([grid_cols, 0.0, 0.0, 0.0]);
    nodes.push(root_node);
    let mut root_vis: GpuVisualStyleInput = GpuVisualStyleInput::default();
    root_vis
        .set_color_rgba(GpuPrimitiveInstance::pack_color_rgba8(Color::rgb(
            18, 24, 38,
        )))
        .set_uv_rect([0, 0, u16::MAX, u16::MAX])
        .set_radii_border([GpuPrimitiveInstance::pack_u16_q4(6.0); 4])
        .set_kind_flags(GpuPrimitiveInstance::pack_kind_flags(
            PrimKind::RoundedRect,
            0,
            0,
            0,
        ))
        .set_clip_ancestor_bfs(GPU_LAYOUT_NO_PARENT)
        .set_opacity_q16(u16::MAX as u32);
    visuals.push(root_vis);
    let child_mode: GpuLayoutMode = match mode {
        GpuLayoutMode::DataViz => GpuLayoutMode::DataViz,
        GpuLayoutMode::Spring => GpuLayoutMode::Spring,
        _ => GpuLayoutMode::Block,
    };
    let child_flags: u32 = pack_gpu_layout_flags(
        child_mode,
        GpuJustifyMode::Start,
        GpuAlignMode::Start,
        true,
        true,
        true,
    );
    let cell_kind_flags: u32 =
        GpuPrimitiveInstance::pack_kind_flags(PrimKind::RoundedRect, 0, 0, 0);
    let cell_radii: [u16; 4] = [GpuPrimitiveInstance::pack_u16_q4(4.0); 4];
    for child_idx in 0..child_count {
        let mut node: GpuLayoutNodeInput = GpuLayoutNodeInput::default();
        node.set_parent_bfs(0)
            .set_first_child(0)
            .set_child_count(0)
            .set_flags_kind(child_flags);
        match mode {
            GpuLayoutMode::Spring => {
                let col: f32 = (child_idx % 200) as f32;
                let row: f32 = (child_idx / 200) as f32;
                let cur_x: f32 = (col * 6.0) % 1260.0;
                let cur_y: f32 = (row * 4.0) % 780.0;
                node.set_pref_min_size([cur_x + 12.0, cur_y + 8.0, 5.0, 3.0])
                    .set_pad_gap_flex([160.0, 16.0, 0.0, 0.0])
                    .set_extra_or_intrinsic([cur_x, cur_y, 1.0, 0.0]);
            }
            GpuLayoutMode::DataViz => {
                node.set_pref_min_size([8.0, 16.0, 0.0, 0.0])
                    .set_pad_gap_flex([0.0, 0.0, 0.0, 0.0])
                    .set_extra_or_intrinsic([
                        ((child_idx + 1) as f32) / (child_count.max(1) as f32),
                        0.0,
                        0.0,
                        0.0,
                    ]);
            }
            _ => {
                if grid_cols >= 64.0 {
                    node.set_pref_min_size([6.0, 5.0, 4.0, 4.0])
                        .set_pad_gap_flex([1.0, 1.0, 0.0, 1.0])
                        .set_extra_or_intrinsic([0.0, 0.0, 6.0, 5.0]);
                } else {
                    node.set_pref_min_size([48.0, 24.0, 16.0, 16.0])
                        .set_pad_gap_flex([2.0, 2.0, 0.0, 1.0])
                        .set_extra_or_intrinsic([0.0, 0.0, 48.0, 24.0]);
                }
            }
        }
        nodes.push(node);
        let mut vis: GpuVisualStyleInput = GpuVisualStyleInput::default();
        vis.set_color_rgba(GpuPrimitiveInstance::pack_color_rgba8(Color::rgb(
            36 + ((child_idx * 13) % 180) as u8,
            116,
            224,
        )))
        .set_uv_rect([0, 0, u16::MAX, u16::MAX])
        .set_radii_border(cell_radii)
        .set_kind_flags(cell_kind_flags)
        .set_clip_ancestor_bfs(GPU_LAYOUT_NO_PARENT)
        .set_opacity_q16(u16::MAX as u32);
        visuals.push(vis);
    }
    let mut scene: GpuComputeSceneInput = GpuComputeSceneInput::default();
    scene
        .set_nodes(nodes)
        .set_visuals(visuals)
        .set_level_offsets(vec![0, 1, total_nodes as u32])
        .set_viewport_size([viewport_width, viewport_height])
        .set_root_boundary_rect([0.0, 0.0, viewport_width, viewport_height])
        .set_dt_secs(1.0 / 120.0)
        .set_clear_color(Color::rgb(10, 14, 24));
    scene
}

/// Builds a `SceneTree` with `card_count` nested card rows (each containing a header and wrapping text body) for CPU serial vs parallel reflow benchmarks.
///
/// # Arguments
///
/// - `usize` - Number of card containers to populate beneath the root column.
/// - `bool` - When `true`, assigns mixed ASCII+CJK wrapping paragraphs to exercise text shaping and line breaking.
///
/// # Returns
///
/// - `(SceneTree, NodeId)` - Built retained scene tree paired with the last leaf text `NodeId`.
#[must_use]
fn build_parallel_ab_card_tree(card_count: usize, heavy_text: bool) -> (SceneTree, NodeId) {
    let mut tree: SceneTree = SceneTree::default();
    let root: NodeId = tree.get_root();
    let mut root_style: Style = Style::default().column();
    root_style
        .get_mut_layout()
        .set_width(Length::Percent(100.0));
    root_style.get_mut_layout().set_row_gap(4.0);
    tree.set_style(root, root_style);
    let mut card_style: Style = Style::default().column();
    card_style
        .get_mut_layout()
        .set_width(Length::Percent(100.0));
    card_style.get_mut_layout().set_padding(Edges::all(8.0));
    card_style
        .get_mut_paint()
        .set_background(Some(Color::rgb(24, 30, 44)));
    let mut body_style: Style = Style::default();
    body_style
        .get_mut_layout()
        .set_width(Length::Percent(100.0));
    body_style.get_mut_text().set_font_size(13.0);
    body_style.get_mut_text().set_overflow(TextOverflow::Wrap);
    let mut last_leaf: NodeId = root;
    for card_idx in 0..card_count {
        let card: NodeId = tree.create_view(card_style);
        tree.append_child(root, card);
        let content: String = if heavy_text {
            format!("{AB_CARD_PREFIX_LABEL} #{card_idx}: {AB_MIXED_TEXT_COPY}")
        } else {
            format!("{AB_CARD_PREFIX_LABEL} #{card_idx}")
        };
        let leaf: NodeId = tree.create_text(content, body_style);
        tree.append_child(card, leaf);
        last_leaf = leaf;
    }
    (tree, last_leaf)
}

/// Computes the maximum absolute bounding-box difference in pixels between two slices of `LayoutBox`.
///
/// # Arguments
///
/// - `&[LayoutBox]` - First resolved layout box slice.
/// - `&[LayoutBox]` - Second resolved layout box slice.
///
/// # Returns
///
/// - `f32` - Maximum absolute coordinate or dimension error in pixels.
#[must_use]
fn max_layout_box_slice_error(first: &[LayoutBox], second: &[LayoutBox]) -> f32 {
    let mut max_err: f32 = 0.0;
    for (left, right) in first.iter().zip(second.iter()) {
        let lb: Rect = left.get_bounds();
        let rb: Rect = right.get_bounds();
        max_err = max_err
            .max((lb.get_x() - rb.get_x()).abs())
            .max((lb.get_y() - rb.get_y()).abs())
            .max((lb.get_width() - rb.get_width()).abs())
            .max((lb.get_height() - rb.get_height()).abs());
    }
    max_err
}

/// Runs AB-1: sparse 2,000-node reactive single-leaf mutation (`CpuSerial` `SplitLayoutCache` vs `GpuCompute` + `AdaptiveExecutionRouter`).
///
/// # Arguments
///
/// - `&mut GpuComputeLayoutEngine` - Active hardware Metal or CPU-reference compute engine.
/// - `usize` - Host worker thread count.
/// - `usize` - Number of timed iterations per arm.
///
/// # Returns
///
/// - `ParallelAbCaseResult` - Measured AB-1 comparison metrics and gate verdict.
#[must_use]
pub fn run_parallel_ab1_sparse_reactive(
    gpu_engine: &mut GpuComputeLayoutEngine,
    worker_threads: usize,
    iterations: usize,
) -> ParallelAbCaseResult {
    let iters: usize = iterations.max(4);
    let (mut tree, leaf_node): (SceneTree, NodeId) =
        build_parallel_ab_card_tree(AB_SPARSE_NODE_COUNT / 2, false);
    let viewport: Size = Size::new(1280.0, 800.0);
    let mut layout_engine: LayoutEngine = LayoutEngine::default();
    let _: LayoutStats = layout_engine.compute_serial(&mut tree, viewport);
    let mut steady_allocs: usize = usize::MAX;
    let start_serial: Instant = Instant::now();
    for iter_idx in 0..iters {
        let next_text: &str = if iter_idx % 2 == 0 {
            AB_SPARSE_LEAF_A
        } else {
            AB_SPARSE_LEAF_B
        };
        let (_, snap): (LayoutStats, AllocationSnapshot) = measure_allocations(|| {
            tree.set_text_str(leaf_node, next_text);
            layout_engine.compute_serial(&mut tree, viewport)
        });
        if iter_idx > 0 {
            steady_allocs = steady_allocs.min(snap.get_alloc_count() as usize);
        }
    }
    if steady_allocs == usize::MAX {
        steady_allocs = 0;
    }
    let serial_us: f64 = (start_serial.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let gpu_scene: GpuComputeSceneInput = build_parallel_ab_compute_scene(
        GpuLayoutMode::Grid,
        AB_SPARSE_NODE_COUNT,
        8.0,
        1280.0,
        800.0,
    );
    let _: GpuComputeDispatchResult = gpu_engine.dispatch(&gpu_scene, true);
    let mut gpu_exec_ns: u64 = 0;
    let mut draw_calls: usize = 0;
    let start_gpu: Instant = Instant::now();
    for _ in 0..iters {
        let res: GpuComputeDispatchResult =
            gpu_engine.dispatch_steady_indirect(&gpu_scene, true, false);
        gpu_exec_ns = res
            .get_gpu_compute_ns()
            .saturating_add(res.get_gpu_render_ns());
        draw_calls = res.get_draw_calls();
    }
    let gpu_us: f64 = (start_gpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
    workload
        .set_dirty_nodes(1)
        .set_visible_nodes(AB_SPARSE_NODE_COUNT)
        .set_tree_depth(3)
        .set_gpu_eligible_nodes(0)
        .set_cpu_chrome_nodes(1)
        .set_dirty_upload_bytes(64)
        .set_wrapping_text_ratio(0.5)
        .set_worker_threads(worker_threads)
        .set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
        .set_thermal_throttled(false);
    let router_lane: ExecutionLane = evaluate_router_lane(workload);
    let speedup_ratio: f64 = if serial_us > 0.0 {
        gpu_us / serial_us
    } else {
        0.0
    };
    let hw_ready: bool = gpu_engine.is_hardware_compute_ready();
    let gpu_verified: bool = !hw_ready || (gpu_exec_ns > 0 && draw_calls > 0 && serial_us < gpu_us);
    let passed: bool =
        router_lane == ExecutionLane::CpuSerial && steady_allocs == 0 && gpu_verified;
    ParallelAbCaseResult {
        name: PARALLEL_AB1_NAME.to_string(),
        arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
        arm_b_label: AB_ARM_GPU_COMPUTE.to_string(),
        arm_a_us: serial_us,
        arm_b_us: gpu_us,
        speedup_ratio,
        gpu_exec_ns,
        draw_calls,
        max_error_px: 0.0,
        upload_savings_ratio: 0.0,
        steady_state_allocs: steady_allocs,
        router_selected_lane: format!("{router_lane:?}"),
        passed,
    }
}

/// Runs AB-2: heavy 2,500-card mixed ASCII+CJK text-wrap reflow comparing `CpuSerial` vs `CpuParallel+SIMD`.
///
/// # Arguments
///
/// - `bool` - Whether hardware GPU compute is available on this host.
/// - `usize` - Host worker thread count.
/// - `usize` - Number of resize iterations per arm.
///
/// # Returns
///
/// - `ParallelAbCaseResult` - Measured AB-2 speedup, parity error, and router decision.
#[must_use]
pub fn run_parallel_ab2_heavy_text_reflow(
    gpu_ready: bool,
    worker_threads: usize,
    iterations: usize,
) -> ParallelAbCaseResult {
    let iters: usize = iterations.max(4);
    let (mut serial_tree, _): (SceneTree, NodeId) =
        build_parallel_ab_card_tree(AB_TEXT_CARD_COUNT, true);
    let (mut parallel_tree, _): (SceneTree, NodeId) =
        build_parallel_ab_card_tree(AB_TEXT_CARD_COUNT, true);
    let mut serial_engine: LayoutEngine = LayoutEngine::default();
    let mut parallel_engine: LayoutEngine = LayoutEngine::default();
    let _: LayoutStats = serial_engine.compute_serial(&mut serial_tree, Size::new(1280.0, 800.0));
    let _: LayoutStats =
        parallel_engine.compute_parallel(&mut parallel_tree, Size::new(1280.0, 800.0));
    let start_serial: Instant = Instant::now();
    for iter_idx in 0..iters {
        let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
        let _: LayoutStats =
            serial_engine.compute_serial(&mut serial_tree, Size::new(width, 800.0));
    }
    let serial_us: f64 = (start_serial.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let start_parallel: Instant = Instant::now();
    for iter_idx in 0..iters {
        let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
        let _: LayoutStats =
            parallel_engine.compute_parallel(&mut parallel_tree, Size::new(width, 800.0));
    }
    let parallel_us: f64 = (start_parallel.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let serial_boxes: Vec<LayoutBox> = serial_tree
        .get_nodes()
        .iter()
        .map(SceneNode::get_layout_box)
        .collect();
    let parallel_boxes: Vec<LayoutBox> = parallel_tree
        .get_nodes()
        .iter()
        .map(SceneNode::get_layout_box)
        .collect();
    let max_err: f32 = max_layout_box_slice_error(&serial_boxes, &parallel_boxes);
    let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
    workload
        .set_dirty_nodes(AB_TEXT_CARD_COUNT * 2)
        .set_visible_nodes(AB_TEXT_CARD_COUNT * 2)
        .set_tree_depth(3)
        .set_gpu_eligible_nodes(0)
        .set_cpu_chrome_nodes(AB_TEXT_CARD_COUNT * 2)
        .set_dirty_upload_bytes(
            (AB_TEXT_CARD_COUNT * 2).saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES),
        )
        .set_wrapping_text_ratio(0.5)
        .set_worker_threads(worker_threads)
        .set_gpu_compute_available(gpu_ready)
        .set_thermal_throttled(false);
    let router_lane: ExecutionLane = evaluate_router_lane(workload);
    let speedup_ratio: f64 = if parallel_us > 0.0 {
        serial_us / parallel_us
    } else {
        0.0
    };
    let expected_lane: ExecutionLane = if worker_threads > 1 {
        ExecutionLane::CpuParallel
    } else {
        ExecutionLane::CpuSerial
    };
    let passed: bool = router_lane == expected_lane
        && max_err <= AB_PARITY_MAX_ERR_PX
        && (worker_threads <= 1 || speedup_ratio > 1.0);
    ParallelAbCaseResult {
        name: PARALLEL_AB2_NAME.to_string(),
        arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
        arm_b_label: AB_ARM_CPU_PARALLEL.to_string(),
        arm_a_us: serial_us,
        arm_b_us: parallel_us,
        speedup_ratio,
        gpu_exec_ns: 0,
        draw_calls: 0,
        max_error_px: max_err,
        upload_savings_ratio: 0.0,
        steady_state_allocs: 0,
        router_selected_lane: format!("{router_lane:?}"),
        passed,
    }
}

/// Software-rasterizes emitted 64-byte `GpuPrimitiveInstance` rounded quads with SDF anti-aliasing and alpha blending into a reusable RGBA8 `Framebuffer` matching `MSL_UI_SHADER` work per pixel.
///
/// # Arguments
///
/// - `&mut Framebuffer` - Reusable destination `1280x800` RGBA8 framebuffer.
/// - `&[GpuPrimitiveInstance]` - Visible compacted primitive instances to rasterize.
fn rasterize_primitives_into_framebuffer(
    fb: &mut Framebuffer,
    primitives: &[GpuPrimitiveInstance],
) {
    let fb_w: i32 = fb.get_width() as i32;
    let fb_h: i32 = fb.get_height() as i32;
    let pixels: &mut [u8] = fb.get_mut_pixels().as_mut_slice();
    pixels.fill(16);
    for prim in primitives.iter() {
        let rect: [f32; 4] = prim.get_rect();
        let x0: i32 = (rect[0].floor() as i32).clamp(0, fb_w);
        let y0: i32 = (rect[1].floor() as i32).clamp(0, fb_h);
        let x1: i32 = ((rect[0] + rect[2]).ceil() as i32).clamp(x0, fb_w);
        let y1: i32 = ((rect[1] + rect[3]).ceil() as i32).clamp(y0, fb_h);
        if x1 <= x0 || y1 <= y0 {
            continue;
        }
        let rgba: [u8; 4] = prim.get_color_rgba().to_le_bytes();
        let half_w: f32 = (rect[2] * 0.5).max(0.5);
        let half_h: f32 = (rect[3] * 0.5).max(0.5);
        let center_x: f32 = rect[0] + half_w;
        let center_y: f32 = rect[1] + half_h;
        let radius: f32 = ((prim.get_radii_border()[0] as f32) * 0.0625)
            .min(half_w)
            .min(half_h);
        let sr: f32 = rgba[0] as f32;
        let sg: f32 = rgba[1] as f32;
        let sb: f32 = rgba[2] as f32;
        let sa: f32 = (rgba[3] as f32) / 255.0;
        for row in y0..y1 {
            let py: f32 = (row as f32) + 0.5;
            let qy: f32 = (py - center_y).abs() - (half_h - radius);
            let row_base: usize = (row as usize) * (fb_w as usize) * 4;
            for col in x0..x1 {
                let px: f32 = (col as f32) + 0.5;
                let qx: f32 = (px - center_x).abs() - (half_w - radius);
                let dist: f32 = (qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0)) - radius;
                let cov: f32 = (0.5 - dist).clamp(0.0, 1.0) * sa;
                if cov <= 0.0 {
                    continue;
                }
                let inv_cov: f32 = 1.0 - cov;
                let off: usize = row_base + (col as usize) * 4;
                if off + 3 < pixels.len() {
                    pixels[off] = (sr * cov + (pixels[off] as f32) * inv_cov) as u8;
                    pixels[off + 1] = (sg * cov + (pixels[off + 1] as f32) * inv_cov) as u8;
                    pixels[off + 2] = (sb * cov + (pixels[off + 2] as f32) * inv_cov) as u8;
                    pixels[off + 3] = 255;
                }
            }
        }
    }
}

/// Runs AB-3: massive 20,000-node responsive `Grid` resize comparing `CpuSerial` vs real Metal `GpuCompute+IndirectDraw`.
///
/// # Arguments
///
/// - `&mut GpuComputeLayoutEngine` - Active hardware Metal or CPU-reference compute engine.
/// - `usize` - Host worker thread count.
/// - `usize` - Number of timed iterations per arm.
///
/// # Returns
///
/// - `ParallelAbCaseResult` - Measured AB-3 timings, GPU hardware proof, parity error, and router verdict.
#[must_use]
pub fn run_parallel_ab3_massive_grid_20k(
    gpu_engine: &mut GpuComputeLayoutEngine,
    worker_threads: usize,
    iterations: usize,
) -> ParallelAbCaseResult {
    let iters: usize = iterations.max(4);
    let scene_a: GpuComputeSceneInput = build_parallel_ab_compute_scene(
        GpuLayoutMode::Grid,
        AB_GRID_20K_CELLS,
        160.0,
        1280.0,
        800.0,
    );
    let scene_b: GpuComputeSceneInput = build_parallel_ab_compute_scene(
        GpuLayoutMode::Grid,
        AB_GRID_20K_CELLS,
        160.0,
        1600.0,
        900.0,
    );
    let cpu_ref: GpuComputeDispatchResult = execute_cpu_reference_compute(&scene_a);
    let mut cpu_fb: Framebuffer = Framebuffer::allocate(1280, 800);
    let start_cpu: Instant = Instant::now();
    for iter_idx in 0..iters {
        let cur: &GpuComputeSceneInput = if iter_idx % 2 == 0 {
            &scene_a
        } else {
            &scene_b
        };
        let cpu_step: GpuComputeDispatchResult = execute_cpu_reference_compute(cur);
        rasterize_primitives_into_framebuffer(&mut cpu_fb, cpu_step.get_primitives().as_slice());
    }
    let cpu_us: f64 = (start_cpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let warmup_gpu: GpuComputeDispatchResult = gpu_engine.dispatch(&scene_a, true);
    let max_err: f32 = max_layout_output_error_px(
        warmup_gpu.get_outputs().as_slice(),
        cpu_ref.get_outputs().as_slice(),
    );
    let mut gpu_exec_ns: u64 = warmup_gpu
        .get_gpu_compute_ns()
        .saturating_add(warmup_gpu.get_gpu_render_ns());
    let mut draw_calls: usize = warmup_gpu.get_draw_calls();
    let start_gpu: Instant = Instant::now();
    for iter_idx in 0..iters {
        let cur: &GpuComputeSceneInput = if iter_idx % 2 == 0 {
            &scene_a
        } else {
            &scene_b
        };
        let res: GpuComputeDispatchResult = gpu_engine.dispatch_steady_indirect(cur, true, false);
        gpu_exec_ns = res
            .get_gpu_compute_ns()
            .saturating_add(res.get_gpu_render_ns());
        draw_calls = res.get_draw_calls();
    }
    let gpu_us: f64 = (start_gpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
    workload
        .set_dirty_nodes(AB_GRID_20K_CELLS)
        .set_visible_nodes(AB_GRID_20K_CELLS)
        .set_tree_depth(2)
        .set_gpu_eligible_nodes(AB_GRID_20K_CELLS)
        .set_cpu_chrome_nodes(0)
        .set_dirty_upload_bytes(AB_GRID_20K_CELLS.saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES))
        .set_wrapping_text_ratio(0.0)
        .set_worker_threads(worker_threads)
        .set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
        .set_thermal_throttled(false);
    let router_lane: ExecutionLane = evaluate_router_lane(workload);
    let speedup_ratio: f64 = if gpu_us > 0.0 { cpu_us / gpu_us } else { 0.0 };
    let expected_lane: ExecutionLane = if gpu_engine.is_hardware_compute_ready() {
        ExecutionLane::GpuCompute
    } else if worker_threads > 1 {
        ExecutionLane::CpuParallel
    } else {
        ExecutionLane::CpuSerial
    };
    let gpu_verified: bool = !gpu_engine.is_hardware_compute_ready()
        || (gpu_exec_ns > 0 && draw_calls > 0 && warmup_gpu.get_offscreen_non_zero_pixels() > 0);
    let passed: bool =
        router_lane == expected_lane && max_err <= AB_PARITY_MAX_ERR_PX && gpu_verified;
    ParallelAbCaseResult {
        name: PARALLEL_AB3_NAME.to_string(),
        arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
        arm_b_label: AB_ARM_GPU_COMPUTE.to_string(),
        arm_a_us: cpu_us,
        arm_b_us: gpu_us,
        speedup_ratio,
        gpu_exec_ns,
        draw_calls,
        max_error_px: max_err,
        upload_savings_ratio: 0.0,
        steady_state_allocs: 0,
        router_selected_lane: format!("{router_lane:?}"),
        passed,
    }
}

/// Runs AB-4: 50,000-node animated Spring/DataViz scene comparing full CPU compute vs real Metal `GpuCompute+IndirectDraw`.
///
/// # Arguments
///
/// - `&mut GpuComputeLayoutEngine` - Active hardware Metal or CPU-reference compute engine.
/// - `usize` - Host worker thread count.
/// - `usize` - Number of timed iterations per arm.
///
/// # Returns
///
/// - `ParallelAbCaseResult` - Measured AB-4 timings, upload savings, GPU execution proof, and parity error.
#[must_use]
pub fn run_parallel_ab4_50k_spring_indirect(
    gpu_engine: &mut GpuComputeLayoutEngine,
    worker_threads: usize,
    iterations: usize,
) -> ParallelAbCaseResult {
    let iters: usize = iterations.max(4);
    let scene: GpuComputeSceneInput = build_parallel_ab_compute_scene(
        GpuLayoutMode::Spring,
        AB_SPRING_50K_NODES,
        1.0,
        1280.0,
        800.0,
    );
    let cpu_ref: GpuComputeDispatchResult = execute_cpu_reference_compute(&scene);
    let mut cpu_fb: Framebuffer = Framebuffer::allocate(1280, 800);
    let start_cpu: Instant = Instant::now();
    for _ in 0..iters {
        let cpu_step: GpuComputeDispatchResult = execute_cpu_reference_compute(&scene);
        rasterize_primitives_into_framebuffer(&mut cpu_fb, cpu_step.get_primitives().as_slice());
    }
    let cpu_us: f64 = (start_cpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let warmup_gpu: GpuComputeDispatchResult = gpu_engine.dispatch(&scene, true);
    let max_err: f32 = max_layout_output_error_px(
        warmup_gpu.get_outputs().as_slice(),
        cpu_ref.get_outputs().as_slice(),
    );
    let mut gpu_exec_ns: u64 = warmup_gpu
        .get_gpu_compute_ns()
        .saturating_add(warmup_gpu.get_gpu_render_ns());
    let mut draw_calls: usize = warmup_gpu.get_draw_calls();
    let start_gpu: Instant = Instant::now();
    for _ in 0..iters {
        let res: GpuComputeDispatchResult =
            gpu_engine.dispatch_steady_indirect(&scene, true, false);
        gpu_exec_ns = res
            .get_gpu_compute_ns()
            .saturating_add(res.get_gpu_render_ns());
        draw_calls = res.get_draw_calls();
    }
    let gpu_us: f64 = (start_gpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let mut coalescer: DirtySpanCoalescer = DirtySpanCoalescer::default();
    let mut prim_stream: Vec<GpuPrimitiveInstance> = warmup_gpu.get_primitives().clone();
    let _: &[DirtyBufferSpan] = coalescer.diff_and_coalesce(prim_stream.as_slice());
    if !prim_stream.is_empty() {
        let mutated_color: u32 = prim_stream[0].get_color_rgba().wrapping_add(1);
        prim_stream[0].set_color_rgba(mutated_color);
    }
    let _: &[DirtyBufferSpan] = coalescer.diff_and_coalesce(prim_stream.as_slice());
    let upload_savings: f32 = coalescer.last_savings_ratio();
    let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
    workload
        .set_dirty_nodes(AB_SPRING_50K_NODES)
        .set_visible_nodes(AB_SPRING_50K_NODES)
        .set_tree_depth(2)
        .set_gpu_eligible_nodes(AB_SPRING_50K_NODES)
        .set_cpu_chrome_nodes(0)
        .set_dirty_upload_bytes(coalescer.get_last_dirty_bytes())
        .set_wrapping_text_ratio(0.0)
        .set_worker_threads(worker_threads)
        .set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
        .set_thermal_throttled(false);
    let router_lane: ExecutionLane = evaluate_router_lane(workload);
    let speedup_ratio: f64 = if gpu_us > 0.0 { cpu_us / gpu_us } else { 0.0 };
    let gpu_verified: bool = !gpu_engine.is_hardware_compute_ready()
        || (gpu_exec_ns > 0 && draw_calls > 0 && warmup_gpu.get_offscreen_non_zero_pixels() > 0);
    let passed: bool = max_err <= AB_PARITY_MAX_ERR_PX && upload_savings >= 0.90 && gpu_verified;
    ParallelAbCaseResult {
        name: PARALLEL_AB4_NAME.to_string(),
        arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
        arm_b_label: AB_ARM_GPU_COMPUTE.to_string(),
        arm_a_us: cpu_us,
        arm_b_us: gpu_us,
        speedup_ratio,
        gpu_exec_ns,
        draw_calls,
        max_error_px: max_err,
        upload_savings_ratio: upload_savings,
        steady_state_allocs: 0,
        router_selected_lane: format!("{router_lane:?}"),
        passed,
    }
}

/// Runs AB-5: mixed production dashboard (500 rich-text chrome cards + 20,000-cell GPU grid body) comparing pure sequential vs `MixedCoExec` overlap.
///
/// # Arguments
///
/// - `&mut GpuComputeLayoutEngine` - Active hardware Metal or CPU-reference compute engine.
/// - `usize` - Host worker thread count.
/// - `usize` - Number of timed iterations per arm.
///
/// # Returns
///
/// - `ParallelAbCaseResult` - Measured AB-5 timings, GPU hardware proof, and `MixedCoExec` router verdict.
#[must_use]
pub fn run_parallel_ab5_mixed_dashboard(
    gpu_engine: &mut GpuComputeLayoutEngine,
    worker_threads: usize,
    iterations: usize,
) -> ParallelAbCaseResult {
    let iters: usize = iterations.max(4);
    let (mut chrome_tree_seq, _): (SceneTree, NodeId) =
        build_parallel_ab_card_tree(AB_DASHBOARD_CHROME_CARDS, true);
    let (mut chrome_tree_co, _): (SceneTree, NodeId) =
        build_parallel_ab_card_tree(AB_DASHBOARD_CHROME_CARDS, true);
    let mut seq_layout: LayoutEngine = LayoutEngine::default();
    let mut co_layout: LayoutEngine = LayoutEngine::default();
    let body_scene: GpuComputeSceneInput = build_parallel_ab_compute_scene(
        GpuLayoutMode::Grid,
        AB_GRID_20K_CELLS,
        160.0,
        1280.0,
        800.0,
    );
    let cpu_body_ref: GpuComputeDispatchResult = execute_cpu_reference_compute(&body_scene);
    let mut cpu_fb: Framebuffer = Framebuffer::allocate(1280, 800);
    let start_seq: Instant = Instant::now();
    for iter_idx in 0..iters {
        let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
        let _: LayoutStats =
            seq_layout.compute_parallel(&mut chrome_tree_seq, Size::new(width, 800.0));
        let body_step: GpuComputeDispatchResult = execute_cpu_reference_compute(&body_scene);
        rasterize_primitives_into_framebuffer(&mut cpu_fb, body_step.get_primitives().as_slice());
    }
    let pure_cpu_us: f64 = (start_seq.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let warmup_gpu: GpuComputeDispatchResult = gpu_engine.dispatch(&body_scene, true);
    let max_err: f32 = max_layout_output_error_px(
        warmup_gpu.get_outputs().as_slice(),
        cpu_body_ref.get_outputs().as_slice(),
    );
    let mut gpu_exec_ns: u64 = warmup_gpu
        .get_gpu_compute_ns()
        .saturating_add(warmup_gpu.get_gpu_render_ns());
    let mut draw_calls: usize = warmup_gpu.get_draw_calls();
    let start_co: Instant = Instant::now();
    for iter_idx in 0..iters {
        let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
        let in_flight: Option<(usize, usize, usize)> =
            gpu_engine.begin_steady_indirect_async(&body_scene, true, false);
        let _: LayoutStats =
            co_layout.compute_parallel(&mut chrome_tree_co, Size::new(width, 800.0));
        let res: GpuComputeDispatchResult = match in_flight {
            Some(token) => gpu_engine.finish_steady_indirect_async(token),
            None => gpu_engine.dispatch_steady_indirect(&body_scene, true, false),
        };
        gpu_exec_ns = res
            .get_gpu_compute_ns()
            .saturating_add(res.get_gpu_render_ns());
        draw_calls = res.get_draw_calls();
    }
    let mixed_us: f64 = (start_co.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
    workload
        .set_dirty_nodes(AB_DASHBOARD_CHROME_CARDS * 2 + AB_GRID_20K_CELLS)
        .set_visible_nodes(AB_DASHBOARD_CHROME_CARDS * 2 + AB_GRID_20K_CELLS)
        .set_tree_depth(3)
        .set_gpu_eligible_nodes(AB_GRID_20K_CELLS)
        .set_cpu_chrome_nodes(AB_DASHBOARD_CHROME_CARDS * 2)
        .set_dirty_upload_bytes(AB_GRID_20K_CELLS.saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES))
        .set_wrapping_text_ratio(0.05)
        .set_worker_threads(worker_threads)
        .set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
        .set_thermal_throttled(false);
    let router_lane: ExecutionLane = evaluate_router_lane(workload);
    let speedup_ratio: f64 = if mixed_us > 0.0 {
        pure_cpu_us / mixed_us
    } else {
        0.0
    };
    let expected_lane: ExecutionLane = if gpu_engine.is_hardware_compute_ready() {
        ExecutionLane::MixedCoExec
    } else if worker_threads > 1 {
        ExecutionLane::CpuParallel
    } else {
        ExecutionLane::CpuSerial
    };
    let gpu_verified: bool =
        !gpu_engine.is_hardware_compute_ready() || (gpu_exec_ns > 0 && draw_calls > 0);
    let passed: bool =
        router_lane == expected_lane && max_err <= AB_PARITY_MAX_ERR_PX && gpu_verified;
    ParallelAbCaseResult {
        name: PARALLEL_AB5_NAME.to_string(),
        arm_a_label: AB_ARM_CPU_PARALLEL.to_string(),
        arm_b_label: AB_ARM_MIXED_COEXEC.to_string(),
        arm_a_us: pure_cpu_us,
        arm_b_us: mixed_us,
        speedup_ratio,
        gpu_exec_ns,
        draw_calls,
        max_error_px: max_err,
        upload_savings_ratio: 0.0,
        steady_state_allocs: 0,
        router_selected_lane: format!("{router_lane:?}"),
        passed,
    }
}

/// Runs AB-6: 10,000-primitive scene with 1% dirty mutation comparing `in_flight=1` full upload vs `in_flight=2` + `DirtySpanCoalescer` on real Metal.
///
/// # Arguments
///
/// - `&mut GpuComputeLayoutEngine` - Active hardware Metal or CPU-reference compute engine for real GPU fence execution.
/// - `usize` - Number of timed iterations per arm.
///
/// # Returns
///
/// - `ParallelAbCaseResult` - Measured AB-6 timings, `>= 90%` byte savings, `0` steady-state allocs, and hardware GPU telemetry.
#[must_use]
pub fn run_parallel_ab6_pipelined_dirty_span(
    gpu_engine: &mut GpuComputeLayoutEngine,
    iterations: usize,
) -> ParallelAbCaseResult {
    let iters: usize = iterations.max(8);
    let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(AB_PIPELINED_PRIMITIVES);
    for idx in 0..AB_PIPELINED_PRIMITIVES {
        let mut quad: GpuQuadInstance = GpuQuadInstance::default();
        let col: f32 = (idx % 100) as f32;
        let row: f32 = (idx / 100) as f32;
        quad.set_rect([col * 12.0, row * 8.0, 10.0, 6.0])
            .set_clip([0.0, 0.0, 1280.0, 800.0])
            .set_color([0.2, 0.55, 0.9, 1.0])
            .set_radii([2.0; 4])
            .set_kind(GpuPrimitiveKind::RoundedRect as u32);
        primitives.push(GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0));
    }
    let mut driver: NativeGpuDriver = NativeGpuDriver::probe(GraphicsBackend::Metal);
    let mut graph_full: RenderGraph = RenderGraph::default();
    graph_full.set_max_frames_in_flight(1);
    let mut graph_dirty: RenderGraph = RenderGraph::default();
    graph_dirty.set_max_frames_in_flight(RENDER_GRAPH_DEFAULT_MAX_IN_FLIGHT);
    let target: RenderGraphFrameTarget =
        RenderGraphFrameTarget::new(1280, 800, Color::rgb(12, 16, 24));
    let mut batch_full: [GpuBatch; 1] = [GpuBatch::default()];
    batch_full[0].set_scissor(Rect::new(0.0, 0.0, 1280.0, 800.0));
    batch_full[0].set_primitives(primitives.clone());
    let mut batch_dirty: [GpuBatch; 1] = [GpuBatch::default()];
    batch_dirty[0].set_scissor(Rect::new(0.0, 0.0, 1280.0, 800.0));
    batch_dirty[0].set_primitives(primitives);
    let _: Result<RenderGraphExecutionReceipt, PlatformError> =
        graph_full.execute_frame(&mut driver, target, &batch_full, &[], None);
    let _: Result<RenderGraphExecutionReceipt, PlatformError> =
        graph_dirty.execute_frame(&mut driver, target, &batch_dirty, &[], None);
    let mut full_staging: Vec<u8> =
        vec![0u8; AB_PIPELINED_PRIMITIVES.saturating_mul(size_of::<GpuPrimitiveInstance>())];
    let warmup_span: [DirtyBufferSpan; 1] = [DirtyBufferSpan::new(0, full_staging.len())];
    let _: Option<(usize, u64)> = gpu_engine.upload_primitive_spans_metal(
        batch_full[0].get_primitives().as_slice(),
        &warmup_span,
        0,
        true,
    );
    let mut gpu_exec_ns: u64 = 0;
    let start_full: Instant = Instant::now();
    for iter_idx in 0..iters {
        for dirty_idx in 0..AB_PIPELINED_DIRTY_PRIMITIVES {
            let slot: usize = dirty_idx;
            let next_rgba: u32 = batch_full[0].get_primitives()[slot]
                .get_color_rgba()
                .wrapping_add((iter_idx as u32).saturating_add(1));
            batch_full[0].get_mut_primitives()[slot].set_color_rgba(next_rgba);
        }
        graph_full.get_mut_dirty_coalescer().reset();
        let _: Result<RenderGraphExecutionReceipt, PlatformError> =
            graph_full.execute_frame(&mut driver, target, &batch_full, &[], None);
        let prim_slice: &[GpuPrimitiveInstance] = batch_full[0].get_primitives().as_slice();
        let spans: &[DirtyBufferSpan] = graph_full.get_dirty_coalescer().get_coalesced();
        if let Some((_, ns)) = gpu_engine.upload_primitive_spans_metal(prim_slice, spans, 0, true) {
            gpu_exec_ns = gpu_exec_ns.max(ns);
        } else {
            // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding.
            let src_bytes: &[u8] = unsafe {
                from_raw_parts(prim_slice.as_ptr().cast::<u8>(), size_of_val(prim_slice))
            };
            for span in spans {
                let start: usize = span.get_byte_offset();
                let end: usize = start
                    .saturating_add(span.get_byte_len())
                    .min(full_staging.len())
                    .min(src_bytes.len());
                if end > start {
                    full_staging[start..end].copy_from_slice(&src_bytes[start..end]);
                }
            }
        }
    }
    let full_us: f64 = (start_full.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    let mut upload_savings: f32 = 0.0;
    let mut draw_calls: usize = 0;
    let mut pending_cmd: usize = 0;
    let start_dirty: Instant = Instant::now();
    for iter_idx in 0..iters {
        for dirty_idx in 0..AB_PIPELINED_DIRTY_PRIMITIVES {
            let slot: usize = dirty_idx;
            let next_rgba: u32 = batch_dirty[0].get_primitives()[slot]
                .get_color_rgba()
                .wrapping_add((iter_idx as u32).saturating_add(1));
            batch_dirty[0].get_mut_primitives()[slot].set_color_rgba(next_rgba);
        }
        let _: Result<RenderGraphExecutionReceipt, PlatformError> =
            graph_dirty.execute_frame(&mut driver, target, &batch_dirty, &[], None);
        let prim_slice: &[GpuPrimitiveInstance] = batch_dirty[0].get_primitives().as_slice();
        let spans: &[DirtyBufferSpan] = graph_dirty.get_dirty_coalescer().get_coalesced();
        if let Some((next_cmd, _)) =
            gpu_engine.upload_primitive_spans_metal(prim_slice, spans, iter_idx & 1, false)
        {
            if pending_cmd != 0 {
                let done_ns: u64 = gpu_engine.finish_upload_metal(pending_cmd);
                gpu_exec_ns = gpu_exec_ns.max(done_ns);
            }
            pending_cmd = next_cmd;
        } else {
            // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding.
            let src_bytes: &[u8] = unsafe {
                from_raw_parts(prim_slice.as_ptr().cast::<u8>(), size_of_val(prim_slice))
            };
            for span in spans {
                let start: usize = span.get_byte_offset();
                let end: usize = start
                    .saturating_add(span.get_byte_len())
                    .min(full_staging.len())
                    .min(src_bytes.len());
                if end > start {
                    full_staging[start..end].copy_from_slice(&src_bytes[start..end]);
                }
            }
        }
        if iter_idx == iters - 1 {
            upload_savings = graph_dirty.get_dirty_coalescer().last_savings_ratio();
        }
    }
    if pending_cmd != 0 {
        let done_ns: u64 = gpu_engine.finish_upload_metal(pending_cmd);
        gpu_exec_ns = gpu_exec_ns.max(done_ns);
    }
    let dirty_us: f64 = (start_dirty.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
    for dirty_idx in 0..AB_PIPELINED_DIRTY_PRIMITIVES {
        let next_rgba: u32 = batch_dirty[0].get_primitives()[dirty_idx]
            .get_color_rgba()
            .wrapping_add(1);
        batch_dirty[0].get_mut_primitives()[dirty_idx].set_color_rgba(next_rgba);
    }
    let (_, alloc_snap): (usize, AllocationSnapshot) = measure_allocations(|| {
        let spans: &[DirtyBufferSpan] = graph_dirty
            .get_mut_dirty_coalescer()
            .diff_and_coalesce(batch_dirty[0].get_primitives().as_slice());
        spans.len()
    });
    let steady_allocs: usize = alloc_snap.get_alloc_count() as usize;
    let verify_scene: GpuComputeSceneInput =
        build_parallel_ab_compute_scene(GpuLayoutMode::Grid, 64, 8.0, 1280.0, 800.0);
    let gpu_receipt: Result<RenderGraphExecutionReceipt, PlatformError> = graph_dirty
        .execute_frame(
            &mut driver,
            target,
            &batch_dirty,
            &[],
            Some((gpu_engine, &verify_scene)),
        );
    if let Ok(receipt) = gpu_receipt {
        gpu_exec_ns = gpu_exec_ns.max(receipt.get_gpu_compute_ns());
        draw_calls = receipt.get_draw_calls();
    }
    let speedup_ratio: f64 = if dirty_us > 0.0 {
        full_us / dirty_us
    } else {
        0.0
    };
    let hw_ready: bool = gpu_engine.is_hardware_compute_ready();
    let gpu_verified: bool =
        !hw_ready || (gpu_exec_ns > 0 && draw_calls > 0 && speedup_ratio > 1.0);
    let passed: bool = upload_savings >= 0.90 && steady_allocs == 0 && gpu_verified;
    ParallelAbCaseResult {
        name: PARALLEL_AB6_NAME.to_string(),
        arm_a_label: AB_ARM_INFLIGHT1_FULL.to_string(),
        arm_b_label: AB_ARM_INFLIGHT2_DIRTY.to_string(),
        arm_a_us: full_us,
        arm_b_us: dirty_us,
        speedup_ratio,
        gpu_exec_ns,
        draw_calls,
        max_error_px: 0.0,
        upload_savings_ratio: upload_savings,
        steady_state_allocs: steady_allocs,
        router_selected_lane: AB_ARM_INFLIGHT2_DIRTY.to_string(),
        passed,
    }
}

/// Returns `true` when `case_name` matches the optional substring `filter`.
///
/// # Arguments
///
/// - `&str` - Candidate benchmark case name.
/// - `Option<&str>` - Optional substring filter.
///
/// # Returns
///
/// - `bool` - `true` when the case should execute.
#[must_use]
fn matches_parallel_ab_filter(case_name: &str, filter: Option<&str>) -> bool {
    match filter {
        Some(pattern) if !pattern.is_empty() => case_name.contains(pattern),
        _ => true,
    }
}

/// Runs the complete `AB-1..AB-6` real-hardware CPU+GPU parallel A/B suite, optionally filtered by substring `filter`.
///
/// # Arguments
///
/// - `Option<&str>` - Optional case name substring filter (`None` runs all 6 benchmarks).
///
/// # Returns
///
/// - `ParallelAbReport` - Complete measured A/B report with hardware Metal verification flags.
#[must_use]
pub fn run_filtered_parallel_ab_suite(filter: Option<&str>) -> ParallelAbReport {
    let mut gpu_engine: GpuComputeLayoutEngine = GpuComputeLayoutEngine::probe();
    let gpu_ready: bool = gpu_engine.is_hardware_compute_ready();
    let gpu_backend: String = if gpu_ready {
        AB_BACKEND_METAL.to_string()
    } else {
        AB_BACKEND_CPU_REF.to_string()
    };
    let worker_threads: usize = global_engine_worker_pool().total_threads();
    let mut cases: Vec<ParallelAbCaseResult> = Vec::with_capacity(6);
    if matches_parallel_ab_filter(PARALLEL_AB1_NAME, filter) {
        cases.push(run_parallel_ab1_sparse_reactive(
            &mut gpu_engine,
            worker_threads,
            16,
        ));
    }
    if matches_parallel_ab_filter(PARALLEL_AB2_NAME, filter) {
        cases.push(run_parallel_ab2_heavy_text_reflow(
            gpu_ready,
            worker_threads,
            6,
        ));
    }
    if matches_parallel_ab_filter(PARALLEL_AB3_NAME, filter) {
        cases.push(run_parallel_ab3_massive_grid_20k(
            &mut gpu_engine,
            worker_threads,
            8,
        ));
    }
    if matches_parallel_ab_filter(PARALLEL_AB4_NAME, filter) {
        cases.push(run_parallel_ab4_50k_spring_indirect(
            &mut gpu_engine,
            worker_threads,
            8,
        ));
    }
    if matches_parallel_ab_filter(PARALLEL_AB5_NAME, filter) {
        cases.push(run_parallel_ab5_mixed_dashboard(
            &mut gpu_engine,
            worker_threads,
            6,
        ));
    }
    if matches_parallel_ab_filter(PARALLEL_AB6_NAME, filter) {
        cases.push(run_parallel_ab6_pipelined_dirty_span(&mut gpu_engine, 16));
    }
    let all_passed: bool = cases
        .iter()
        .all(|case: &ParallelAbCaseResult| case.get_passed());
    ParallelAbReport::new(
        gpu_backend,
        gpu_ready,
        allocation_tracking_active(),
        worker_threads,
        cases,
        all_passed,
    )
}

/// Formats a `ParallelAbReport` as a concise human-readable terminal table.
///
/// # Arguments
///
/// - `&ParallelAbReport` - Completed A/B benchmark report.
///
/// # Returns
///
/// - `String` - Formatted report text.
#[must_use]
pub fn format_parallel_ab_report(report: &ParallelAbReport) -> String {
    let mut out: String = String::from(AB_REPORT_HEADER);
    let _: fmt::Result = writeln!(
        out,
        "Backend: {} | HardwareGPU: {} | Workers: {} | AllocTracking: {}",
        report.get_gpu_backend(),
        report.get_hardware_gpu_verified(),
        report.get_worker_threads(),
        report.get_allocation_tracking()
    );
    for case in report.get_cases() {
        let status: &str = if case.get_passed() {
            AB_STATUS_PASS
        } else {
            AB_STATUS_FAIL
        };
        let _: fmt::Result = writeln!(
            out,
            "[{status}] {:<32} | {}: {:>8.1}us vs {}: {:>8.1}us | x{:.2} | gpu_ns={} draws={} err={:.4}px save={:.1}% allocs={} lane={}",
            case.get_name(),
            case.get_arm_a_label(),
            case.get_arm_a_us(),
            case.get_arm_b_label(),
            case.get_arm_b_us(),
            case.get_speedup_ratio(),
            case.get_gpu_exec_ns(),
            case.get_draw_calls(),
            case.get_max_error_px(),
            case.get_upload_savings_ratio() * 100.0,
            case.get_steady_state_allocs(),
            case.get_router_selected_lane(),
        );
    }
    let _: fmt::Result = writeln!(
        out,
        "Summary: {}/{} passed (all_passed={})",
        report.passed_count(),
        report.get_cases().len(),
        report.get_all_passed()
    );
    out
}

/// Serializes a `ParallelAbReport` into pretty-printed JSON.
///
/// # Arguments
///
/// - `&ParallelAbReport` - Completed A/B benchmark report.
///
/// # Returns
///
/// - `String` - Pretty-printed JSON payload.
#[must_use]
pub fn parallel_ab_report_to_json(report: &ParallelAbReport) -> String {
    to_string_pretty(report).unwrap_or_default()
}