Skip to main content

qualia_core_db/render/
contract.rs

1//! Phenomenal viewport CI contract — WGSL bindings, binary layout, and regression oracles.
2//!
3//! Run via `cargo test -p qualia-core-db render::contract::tests::phenomenal_ --lib` or
4//! `node docs/tests/phenomenal-verify.mjs`.
5
6/// Rust `portal_gpu` projector camera bind group (group 0).
7pub const PROJECTOR_GROUP0_BINDINGS: &[u32] = &[0, 1];
8/// Rust `portal_gpu` projector tensor SOA bind group (group 1).
9pub const PROJECTOR_GROUP1_BINDINGS: &[u32] = &[0];
10/// Rust ambient layout — binding 4 is reserved for `ObserverStandpoint` (not yet in WGSL).
11pub const AMBIENT_GROUP0_BINDINGS: &[u32] = &[0, 1, 2, 3, 4];
12pub const BLOOM_GROUP0_BINDINGS: &[u32] = &[0, 1, 2, 3, 4];
13/// Mesh frame group: camera/observer plus shadow, AO and atmosphere bindings.
14pub const MESH_GROUP0_BINDINGS: &[u32] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
15pub const MESH_GROUP1_BINDINGS: &[u32] = &[0];
16/// Dynamic material factors, six textures, six samplers, and the environment probe contract.
17pub const MESH_GROUP2_BINDINGS: &[u32] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
18pub const MESH_GROUP3_BINDINGS: &[u32] = &[0];
19
20/// Parse `@group(G) @binding(B)` declarations from WGSL source lines.
21pub fn parse_wgsl_bindings(source: &str) -> Vec<(u32, u32)> {
22    let mut out = Vec::new();
23    for line in source.lines() {
24        if !line.contains("@group(") || !line.contains("@binding(") {
25            continue;
26        }
27        let Some(group) = parse_u32_after(line, "@group(") else {
28            continue;
29        };
30        let Some(binding) = parse_u32_after(line, "@binding(") else {
31            continue;
32        };
33        if !out.contains(&(group, binding)) {
34            out.push((group, binding));
35        }
36    }
37    out.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
38    out
39}
40
41fn parse_u32_after(line: &str, token: &str) -> Option<u32> {
42    let rest = line.split(token).nth(1)?;
43    let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
44    digits.parse().ok()
45}
46
47/// Every WGSL-declared binding must exist in the Rust bind-group layout manifest.
48pub fn assert_wgsl_bindings_covered(
49    wgsl_source: &str,
50    group: u32,
51    rust_bindings: &[u32],
52) -> Result<(), String> {
53    let wgsl: Vec<u32> = parse_wgsl_bindings(wgsl_source)
54        .into_iter()
55        .filter(|(g, _)| *g == group)
56        .map(|(_, b)| b)
57        .collect();
58    for b in wgsl {
59        if !rust_bindings.contains(&b) {
60            return Err(format!(
61                "WGSL group({group}) binding({b}) missing from Rust layout {rust_bindings:?}"
62            ));
63        }
64    }
65    Ok(())
66}
67
68#[cfg(test)]
69fn validate_wgsl_smoke(label: &str, source: &str) {
70    use naga::front::wgsl::Frontend;
71
72    // Validate the complete module on native CI, including WGSL semantics, resource
73    // declarations and entry-point interfaces. This is stronger than syntax parsing
74    // and catches instance-record ABI drift before an adapter-backed pipeline test.
75    let module = Frontend::new()
76        .parse(source)
77        .unwrap_or_else(|e| panic!("{label}: WGSL parse failed: {e:?}"));
78    naga::valid::Validator::new(
79        naga::valid::ValidationFlags::all(),
80        naga::valid::Capabilities::all(),
81    )
82    .validate(&module)
83    .unwrap_or_else(|e| panic!("{label}: WGSL validation failed: {e:?}"));
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use crate::audio::acoustic_plane::{AcousticUniform, SONIC_RING_CAP};
90    use crate::audio::acoustic_sab::{init_acoustic_sab, ACOUSTIC_SAB_BYTES};
91    use crate::audio::audio_spectral_sheet::SPECTRAL_PREVIEW_BINS;
92    use crate::audio::hrtf::binaural_from_position;
93    use crate::gpu_context::{
94        ambient_draw_instances_for_mode, ComputeUniverse, OperationalMode, UniverseOrchestrator,
95    };
96    use crate::render::acoustic::{
97        sigma_to_center_frequency_hz, sigma_to_wavelength_nm, ACOUSTIC_UNIFORM_FLOAT_COUNT,
98    };
99    use crate::render::control::{PortalControlCommand, CONTROL_RING_CAP, ICP_MAGIC_BIT};
100    use crate::render::pga::motor_rq_gated;
101    use crate::render::spectral::sigma_to_cie_xyz;
102    use crate::render::telemetry::{
103        CameraUniform, ObserverStandpoint, ParticleInstance, SystemTelemetry, STANDPOINT_DID,
104        STANDPOINT_EPHEMERAL, STANDPOINT_SPECTATOR, STANDPOINT_VAULT,
105    };
106    use crate::shaders::viewport::{
107        AMBIENT_WGSL, AO_GENERATE_WGSL, AO_PREPASS_WGSL, BLOOM_WGSL, HOLOGRAPHIC_WGSL, MESH_WGSL,
108        OUTPUT_WGSL, PROJECTOR_WGSL, SUN_SHADOW_WGSL,
109    };
110    use crate::sonic_token::SonicToken;
111    use crate::tensor::buffer_export::tensor_node_count;
112    use crate::tensor::buffer_export::{TensorBufferHeader, TENSOR_HEADER_BYTES, TENSOR_STRIDE};
113    use crate::tensor::Tensor10D;
114
115    const IDENTITY_ROTOR: [f32; 4] = [1.0, 0.0, 0.0, 0.0];
116
117    #[test]
118    fn phenomenal_shader_modules_parse() {
119        validate_wgsl_smoke("ambient", AMBIENT_WGSL);
120        validate_wgsl_smoke("projector", PROJECTOR_WGSL);
121        validate_wgsl_smoke("mesh", MESH_WGSL);
122        validate_wgsl_smoke("holographic", HOLOGRAPHIC_WGSL);
123        validate_wgsl_smoke("sun shadow", SUN_SHADOW_WGSL);
124        validate_wgsl_smoke("AO prepass", AO_PREPASS_WGSL);
125        validate_wgsl_smoke("AO generate", AO_GENERATE_WGSL);
126        validate_wgsl_smoke("SDR output", OUTPUT_WGSL);
127        validate_wgsl_smoke("bloom", BLOOM_WGSL);
128        assert!(
129            BLOOM_WGSL.contains("let combined = hdr + bloom * uniforms.composite.bloom_strength;")
130        );
131        assert_eq!(
132            BLOOM_WGSL
133                .matches("scene_linear * exposure * white_balance_gains")
134                .count(),
135            1,
136            "exposure and white balance belong to one shared output transform"
137        );
138    }
139
140    #[test]
141    fn phenomenal_binding_layout_matches_wgsl() {
142        assert_wgsl_bindings_covered(AMBIENT_WGSL, 0, AMBIENT_GROUP0_BINDINGS)
143            .expect("ambient bindings");
144        assert_wgsl_bindings_covered(PROJECTOR_WGSL, 0, PROJECTOR_GROUP0_BINDINGS)
145            .expect("projector group0");
146        assert_wgsl_bindings_covered(PROJECTOR_WGSL, 1, PROJECTOR_GROUP1_BINDINGS)
147            .expect("projector group1");
148        assert_wgsl_bindings_covered(BLOOM_WGSL, 0, BLOOM_GROUP0_BINDINGS).expect("bloom");
149        assert_wgsl_bindings_covered(OUTPUT_WGSL, 0, &[0, 1, 2]).expect("SDR output");
150        assert_wgsl_bindings_covered(MESH_WGSL, 0, MESH_GROUP0_BINDINGS)
151            .expect("mesh frame, shadow, AO and atmosphere");
152        assert_wgsl_bindings_covered(MESH_WGSL, 1, MESH_GROUP1_BINDINGS).expect("mesh model");
153        assert_wgsl_bindings_covered(MESH_WGSL, 2, MESH_GROUP2_BINDINGS)
154            .expect("combined material factors and textures");
155        assert_wgsl_bindings_covered(MESH_WGSL, 3, MESH_GROUP3_BINDINGS)
156            .expect("instanced mesh storage");
157        assert_wgsl_bindings_covered(SUN_SHADOW_WGSL, 0, &[0]).expect("shadow matrix");
158        assert_wgsl_bindings_covered(SUN_SHADOW_WGSL, 1, &[0]).expect("shadow model");
159        assert_wgsl_bindings_covered(SUN_SHADOW_WGSL, 2, MESH_GROUP2_BINDINGS)
160            .expect("shadow material and alpha-mask texture");
161        assert_wgsl_bindings_covered(SUN_SHADOW_WGSL, 3, &[0]).expect("shadow instances");
162        assert_wgsl_bindings_covered(AO_PREPASS_WGSL, 0, &[0, 1, 2])
163            .expect("AO camera and uniform");
164        assert_wgsl_bindings_covered(AO_PREPASS_WGSL, 1, &[0]).expect("AO model");
165        assert_wgsl_bindings_covered(AO_PREPASS_WGSL, 2, MESH_GROUP2_BINDINGS)
166            .expect("AO material and alpha-mask texture");
167        assert_wgsl_bindings_covered(AO_PREPASS_WGSL, 3, &[0]).expect("AO instances");
168        for shader in [MESH_WGSL, SUN_SHADOW_WGSL, AO_PREPASS_WGSL] {
169            assert!(
170                parse_wgsl_bindings(shader)
171                    .iter()
172                    .all(|(group, _)| *group <= 3),
173                "mesh-related shaders must fit the four-group WebGPU baseline"
174            );
175        }
176    }
177
178    #[test]
179    fn phenomenal_uniform_struct_sizes_match_wgsl() {
180        assert_eq!(std::mem::size_of::<TensorBufferHeader>(), 32);
181        assert_eq!(TENSOR_HEADER_BYTES, 32);
182        assert_eq!(std::mem::size_of::<Tensor10D>(), 40);
183        assert_eq!(TENSOR_STRIDE, 40);
184        assert_eq!(std::mem::size_of::<SystemTelemetry>(), 48);
185        assert_eq!(std::mem::size_of::<ParticleInstance>(), 16);
186        assert_eq!(std::mem::size_of::<CameraUniform>(), 128);
187        assert_eq!(std::mem::size_of::<ObserverStandpoint>(), 128);
188    }
189
190    #[test]
191    fn phenomenal_tensor_header_stride_matches_gpu_upload() {
192        let tensors = [Tensor10D::ground_truth(
193            0.0, 0.0, 0.1, 0.2, 0.3, 0.0, 1.0, 0.0, 0.5,
194        )];
195        let need = TensorBufferHeader::total_bytes(tensors.len());
196        let mut buf = vec![0u8; need];
197        crate::tensor::buffer_export::write_tensor_buffer(&tensors, &mut buf).unwrap();
198        let (header, header_len) =
199            crate::tensor::buffer_export::parse_header(&buf).expect("header");
200        assert_eq!(header_len, TENSOR_HEADER_BYTES);
201        assert_eq!(header.stride as usize, TENSOR_STRIDE);
202        assert_eq!(tensor_node_count(&buf).unwrap(), 1);
203        // `PortalGpu::upload_tensor_buffer` skips the 32 B header when binding SOA storage.
204        assert_eq!(
205            header_len + header.node_count as usize * TENSOR_STRIDE,
206            buf.len()
207        );
208    }
209
210    #[test]
211    fn phenomenal_standpoint_rq_motor_identity_gate() {
212        for class in [
213            STANDPOINT_SPECTATOR,
214            STANDPOINT_EPHEMERAL,
215            STANDPOINT_DID,
216            STANDPOINT_VAULT,
217        ] {
218            assert_eq!(
219                motor_rq_gated(0.0, 0.5, 1.0, 1.0, class, 1.0),
220                IDENTITY_ROTOR,
221                "collapsed q class={class}"
222            );
223        }
224        assert_eq!(
225            motor_rq_gated(0.9, 0.5, 1.0, 1.0, STANDPOINT_DID, 0.0),
226            IDENTITY_ROTOR,
227            "DID epistemic aperture 0"
228        );
229        assert_eq!(
230            motor_rq_gated(0.9, 0.5, 1.0, 1.0, STANDPOINT_VAULT, 1.0),
231            IDENTITY_ROTOR,
232            "vault always identity"
233        );
234        let active = motor_rq_gated(0.5, 0.25, 2.0, 1.0, STANDPOINT_SPECTATOR, 1.0);
235        assert!(
236            (active[0] - 1.0).abs() > 1e-4 || active[1].abs() > 1e-4,
237            "sandbox q should spin: {active:?}"
238        );
239    }
240
241    #[test]
242    fn phenomenal_vram_ledger_full_mode_draws_above_eco_cap() {
243        let resident = 50_000_u32;
244        let full = ambient_draw_instances_for_mode(resident, OperationalMode::Full);
245        let eco = ambient_draw_instances_for_mode(resident, OperationalMode::Eco);
246        assert!(full > 8_000, "Full mode must draw >8k instances");
247        assert_eq!(eco, 8_000, "Eco mode caps at 8k");
248        assert_eq!(
249            UniverseOrchestrator::from_total_budget(6 * 1024 * 1024 * 1024, OperationalMode::Full)
250                .max_particles(ComputeUniverse::Viewport, OperationalMode::Full),
251            50_000
252        );
253    }
254
255    #[test]
256    fn phenomenal_vram_ledger_pressure_step_down() {
257        let local = crate::gpu_context::VramLedger::new(1000);
258        local.record_tensor(500);
259        assert_eq!(local.mode(), OperationalMode::Full);
260        local.record_kv_cache(300);
261        assert_eq!(local.mode(), OperationalMode::Eco);
262        local.record_render(200);
263        assert_eq!(local.mode(), OperationalMode::Reserve);
264    }
265
266    #[test]
267    fn phenomenal_acoustic_uniform_layout() {
268        assert_eq!(std::mem::size_of::<SonicToken>(), 8);
269        assert_eq!(SONIC_RING_CAP, 128);
270        let uniform = AcousticUniform::default();
271        let bytes = bytemuck::bytes_of(&uniform);
272        assert_eq!(bytes.len(), std::mem::size_of::<AcousticUniform>());
273        // 18 scalars (binaural + STFT frame) + 64 preview bins
274        assert_eq!(
275            std::mem::size_of::<AcousticUniform>(),
276            72 + SPECTRAL_PREVIEW_BINS * 4
277        );
278        assert_eq!(std::mem::size_of::<AcousticUniform>(), 328);
279    }
280
281    #[test]
282    fn phenomenal_sigma_visual_audio_parity() {
283        for i in 0..=10 {
284            let sigma = i as f32 / 10.0;
285            let lambda = sigma_to_wavelength_nm(sigma);
286            assert!(lambda >= 400.0 && lambda <= 700.0);
287            let _xyz = sigma_to_cie_xyz(sigma);
288            let hz = sigma_to_center_frequency_hz(sigma);
289            assert!(hz >= 55.0 && hz <= 8_000.0);
290            let hz2 = sigma_to_center_frequency_hz(sigma + 1.0);
291            assert!((hz - hz2).abs() < 1e-3, "σ fract parity");
292        }
293        assert_eq!(ACOUSTIC_UNIFORM_FLOAT_COUNT, 82);
294    }
295
296    #[test]
297    fn phenomenal_hrtf_and_sab_layout() {
298        let g = binaural_from_position([1.0, 0.0, -1.0], 0.0);
299        assert!(g.gain_r > g.gain_l);
300        let mut sab = [0u8; ACOUSTIC_SAB_BYTES];
301        assert!(init_acoustic_sab(&mut sab));
302        assert_eq!(ACOUSTIC_SAB_BYTES, 1024);
303    }
304
305    #[test]
306    fn phenomenal_icp_command_layout() {
307        let cmd = PortalControlCommand::navigate_index(9);
308        assert_eq!(std::mem::size_of::<PortalControlCommand>(), 8);
309        assert!((cmd.raw & ICP_MAGIC_BIT) != 0);
310        assert_eq!(cmd.tensor_or_menu_index(), 9);
311        assert!(CONTROL_RING_CAP >= 64);
312    }
313
314    #[test]
315    fn phenomenal_u3_aliases_u1_partition() {
316        let orch = UniverseOrchestrator::from_total_budget_full(10_000);
317        let u1 = orch.partition(ComputeUniverse::Tensor10D).ledger_range;
318        let u3 = orch.partition(ComputeUniverse::AcousticPlane).ledger_range;
319        assert_eq!(u1.offset, u3.offset);
320        assert_eq!(u1.size, u3.size);
321        assert_eq!(
322            orch.effective_mode(ComputeUniverse::AcousticPlane, OperationalMode::Reserve),
323            OperationalMode::Reserve
324        );
325    }
326}