Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/dwarves

crates/nornir-warehouse-nav/tests/robot_world_universe.rs

//! **robot_world_universe** — the RED-when-broken proof that UNIVERSE mode renders the ENTIRE
//! code universe with **NO budget cap**, as a **pure GPU star-field** (labels off), coloured by
//! repo/crate, with the layout built **once** and reused across repaints.
//!
//! The owner loves the world mode (~12k nodes, no text, spread coloured galaxy). Universe is the
//! uncapped sibling: flip it on and the [`WORLD_PREVIEW_CAP`] (4 000-node) preview limit is gone —
//! the full `world_target` (12k → 100k → 1M) is laid out through the O(n) galaxy placement and
//! handed to the shared **instanced GPU cloud** (`facett_graphpan::paint_scene_opts` with
//! `gpu_cloud` — the SAME renderer `facett_graphview::world_still` rasterises headless at
//! 100k/1M), NOT egui CPU tessellation.
//!
//! The invariants this guard pins (all as data on `state_json`, no pixel-peeking):
//!   1. **No cap** — `universe == true`, `cap_applied == false`, and `preview_nodes` (the full
//!      count actually built + rendered) FAR exceeds `WORLD_PREVIEW_CAP`. The bounded "world"
//!      mode clamps to 4 000; Universe does not.
//!   2. **Labels off** — `labels == "off"` (pure star-field; text would be noise at 100k+).
//!   3. **Layout built once** — over N repaints `world_build_calls()` stays flat (the O(n) galaxy
//!      placement is cached; the frame-budget guard is green).
//!   4. **Colour variance** — many distinct node fills (repo/crate/function hues), not grey.
//!   5. **GPU lane** (self-gated) — with the `gpu` feature AND an installed cloud renderer,
//!      `universe_gpu_cloud == true` (the instanced star-field drew). Without a renderer the pane
//!      falls back to the CPU dot painter (every node still renders) and this is LOUD-SKIPPED.
//!
//! Run the GPU proof: `cargo test -p nornir-warehouse-nav --features gpu --test robot_world_universe`
//! (needs a wgpu adapter — the RTX 4090 on oden; degrades to the data-level guards otherwise).

#![cfg(not(target_arch = "wasm32"))]

use std::cell::RefCell;
use std::collections::BTreeSet;
use std::rc::Rc;

use egui::vec2;
use egui_kittest::Harness;
use facett_core::Facet;
use nornir_warehouse_nav::{world_build_calls, WarehouseNav, WORLD_PREVIEW_CAP};

/// The interactive universe size this guard drives — the owner's beloved ~12k, comfortably above
/// the 4 000 preview cap so "no cap" is unmistakable, small enough that the O(n) galaxy layout
/// (built ONCE) keeps the test brisk. The GPU renders far more (see the report); this is the
/// deterministic guard, not the ceiling.
const UNIVERSE_TARGET: u64 = 12_000;

/// Distinct node fill colours in the lowered model (the COLOUR proxy — grey blobs ⇒ ~1).
fn distinct_fills(nav: &WarehouseNav) -> usize {
    nav.world_preview_model()
        .nodes
        .iter()
        .map(|n| (n.fill.r(), n.fill.g(), n.fill.b()))
        .collect::<BTreeSet<_>>()
        .len()
}

