Files
ruvnet--RuView/v2/crates/wifi-densepose-occworld-candle/tests/input_validation.rs
T
rUv c859f6f743 security(occworld-candle): int32-checkpoint crash + degenerate-input guards + ADR-179 (closes Milestone #9) (#1101)
* fix(occworld-candle): security review fixes — int32 checkpoint crash + predict input validation

Beyond-SOTA security + correctness review of wifi-densepose-occworld-candle
(Milestone #9, crate 4/4 — the last ungated crate).

Findings fixed:

1. HIGH (MEASURED) — checkpoint-load crash on any int32 tensor.
   model.rs mapped safetensors I32 -> candle DType::I64 and passed the raw
   int32 byte buffer (4 bytes/elem) to Tensor::from_raw_buffer(.., I64, ..).
   Candle derives elem_count = data.len() / dtype.size(), so the I64 path
   halved the count while keeping the original shape -> a tensor whose shape
   claims 2x its storage. Reading it PANICS (slice OOB: "range end index 6
   out of range for slice of length 3") on any checkpoint containing an int32
   tensor. Fixed: I32 -> DType::I32, I16 -> DType::I16 (both first-class
   candle dtypes). Reproduced on old code; pinned in tests/checkpoint_loading.rs.

2. LOW (MEASURED) — predict() lacked frame/batch validation at the input
   boundary. f_in > num_frames*2 over-indexed the temporal embedding (cryptic
   candle "gather" error); zero frame/batch fed a zero-element tensor in. Now
   rejected with a clear ShapeMismatch. Pinned in tests/input_validation.rs.

3. LOW (MEASURED) — divide-by-zero panic in the public VQCodebook::encode on a
   rank-0 / empty-last-dim tensor (last == 0). Now fails closed with a clear
   error. Pinned in vqvae.rs unit tests.

Dimensions confirmed clean with evidence: panic surface (no unwrap/expect/
panic in prod paths), NaN-state-poisoning (N/A — stateless engine, u8 input),
unbounded-alloc/shape-data mismatch (defended upstream by safetensors::
validate), secrets (none). unsafe_code = forbid.

Validation (MEASURED, Windows): crate 31/31 pass; workspace 0 failed (lone
desktop api_integration "Access is denied" file-lock flake passes 21/21 in
isolation); Python proof VERDICT PASS, hash f8e76f21…446f7a unchanged.

Warrants ADR slot 179 (parent to author).

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr): ADR-179 — occworld-candle checkpoint-load hardening (closes Milestone #9)

Records the HIGH int32-checkpoint crash fix (I32→I64 dtype-widening → slice-OOB
panic on load = DoS) + 2 LOW degenerate-input fixes from 5e77f47e5. Stateless
engine (NaN-poisoning N/A), unsafe forbidden, safetensors validate() defends
malloc upstream. occworld 31/31. Final ungated crate — Milestone #9 complete.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-06-15 12:35:29 -04:00

140 lines
4.7 KiB
Rust

//! Input-validation boundary tests for `OccWorldCandle::predict`.
//!
//! Security review (Milestone #9, crate 4/4). `predict` takes an
//! externally-supplied occupancy tensor; per the project's "validate input at
//! system boundaries" rule it must reject degenerate / out-of-capacity shapes
//! with a clear domain error rather than surfacing a cryptic deep-pipeline
//! Candle error (over-capacity frame counts over-index the temporal positional
//! embedding) or processing a zero-element tensor.
//!
//! These exercise only the public API and live here (not inline in
//! `inference.rs`) to keep that module under the 500-line cap.
use candle_core::{DType, Device, Tensor};
use wifi_densepose_occworld_candle::config::OccWorldConfig;
use wifi_densepose_occworld_candle::inference::OccWorldCandle;
use wifi_densepose_occworld_candle::error::OccWorldError;
fn small_cfg() -> OccWorldConfig {
OccWorldConfig {
grid_h: 8,
grid_w: 8,
grid_d: 4,
num_classes: 4,
free_class: 3,
base_channels: 8,
z_channels: 8,
codebook_size: 4,
embed_dim: 8,
num_frames: 2,
token_h: 4,
token_w: 4,
num_heads: 2,
num_layers: 1,
ffn_hidden: 16,
}
}
/// Zero frames is a degenerate input that would otherwise feed a zero-element
/// tensor into the reshape/conv pipeline. Must be rejected at the boundary.
#[test]
fn predict_rejects_zero_frames() {
let device = Device::Cpu;
let cfg = small_cfg();
let engine = OccWorldCandle::dummy(cfg.clone(), device.clone()).unwrap();
let past = Tensor::zeros(
(1usize, 0usize, cfg.grid_h, cfg.grid_w, cfg.grid_d),
DType::U8,
&device,
)
.unwrap();
let result = engine.predict(&past);
assert!(
matches!(result, Err(OccWorldError::ShapeMismatch(_))),
"zero-frame input must be rejected with ShapeMismatch"
);
}
/// Zero batch must also be rejected (same zero-element-tensor hazard).
#[test]
fn predict_rejects_zero_batch() {
let device = Device::Cpu;
let cfg = small_cfg();
let engine = OccWorldCandle::dummy(cfg.clone(), device.clone()).unwrap();
let past = Tensor::zeros(
(0usize, cfg.num_frames, cfg.grid_h, cfg.grid_w, cfg.grid_d),
DType::U8,
&device,
)
.unwrap();
let result = engine.predict(&past);
assert!(
matches!(result, Err(OccWorldError::ShapeMismatch(_))),
"zero-batch input must be rejected with ShapeMismatch"
);
}
/// More frames than the temporal embedding can index (`> num_frames*2`).
///
/// On the old code this over-indexed the temporal positional embedding deep in
/// the transformer and surfaced as a cryptic Candle "gather" `InvalidIndex`
/// error. The boundary guard now rejects it cleanly with `ShapeMismatch`.
#[test]
fn predict_rejects_too_many_frames() {
let device = Device::Cpu;
let cfg = small_cfg(); // num_frames = 2 → temporal capacity = 4
let engine = OccWorldCandle::dummy(cfg.clone(), device.clone()).unwrap();
let too_many = cfg.num_frames * 2 + 1;
let past = Tensor::zeros(
(1usize, too_many, cfg.grid_h, cfg.grid_w, cfg.grid_d),
DType::U8,
&device,
)
.unwrap();
let result = engine.predict(&past);
assert!(
matches!(result, Err(OccWorldError::ShapeMismatch(_))),
"over-capacity frame count must be rejected with ShapeMismatch"
);
}
/// A frame count exactly at capacity (`num_frames*2`) must still succeed —
/// the guard rejects only *over*-capacity, not the boundary value.
#[test]
fn predict_accepts_frame_count_at_capacity() {
let device = Device::Cpu;
let cfg = small_cfg();
let engine = OccWorldCandle::dummy(cfg.clone(), device.clone()).unwrap();
let at_cap = cfg.num_frames * 2;
let past = Tensor::zeros(
(1usize, at_cap, cfg.grid_h, cfg.grid_w, cfg.grid_d),
DType::U8,
&device,
)
.unwrap();
let out = engine
.predict(&past)
.expect("at-capacity frame count must predict");
assert_eq!(out.sem_pred.dims()[1], at_cap, "frame dim preserved");
}
/// Wrong spatial geometry (H/W/D) is still rejected — pins the pre-existing
/// guard alongside the new frame/batch ones.
#[test]
fn predict_rejects_wrong_grid_dims() {
let device = Device::Cpu;
let cfg = small_cfg();
let engine = OccWorldCandle::dummy(cfg.clone(), device.clone()).unwrap();
let past = Tensor::zeros(
(1usize, cfg.num_frames, cfg.grid_h + 1, cfg.grid_w, cfg.grid_d),
DType::U8,
&device,
)
.unwrap();
let result = engine.predict(&past);
assert!(
matches!(result, Err(OccWorldError::ShapeMismatch(_))),
"wrong grid dims must be rejected with ShapeMismatch"
);
}