Skip to main content

qualia_core_db/poet_host/vibe_sentinel/
mod.rs

1//! QualiaDB Governed VibeScript Extension Host (`vibe_sentinel`, `VS03-09`, `VS03-10`, `VS03-11`, `VS03-12`, `VS03-13`).
2//!
3//! Integrates `vibescript-abi` and `vibe::extension_registry` with QualiaDB's
4//! zero-heap deontic contract evaluator (`crate::modalities::logic::deontic`),
5//! reversible `NQuin` staging, fail-closed receipt persistence, bounded
6//! ontology `NQuin` mounting, WGSL Forge / wgpu compute dispatch, and per-token
7//! governed inference sessions.
8
9pub mod gpu_inference_host;
10pub mod ontology_mount;
11pub mod policy_gate;
12pub mod receipt_commit;
13
14pub use gpu_inference_host::{
15    execute_governed_per_token_inference, execute_wgpu_forge_affine_f32_with_cleanup,
16    GovernedInferenceStreamSummary, WgpuForgeExtensionProvider,
17};
18pub use ontology_mount::{
19    BoundedOntologyMount, MountedProviderSpan, PermittedFunctionSummary,
20    MAX_MOUNTED_ONTOLOGY_PROVIDERS,
21};
22pub use policy_gate::{
23    make_deontic_norm_quin, norm_property_hash55, nquin_to_quin48, quin48_to_nquin,
24    WebizenSentinelGate, MAX_SENTINEL_VERDICTS,
25};
26pub use receipt_commit::execute_governed_staged_call;
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use crate::modalities::logic::deontic::{OP_FORBID, OP_PERMIT};
32    use crate::NQuin;
33    use vibe::extension_registry::{
34        prepare_extension_call, CallExecutionContext, DeterministicMechanicsProvider,
35        ExtensionRegistry,
36    };
37    use vibescript_abi::{
38        q_hash_str, BorrowedSliceView, CallerOutputSlice, CompletionStatus, EffectSet,
39        ExecutionMode, PrimitiveKind, ResourceEnvelope, SemVerReq, TargetProfileMask, VibeTrap,
40    };
41
42    fn f64_1_to_bytes(v: f64) -> [u8; 8] {
43        v.to_le_bytes()
44    }
45
46    fn f64_3_to_bytes(vals: [f64; 3]) -> [u8; 24] {
47        let mut out = [0u8; 24];
48        for (i, v) in vals.iter().enumerate() {
49            out[i * 8..(i + 1) * 8].copy_from_slice(&v.to_le_bytes());
50        }
51        out
52    }
53
54    #[test]
55    fn vs03_sentinel_permit_forbid_defeater_and_expiry_precedence() {
56        let actor = q_hash_str("did:q42:alice");
57        let world = q_hash_str("did:q42:world:lab-1");
58        let prov_hash = q_hash_str("https://qualiadb.org/ext/etalon/mechanics");
59        let verlet_hash =
60            q_hash_str("https://qualiadb.org/ext/etalon/mechanics/kinematics/verlet_step");
61        let ke_hash =
62            q_hash_str("https://qualiadb.org/ext/etalon/mechanics/kinematics/kinetic_energy");
63
64        // Norm 1: Permit provider-wide in `world` until t = 1000
65        let n_permit =
66            make_deontic_norm_quin(actor, OP_PERMIT, false, prov_hash, prov_hash, world, 1000);
67        // Norm 2: Explicitly forbid `kinetic_energy` in `world`
68        let n_forbid_ke =
69            make_deontic_norm_quin(actor, OP_FORBID, false, ke_hash, prov_hash, world, 1000);
70
71        let norms = [n_permit, n_forbid_ke];
72        let mut receipt_sink = [NQuin::default(); 8];
73        let gate = WebizenSentinelGate::new(
74            &norms,
75            &mut receipt_sink,
76            1,
77            EffectSet::PURE_COMPUTE,
78            ResourceEnvelope::hot_zero_heap(100, 128),
79        );
80
81        // 1. `verlet_step` is permitted at t = 500
82        assert_eq!(gate.evaluate_access(actor, verlet_hash, prov_hash, world, 500), Ok(()));
83        // 2. `kinetic_energy` is explicitly denied by `OP_FORBID`
84        assert_eq!(
85            gate.evaluate_access(actor, ke_hash, prov_hash, world, 500),
86            Err(VibeTrap::ExplicitDenyRule)
87        );
88        // 3. Wrong world context -> DelegationScopeMismatch
89        assert_eq!(
90            gate.evaluate_access(actor, verlet_hash, prov_hash, world ^ 1, 500),
91            Err(VibeTrap::DelegationScopeMismatch)
92        );
93        // 4. After t = 1000 -> AuthorityExpired
94        assert_eq!(
95            gate.evaluate_access(actor, verlet_hash, prov_hash, world, 1001),
96            Err(VibeTrap::AuthorityExpired)
97        );
98
99        // 5. Adding a DEFEATER_BIT (`q42:unless`) exception norm defeats `n_forbid_ke`
100        let n_defeat_ke =
101            make_deontic_norm_quin(actor, OP_PERMIT, true, ke_hash, prov_hash, world, 1000);
102        let norms_with_defeater = [n_permit, n_forbid_ke, n_defeat_ke];
103        let gate2 = WebizenSentinelGate::new(
104            &norms_with_defeater,
105            &mut receipt_sink,
106            2,
107            EffectSet::PURE_COMPUTE,
108            ResourceEnvelope::hot_zero_heap(100, 128),
109        );
110        assert_eq!(gate2.evaluate_access(actor, ke_hash, prov_hash, world, 500), Ok(()));
111    }
112
113    #[test]
114    fn vs03_staged_commit_and_fail_closed_receipt_rollback() {
115        static PROVIDER: DeterministicMechanicsProvider = DeterministicMechanicsProvider;
116        let mut reg = ExtensionRegistry::new();
117        reg.register(&PROVIDER).unwrap();
118
119        let handle = prepare_extension_call(
120            &reg, "mech", "kinematics", "kinetic_energy",
121            SemVerReq::AnyStable, TargetProfileMask::NATIVE_DESKTOP,
122        ).unwrap();
123
124        let actor = q_hash_str("did:q42:alice");
125        let world = q_hash_str("did:q42:world:lab-1");
126        let prov_hash = handle.provider_iri_hash;
127        let norms = [make_deontic_norm_quin(
128            actor, OP_PERMIT, false, prov_hash, prov_hash, world, 2000,
129        )];
130
131        // Receipt sink has space for exactly 1 call (2 NQuins)
132        let mut receipt_sink = [NQuin::default(); 2];
133        let mut gate = WebizenSentinelGate::new(
134            &norms,
135            &mut receipt_sink,
136            7,
137            EffectSet::PURE_COMPUTE,
138            ResourceEnvelope::hot_zero_heap(100, 128),
139        );
140
141        let mass_b = f64_1_to_bytes(4.0);
142        let vel_b = f64_3_to_bytes([3.0, 0.0, 4.0]); // |v|^2 = 25 -> KE = 0.5 * 4 * 25 = 50
143        let inputs = [
144            BorrowedSliceView::from_raw_bytes(&mass_b, PrimitiveKind::F64, 1).unwrap(),
145            BorrowedSliceView::from_raw_bytes(&vel_b, PrimitiveKind::F64, 3).unwrap(),
146        ];
147
148        let staged_mutation = NQuin {
149            subject: actor,
150            predicate: q_hash_str("https://qualiadb.org/schema/vibe#recordedEnergy"),
151            object: 50,
152            context: world,
153            metadata: 100,
154            parity: actor
155                ^ q_hash_str("https://qualiadb.org/schema/vibe#recordedEnergy")
156                ^ 50
157                ^ world
158                ^ 100,
159        };
160        let mut published_graph = [NQuin::default(); 4];
161        let mut published_len = 0usize;
162
163        let ctx = CallExecutionContext {
164            actor_did_hash: actor,
165            context_world_hash: world,
166            lamport_timestamp: 100,
167            mode: ExecutionMode::IntegratedGovernanceTest,
168        };
169
170        // Call 1 succeeds: receipt persisted (2 NQuins) and staged mutation published
171        let mut out_raw1 = [0u8; 8];
172        let mut out1 = CallerOutputSlice::new(&mut out_raw1, PrimitiveKind::F64).unwrap();
173        let outcome = execute_governed_staged_call(
174            &reg, &handle, &ctx, &mut gate, &inputs, &mut out1,
175            &[staged_mutation], &mut published_graph, &mut published_len,
176        ).expect("first governed call commits");
177        assert_eq!(outcome.receipt.status, CompletionStatus::Committed);
178        assert_eq!(gate.persisted_receipt_quin_count(), 2);
179        assert_eq!(published_len, 1);
180
181        // Call 2: receipt_sink is now full (2/2 used) -> commit_receipt fails with ReceiptPersistenceFailed,
182        // and `published_len` MUST remain 1 (staged mutation rolled back / withheld!).
183        let mut out_raw2 = [0u8; 8];
184        let mut out2 = CallerOutputSlice::new(&mut out_raw2, PrimitiveKind::F64).unwrap();
185        let err = execute_governed_staged_call(
186            &reg, &handle, &ctx, &mut gate, &inputs, &mut out2,
187            &[staged_mutation], &mut published_graph, &mut published_len,
188        ).unwrap_err();
189        assert_eq!(err, VibeTrap::ReceiptPersistenceFailed);
190        assert_eq!(
191            published_len, 1,
192            "staged state must not be published when receipt persistence fails"
193        );
194    }
195
196    #[test]
197    fn vs03_bounded_ontology_mount_discovery_and_unmount() {
198        static PROVIDER: DeterministicMechanicsProvider = DeterministicMechanicsProvider;
199        let mut store_buf = [NQuin::default(); 32];
200        let mut mount = BoundedOntologyMount::new(&mut store_buf, 16);
201
202        let span = mount.mount_provider(&PROVIDER).expect("mounts cleanly");
203        assert_eq!(span.len, 3);
204        assert_eq!(mount.mounted_quin_count(), 3);
205
206        // Mounting only permits `verlet_step` for `actor`
207        let actor = q_hash_str("did:q42:bob");
208        let world = q_hash_str("did:q42:world:2");
209        let prov_hash = q_hash_str("https://qualiadb.org/ext/etalon/mechanics");
210        let verlet_hash =
211            q_hash_str("https://qualiadb.org/ext/etalon/mechanics/kinematics/verlet_step");
212        let norms = [make_deontic_norm_quin(
213            actor, OP_PERMIT, false, verlet_hash, prov_hash, world, 900,
214        )];
215        let mut receipt_sink = [NQuin::default(); 4];
216        let gate = WebizenSentinelGate::new(
217            &norms,
218            &mut receipt_sink,
219            1,
220            EffectSet::PURE_COMPUTE,
221            ResourceEnvelope::hot_zero_heap(100, 128),
222        );
223
224        let mut discovered = [PermittedFunctionSummary {
225            provider_iri_hash: 0,
226            func_iri_hash: 0,
227            stable_id: vibescript_abi::StableFuncId::new(0, 0),
228        }; 4];
229        let count = mount
230            .discover_permitted_functions(&PROVIDER, &gate, actor, world, 100, &mut discovered)
231            .unwrap();
232        // Only `verlet_step` (1 of the 5 functions) is permitted for Bob!
233        assert_eq!(count, 1);
234        assert_eq!(discovered[0].func_iri_hash, verlet_hash);
235
236        // Unmount provider cleans up mounted ontology records
237        mount.unmount_provider(prov_hash).unwrap();
238        assert_eq!(mount.mounted_quin_count(), 0);
239        assert_eq!(
240            mount.discover_permitted_functions(&PROVIDER, &gate, actor, world, 100, &mut discovered),
241            Err(VibeTrap::NamespaceNotFound)
242        );
243
244        // Mount all 11 built-in providers (8 Etalon + 3 Qualia, 3 ontology NQuins each = 33 NQuins)
245        let reg = ExtensionRegistry::with_builtin_providers();
246        let mut full_buf = [NQuin::default(); 128];
247        let mut full_mount = BoundedOntologyMount::new(&mut full_buf, 16);
248        let mounted_providers = full_mount
249            .mount_registry_providers(&reg)
250            .expect("mounts all 11 built-in providers");
251        assert_eq!(mounted_providers, 11);
252        assert_eq!(full_mount.mounted_quin_count(), 33);
253        for q in full_mount.mounted_quins() {
254            assert!(nquin_to_quin48(q).verify_parity());
255        }
256    }
257
258    #[test]
259    fn vs03_12_wgpu_forge_provider_dispatch_and_transient_cleanup() {
260        static WGPU_PROV: WgpuForgeExtensionProvider = WgpuForgeExtensionProvider;
261        let mut reg = ExtensionRegistry::new();
262        reg.register(&WGPU_PROV).unwrap();
263
264        let handle = prepare_extension_call(
265            &reg,
266            "wgpu_forge",
267            "compute",
268            "affine_f32",
269            SemVerReq::AnyStable,
270            TargetProfileMask::NATIVE_DESKTOP,
271        )
272        .unwrap();
273
274        let actor = q_hash_str("did:q42:alice");
275        let world = q_hash_str("did:q42:world:gpu-lab");
276        let prov_hash = handle.provider_iri_hash;
277        let norms = [make_deontic_norm_quin(
278            actor,
279            OP_PERMIT,
280            false,
281            prov_hash,
282            prov_hash,
283            world,
284            5000,
285        )];
286        let mut receipt_sink = [NQuin::default(); 4];
287        let mut gate = WebizenSentinelGate::new(
288            &norms,
289            &mut receipt_sink,
290            1,
291            EffectSet::PURE_COMPUTE.union(EffectSet::HARDWARE_IO),
292            ResourceEnvelope {
293                max_ticks: 128,
294                max_scratch_bytes: 0,
295                max_vram_bytes: 1024,
296                max_output_bytes: 64,
297                max_spawned_tasks: 0,
298                flags: 0,
299            },
300        );
301
302        let x = [1.0f32, 2.0, -3.0, 4.5];
303        let sb = [2.0f32, 0.5];
304        let mut x_bytes = [0u8; 16];
305        for (i, v) in x.iter().enumerate() {
306            x_bytes[i * 4..(i + 1) * 4].copy_from_slice(&v.to_le_bytes());
307        }
308        let mut sb_bytes = [0u8; 8];
309        sb_bytes[0..4].copy_from_slice(&sb[0].to_le_bytes());
310        sb_bytes[4..8].copy_from_slice(&sb[1].to_le_bytes());
311
312        let inputs = [
313            BorrowedSliceView::from_raw_bytes(&x_bytes, PrimitiveKind::F32, 4).unwrap(),
314            BorrowedSliceView::from_raw_bytes(&sb_bytes, PrimitiveKind::F32, 2).unwrap(),
315        ];
316        let mut out_raw = [0u8; 16];
317        let mut out = CallerOutputSlice::new(&mut out_raw, PrimitiveKind::F32).unwrap();
318
319        let ctx = CallExecutionContext {
320            actor_did_hash: actor,
321            context_world_hash: world,
322            lamport_timestamp: 200,
323            mode: ExecutionMode::IntegratedGovernanceTest,
324        };
325        let mut published_graph = [NQuin::default(); 2];
326        let mut published_len = 0usize;
327
328        let outcome = execute_governed_staged_call(
329            &reg,
330            &handle,
331            &ctx,
332            &mut gate,
333            &inputs,
334            &mut out,
335            &[],
336            &mut published_graph,
337            &mut published_len,
338        )
339        .expect("governed wgpu_forge affine_f32 succeeds");
340        assert_eq!(outcome.receipt.status, CompletionStatus::Committed);
341
342        let view = BorrowedSliceView::from_raw_bytes(out.written_byte_slice(), PrimitiveKind::F32, 4)
343            .unwrap();
344        let expected = vibe::extension_registry::oracle_gpu_affine_f32(x, sb[0], sb[1]);
345        for (i, &exp) in expected.iter().enumerate() {
346            let got = view.read_f32_le(i).unwrap();
347            assert!(
348                (got - exp).abs() <= 1e-5,
349                "element {i}: got {got}, expected {exp}"
350            );
351        }
352
353        // Verify direct cleanup invariant (`post_cleanup_bytes == 0`)
354        let (direct_out, _used_hw, post_bytes) =
355            execute_wgpu_forge_affine_f32_with_cleanup(x, sb[0], sb[1]).unwrap();
356        assert_eq!(post_bytes, 0, "transient GPU allocations must be reclaimed");
357        for (i, &exp) in expected.iter().enumerate() {
358            assert!((direct_out[i] - exp).abs() <= 1e-5);
359        }
360    }
361
362    #[test]
363    fn vs03_12_governed_per_token_inference_commit_and_midstream_rollback() {
364        let reg = ExtensionRegistry::with_builtin_providers();
365        let actor = q_hash_str("did:q42:alice");
366        let world = q_hash_str("did:q42:world:infer-1");
367        let infer_prov_hash = q_hash_str("https://qualiadb.org/ext/qualia/inference");
368
369        let norms = [make_deontic_norm_quin(
370            actor,
371            OP_PERMIT,
372            false,
373            infer_prov_hash,
374            infer_prov_hash,
375            world,
376            5000,
377        )];
378
379        let steps = [
380            [0.1, 2.4, 0.5, -1.0], // token 1
381            [3.2, 0.1, -0.5, 0.0], // token 0
382            [-0.2, 0.4, 1.1, 4.8], // token 3
383        ];
384
385        // 1. Full 3-step stream succeeds when policy remains valid and receipt sink has capacity (6 NQuins)
386        let mut receipt_sink = [NQuin::default(); 8];
387        let mut gate = WebizenSentinelGate::new(
388            &norms,
389            &mut receipt_sink,
390            10,
391            EffectSet::PURE_COMPUTE
392                .union(EffectSet::HARDWARE_IO)
393                .union(EffectSet::GRAPH_MUTATE),
394            ResourceEnvelope {
395                max_ticks: 256,
396                max_scratch_bytes: 256,
397                max_vram_bytes: 256,
398                max_output_bytes: 64,
399                max_spawned_tasks: 0,
400                flags: 0,
401            },
402        );
403        let ctx = CallExecutionContext {
404            actor_did_hash: actor,
405            context_world_hash: world,
406            lamport_timestamp: 300,
407            mode: ExecutionMode::IntegratedGovernanceTest,
408        };
409        let mut kv_hash = 0xCAFE_BABE_0000_0001u64;
410        let mut published_graph = [NQuin::default(); 8];
411        let mut published_len = 0usize;
412        let mut decoded = [(0u64, 0u64); 3];
413
414        let summary = execute_governed_per_token_inference(
415            &reg,
416            &ctx,
417            &mut gate,
418            &steps,
419            &mut kv_hash,
420            &mut published_graph,
421            &mut published_len,
422            &mut decoded,
423            |_step, _gate| {},
424        )
425        .expect("3-step governed token stream commits");
426        assert_eq!(summary.committed_steps, 3);
427        assert_eq!(published_len, 3);
428        assert_eq!(decoded[0].0, 1);
429        assert_eq!(decoded[1].0, 0);
430        assert_eq!(decoded[2].0, 3);
431        assert_eq!(gate.persisted_receipt_quin_count(), 6);
432
433        // 2. Mid-stream revocation (receipt sink exhausted on step 2 -> ReceiptPersistenceFailed)
434        // must roll back ALL staged token NQuins and restore initial `kv_hash`!
435        let mut short_receipt_sink = [NQuin::default(); 4]; // only enough for 2 steps, fails on 3rd!
436        let mut gate_revoke = WebizenSentinelGate::new(
437            &norms,
438            &mut short_receipt_sink,
439            11,
440            EffectSet::PURE_COMPUTE
441                .union(EffectSet::HARDWARE_IO)
442                .union(EffectSet::GRAPH_MUTATE),
443            ResourceEnvelope {
444                max_ticks: 256,
445                max_scratch_bytes: 256,
446                max_vram_bytes: 256,
447                max_output_bytes: 64,
448                max_spawned_tasks: 0,
449                flags: 0,
450            },
451        );
452        let initial_kv = 0xDEAD_BEEF_1234_5678u64;
453        let mut kv_hash_rollback = initial_kv;
454        let mut published_rollback = [NQuin::default(); 8];
455        let mut published_rollback_len = 1usize; // 1 pre-existing committed record
456        let mut decoded_rollback = [(0u64, 0u64); 3];
457
458        let err = execute_governed_per_token_inference(
459            &reg,
460            &ctx,
461            &mut gate_revoke,
462            &steps,
463            &mut kv_hash_rollback,
464            &mut published_rollback,
465            &mut published_rollback_len,
466            &mut decoded_rollback,
467            |_step, _gate| {},
468        )
469        .unwrap_err();
470        assert_eq!(err, VibeTrap::ReceiptPersistenceFailed);
471        assert_eq!(
472            published_rollback_len, 1,
473            "all staged token NQuins from aborted stream must be rolled back"
474        );
475        assert_eq!(
476            kv_hash_rollback, initial_kv,
477            "KV state hash must be restored on mid-stream abort"
478        );
479        assert_eq!(decoded_rollback, [(0, 0); 3]);
480    }
481}