#[test]
fn universe_is_uncapped_labels_off_layout_cached_and_coloured() {
    // the universe needs stars: the tests' generated tier, sized to the target
    let nav = Rc::new(RefCell::new(WarehouseNav::from_fixture_with_functions(
        UNIVERSE_TARGET as usize,
    )));
    let n = nav.clone();

    // Build the harness. With the `gpu` feature we install the SHARED instanced cloud renderer
    // into the wgpu RenderState the harness renders through, so the star-field draws on the GPU
    // (the same path world_still uses); otherwise a plain harness exercises the CPU fallback.
    #[cfg(feature = "gpu")]
    let mut h = {
        use egui_kittest::wgpu::{create_render_state, default_wgpu_setup, WgpuTestRenderer};
        let rs = create_render_state(default_wgpu_setup(), Default::default());
        facett_core::render::gpu::graphcloud::cloud::install_cloud_renderer(&rs);
        Harness::builder()
            .with_size(vec2(1400.0, 1000.0))
            .renderer(WgpuTestRenderer::from_render_state(rs))
            .build_ui(move |ui| {
                n.borrow_mut().ui(ui);
            })
    };
    #[cfg(not(feature = "gpu"))]
    let mut h = Harness::builder()
        .with_size(vec2(1400.0, 1000.0))
        .build_ui(move |ui| {
            n.borrow_mut().ui(ui);
        });

    // ── Enter the world graph at the 12k target, then flip UNIVERSE on (removes the cap). ──
    nav.borrow_mut()
        .update_json(&format!(r#"{{"world_target":{UNIVERSE_TARGET}}}"#));
    nav.borrow_mut().update_json(r#"{"world":true}"#);

    // Snapshot the build count JUST before entering Universe — entering rebuilds the layout
    // exactly once (a new cache key), and no repaint after may rebuild it again.
    let base_builds = world_build_calls();
    nav.borrow_mut().update_json(r#"{"universe":true}"#);
    h.run();
    h.run(); // second frame: the fit is applied; the cache is warm
    let builds_after_enter = world_build_calls() - base_builds;

    let s = Facet::state_json(&*nav.borrow());

    // 1. NO CAP: the full galaxy is built + rendered, far past the bounded preview cap.
    assert_eq!(s["world"], true, "world graph on: {s}");
    assert_eq!(s["universe"], true, "universe mode on: {s}");
    assert_eq!(
        s["cap_applied"], false,
        "universe applies NO budget cap: {s}"
    );
    let nodes = s["preview_nodes"].as_u64().unwrap();
    assert!(
        nodes as usize > WORLD_PREVIEW_CAP,
        "universe renders the FULL cloud uncapped — {nodes} nodes must exceed the {WORLD_PREVIEW_CAP} preview cap: {s}"
    );
    assert!(
        nodes >= 8_000,
        "the ~12k universe is populated (got {nodes}): {s}"
    );
    assert_eq!(
        s["universe_nodes"].as_u64().unwrap(),
        nodes,
        "universe_nodes == the full count: {s}"
    );
    // The layout is the O(n) galaxy placement (not the bounded force lane).
    assert_eq!(
        s["preview_lane"], "galaxy",
        "universe uses the O(n) galaxy placement: {s}"
    );

    // 2. LABELS OFF — a pure star-field.
    assert_eq!(
        s["labels"], "off",
        "universe is a pure star-field, no text: {s}"
    );

    // 4. COLOUR variance (repo/crate/function hues), not grey blobs.
    let fills = distinct_fills(&nav.borrow());
    assert!(
        fills > 12,
        "universe is multi-coloured ({fills} distinct fills), not grey: {s}"
    );

    // 3. LAYOUT BUILT ONCE — entering built it once; now many repaints add ZERO rebuilds.
    assert_eq!(
        builds_after_enter, 1,
        "entering universe builds the O(n) galaxy layout exactly once (got {builds_after_enter})"
    );
    let before = world_build_calls();
    for _ in 0..60 {
        h.run();
    }
    let repaint_builds = world_build_calls() - before;
    assert_eq!(
        repaint_builds, 0,
        "no repaint re-lays the universe — the frame-budget guard stays green (got {repaint_builds} rebuilds over 60 frames)"
    );

    // 5. GPU LANE — self-gated. Assert the instanced cloud drew only where a renderer is installed.
    let gpu_available = facett_graphpan::legible::gpu_cloud_available();
    let drew_on_gpu = s["universe_gpu_cloud"].as_bool().unwrap_or(false);
    if gpu_available {
        assert!(
            drew_on_gpu,
            "with the cloud renderer installed, the universe star-field must draw on the GPU (instanced), not the CPU: {s}"
        );
        eprintln!("[universe] GPU instanced star-field: {nodes} nodes on the GPU, {fills} fills, 0 relayouts/60 frames");
    } else {
        eprintln!(
            "[universe] no cloud renderer installed (no `gpu` feature / no adapter) — GPU-lane assertion \
             LOUD-SKIPPED; the CPU fallback still rendered all {nodes} nodes ({fills} fills, uncapped)"
        );
    }

    let ok = nodes as usize > WORLD_PREVIEW_CAP
        && repaint_builds == 0
        && builds_after_enter == 1
        && fills > 12
        && (!gpu_available || drew_on_gpu);

    // A SHIPPED surface (the warehouse landing pane's uncapped GPU star-field) → owes the
    // coverage board a row. Reuse edda's testmatrix rather than hand-roll a harness.
    #[cfg(feature = "testmatrix")]
    nornir_testmatrix::functional_status(
        "nornir-warehouse-nav",
        "universe_is_uncapped_labels_off_layout_cached_and_coloured",
        ok,
        "UNIVERSE mode removes the 4 000-node preview cap and renders the ENTIRE code universe \
         (~12k here; 100k/1M on the GPU) as a pure instanced star-field: state_json reports \
         universe=true, cap_applied=false, preview_nodes far beyond WORLD_PREVIEW_CAP, labels=off, \
         the O(n) 'galaxy' layout built exactly once (0 rebuilds across 60 repaints — frame-budget \
         green), >12 distinct fills (coloured by repo/crate), and — with the shared cloud renderer \
         installed — universe_gpu_cloud=true (the instanced GPU lane drew, not CPU tessellation)",
    );
    let _ = ok;
}