Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

67.9 KB
Raw Blame
//! Headless DX12 regression & stress tests for:
//! 1. 4K (`3840×2160`) & Manga B4 (`6071×8598`) tight `64 MB` VRAM pool stress at `zoom = 0.25`,
//!    solid-color deduplication (`<= 4` slots for 816-tile solid Background), chunked stroke commit,
//!    and pixel-accurate parity against an unconstrained `512 MB` reference.
//! 2. Mouse 120 Hz input stream (`NativeNavEvent::MouseDraw` spaced `8 ms` apart) proving zero
//!    250 ms self-throttling and proving active mouse `phase == 3` is never dropped even if a
//!    stylus packet arrives within 250 ms.
//! 3. Multi-tile `CspBlendTipsMode::Darken` stroke across 4+ tiles in 2 batches proving dynamic
//!    uniform offsets eliminate tile-slot uniform overwrite/duplication.
//! 4. Evicted-sibling mipmap preservation in `regenerate_layer_mipmaps` + `LiveGpuStrokeOverlay`
//!    dirty-rect scissor & predicted dab clipping at `zoom = 0.25` across `dpr = 1.0, 1.25, 1.5`.

use crate::brush::{CspBlendTipsMode, GpuBrushDab, NativeBrushConfig, StrokeDabEmitter};
use crate::clock;
use crate::compositor::{CompositorDisplayConfig, DocBounds};
use crate::document::{CanvasColorMode, CanvasDimensions, Document, LayerNodeMeta};
use crate::engine::{EngineConfig, EngineHandle};
use crate::gpu::GpuRenderer;
use crate::memory::MemoryBudgetConfig;
use crate::stroke::{SplineGenerator, StrokePoint};
use crate::tiles::{RectI32, TileCoord, BYTES_16F, TILE_SIZE};
use crate::types::{
    CameraState, CursorConfig, EngineCommand, EngineEvent, NativeInputSample, NativeNavEvent,
    SurfaceTarget, ViewportRect,
};
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};

fn lock_dx12() -> std::sync::MutexGuard<'static, ()> {
    crate::lock_dx12_test()
}

fn make_headless_renderer_vram(
    vp_w: u32,
    vp_h: u32,
    doc_w: u32,
    doc_h: u32,
    vram_bytes: u64,
) -> Option<GpuRenderer> {
    match GpuRenderer::new_with_vram(
        SurfaceTarget::Headless {
            width: vp_w,
            height: vp_h,
        },
        doc_w,
        doc_h,
        vram_bytes,
    ) {
        Ok(r) => Some(r),
        Err(err) => {
            eprintln!("Skipping DX12 regression GPU test (no adapter available): {err}");
            None
        }
    }
}

fn make_white_doc(id: &str, w: u32, h: u32) -> Document {
    Document::new_blank(
        id,
        "DX12 Regression Doc",
        CanvasDimensions {
            width: w,
            height: h,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        50,
    )
}

fn fnv1a_hash(bytes: &[u8]) -> u64 {
    let mut h = 0xcbf29ce484222325u64;
    for &b in bytes {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x100000001b3);
    }
    h
}

fn make_curved_stroke_points(
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    amp: f64,
    freq: f64,
    count: usize,
    width: f32,
) -> Vec<StrokePoint> {
    let dx = x1 - x0;
    let dy = y1 - y0;
    let len = dx.hypot(dy).max(1.0);
    let nx = -dy / len;
    let ny = dx / len;
    let mut pts = Vec::with_capacity(count);
    for i in 0..count {
        let t = if count <= 1 {
            0.0
        } else {
            i as f64 / (count - 1) as f64
        };
        let wave = (t * std::f64::consts::TAU * freq).sin() * amp;
        pts.push(StrokePoint {
            x: x0 + dx * t + nx * wave,
            y: y0 + dy * t + ny * wave,
            pressure: 0.9,
            width,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            velocity: 0.5,
            timestamp_ms: i as f64 * 8.0,
            is_corner: false,
        });
    }
    pts
}

fn emit_and_commit_stroke(
    renderer: &mut GpuRenderer,
    doc: &mut Document,
    layer_id: &str,
    brush: NativeBrushConfig,
    pts: &[StrokePoint],
    seed: u64,
) {
    let (tip_count, tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
    let mut emitter = StrokeDabEmitter::new(brush.clone(), seed, tip_count, tip_aspect);
    let rand_off = emitter.stroke_grain_offset;
    renderer.begin_gpu_stroke(
        doc.dimensions.width,
        doc.dimensions.height,
        false,
        brush,
        rand_off,
    );

    let mut spline = SplineGenerator::new(0.0);
    let mut dabs = Vec::new();
    if let Some(&first) = pts.first() {
        spline.push_knot(first);
        emitter.emit_initial_point(&first, None, 0.0, &mut dabs);
    }
    for &pt in pts.iter().skip(1) {
        for seg in spline.push_knot(pt) {
            emitter.emit_segment(&seg, None, 0.0, &mut dabs);
        }
    }
    for seg in spline.finish() {
        emitter.emit_segment(&seg, None, 0.0, &mut dabs);
    }

    renderer.stamp_gpu_stroke_dabs(&dabs, &[]);
    let doc_id = doc.id.clone();
    let committed = {
        let layer = doc.layer(layer_id).expect("layer exists");
        renderer
            .commit_gpu_stroke_to_layer(&doc_id, layer_id, &layer.grid, None, false, false)
            .expect("commit_gpu_stroke_to_layer must succeed")
    };

    let mut before_map = HashMap::new();
    {
        let layer = doc.layer_mut(layer_id).expect("layer exists");
        for (coord, _, _) in &committed.tiles {
            before_map.insert(*coord, layer.grid.tiles.get(coord).cloned());
        }
        let (_deltas, cleared) =
            layer
                .grid
                .apply_gpu_committed_tiles(layer_id, committed.tiles, &before_map, 128);
        renderer.regenerate_layer_mipmaps(&doc_id, layer_id, &mut layer.grid, &cleared, None);
    }
    renderer.clear_live_stroke();
}

fn render_viewport_zoom_025(
    renderer: &mut GpuRenderer,
    doc: &Document,
    vp_w: u32,
    vp_h: u32,
) -> Vec<u8> {
    let vp = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: vp_w,
        height_px: vp_h,
        dpr: 1.0,
    };
    let cam = CameraState {
        pan_x: vp_w as f32 * 0.5,
        pan_y: vp_h as f32 * 0.5,
        zoom: 0.25,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };
    let display = CompositorDisplayConfig {
        show_checkerboard: true,
        matte_color: [0.05, 0.05, 0.05, 1.0],
        layer_stack_caching: true,
        ..Default::default()
    };
    let cursor = CursorConfig {
        visible: false,
        ..Default::default()
    };
    let _ = renderer.render_document_frame(
        doc,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        false,
        &cursor,
        None,
        true,
    );
    let (rw, rh, rgba) = renderer
        .readback_headless_rgba8()
        .expect("headless DX12 viewport readback must succeed");
    assert_eq!((rw, rh), (vp_w, vp_h));
    rgba
}

