aprender-viz 0.31.1

SIMD/GPU/WASM-accelerated visualization library for data science and ML
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
//! WGPU Multi-GPU Tests - Popperian Falsification Claims 26-50
//!
//! EXTREME TDD: These tests are written FIRST, before implementation.
//! All tests should FAIL initially until implementation is complete.
//!
//! Run: cargo test --features "gpu-wgpu,monitor" --test `wgpu_multi_gpu_test`
//! Run with GPU: cargo test --features "gpu-wgpu,monitor" --test `wgpu_multi_gpu_test` -- --ignored
//!
//! NOTE: These tests require real GPU hardware and may block on Metal initialization.
//! They are marked #[ignore] by default and should be run manually on systems with GPUs.

#![cfg(feature = "gpu-wgpu")]
#![allow(unused_macros, unused_imports, unused_variables, unused_mut, dead_code)]

/// Helper macro to mark tests as requiring real GPU
macro_rules! gpu_test {
    ($name:ident, $body:block) => {
        #[test]
        #[ignore = "Requires real GPU - run with --ignored"]
        fn $name() $body
    };
}

use std::time::{Duration, Instant};

// These imports will fail until we implement the modules
#[cfg(feature = "gpu-wgpu")]
use trueno_viz::monitor::ffi::wgpu::{GpuAdapterInfo, WgpuBackendType, WgpuMonitor};

// ============================================================================
// CLAIMS 26-35: GPU Detection & Enumeration
// ============================================================================

/// Claim 26: WGPU detects all physical GPUs
/// Failure criterion: Missing GPU compared to `system_profiler`
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_26_wgpu_detects_all_gpus() {
    let monitor = WgpuMonitor::new();
    let adapters = monitor.adapters();

    // Must detect at least one GPU on any modern system
    assert!(!adapters.is_empty(), "FALSIFIED Claim 26: No GPUs detected by WGPU");

    println!("Detected {} GPU adapter(s):", adapters.len());
    for adapter in adapters {
        println!("  - {} ({:?})", adapter.name, adapter.backend);
    }
}

/// Claim 27: Dual AMD W5700X both enumerated (Mac Pro specific)
/// Failure criterion: Count != 2 on Mac Pro with dual GPUs
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(all(feature = "gpu-wgpu", target_os = "macos"))]
fn claim_27_dual_amd_w5700x_enumerated() {
    let monitor = WgpuMonitor::new();

    if monitor.has_dual_amd() {
        let amd_count =
            monitor.adapters().iter().filter(|a| a.name.contains("AMD") && a.is_discrete()).count();

        assert_eq!(amd_count, 2, "FALSIFIED Claim 27: Expected 2 AMD GPUs, found {}", amd_count);
    } else {
        println!("Skipping Claim 27: No dual AMD configuration detected");
    }
}

/// Claim 28: GPU names match system report
/// Failure criterion: Name mismatch with `system_profiler`
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_28_gpu_names_accurate() {
    let monitor = WgpuMonitor::new();

    for adapter in monitor.adapters() {
        // Name should not be empty or generic
        assert!(!adapter.name.is_empty(), "FALSIFIED Claim 28: GPU name is empty");
        assert!(!adapter.name.contains("Unknown"), "FALSIFIED Claim 28: GPU name is 'Unknown'");

        println!("GPU name: {}", adapter.name);
    }
}

/// Claim 29: Backend correctly identified as Metal on macOS
/// Failure criterion: Wrong backend on macOS
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(all(feature = "gpu-wgpu", target_os = "macos"))]
fn claim_29_metal_backend_on_macos() {
    let monitor = WgpuMonitor::new();

    // On macOS, primary backend should be Metal
    if let Some(primary) = monitor.primary_adapter() {
        assert!(
            matches!(primary.backend, WgpuBackendType::Metal),
            "FALSIFIED Claim 29: Expected Metal backend on macOS, got {:?}",
            primary.backend
        );
    }
}