fn run_tight_vram_64mb_stress(label: &str, doc_w: u32, doc_h: u32, vp_w: u32, vp_h: u32) {
    let w = doc_w as f64;
    let h = doc_h as f64;
    let stroke_specs: [([f32; 3], (f64, f64), (f64, f64), f64, f64, f32, u64); 4] = [
        (
            [0.88, 0.12, 0.16],
            (w * 0.08, h * 0.12),
            (w * 0.92, h * 0.88),
            120.0,
            1.3,
            48.0,
            101,
        ),
        (
            [0.10, 0.35, 0.90],
            (w * 0.90, h * 0.14),
            (w * 0.10, h * 0.86),
            140.0,
            1.7,
            44.0,
            202,
        ),
        (
            [0.12, 0.72, 0.24],
            (w * 0.12, h * 0.50),
            (w * 0.88, h * 0.42),
            180.0,
            2.1,
            40.0,
            303,
        ),
        (
            [0.45, 0.10, 0.75],
            (w * 0.46, h * 0.08),
            (w * 0.56, h * 0.92),
            150.0,
            1.9,
            36.0,
            404,
        ),
    ];

    // Phase 1: Run on tight 64 MB pool, capture viewport & tiles, then drop DX12 device before Phase 2
    let mut doc_tight = make_white_doc("stress-tight", doc_w, doc_h);
    let lid_tight = doc_tight.active_layer_id.clone().unwrap();
    let tight_vp = {
        let Some(mut r_tight) =
            make_headless_renderer_vram(vp_w, vp_h, doc_w, doc_h, 64 * 1024 * 1024)
        else {
            return;
        };

        // First verify solid white Background uses <= 4 VRAM slots (not 135..816!)
        r_tight
            .sync_document(&mut doc_tight, None)
            .expect("sync_document tight");
        let _ = render_viewport_zoom_025(&mut r_tight, &doc_tight, vp_w, vp_h);
        let bg_stats = r_tight.gpu_pool_stats();
        assert!(
            bg_stats.slots_used <= 4,
            "[{label}] Solid-color {doc_w}x{doc_h} Background must use <= 4 VRAM slots, got {}",
            bg_stats.slots_used
        );

        for &(color, (x0, y0), (x1, y1), amp, freq, size, seed) in &stroke_specs {
            let brush = NativeBrushConfig {
                fg_color: color,
                size,
                hardness: 0.92,
                spacing: 0.16,
                opacity: 1.0,
                ..Default::default()
            };
            let pts = make_curved_stroke_points(x0, y0, x1, y1, amp, freq, 96, size);
            emit_and_commit_stroke(&mut r_tight, &mut doc_tight, &lid_tight, brush, &pts, seed);
            let _ = render_viewport_zoom_025(&mut r_tight, &doc_tight, vp_w, vp_h);
        }

        render_viewport_zoom_025(&mut r_tight, &doc_tight, vp_w, vp_h)
    };

    // Phase 2: Run identical strokes on unconstrained 512 MB reference pool
    let mut doc_ref = make_white_doc("stress-ref", doc_w, doc_h);
    let lid_ref = doc_ref.active_layer_id.clone().unwrap();
    let ref_vp = {
        let Some(mut r_ref) =
            make_headless_renderer_vram(vp_w, vp_h, doc_w, doc_h, 512 * 1024 * 1024)
        else {
            return;
        };
        r_ref
            .sync_document(&mut doc_ref, None)
            .expect("sync_document ref");

        for &(color, (x0, y0), (x1, y1), amp, freq, size, seed) in &stroke_specs {
            let brush = NativeBrushConfig {
                fg_color: color,
                size,
                hardness: 0.92,
                spacing: 0.16,
                opacity: 1.0,
                ..Default::default()
            };
            let pts = make_curved_stroke_points(x0, y0, x1, y1, amp, freq, 96, size);
            emit_and_commit_stroke(&mut r_ref, &mut doc_ref, &lid_ref, brush, &pts, seed);
        }

        render_viewport_zoom_025(&mut r_ref, &doc_ref, vp_w, vp_h)
    };

    // 1. Verify committed tile hashes: 0 unintended duplicate inked tiles AND exact match vs 512 MB ref
    let tight_layer = doc_tight.layer(&lid_tight).unwrap();
    let ref_layer = doc_ref.layer(&lid_ref).unwrap();
    assert_eq!(
        tight_layer.grid.tiles.len(),
        ref_layer.grid.tiles.len(),
        "[{label}] Tight 64 MB pool committed tile count must match 512 MB reference"
    );
    assert!(
        tight_layer.grid.tiles.len() >= 20,
        "[{label}] 4 canvas-spanning strokes should touch >= 20 tiles, got {}",
        tight_layer.grid.tiles.len()
    );

    let mut seen_hashes: HashMap<u64, TileCoord> = HashMap::new();
    let mut max_tile_premul_diff = 0u8;
    for (&coord, tight_tile) in &tight_layer.grid.tiles {
        let tight_rgba = tight_tile.to_rgba8(None, false).unwrap();
        let ref_tile = ref_layer
            .grid
            .tiles
            .get(&coord)
            .expect("coord exists in ref");
        let ref_rgba = ref_tile.to_rgba8(None, false).unwrap();

        let h_tight = fnv1a_hash(&tight_rgba);
        // Compare premultiplied RGBA (since evicting an Rgba16Float tile to RGBA8 and reloading
        // before an overlapping stroke only quantizes straight-RGB on near-zero-alpha fringe pixels).
        let mut tile_max_diff = 0u8;
        let mut tile_big_diffs = 0usize;
        for (tp, rp) in tight_rgba.chunks_exact(4).zip(ref_rgba.chunks_exact(4)) {
            let ta = tp[3] as u32;
            let ra = rp[3] as u32;
            let dr = ((tp[0] as u32 * ta + 127) / 255).abs_diff((rp[0] as u32 * ra + 127) / 255) as u8;
            let dg = ((tp[1] as u32 * ta + 127) / 255).abs_diff((rp[1] as u32 * ra + 127) / 255) as u8;
            let db = ((tp[2] as u32 * ta + 127) / 255).abs_diff((rp[2] as u32 * ra + 127) / 255) as u8;
            let da = tp[3].abs_diff(rp[3]);
            let d = dr.max(dg).max(db).max(da);
            if d > tile_max_diff {
                tile_max_diff = d;
            }
            if d > 2 {
                tile_big_diffs += 1;
            }
        }
        max_tile_premul_diff = max_tile_premul_diff.max(tile_max_diff);
        assert_eq!(
            tile_big_diffs, 0,
            "[{label}] Tile {coord:?} had {tile_big_diffs} premultiplied pixel diffs > 2 between 64 MB pool and 512 MB reference (max_diff={tile_max_diff})"
        );

        // Non-solid inked tiles along distinct curves must never duplicate each other's contents
        if tight_tile.solid_rgba8().is_none() {
            if let Some(prev_coord) = seen_hashes.insert(h_tight, coord) {
                panic!(
                    "[{label}] Duplicate inked tile hash detected! Tile {coord:?} cloned tile {prev_coord:?}"
                );
            }
        }
    }
    println!(
        "[{label}] Committed {} tiles (0 duplicate hashes, max premul diff vs 512 MB ref = {max_tile_premul_diff})",
        tight_layer.grid.tiles.len()
    );

    // 2. Compare final rendered viewports at zoom = 0.25 and verify 0 missing background pixels + match vs 512 MB ref

    let doc_half_w_vp = (doc_w as f32 * 0.25 * 0.5) as i32;
    let doc_half_h_vp = (doc_h as f32 * 0.25 * 0.5) as i32;
    let cx = vp_w as i32 / 2;
    let cy = vp_h as i32 / 2;
    let x_min = (cx - doc_half_w_vp + 2).max(0) as u32;
    let x_max = (cx + doc_half_w_vp - 2).min(vp_w as i32) as u32;
    let y_min = (cy - doc_half_h_vp + 2).max(0) as u32;
    let y_max = (cy + doc_half_h_vp - 2).min(vp_h as i32) as u32;

    let mut mismatched = 0usize;
    let mut max_diff = 0u8;
    let mut missing_bg_holes = 0usize;
    let mut pure_white_bg_pixels = 0usize;
    let mut inked_pixels = 0usize;

    for y in y_min..y_max {
        for x in x_min..x_max {
            let off = ((y * vp_w + x) * 4) as usize;
            let tp = &tight_vp[off..off + 4];
            let rp = &ref_vp[off..off + 4];

            let diff = tp[0]
                .abs_diff(rp[0])
                .max(tp[1].abs_diff(rp[1]))
                .max(tp[2].abs_diff(rp[2]))
                .max(tp[3].abs_diff(rp[3]));
            max_diff = max_diff.max(diff);
            if diff > 3 {
                mismatched += 1;
            }

            // Detect checkerboard hole where reference is pure white Background (255,255,255)
            // but tight pool fell back to gray checkerboard (<240)!
            if rp[0] >= 252 && rp[1] >= 252 && rp[2] >= 252 {
                if tp[0] < 245 || tp[1] < 245 || tp[2] < 245 {
                    missing_bg_holes += 1;
                } else {
                    pure_white_bg_pixels += 1;
                }
            } else {
                inked_pixels += 1;
            }
        }
    }

    assert_eq!(
        missing_bg_holes, 0,
        "[{label}] Found {missing_bg_holes} missing white background / checkerboard hole pixels!"
    );
    assert_eq!(
        mismatched, 0,
        "[{label}] Tight 64 MB viewport had {mismatched} pixels differing >3 from 512 MB ref (max_diff={max_diff})"
    );
    assert!(
        pure_white_bg_pixels > 10_000 && inked_pixels > 1_000,
        "[{label}] Sanity check failed: white_bg={pure_white_bg_pixels}, inked={inked_pixels}"
    );
}

#[test]
fn test_dx12_4k_and_manga_b4_tight_vram_64mb_stress_and_solid_dedup() {
    let _guard = lock_dx12();
    // 1. Illustration 4K (3840x2160) on tight 64 MB pool at zoom = 0.25
    run_tight_vram_64mb_stress("Illustration-4K", 3840, 2160, 1024, 600);
    // 2. Manga B4 (6071x8598, 816 tiles!) on tight 64 MB pool at zoom = 0.25
    run_tight_vram_64mb_stress("Manga-B4-6071x8598", 6071, 8598, 1600, 2200);
}

#[test]
fn test_dx12_chunked_commit_exceeding_pool_capacity_zero_duplication() {
    let _guard = lock_dx12();
    // Force a single stroke touching >24 distinct tiles onto a tiny 16-slot (8 MB) pool
    // so `commit_to_layer_pool_with_selection` MUST split across multiple sub-batches!
    let brush = NativeBrushConfig {
        fg_color: [0.85, 0.20, 0.15],
        size: 64.0,
        hardness: 0.9,
        spacing: 0.15,
        opacity: 1.0,
        ..Default::default()
    };
    let pts = make_curved_stroke_points(120.0, 180.0, 3920.0, 3840.0, 240.0, 2.3, 140, 64.0);

    let mut doc_tiny = make_white_doc("chunk-tiny", 4096, 4096);
    let lid_tiny = doc_tiny.active_layer_id.clone().unwrap();
    {
        let Some(mut r_tiny) =
            make_headless_renderer_vram(1024, 1024, 4096, 4096, 16 * BYTES_16F as u64)
        else {
            return;
        };
        emit_and_commit_stroke(&mut r_tiny, &mut doc_tiny, &lid_tiny, brush.clone(), &pts, 777);
    }

    let mut doc_ref = make_white_doc("chunk-ref", 4096, 4096);
    let lid_ref = doc_ref.active_layer_id.clone().unwrap();
    {
        let Some(mut r_ref) =
            make_headless_renderer_vram(1024, 1024, 4096, 4096, 512 * 1024 * 1024)
        else {
            return;
        };
        emit_and_commit_stroke(&mut r_ref, &mut doc_ref, &lid_ref, brush, &pts, 777);
    }

    let l_tiny = doc_tiny.layer(&lid_tiny).unwrap();
    let l_ref = doc_ref.layer(&lid_ref).unwrap();
    assert!(
        l_tiny.grid.tiles.len() > 24,
        "Stroke must exceed 16-slot pool capacity to exercise chunking, got {} tiles",
        l_tiny.grid.tiles.len()
    );
    assert_eq!(l_tiny.grid.tiles.len(), l_ref.grid.tiles.len());

    let mut hashes = HashSet::new();
    for (&coord, t_tiny) in &l_tiny.grid.tiles {
        let b_tiny = t_tiny.to_rgba8(None, false).unwrap();
        let b_ref = l_ref.grid.tiles.get(&coord).unwrap().to_rgba8(None, false).unwrap();
        assert_eq!(
            fnv1a_hash(&b_tiny),
            fnv1a_hash(&b_ref),
            "Chunked commit tile {coord:?} diverged from 512 MB reference"
        );
        assert!(
            hashes.insert(fnv1a_hash(&b_tiny)),
            "Chunked commit produced duplicate tile contents at {coord:?}"
        );
    }
}