/// Claim 30: Backend correctly identified as Vulkan on Linux
/// Failure criterion: Wrong backend on Linux
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(all(feature = "gpu-wgpu", target_os = "linux"))]
fn claim_30_vulkan_backend_on_linux() {
    let monitor = WgpuMonitor::new();

    if let Some(primary) = monitor.primary_adapter() {
        assert!(
            matches!(primary.backend, WgpuBackendType::Vulkan),
            "FALSIFIED Claim 30: Expected Vulkan backend on Linux, got {:?}",
            primary.backend
        );
    }
}

/// Claim 31: Device type is `DiscreteGpu` for dedicated cards
/// Failure criterion: Wrong device type for discrete GPU
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_31_discrete_gpu_type() {
    let monitor = WgpuMonitor::new();

    for adapter in monitor.adapters() {
        if adapter.name.contains("Radeon")
            || adapter.name.contains("GeForce")
            || adapter.name.contains("RTX")
        {
            assert!(
                adapter.is_discrete(),
                "FALSIFIED Claim 31: {} should be DiscreteGpu",
                adapter.name
            );
        }
    }
}

/// Claim 32: WGPU initialization < 100ms
/// Failure criterion: Init > 100ms
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_32_wgpu_init_under_100ms() {
    let start = Instant::now();
    let _monitor = WgpuMonitor::new();
    let elapsed = start.elapsed();

    assert!(
        elapsed < Duration::from_millis(100),
        "FALSIFIED Claim 32: WGPU init took {elapsed:?}, expected < 100ms"
    );
}

/// Claim 33: Adapter enumeration < 50ms
/// Failure criterion: Enum > 50ms
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_33_adapter_enum_under_50ms() {
    let monitor = WgpuMonitor::new();

    let start = Instant::now();
    let _adapters = monitor.adapters();
    let elapsed = start.elapsed();

    assert!(
        elapsed < Duration::from_millis(50),
        "FALSIFIED Claim 33: Adapter enumeration took {elapsed:?}, expected < 50ms"
    );
}

/// Claim 34: No blocking in WGPU discovery
/// Failure criterion: Main thread blocked (tested via timeout)
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_34_non_blocking_discovery() {
    // If this test doesn't complete in 500ms, it's blocking
    let start = Instant::now();

    let monitor = WgpuMonitor::new();
    let _ = monitor.adapters();
    let _ = monitor.discrete_gpu_count();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_millis(500),
        "FALSIFIED Claim 34: Discovery appears to block ({elapsed:?})"
    );
}

/// Claim 35: WGPU works without GPU (software fallback)
/// Failure criterion: Crash without GPU
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_35_graceful_without_gpu() {
    // This should not panic even if no GPU is available
    let monitor = WgpuMonitor::new();

    // These should all return valid (possibly empty) results
    let adapters = monitor.adapters();
    let count = monitor.discrete_gpu_count();
    let primary = monitor.primary_adapter();

    // At minimum, should not crash
    println!(
        "Adapters: {}, Discrete: {}, Primary: {:?}",
        adapters.len(),
        count,
        primary.map(|a| a.name.clone())
    );
}

// ============================================================================
// CLAIMS 36-45: Metrics & Tracking
// ============================================================================

/// Claim 36: Queue submission count increments correctly
/// Failure criterion: Count mismatch
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_36_queue_submission_tracking() {
    let mut monitor = WgpuMonitor::new();

    let initial = monitor.queue_submissions(0);

    // Simulate some submissions (in real impl, this would track actual submissions)
    monitor.record_submission(0);
    monitor.record_submission(0);
    monitor.record_submission(0);

    let final_count = monitor.queue_submissions(0);

    assert_eq!(
        final_count,
        initial + 3,
        "FALSIFIED Claim 36: Expected {} submissions, got {}",
        initial + 3,
        final_count
    );
}

/// Claim 37: Buffer allocation tracking accurate to 1KB
/// Failure criterion: Tracking error > 1KB
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_37_buffer_allocation_tracking() {
    let mut monitor = WgpuMonitor::new();

    let test_size = 1024 * 1024; // 1MB
    monitor.record_buffer_allocation(0, test_size);

    let tracked = monitor.buffer_allocated_bytes(0);

    let error = (tracked as i64 - test_size as i64).unsigned_abs();
    assert!(error <= 1024, "FALSIFIED Claim 37: Buffer tracking error {error} > 1KB");
}