#[test]
fn test_dx12_mouse_120hz_stream_and_active_mouse_up_never_dropped() {
    let _guard = lock_dx12();
    let (handle, mut producers) = match EngineHandle::spawn(
        SurfaceTarget::Headless {
            width: 1024,
            height: 768,
        },
        EngineConfig {
            doc_width: 1024,
            doc_height: 768,
            show_checkerboard: true,
            matte_color: [0.086, 0.086, 0.086, 1.0],
            memory_budget: MemoryBudgetConfig {
                vram_budget_bytes: 64 * 1024 * 1024,
                ..Default::default()
            },
            ..Default::default()
        },
    ) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!("Skipping DX12 mouse 120 Hz stream test (no adapter available): {err}");
            return;
        }
    };

    {
        let docs = handle.documents();
        let mut mgr = docs.write();
        mgr.create_document(
            "mouse-120hz-doc",
            "Mouse 120Hz Doc",
            CanvasDimensions {
                width: 1024,
                height: 768,
                dpi: 300,
            },
            CanvasColorMode::Color,
            "#ffffff",
            60.0,
        );
    }
    handle.send_command(EngineCommand::SyncActiveDocument);
    handle.send_command(EngineCommand::SetVisible(true));
    handle.send_command(EngineCommand::SetViewport(ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 1024,
        height_px: 768,
        dpr: 1.0,
    }));
    handle.send_command(EngineCommand::SetCamera(CameraState {
        pan_x: 512.0,
        pan_y: 384.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    }));
    handle.send_command(EngineCommand::SetCollabPointsEnabled(true));
    handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
        NativeBrushConfig {
            fg_color: [0.1, 0.1, 0.1],
            size: 18.0,
            hardness: 0.95,
            spacing: 0.15,
            stabilization: 0.0,
            smoothing: false,
            post_correction: 0,
            ..Default::default()
        },
    )));
    // Wait briefly so initial viewport/camera/brush commands settle before input stream
    std::thread::sleep(Duration::from_millis(60));

    // Push 60 MouseDraw samples spaced 8 ms apart (125 Hz): phase 1 -> 58x phase 2 -> phase 3
    // Use low timestamps starting near 10.0 ms as well to verify NEG_INFINITY init never suppresses!
    let base_ts = 10.0f64;
    let total_samples = 60usize;
    for i in 0..total_samples {
        let t = i as f64 / (total_samples - 1) as f64;
        let x = 100.0 + 800.0 * t;
        let y = 140.0 + 480.0 * t + (t * std::f64::consts::TAU * 2.0).sin() * 45.0;
        let phase = if i == 0 {
            1
        } else if i + 1 == total_samples {
            3
        } else {
            2
        };
        assert!(producers.nav.push(NativeNavEvent::MouseDraw {
            phys_x: x as f32,
            phys_y: y as f32,
            phase,
            shift_held: false,
            timestamp_ms: base_ts + i as f64 * 8.0,
        }));
    }

    let mut committed_points = None;
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline && committed_points.is_none() {
        for ev in handle.events().try_iter() {
            if let EngineEvent::StrokeCommitted {
                dirty_rect, points, ..
            } = ev
            {
                assert!(!dirty_rect.is_empty(), "Committed mouse stroke dirty_rect must be non-empty");
                committed_points = Some(points);
                break;
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    }

    let points = committed_points.expect("StrokeCommitted must fire cleanly on MouseDraw phase 3");
    // Before our fix, 250ms self-throttling dropped 58 of 60 samples (<= 3 points, dropped phase 3!)
    assert!(
        points.len() >= 55,
        "All 60 120Hz mouse samples must be processed (not throttled to 4 Hz), got {} points",
        points.len()
    );

    // Wait for throttled diagnostics tick (250 ms) and assert active_stroke_dabs > 50
    let mut observed_dabs = handle.diagnostics().active_stroke_dabs;
    let diag_deadline = Instant::now() + Duration::from_secs(2);
    while Instant::now() < diag_deadline && observed_dabs <= 50 {
        std::thread::sleep(Duration::from_millis(40));
        // Poke hover so engine loop wakes and flushes diagnostics even when idle
        let _ = producers.nav.push(NativeNavEvent::Hover {
            phys_x: 512.0,
            phys_y: 384.0,
            timestamp_ms: base_ts + 800.0,
        });
        observed_dabs = handle.diagnostics().active_stroke_dabs;
    }
    assert!(
        observed_dabs > 50,
        "Expected active_stroke_dabs > 50 for 60-sample 120 Hz mouse stroke, got {observed_dabs}"
    );

    // Part 2: Verify an active mouse stroke's phase == 3 mouse-up is NEVER dropped even if a
    // stylus packet arrives < 250 ms earlier (so mouse strokes can never get stuck!)
    let t2 = clock::now_ms() + 2000.0;
    assert!(producers.nav.push(NativeNavEvent::MouseDraw {
        phys_x: 200.0,
        phys_y: 500.0,
        phase: 1,
        shift_held: false,
        timestamp_ms: t2,
    }));
    for step in 1..=10 {
        assert!(producers.nav.push(NativeNavEvent::MouseDraw {
            phys_x: 200.0 + step as f32 * 25.0,
            phys_y: 500.0,
            phase: 2,
            shift_held: false,
            timestamp_ms: t2 + step as f64 * 8.0,
        }));
    }
    // Wait so engine processes the mouse stroke start + moves first
    std::thread::sleep(Duration::from_millis(50));

    // Inject a stylus hover packet 5 ms before mouse-up!
    assert!(producers.wintab.push(NativeInputSample {
        phys_x: 450.0,
        phys_y: 500.0,
        pressure: 0.0,
        tilt_x: 0.0,
        tilt_y: 0.0,
        twist: 0.0,
        timestamp_ms: t2 + 85.0,
        buttons: 0,
        phase: 0,
        backend: 1,
    }));
    assert!(producers.nav.push(NativeNavEvent::MouseDraw {
        phys_x: 450.0,
        phys_y: 500.0,
        phase: 3,
        shift_held: false,
        timestamp_ms: t2 + 90.0,
    }));

    let mut second_committed = false;
    let deadline2 = Instant::now() + Duration::from_secs(3);
    while Instant::now() < deadline2 && !second_committed {
        for ev in handle.events().try_iter() {
            if matches!(ev, EngineEvent::StrokeCommitted { .. }) {
                second_committed = true;
                break;
            }
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(
        second_committed,
        "Active mouse stroke phase == 3 must NEVER be dropped even when a stylus packet arrived within 250 ms"
    );

    handle.shutdown();
}

#[test]
fn test_dx12_multi_tile_darken_brush_distinct_tiles() {
    let _guard = lock_dx12();
    let Some(mut renderer) =
        make_headless_renderer_vram(1024, 1024, 1024, 1024, 128 * 1024 * 1024)
    else {
        return;
    };

    let mut doc = Document::new_blank(
        "darken-doc",
        "Darken Multi-Tile",
        CanvasDimensions {
            width: 1024,
            height: 1024,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "transparent",
        60.0,
        50,
    );
    let lid = doc.active_layer_id.clone().unwrap();

    // Non-45° diagonal so every crossed 256x256 tile has a DISTINCT local pixel geometry!
    // Slope ~0.78 crosses (0,0), (1,0)/(1,1), (2,1)/(2,2), (3,2)/(3,3) cleanly at distinct offsets.
    let mut brush = NativeBrushConfig {
        fg_color: [0.85, 0.55, 0.30],
        size: 36.0,
        hardness: 0.95,
        spacing: 0.18,
        opacity: 1.0,
        blend_tips_mode: CspBlendTipsMode::Darken,
        ..Default::default()
    };

    let (tip_count, tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
    let mut emitter1 = StrokeDabEmitter::new(brush.clone(), 4242, tip_count, tip_aspect);
    let rand_off = emitter1.stroke_grain_offset;
    renderer.begin_gpu_stroke(1024, 1024, false, brush.clone(), rand_off);

    // Batch 1: stamps warm orange across >= 4 distinct 256x256 tiles (allocating them `is_new = true`)
    let mut batch1_dabs = Vec::new();
    let pts1 = make_curved_stroke_points(60.0, 90.0, 960.0, 790.0, 0.0, 0.0, 64, 36.0);
    let mut sp1 = SplineGenerator::new(0.0);
    sp1.push_knot(pts1[0]);
    emitter1.emit_initial_point(&pts1[0], None, 0.0, &mut batch1_dabs);
    for &p in pts1.iter().skip(1) {
        for seg in sp1.push_knot(p) {
            emitter1.emit_segment(&seg, None, 0.0, &mut batch1_dabs);
        }
    }
    for seg in sp1.finish() {
        emitter1.emit_segment(&seg, None, 0.0, &mut batch1_dabs);
    }
    let touched1 = renderer.stamp_gpu_stroke_dabs(&batch1_dabs, &[]);
    assert!(
        touched1.len() >= 4,
        "Batch 1 must touch at least 4 distinct 256x256 tiles, got {}",
        touched1.len()
    );

    // Batch 2: stamps darker blue-green over the EXACT SAME 4+ tiles (`is_new = false` -> Darken compute merge!)
    brush.fg_color = [0.15, 0.30, 0.75];
    let mut emitter2 = StrokeDabEmitter::new(brush.clone(), 9001, tip_count, tip_aspect);
    let mut batch2_dabs = Vec::new();
    let pts2 = make_curved_stroke_points(60.0, 90.0, 960.0, 790.0, 0.0, 0.0, 64, 36.0);
    let mut sp2 = SplineGenerator::new(0.0);
    sp2.push_knot(pts2[0]);
    emitter2.emit_initial_point(&pts2[0], None, 0.0, &mut batch2_dabs);
    for &p in pts2.iter().skip(1) {
        for seg in sp2.push_knot(p) {
            emitter2.emit_segment(&seg, None, 0.0, &mut batch2_dabs);
        }
    }
    for seg in sp2.finish() {
        emitter2.emit_segment(&seg, None, 0.0, &mut batch2_dabs);
    }
    let touched2 = renderer.stamp_gpu_stroke_dabs(&batch2_dabs, &[]);
    assert!(
        touched2.is_empty(),
        "Batch 2 should hit existing tiles (`is_new == false`) to trigger Darken compute merge"
    );

    let doc_id = doc.id.clone();
    let committed = {
        let layer = doc.layer(&lid).unwrap();
        renderer
            .commit_gpu_stroke_to_layer(&doc_id, &lid, &layer.grid, None, false, false)
            .expect("Darken commit must succeed")
    };
    {
        let layer = doc.layer_mut(&lid).unwrap();
        let empty = HashMap::new();
        let (_deltas, cleared) =
            layer
                .grid
                .apply_gpu_committed_tiles(&lid, committed.tiles, &empty, 128);
        renderer.regenerate_layer_mipmaps(&doc_id, &lid, &mut layer.grid, &cleared, None);
    }
    renderer.clear_live_stroke();

    let layer = doc.layer(&lid).unwrap();
    assert!(
        layer.grid.tiles.len() >= 4,
        "Committed Darken stroke must span >= 4 tiles, got {}",
        layer.grid.tiles.len()
    );

    // 1. Assert every committed tile has a unique hash (zero duplicated tile contents!)
    let mut tile_hashes: HashMap<u64, TileCoord> = HashMap::new();
    for (&coord, tile) in &layer.grid.tiles {
        let rgba = tile.to_rgba8(None, false).unwrap();
        let h = fnv1a_hash(&rgba);
        if let Some(prev) = tile_hashes.insert(h, coord) {
            panic!(
                "Multi-tile Darken bug: tile {coord:?} duplicated pixels from tile {prev:?}!"
            );
        }
    }

    // 2. Verify document-coordinate accuracy along the diagonal in 4 distinct tiles:
    // Line equation: x(t) = 60 + 900*t, y(t) = 90 + 700*t.
    // Darken(rgb1=[0.85, 0.55, 0.30], rgb2=[0.15, 0.30, 0.75]) = [0.15, 0.30, 0.30] -> (~38, ~77, ~77)!
    let probe_ts = [0.08f64, 0.36, 0.66, 0.94];
    let mut probed_tiles = HashSet::new();
    for &t in &probe_ts {
        let px = (60.0 + 900.0 * t).round() as i32;
        let py = (90.0 + 700.0 * t).round() as i32;
        let coord = TileCoord::new(px / TILE_SIZE as i32, py / TILE_SIZE as i32);
        probed_tiles.insert(coord);

        let rgba = layer.grid.get_pixel_rgba8(px, py, None);
        assert!(
            rgba[3] > 220,
            "Probe at ({px}, {py}) in tile {coord:?} must be inked, got {rgba:?}"
        );
        // Darken min([0.85,0.55,0.30], [0.15,0.30,0.75]) = [0.15, 0.30, 0.30] => R~38, G~77, B~77
        assert!(
            rgba[0] < 70 && rgba[1] < 105 && rgba[2] < 105,
            "Darken merge at ({px}, {py}) in tile {coord:?} should preserve min(R,G,B) ~= (38,77,77), got {rgba:?}"
        );

        // Verify an off-diagonal point in the SAME tile (far from the line) is completely transparent
        let tile_origin_x = coord.tx * TILE_SIZE as i32;
        let tile_origin_y = coord.ty * TILE_SIZE as i32;
        let off_y = if (py - tile_origin_y) < 128 {
            tile_origin_y + 240
        } else {
            tile_origin_y + 12
        };
        let off_x = if (px - tile_origin_x) < 128 {
            tile_origin_x + 240
        } else {
            tile_origin_x + 12
        };
        let empty_px = layer.grid.get_pixel_rgba8(off_x, off_y, None);
        assert_eq!(
            empty_px[3], 0,
            "Off-diagonal corner ({off_x}, {off_y}) in tile {coord:?} must remain transparent (not polluted by another tile's Darken slot!), got {empty_px:?}"
        );
    }
    assert_eq!(
        probed_tiles.len(),
        4,
        "Probes must span 4 distinct 256x256 tiles, got {probed_tiles:?}"
    );
}

#[test]
fn test_dx12_mipmap_preserves_evicted_sibling_and_live_scissor_dpr() {
    let _guard = lock_dx12();
    // Part A: Evicted sibling quadrant preservation in `regenerate_layer_mipmaps`
    let Some(mut renderer) =
        make_headless_renderer_vram(512, 512, 1024, 1024, 16 * BYTES_16F as u64)
    else {
        return;
    };
    let mut doc = make_white_doc("mip-evict-doc", 1024, 1024);
    let lid = doc.active_layer_id.clone().unwrap();

    // Stroke 1: bright RED inside tile (0, 0)
    let red_brush = NativeBrushConfig {
        fg_color: [0.95, 0.05, 0.05],
        size: 90.0,
        hardness: 0.98,
        spacing: 0.15,
        opacity: 1.0,
        ..Default::default()
    };
    let pts_red = make_curved_stroke_points(80.0, 128.0, 180.0, 128.0, 0.0, 0.0, 12, 90.0);
    emit_and_commit_stroke(&mut renderer, &mut doc, &lid, red_brush, &pts_red, 11);

    // Explicitly evict tile (0, 0) from L1 VRAM before committing a stroke in sibling tile (1, 0)!
    let evict_key = renderer.tile_pool_mut().make_key(&doc.id, &lid, 0, TileCoord::new(0, 0));
    renderer.tile_pool_mut().evict_key(&evict_key);

    // Stroke 2: bright BLUE inside sibling tile (1, 0) — triggers regenerate_layer_mipmaps for LOD 1 (0, 0)!
    let blue_brush = NativeBrushConfig {
        fg_color: [0.05, 0.10, 0.95],
        size: 90.0,
        hardness: 0.98,
        spacing: 0.15,
        opacity: 1.0,
        ..Default::default()
    };
    let pts_blue = make_curved_stroke_points(320.0, 128.0, 440.0, 128.0, 0.0, 0.0, 12, 90.0);
    emit_and_commit_stroke(&mut renderer, &mut doc, &lid, blue_brush, &pts_blue, 22);

    // Render at zoom = 0.25 (LOD 2) and verify BOTH red (0,0) AND blue (1,0) quadrants survived!
    let vp_rgba = render_viewport_zoom_025(&mut renderer, &doc, 512, 512);
    // Doc (128, 128) maps to vp (256 + (128-512)*0.25, 256 + (128-512)*0.25) = (160, 160)
    // Doc (380, 128) maps to vp (256 + (380-512)*0.25, 160) = (223, 160)
    let red_off = ((160 * 512 + 160) * 4) as usize;
    let blue_off = ((160 * 512 + 223) * 4) as usize;
    let r_px = &vp_rgba[red_off..red_off + 4];
    let b_px = &vp_rgba[blue_off..blue_off + 4];
    assert!(
        r_px[0] > 180 && r_px[1] < 80 && r_px[2] < 80,
        "Evicted sibling quadrant (0,0) MUST remain red after mipmap regeneration, got {r_px:?}"
    );
    assert!(
        b_px[2] > 180 && b_px[0] < 80,
        "Updated sibling quadrant (1,0) MUST be blue after mipmap regeneration, got {b_px:?}"
    );

    // Part B: LiveGpuStrokeOverlay scissor + predicted dab clipping at zoom = 0.25 across dpr = 1.0, 1.25, 1.5
    for dpr in [1.0f32, 1.25, 1.5] {
        let vp_w = (512.0 * dpr).round() as u32;
        let vp_h = (512.0 * dpr).round() as u32;
        let Some(mut r_live) =
            make_headless_renderer_vram(vp_w, vp_h, 1024, 1024, 64 * 1024 * 1024)
        else {
            return;
        };
        let mut live_doc = make_white_doc("live-scissor-doc", 1024, 1024);
        r_live.sync_document(&mut live_doc, None).unwrap();

        let vp = ViewportRect {
            x_px: 0,
            y_px: 0,
            width_px: vp_w,
            height_px: vp_h,
            dpr,
        };
        let cam = CameraState {
            pan_x: 256.0,
            pan_y: 256.0,
            zoom: 0.25,
            rotation: 0.0,
            flip_x: false,
            flip_y: false,
        };
        let display = CompositorDisplayConfig {
            show_checkerboard: true,
            matte_color: [0.05, 0.05, 0.05, 1.0],
            layer_stack_caching: true,
            ..Default::default()
        };
        let cursor = CursorConfig {
            visible: false,
            ..Default::default()
        };

        let brush = NativeBrushConfig {
            fg_color: [0.05, 0.65, 0.15],
            size: 48.0,
            hardness: 0.95,
            spacing: 0.15,
            opacity: 1.0,
            ..Default::default()
        };
        r_live.begin_gpu_stroke(1024, 1024, false, brush.clone(), [0.0, 0.0]);

        let make_dab = |cx: f32, cy: f32| GpuBrushDab {
            pos_size: [cx, cy, 24.0, 24.0],
            rot_tip: [1.0, 0.0, 0.0, 0.95],
            color_rgba: [0.05, 0.65, 0.15, 1.0],
            bg_grain: [1.0, 1.0, 1.0, 0.0],
            extra: [1.0, 1.0, 1.0, 0.0],
        };

        // Frame 1: stamp first segment left of x=256 + predicted dab far right at (800, 512)
        let d1 = make_dab(220.0, 512.0);
        r_live.stamp_gpu_stroke_dabs(&[d1], &[]);
        let pred_far = make_dab(800.0, 512.0);
        let _ = r_live.render_document_frame_with_brush(
            &live_doc,
            None,
            &display,
            &vp,
            &cam,
            &[],
            false,
            true,
            &[pred_far],
            Some(DocBounds {
                min_x: 190,
                min_y: 480,
                max_x: 250,
                max_y: 544,
            }),
            &cursor,
            None,
            true,
        );

        // Frame 2: stroke crosses x=256 boundary (256..300) and predicted dab disappears (empty slice)
        let d2 = make_dab(260.0, 512.0);
        r_live.stamp_gpu_stroke_dabs(&[d2], &[]);
        let _ = r_live.render_document_frame_with_brush(
            &live_doc,
            None,
            &display,
            &vp,
            &cam,
            &[],
            false,
            true,
            &[],
            Some(DocBounds {
                min_x: 230,
                min_y: 480,
                max_x: 290,
                max_y: 544,
            }),
            &cursor,
            None,
            true,
        );

        let (_, _, rgba2) = r_live.readback_headless_rgba8().unwrap();
        // Check stroke pixel right on x=256 tile boundary: doc (256, 512) -> css (256 + (256-512)*0.25, 256) = (192, 256)
        let bx = (192.0 * dpr).round() as u32;
        let by = (256.0 * dpr).round() as u32;
        let b_off = ((by * vp_w + bx) * 4) as usize;
        assert!(
            rgba2[b_off + 1] > 120 && rgba2[b_off] < 80,
            "[dpr={dpr}] Live stroke across x=256 boundary must be visibly green, got {:?}",
            &rgba2[b_off..b_off + 4]
        );

        // Check former predicted dab location (800, 512) -> css (256 + (800-512)*0.25, 256) = (328, 256)
        // MUST be cleanly cleared back to pure white (0 ghost trails!)
        let gx = (328.0 * dpr).round() as u32;
        let gy = (256.0 * dpr).round() as u32;
        let g_off = ((gy * vp_w + gx) * 4) as usize;
        let gp = &rgba2[g_off..g_off + 4];
        assert!(
            gp[0] >= 250 && gp[1] >= 250 && gp[2] >= 250,
            "[dpr={dpr}] Former predicted dab at (800,512) left ghost trail pixels: {gp:?}"
        );
    }
}

/// Headless DX12 benchmark & regression test for the full live-stroke pipeline on a 4K (`3840×2160`) canvas:
/// 1. Simulates 100 consecutive live-stroke frames with 5 tablet input samples per frame (500 samples total),
///    proving all 5 samples per frame are batched into ONE GPU stamp dispatch per frame (not 5).
/// 2. Intentionally inserts a 380 ms idle gap before the stroke to reproduce the historical `3 FPS` HUD bug,
///    verifying active FPS stays realistic (`>= 30 FPS` when frame time `< 16 ms`, never `3 FPS`).
/// 3. Commits pen-up cleanly and proves ZERO PNG thumbnails are generated synchronously on the DX12 render
///    thread (`sync_render_thread_thumbnails == 0`), while `EngineEvent::ThumbnailsUpdated` arrives
///    asynchronously from the background thumbnail worker.
#[test]
fn test_dx12_4k_100frame_batched_live_stroke_benchmark() {
    let _guard = lock_dx12();
    let vp_w = 1280u32;
    let vp_h = 720u32;
    let doc_w = 3840u32;
    let doc_h = 2160u32;

    let (handle, mut producers) = match EngineHandle::spawn(
        SurfaceTarget::Headless {
            width: vp_w,
            height: vp_h,
        },
        EngineConfig {
            doc_width: doc_w,
            doc_height: doc_h,
            show_checkerboard: true,
            matte_color: [0.086, 0.086, 0.086, 1.0],
            memory_budget: MemoryBudgetConfig {
                vram_budget_bytes: 128 * 1024 * 1024,
                ..Default::default()
            },
            ..Default::default()
        },
    ) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!("Skipping DX12 4K 100-frame benchmark test (no adapter available): {err}");
            return;
        }
    };

    {
        let docs = handle.documents();
        let mut mgr = docs.write();
        mgr.create_document(
            "bench-4k-doc",
            "4K Live Stroke Bench",
            CanvasDimensions {
                width: doc_w,
                height: doc_h,
                dpi: 300,
            },
            CanvasColorMode::Color,
            "#ffffff",
            60.0,
        );
    }
    handle.send_command(EngineCommand::SyncActiveDocument);
    handle.send_command(EngineCommand::SetVisible(true));
    handle.send_command(EngineCommand::SetViewport(ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: vp_w,
        height_px: vp_h,
        dpr: 1.0,
    }));
    handle.send_command(EngineCommand::SetCamera(CameraState {
        pan_x: vp_w as f32 * 0.5,
        pan_y: vp_h as f32 * 0.5,
        zoom: 0.25,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    }));
    handle.send_command(EngineCommand::SetCollabPointsEnabled(true));
    handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
        NativeBrushConfig {
            fg_color: [0.12, 0.22, 0.68],
            size: 32.0,
            hardness: 0.92,
            spacing: 0.15,
            opacity: 1.0,
            stabilization: 0.0,
            smoothing: false,
            post_correction: 0,
            ..Default::default()
        },
    )));

    // Wait for initial viewport frame to render cleanly
    let init_deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < init_deadline && handle.diagnostics().total_frames_rendered == 0 {
        std::thread::sleep(Duration::from_millis(5));
    }
    assert!(
        handle.diagnostics().total_frames_rendered >= 1,
        "Initial 4K viewport frame must render before benchmark begins"
    );

    // Deliberately sleep > 350 ms to create an idle gap (reproducing the historical "3 FPS" bug!)
    std::thread::sleep(Duration::from_millis(380));

    let perf_before = handle.perf_snapshot();
    let mut prev_frames = handle.diagnostics().total_frames_rendered;
    let total_stroke_frames = 100usize;
    let samples_per_frame = 5usize;
    let total_samples = total_stroke_frames * samples_per_frame;

    let bench_start = Instant::now();
    let mut first_frame_diag = None;
    let mut frames_rendered = 0u64;

    for frame_idx in 0..total_stroke_frames {
        let now_ts = clock::now_ms();
        let mut batch = Vec::with_capacity(samples_per_frame);
        for k in 0..samples_per_frame {
            let global_i = frame_idx * samples_per_frame + k;
            let t = global_i as f64 / (total_samples - 1) as f64;
            // Sweep smoothly inside the visible 4K artboard (zoom=0.25 => artboard spans x=[160..1120], y=[90..630])
            let phys_x = (220.0 + 840.0 * t) as f32;
            let phys_y = (200.0 + 300.0 * t + (t * std::f64::consts::TAU * 3.0).sin() * 65.0) as f32;
            let phase = if global_i == 0 { 1u8 } else { 2u8 };
            batch.push(NativeInputSample {
                phys_x,
                phys_y,
                pressure: 0.75 + 0.2 * (t as f32).sin(),
                tilt_x: 0.0,
                tilt_y: 0.0,
                twist: 0.0,
                timestamp_ms: now_ts - ((samples_per_frame - 1 - k) as f64 * 0.4),
                buttons: 1,
                phase,
                backend: 1,
            });
        }

        let pushed = producers.wintab.push_batch(&batch);
        assert_eq!(pushed, samples_per_frame, "All 5 frame samples must push cleanly");

        // Wait for the engine to drain all 5 samples and present this frame
        let frame_deadline = Instant::now() + Duration::from_secs(2);
        let mut cur_frames = handle.diagnostics().total_frames_rendered;
        while cur_frames <= prev_frames && Instant::now() < frame_deadline {
            std::thread::yield_now();
            cur_frames = handle.diagnostics().total_frames_rendered;
        }
        assert!(
            cur_frames > prev_frames,
            "Engine did not render frame {frame_idx} within 2s"
        );
        frames_rendered += cur_frames - prev_frames;
        prev_frames = cur_frames;

        if frame_idx == 0 {
            first_frame_diag = Some(handle.diagnostics());
        }
    }

    let stroke_elapsed = bench_start.elapsed();
    let perf_after_move = handle.perf_snapshot();
    let diag_after_move = handle.diagnostics();
    let dispatches_during_move = perf_after_move.stamp_dispatches - perf_before.stamp_dispatches;

    eprintln!(
        "[4K 100-frame live-stroke bench] elapsed={:.1}ms, frames={}, stamp_dispatches={} (for {} samples), fps={:.1}, frame_ms={:.2}ms, i2p={:.2}ms",
        stroke_elapsed.as_secs_f64() * 1000.0,
        frames_rendered,
        dispatches_during_move,
        total_samples,
        diag_after_move.fps,
        diag_after_move.frame_time_ms,
        diag_after_move.input_to_present_ms,
    );

    // 1. Verify all 5 samples per frame are batched into 1 stamp dispatch per frame (NOT 500!)
    assert!(
        dispatches_during_move > 0 && dispatches_during_move <= frames_rendered,
        "Expected <= 1 stamp dispatch per rendered frame (got {dispatches_during_move} dispatches across {frames_rendered} frames for {total_samples} input samples)"
    );
    assert!(
        dispatches_during_move <= total_stroke_frames as u64,
        "100 live-stroke frames with 5 samples/frame must trigger <= 100 stamp dispatches, got {dispatches_during_move}"
    );

    // 2. Verify active FPS telemetry never falsely reports "3 FPS" after the prior 380 ms idle gap!
    let first_diag = first_frame_diag.expect("First frame diagnostics must be captured");
    assert!(
        !first_diag.is_idle,
        "Engine diagnostics must report active (!is_idle) immediately after rendering a frame"
    );
    if first_diag.frame_time_ms < 16.0 {
        assert!(
            first_diag.fps >= 30.0,
            "First frame after 380 ms idle gap with frame_time_ms={:.2}ms must report >= 30 FPS (never 3 FPS!), got {:.1} FPS",
            first_diag.frame_time_ms,
            first_diag.fps
        );
    }
    assert!(
        !diag_after_move.is_idle,
        "Engine diagnostics must report active (!is_idle) after 100 consecutive live-stroke frames"
    );
    if diag_after_move.frame_time_ms < 16.0 {
        assert!(
            diag_after_move.fps >= 30.0,
            "100 consecutive live-stroke frames with frame_time_ms={:.2}ms must report >= 30 FPS, got {:.1} FPS",
            diag_after_move.frame_time_ms,
            diag_after_move.fps
        );
    }
    assert!(
        diag_after_move.input_to_present_ms < 120.0,
        "I2P latency must not be polluted by prior 380 ms idle gap, got {:.2}ms",
        diag_after_move.input_to_present_ms
    );

    // 3. Pen-up commit: verify clean commit, ZERO synchronous render-thread PNG thumbnails,
    //    and asynchronous EngineEvent::ThumbnailsUpdated delivery from background worker!
    assert!(producers.wintab.push(NativeInputSample {
        phys_x: 1060.0,
        phys_y: 500.0,
        pressure: 0.0,
        tilt_x: 0.0,
        tilt_y: 0.0,
        twist: 0.0,
        timestamp_ms: clock::now_ms(),
        buttons: 0,
        phase: 3,
        backend: 1,
    }));

    let mut saw_stroke_committed = false;
    let mut saw_async_thumbnail = false;
    let commit_deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < commit_deadline && (!saw_stroke_committed || !saw_async_thumbnail) {
        for ev in handle.events().try_iter() {
            match ev {
                EngineEvent::StrokeCommitted { dirty_rect, points, .. } => {
                    assert!(
                        !dirty_rect.is_empty(),
                        "Pen-up StrokeCommitted dirty_rect must be non-empty"
                    );
                    assert!(
                        points.len() >= 100,
                        "Pen-up committed stroke should retain sampled path points, got {}",
                        points.len()
                    );
                    saw_stroke_committed = true;
                }
                EngineEvent::ThumbnailsUpdated { updates, .. } => {
                    if updates.iter().any(|u| {
                        u.thumbnail_url
                            .as_deref()
                            .is_some_and(|s| s.starts_with("data:image/png;base64,"))
                    }) {
                        saw_async_thumbnail = true;
                    }
                }
                _ => {}
            }
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    let perf_after_commit = handle.perf_snapshot();
    assert!(
        saw_stroke_committed,
        "Pen-up must emit EngineEvent::StrokeCommitted cleanly"
    );
    assert_eq!(
        perf_after_commit.sync_render_thread_thumbnails, 0,
        "Render thread must NEVER generate PNG thumbnails synchronously on pen-up!"
    );
    assert!(
        saw_async_thumbnail && perf_after_commit.async_thumbnails_completed >= 1,
        "Background thumbnail worker must asynchronously emit EngineEvent::ThumbnailsUpdated (saw={saw_async_thumbnail}, completed={})",
        perf_after_commit.async_thumbnails_completed
    );

    // Verify committed 4K document layer contains painted tiles cleanly
    {
        let docs = handle.documents();
        let mgr = docs.read();
        let doc = mgr.active_document().expect("Active 4K doc must exist");
        let aid = doc.active_layer_id.as_deref().expect("Active layer must exist");
        let layer = doc.layer(aid).expect("Active layer node must exist");
        assert!(
            !layer.grid.tiles.is_empty(),
            "Committed 4K stroke must populate painted tiles on the active layer"
        );
    }

    handle.shutdown();
}

// ============================================================================
// Phase 7 Compositor & Latency Audit Regression Tests
// ============================================================================

/// Regression 1: Pure 240 Hz hover cursor moves & 30 Hz marching-ants ticks must hit the
/// `final_scene_sig` fast path with ZERO BelowCache/AboveCache/FinalScene recompositing passes,
/// and `GpuSelectionOverlay::encode_viewport_mask` must NOT re-project when selection & camera
/// are unchanged.
#[test]
fn test_hover_and_marching_ants_perform_zero_recompositing_passes() {
    let _dx12_guard = lock_dx12();
    let Some(mut renderer) =
        make_headless_renderer_vram(512, 512, 512, 512, 128 * 1024 * 1024)
    else {
        return;
    };

    let mut doc = Document::new_blank(
        "doc-hover-fastpath",
        "Hover Fast Path",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        20,
    );
    let below_id = "layer-below".to_string();
    let active_id = "layer-active".to_string();
    let above_id = "layer-above".to_string();
    doc.add_layer(LayerNodeMeta::new_raster(&below_id, "Below"), None, false, false);
    doc.add_layer(LayerNodeMeta::new_raster(&active_id, "Active"), None, false, false);
    doc.add_layer(LayerNodeMeta::new_raster(&above_id, "Above"), None, false, false);
    doc.active_layer_id = Some(active_id.clone());

    // Paint distinct tiles on below, active, and above layers + add an active selection
    let red_px = vec![220u8, 40, 40, 255].repeat(64 * 64);
    let blue_px = vec![40u8, 80, 220, 255].repeat(64 * 64);
    let green_px = vec![40u8, 200, 80, 255].repeat(64 * 64);
    doc.layer_mut(&below_id)
        .unwrap()
        .grid
        .write_rgba8_rect(&red_px, RectI32::new(32, 32, 64, 64), 128, None)
        .unwrap();
    doc.layer_mut(&active_id)
        .unwrap()
        .grid
        .write_rgba8_rect(&blue_px, RectI32::new(128, 128, 64, 64), 128, None)
        .unwrap();
    doc.layer_mut(&above_id)
        .unwrap()
        .grid
        .write_rgba8_rect(&green_px, RectI32::new(256, 256, 64, 64), 128, None)
        .unwrap();

    crate::selection::select_rect(
        &mut doc,
        RectI32::new(64, 64, 192, 192),
        crate::selection::SelectionCombineMode::Replace,
    );

    let display = CompositorDisplayConfig {
        layer_stack_caching: true,
        ..Default::default()
    };
    let vp = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 512,
        height_px: 512,
        dpr: 1.0,
    };
    let cam = CameraState {
        pan_x: 256.0,
        pan_y: 256.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };
    let cursor_cfg = CursorConfig {
        visible: true,
        size: 32.0,
        ..Default::default()
    };

    // Frame 1: initial full build
    let _ = renderer.render_document_frame(
        &doc,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        false,
        &cursor_cfg,
        Some((100.0, 100.0)),
        false,
    );
    let base_stats = renderer.stack_cache_stats();
    let base_sel_rebuilds = renderer.selection_vp_mask_rebuilds();
    assert_eq!(base_stats.below_rebuilds, 1);
    assert_eq!(base_stats.above_rebuilds, 1);
    assert_eq!(base_stats.final_scene_rebuilds, 1);
    assert_eq!(base_sel_rebuilds, 1);

    // Frames 2..=25: pure hover cursor movement + marching-ants ticks (unchanged scene & camera)
    for i in 0..24 {
        let cx = 120.0 + (i as f32) * 10.0;
        let cy = 140.0 + (i as f32) * 6.0;
        let _ = renderer.render_document_frame(
            &doc,
            None,
            &display,
            &vp,
            &cam,
            &[],
            false,
            false,
            &cursor_cfg,
            Some((cx, cy)),
            false,
        );
        assert!(
            renderer
                .last_composite_scissor()
                .is_some_and(|s| s.is_empty()),
            "Pure hover frame {i} must perform ZERO FinalScene compositing"
        );
    }

    let after_stats = renderer.stack_cache_stats();
    assert_eq!(
        after_stats.below_rebuilds, base_stats.below_rebuilds,
        "Pure hover frames must perform ZERO BelowCache rebuilds"
    );
    assert_eq!(
        after_stats.above_rebuilds, base_stats.above_rebuilds,
        "Pure hover frames must perform ZERO AboveCache rebuilds"
    );
    assert_eq!(
        after_stats.final_scene_rebuilds, base_stats.final_scene_rebuilds,
        "Pure hover frames must perform ZERO ActiveUnit/FinalScene recompositing passes"
    );
    assert_eq!(
        after_stats.final_scene_hits, 24,
        "All 24 hover frames must hit the final_scene_sig fast path"
    );
    assert_eq!(
        renderer.selection_vp_mask_rebuilds(),
        base_sel_rebuilds,
        "Selection viewport mask must NOT be re-projected during hover / marching-ants ticks"
    );
}