/// Claim 38: Compute dispatch counting accurate
/// Failure criterion: Count mismatch
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_38_compute_dispatch_counting() {
    let mut monitor = WgpuMonitor::new();

    let initial = monitor.compute_dispatches(0);

    monitor.record_dispatch(0);
    monitor.record_dispatch(0);

    let final_count = monitor.compute_dispatches(0);

    assert_eq!(final_count, initial + 2, "FALSIFIED Claim 38: Dispatch count mismatch");
}

/// Claim 39: Per-GPU workload isolation
/// Failure criterion: Cross-GPU interference
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_39_per_gpu_isolation() {
    let mut monitor = WgpuMonitor::new();

    // Record to GPU 0 only
    monitor.record_dispatch(0);
    monitor.record_dispatch(0);
    monitor.record_dispatch(0);

    // GPU 1 should be unaffected
    let gpu1_dispatches = monitor.compute_dispatches(1);

    assert_eq!(gpu1_dispatches, 0, "FALSIFIED Claim 39: GPU 1 affected by GPU 0 operations");
}

/// Claim 40: WGPU collector is 100% safe Rust
/// Failure criterion: Unsafe code found
/// This is a compile-time check - the module should have #![`forbid(unsafe_code)`]
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_40_wgpu_is_safe_rust() {
    // This test verifies at compile time that the wgpu module forbids unsafe
    // If it compiles, the module is safe
    let _ = WgpuMonitor::new();

    // The actual verification is in the module's #![forbid(unsafe_code)] attribute
    // This test just ensures the module compiles and is usable
}

/// Claim 41: WGPU feature is optional
/// Failure criterion: Compile error without feature
/// This is tested by CI building without the feature
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
fn claim_41_wgpu_feature_optional() {
    // This test always passes - the actual test is that
    // `cargo build` works without `gpu-wgpu` feature
    #[cfg(feature = "gpu-wgpu")]
    {
        let _ = WgpuMonitor::new();
    }

    #[cfg(not(feature = "gpu-wgpu"))]
    {
        // Without the feature, WgpuMonitor shouldn't exist
        // This branch should compile fine
    }
}

/// Claim 42: Graceful fallback without WGPU feature
/// Failure criterion: Panic without feature
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_42_graceful_fallback() {
    // Create monitor and verify it doesn't panic
    let monitor = WgpuMonitor::new();

    // All operations should be safe even if WGPU fails to initialize
    let _ = monitor.adapters();
    let _ = monitor.discrete_gpu_count();
    let _ = monitor.primary_adapter();
}

/// Claim 43: WGPU errors don't crash the application
/// Failure criterion: Crash on error
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_43_error_handling() {
    let monitor = WgpuMonitor::new();

    // Request invalid GPU index - should not crash
    let result = monitor.adapter_info(999);
    assert!(result.is_none(), "FALSIFIED Claim 43: Invalid index should return None");

    // Request metrics for non-existent GPU - should not crash
    let dispatches = monitor.compute_dispatches(999);
    assert_eq!(dispatches, 0, "Invalid GPU should return 0 dispatches");
}

/// Claim 44: GPU memory limits respected
/// Failure criterion: OOM crash
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_44_memory_limits() {
    let monitor = WgpuMonitor::new();

    // Should be able to query limits without crashing
    if let Some(adapter) = monitor.primary_adapter() {
        let limits = monitor.adapter_limits(0);
        assert!(limits.max_buffer_size > 0, "FALSIFIED Claim 44: Invalid memory limits");
        println!("Max buffer size: {} bytes", limits.max_buffer_size);
    }
}

/// Claim 45: WGPU instance is reusable
/// Failure criterion: Resource leak
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_45_instance_reusable() {
    let mut monitor = WgpuMonitor::new();

    // Collect multiple times - should not leak
    for i in 0..100 {
        let adapters = monitor.adapters();
        let _ = monitor.collect_metrics();

        if i == 0 {
            println!("First collection: {} adapters", adapters.len());
        }
    }

    // If we get here without OOM, we pass
}

// ============================================================================
// CLAIMS 46-50: Advanced Features
// ============================================================================

/// Claim 46: Adapter info is cacheable
/// Failure criterion: Stale data served after GPU change
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_46_adapter_caching() {
    let monitor = WgpuMonitor::new();

    // First call
    let adapters1 = monitor.adapters();

    // Second call should return same data (cached)
    let adapters2 = monitor.adapters();

    assert_eq!(
        adapters1.len(),
        adapters2.len(),
        "FALSIFIED Claim 46: Adapter count changed between calls"
    );
}

/// Claim 47: WGPU works in async context
/// Failure criterion: Blocking detected
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_47_async_compatible() {
    // Verify the monitor can be used in async code
    // The actual async test would use tokio/async-std

    let monitor = WgpuMonitor::new();

    // Monitor should be Send + Sync for async usage
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<WgpuMonitor>();

    let _ = monitor.adapters();
}

/// Claim 48: Multi-GPU load balancing works
/// Failure criterion: Imbalanced load
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_48_load_balancing() {
    let mut monitor = WgpuMonitor::new();

    if monitor.discrete_gpu_count() >= 2 {
        // Simulate round-robin dispatch
        for i in 0..10 {
            let gpu = monitor.next_gpu_round_robin();
            monitor.record_dispatch(gpu);
        }

        // Check balance (should be roughly even)
        let gpu0_load = monitor.compute_dispatches(0);
        let gpu1_load = monitor.compute_dispatches(1);

        let diff = (gpu0_load as i64 - gpu1_load as i64).unsigned_abs();
        assert!(
            diff <= 2,
            "FALSIFIED Claim 48: Imbalanced load: GPU0={gpu0_load}, GPU1={gpu1_load}"
        );
    }
}

/// Claim 49: GPU hotplug handled gracefully
/// Failure criterion: Crash on GPU removal
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_49_hotplug_handling() {
    let mut monitor = WgpuMonitor::new();

    // Simulate GPU removal by invalidating adapter
    monitor.invalidate_adapter(0);

    // Should not crash when accessing invalidated adapter
    let info = monitor.adapter_info(0);
    // May be None or return stale data, but should NOT crash

    // Refresh should recover
    monitor.refresh_adapters();
    let _ = monitor.adapters();
}

/// Claim 50: WGPU metrics update at 10Hz minimum
/// Failure criterion: Update rate < 10Hz
#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn claim_50_update_rate() {
    let mut monitor = WgpuMonitor::new();

    let start = Instant::now();
    let mut updates = 0;

    // Try to update for 200ms
    while start.elapsed() < Duration::from_millis(200) {
        let _ = monitor.collect_metrics();
        updates += 1;
    }

    // At 10Hz minimum, we should get at least 2 updates in 200ms
    assert!(updates >= 2, "FALSIFIED Claim 50: Only {updates} updates in 200ms (need 10Hz)");

    let hz = f64::from(updates) / 0.2;
    println!("Update rate: {hz:.1} Hz");
}

// ============================================================================
// Helper test for coverage
// ============================================================================

#[test]
#[ignore = "Requires real GPU - run with --ignored"]
#[cfg(feature = "gpu-wgpu")]
fn test_wgpu_monitor_full_api() {
    let mut monitor = WgpuMonitor::new();

    // Exercise full API for coverage
    let _ = monitor.adapters();
    let _ = monitor.discrete_gpu_count();
    let _ = monitor.primary_adapter();
    let _ = monitor.adapter_info(0);
    let _ = monitor.adapter_limits(0);
    let _ = monitor.has_dual_amd();

    monitor.record_submission(0);
    monitor.record_dispatch(0);
    monitor.record_buffer_allocation(0, 1024);

    let _ = monitor.queue_submissions(0);
    let _ = monitor.compute_dispatches(0);
    let _ = monitor.buffer_allocated_bytes(0);

    let _ = monitor.next_gpu_round_robin();
    monitor.invalidate_adapter(0);
    monitor.refresh_adapters();

    let _ = monitor.collect_metrics();
}