/// Regression 2: A 1-tile stroke on a 4×4-tile layer must regenerate strictly <= 3 LOD tiles
/// (1 per LOD 1..3) in ONE batched `queue.submit`, with ZERO invalidation of untouched siblings.
#[test]
fn test_mipmap_1_tile_stroke_regenerates_at_most_3_lods_in_1_submit() {
    let _dx12_guard = lock_dx12();
    let Some(mut renderer) =
        make_headless_renderer_vram(512, 512, 1024, 1024, 128 * 1024 * 1024)
    else {
        return;
    };

    let mut doc = Document::new_blank(
        "doc-mip-4x4",
        "Mipmap 4x4",
        CanvasDimensions {
            width: 1024,
            height: 1024,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        20,
    );
    let lid = "layer-4x4".to_string();
    doc.add_layer(LayerNodeMeta::new_raster(&lid, "4x4 Grid"), None, false, false);
    doc.active_layer_id = Some(lid.clone());

    // Populate all 4×4 LOD-0 tiles with non-solid textured pixels (so none take the SolidColor shortcut)
    {
        let layer = doc.layer_mut(&lid).unwrap();
        for ty in 0..4i32 {
            for tx in 0..4i32 {
                let mut tile_rgba = vec![0u8; TILE_SIZE * TILE_SIZE * 4];
                for y in 0..TILE_SIZE {
                    for x in 0..TILE_SIZE {
                        let o = (y * TILE_SIZE + x) * 4;
                        tile_rgba[o] = ((tx * 50 + (x & 31) as i32) & 255) as u8;
                        tile_rgba[o + 1] = ((ty * 50 + (y & 31) as i32) & 255) as u8;
                        tile_rgba[o + 2] = 180;
                        tile_rgba[o + 3] = 255;
                    }
                }
                let td = crate::tiles::TileData::from_raw(
                    crate::tiles::TileFormat::Color32Bit,
                    crate::tiles::TileKind::Raster,
                    tile_rgba,
                );
                layer.grid.set_tile(TileCoord::new(tx, ty), std::sync::Arc::new(td));
            }
        }
    }

    // Build initial full mipmap pyramid (4 LOD-1 + 1 LOD-2 + 1 LOD-3 = 6 LOD tiles)
    renderer.sync_document(&mut doc, None).unwrap();

    // Record untouched sibling LOD-1 slots & versions BEFORE 1-tile stroke in (0, 0)
    let sibling_coords = [
        TileCoord::new(1, 0),
        TileCoord::new(0, 1),
        TileCoord::new(1, 1),
    ];
    let sibling_versions_before: Vec<u64> = {
        let grid = &doc.layer(&lid).unwrap().grid;
        sibling_coords
            .iter()
            .map(|&c| crate::memory::compute_lod_tile_version(grid, 1, c))
            .collect()
    };
    let mipmaps_before = renderer.gpu_pool_stats().mipmaps_generated;
    let submits_before = renderer.tile_pool().mipmap_submits();

    // Mutate ONLY 1 tile: (0, 0) (simulating a localized 1-tile brush stroke commit)
    let dirty_lods = {
        let layer = doc.layer_mut(&lid).unwrap();
        let mut tile_rgba = vec![0u8; TILE_SIZE * TILE_SIZE * 4];
        for y in 0..TILE_SIZE {
            for x in 0..TILE_SIZE {
                let o = (y * TILE_SIZE + x) * 4;
                tile_rgba[o] = 255;
                tile_rgba[o + 1] = (x & 63) as u8;
                tile_rgba[o + 2] = (y & 63) as u8;
                tile_rgba[o + 3] = 255;
            }
        }
        let td = crate::tiles::TileData::from_raw(
            crate::tiles::TileFormat::Color32Bit,
            crate::tiles::TileKind::Raster,
            tile_rgba,
        );
        layer.grid.set_tile(TileCoord::new(0, 0), std::sync::Arc::new(td));
        [
            layer.grid.dirty_lods[0].drain().collect::<Vec<_>>(),
            layer.grid.dirty_lods[1].drain().collect::<Vec<_>>(),
            layer.grid.dirty_lods[2].drain().collect::<Vec<_>>(),
        ]
    };

    // Regenerate dirty mipmaps for the 1-tile stroke
    let grid_ref = &doc.layer(&lid).unwrap().grid;
    renderer.regenerate_layer_mipmaps_from_dirty(&doc.id, &lid, grid_ref, &dirty_lods, &[], None);

    let mipmaps_delta = renderer.gpu_pool_stats().mipmaps_generated - mipmaps_before;
    let submits_delta = renderer.tile_pool().mipmap_submits() - submits_before;
    assert!(
        mipmaps_delta <= 3 && mipmaps_delta > 0,
        "1-tile stroke on 4x4 layer must regenerate strictly <= 3 LOD tiles (1 per LOD 1..3), got {mipmaps_delta}"
    );
    assert_eq!(
        submits_delta, 1,
        "1-tile stroke mipmap update must execute in exactly 1 batched queue.submit, got {submits_delta}"
    );

    // Verify all 3 untouched LOD-1 siblings kept identical versions AND remained resident in VRAM!
    for (i, &sc) in sibling_coords.iter().enumerate() {
        let v_after = crate::memory::compute_lod_tile_version(&doc.layer(&lid).unwrap().grid, 1, sc);
        assert_eq!(
            v_after, sibling_versions_before[i],
            "Untouched LOD-1 sibling {sc:?} version must remain unchanged"
        );
        let key = renderer.tile_pool_mut().make_key(&doc.id, &lid, 1, sc);
        assert!(
            renderer
                .tile_pool_mut()
                .get_slot_if_version(&key, v_after)
                .is_some(),
            "Untouched LOD-1 sibling {sc:?} must remain resident without invalidation"
        );
    }

    // Also verify zoomed-out viewport render at zoom=0.25 (LOD 2) regenerates ZERO extra mipmaps!
    let mipmaps_before_zoom_render = renderer.gpu_pool_stats().mipmaps_generated;
    let display = CompositorDisplayConfig::default();
    let vp = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 512,
        height_px: 512,
        dpr: 1.0,
    };
    let cam_zoom_out = CameraState {
        pan_x: 256.0,
        pan_y: 256.0,
        zoom: 0.25,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };
    let _ = renderer.render_document_frame(
        &doc,
        None,
        &display,
        &vp,
        &cam_zoom_out,
        &[],
        false,
        false,
        &CursorConfig::default(),
        None,
        true,
    );
    assert_eq!(
        renderer.gpu_pool_stats().mipmaps_generated,
        mipmaps_before_zoom_render,
        "Zoomed-out render after 1-tile stroke must hit cached LOD pyramid with ZERO extra mipmaps"
    );
}

/// Regression 3: Raster strokes on a masked layer must NOT bump `grid.mask_version` and must
/// NOT trigger `DocMaskCache` mask rebuilds!
#[test]
fn test_raster_strokes_on_masked_layer_do_not_rebuild_mask() {
    let _dx12_guard = lock_dx12();
    let Some(mut renderer) =
        make_headless_renderer_vram(512, 512, 512, 512, 128 * 1024 * 1024)
    else {
        return;
    };

    let mut doc = Document::new_blank(
        "doc-mask-version",
        "Mask Version",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        20,
    );
    let lid = "layer-masked".to_string();
    doc.add_layer(LayerNodeMeta::new_raster(&lid, "Masked"), None, false, false);
    doc.active_layer_id = Some(lid.clone());

    // Attach a non-destructive 8-bit mask with a crisp 128×128 reveal hole
    doc.add_layer_mask(&lid, 0, false).unwrap();
    let reveal_box = vec![255u8; 128 * 128];
    doc.layer_mut(&lid)
        .unwrap()
        .grid
        .write_mask8_rect(&reveal_box, RectI32::new(128, 128, 128, 128), None)
        .unwrap();

    let mask_ver_initial = doc.layer(&lid).unwrap().grid.mask_version;
    let display = CompositorDisplayConfig {
        layer_stack_caching: true,
        ..Default::default()
    };
    let vp = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 512,
        height_px: 512,
        dpr: 1.0,
    };
    let cam = CameraState {
        pan_x: 256.0,
        pan_y: 256.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };

    // Initial render projects the viewport-resolution GPU mask once
    let _ = renderer.render_document_frame(
        &doc,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        false,
        &CursorConfig::default(),
        None,
        true,
    );
    let mask_rebuilds_after_init = renderer.doc_mask_rebuilds();
    assert_eq!(mask_rebuilds_after_init, 1);

    // Commit 3 separate raster strokes on the masked layer & render after each
    for s in 0..3i32 {
        let brush = NativeBrushConfig {
            fg_color: [0.9, 0.1 + s as f32 * 0.2, 0.2],
            size: 36.0,
            hardness: 0.95,
            spacing: 0.2,
            opacity: 1.0,
            ..Default::default()
        };
        let pts = make_curved_stroke_points(
            140.0,
            150.0 + s as f64 * 25.0,
            230.0,
            150.0 + s as f64 * 25.0,
            0.0,
            0.0,
            8,
            36.0,
        );
        emit_and_commit_stroke(&mut renderer, &mut doc, &lid, brush, &pts, 100 + s as u64);

        assert_eq!(
            doc.layer(&lid).unwrap().grid.mask_version,
            mask_ver_initial,
            "Raster stroke {s} must NEVER bump grid.mask_version"
        );

        let _ = renderer.render_document_frame(
            &doc,
            None,
            &display,
            &vp,
            &cam,
            &[],
            false,
            false,
            &CursorConfig::default(),
            None,
            true,
        );
        assert_eq!(
            renderer.doc_mask_rebuilds(),
            mask_rebuilds_after_init,
            "Raster stroke {s} must trigger ZERO DocMaskCache rebuilds!"
        );
    }

    // Mutating the mask MUST bump mask_version and rebuild the GPU viewport mask exactly once
    let extra_reveal = vec![255u8; 32 * 32];
    doc.layer_mut(&lid)
        .unwrap()
        .grid
        .write_mask8_rect(&extra_reveal, RectI32::new(260, 260, 32, 32), None)
        .unwrap();
    assert_ne!(
        doc.layer(&lid).unwrap().grid.mask_version,
        mask_ver_initial,
        "Mask mutation must bump grid.mask_version"
    );
    let _ = renderer.render_document_frame(
        &doc,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        false,
        &CursorConfig::default(),
        None,
        true,
    );
    assert_eq!(
        renderer.doc_mask_rebuilds(),
        mask_rebuilds_after_init + 1,
        "Mask edit must rebuild DocMaskCache exactly once"
    );
}

/// Regression 4: Active-stroke frames with NO newly sealed segments (`dirty_doc_bounds == None`)
/// and NO predicted dabs (`predicted_dabs.is_empty()`) — e.g. during stabilizer hold — must NOT
/// fall back to `full_scissor`!
#[test]
fn test_active_stroke_no_new_segments_does_not_fallback_to_full_scissor() {
    let _dx12_guard = lock_dx12();
    let Some(mut renderer) =
        make_headless_renderer_vram(512, 512, 512, 512, 128 * 1024 * 1024)
    else {
        return;
    };

    let mut doc = Document::new_blank(
        "doc-live-zero-skip",
        "Live Stroke Zero Skip",
        CanvasDimensions {
            width: 512,
            height: 512,
            dpi: 300,
        },
        CanvasColorMode::Color,
        "#ffffff",
        60.0,
        20,
    );
    let lid = "layer-ink".to_string();
    doc.add_layer(LayerNodeMeta::new_raster(&lid, "Ink"), None, false, false);
    doc.active_layer_id = Some(lid.clone());

    let display = CompositorDisplayConfig {
        layer_stack_caching: true,
        ..Default::default()
    };
    let vp = ViewportRect {
        x_px: 0,
        y_px: 0,
        width_px: 512,
        height_px: 512,
        dpr: 1.0,
    };
    let cam = CameraState {
        pan_x: 256.0,
        pan_y: 256.0,
        zoom: 1.0,
        rotation: 0.0,
        flip_x: false,
        flip_y: false,
    };

    // Start a live GPU brush stroke and stamp an initial dab at (200, 200)
    let brush = NativeBrushConfig {
        fg_color: [0.1, 0.1, 0.1],
        size: 24.0,
        hardness: 0.9,
        spacing: 0.15,
        opacity: 1.0,
        ..Default::default()
    };
    let mut emitter = StrokeDabEmitter::new(brush.clone(), 1, 777, 1.0);
    let mut initial_dabs = Vec::new();
    emitter.emit_initial_point(
        &StrokePoint {
            x: 200.0,
            y: 200.0,
            pressure: 1.0,
            width: 24.0,
            tilt_x: 0.0,
            tilt_y: 0.0,
            twist: 0.0,
            velocity: 0.0,
            timestamp_ms: 0.0,
            is_corner: false,
        },
        None,
        0.0,
        &mut initial_dabs,
    );
    renderer.begin_gpu_stroke(512, 512, false, brush, emitter.stroke_grain_offset);
    let _ = renderer.stamp_gpu_stroke_dabs(&initial_dabs, &[]);

    // Frame 1: stroke init (needs_init == true -> full_scissor expected)
    let _ = renderer.render_document_frame_with_brush(
        &doc,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        true,
        &[],
        Some(crate::compositor::DocBounds {
            min_x: 180,
            min_y: 180,
            max_x: 220,
            max_y: 220,
        }),
        &CursorConfig::default(),
        Some((200.0, 200.0)),
        false,
    );
    assert_eq!(
        renderer.last_composite_scissor(),
        Some(crate::compositor::ScissorRect::full(512, 512)),
        "First live-stroke frame should initialize with full_scissor"
    );

    // Frame 2: stabilizer hold — stroke is active, pointer moved slightly, ZERO new sealed
    // segments (`dirty_doc_bounds = None`) and ZERO predicted dabs (`&[]`)!
    let skips_before = renderer.stack_cache_stats().live_stroke_zero_skips;
    let _ = renderer.render_document_frame_with_brush(
        &doc,
        None,
        &display,
        &vp,
        &cam,
        &[],
        false,
        true,
        &[],
        None,
        &CursorConfig::default(),
        Some((201.0, 200.0)),
        false,
    );

    let sc = renderer
        .last_composite_scissor()
        .expect("last_composite_scissor must be recorded");
    assert!(
        sc.is_empty(),
        "Active-stroke frame with no newly sealed segments and no predicted dabs must NOT fall back to full_scissor (got {sc:?})"
    );
    assert_eq!(
        renderer.stack_cache_stats().live_stroke_zero_skips,
        skips_before + 1,
        "live_stroke_zero_skips must increment on zero-change active-stroke frame"
    );
}