Skip to main content

qualia_core_db/services/
daemon_tensor.rs

1//! Cold-path export: daemon graph `NQuin` slice → binary `Tensor10D` SOA for U2 viewport upload.
2//!
3//! Layout: `TensorBufferHeader` (32 B) + N × `Tensor10D` (40 B). Served at `GET /tensor/slice`.
4//! Identifier/Vault standpoints (class ≥ 2) require Ed25519 over the canonical request string.
5
6use crate::key_vault::KeyVault;
7use crate::render::telemetry::{STANDPOINT_DID, STANDPOINT_VAULT};
8use crate::tensor::bake_pipeline::bake_quin_to_tensor;
9use crate::tensor::buffer_export::{write_tensor_buffer, TensorBufferHeader};
10use crate::NQuin;
11
12pub const DEFAULT_SLICE_MAX_NODES: usize = 12_000;
13pub const ABSOLUTE_SLICE_MAX_NODES: usize = 50_000;
14
15/// Routing lane mirrored from `ObserverStandpoint` (PR-C9c.2 vault vs commons).
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum TensorSliceLane {
18    Commons,
19    Identifier,
20}
21
22impl TensorSliceLane {
23    /// Builds `TensorSliceLane` from `header`.
24    pub fn from_header(value: &str) -> Self {
25        match value.trim().to_ascii_lowercase().as_str() {
26            "identifier" | "did" | "vault" => Self::Identifier,
27            _ => Self::Commons,
28        }
29    }
30}
31
32/// Standpoint-aligned slice parameters (matches WGSL temporal discard).
33#[derive(Debug, Clone, Copy)]
34pub struct TensorSliceRequest {
35    pub max_nodes: usize,
36    pub t_slice: f32,
37    pub t_window: f32,
38    pub lane: TensorSliceLane,
39    pub standpoint_class: u32,
40}
41
42impl Default for TensorSliceRequest {
43    fn default() -> Self {
44        Self {
45            max_nodes: DEFAULT_SLICE_MAX_NODES,
46            t_slice: 0.5,
47            t_window: 1.0,
48            lane: TensorSliceLane::Commons,
49            standpoint_class: 0,
50        }
51    }
52}
53
54impl TensorSliceRequest {
55    #[inline]
56    /// `TensorSliceRequest::clamp_max_nodes`.
57    pub fn clamp_max_nodes(max_nodes: usize) -> usize {
58        max_nodes.clamp(1, ABSOLUTE_SLICE_MAX_NODES)
59    }
60
61    #[inline]
62    /// `TensorSliceRequest::temporal_passes`.
63    pub fn temporal_passes(&self, tensor_t: f32) -> bool {
64        if self.t_window <= 0.0 {
65            return true;
66        }
67        (tensor_t - self.t_slice).abs() <= self.t_window
68    }
69
70    #[inline]
71    /// `TensorSliceRequest::requires_identifier_auth`.
72    pub fn requires_identifier_auth(&self) -> bool {
73        self.standpoint_class >= STANDPOINT_DID
74    }
75
76    /// Vault standpoints export the full sealed graph (identifier lane, no commons filter).
77    #[inline]
78    pub fn requires_vault_export(&self) -> bool {
79        self.standpoint_class >= STANDPOINT_VAULT
80    }
81
82    /// Resolve the effective routing lane for cold-path tensor export.
83    #[inline]
84    pub fn export_lane(&self) -> TensorSliceLane {
85        if self.requires_vault_export() || self.requires_identifier_auth() {
86            TensorSliceLane::Identifier
87        } else {
88            self.lane
89        }
90    }
91}
92
93#[derive(Debug, PartialEq, Eq)]
94pub enum TensorSliceError {
95    EmptyGraph,
96    BufferTooSmall,
97}
98
99#[derive(Debug, PartialEq, Eq)]
100pub enum TensorSliceAuthError {
101    IdentifierDidRequired,
102    SessionNonceRequired,
103    SignatureRequired,
104    InvalidSignatureEncoding,
105    InvalidSignature,
106}
107
108/// Canonical UTF-8 bytes both client (`crypto.subtle`) and daemon must sign/verify.
109/// Format: `"{nonce}|{standpoint_class}|{t_slice}|{t_window}"`
110pub fn canonical_tensor_slice_payload(
111    nonce: &str,
112    standpoint_class: u32,
113    t_slice: f32,
114    t_window: f32,
115) -> String {
116    format!(
117        "{}|{}|{}|{}",
118        nonce,
119        standpoint_class,
120        format_canonical_f32(t_slice),
121        format_canonical_f32(t_window),
122    )
123}
124
125#[inline]
126fn format_canonical_f32(v: f32) -> String {
127    let s = format!("{:.6}", v);
128    s.trim_end_matches('0').trim_end_matches('.').to_string()
129}
130
131/// Verify Ed25519 signature for identifier/vault tensor slice requests (fail closed).
132pub fn verify_tensor_slice_signature(
133    vault: &KeyVault,
134    identifier_did: &str,
135    nonce: &str,
136    standpoint_class: u32,
137    t_slice: f32,
138    t_window: f32,
139    signature_hex: &str,
140) -> Result<(), TensorSliceAuthError> {
141    if identifier_did.trim().is_empty() {
142        return Err(TensorSliceAuthError::IdentifierDidRequired);
143    }
144    if nonce.trim().is_empty() {
145        return Err(TensorSliceAuthError::SessionNonceRequired);
146    }
147    if signature_hex.trim().is_empty() {
148        return Err(TensorSliceAuthError::SignatureRequired);
149    }
150
151    let payload = canonical_tensor_slice_payload(nonce, standpoint_class, t_slice, t_window);
152    let sig_bytes = hex::decode(signature_hex.trim())
153        .map_err(|_| TensorSliceAuthError::InvalidSignatureEncoding)?;
154    if sig_bytes.len() != 64 {
155        return Err(TensorSliceAuthError::InvalidSignatureEncoding);
156    }
157    let mut sig_arr = [0u8; 64];
158    sig_arr.copy_from_slice(&sig_bytes);
159
160    let pk = vault.public_key_bytes_for_context(identifier_did);
161    KeyVault::verify_signature(&pk, payload.as_bytes(), &sig_arr)
162        .map_err(|_| TensorSliceAuthError::InvalidSignature)
163}
164
165/// Commons = public sensitivity only; identifier/vault = full sealed graph.
166#[inline]
167pub fn quin_matches_lane(quin: &NQuin, lane: TensorSliceLane) -> bool {
168    match lane {
169        TensorSliceLane::Commons => quin.get_sensitivity_byte() == NQuin::SENSITIVITY_PUBLIC,
170        TensorSliceLane::Identifier => true,
171    }
172}
173
174/// Bake filtered graph quins into a tensor buffer blob (cold path; heap OK).
175pub fn build_tensor_slice_bytes(
176    quins: &[NQuin],
177    req: &TensorSliceRequest,
178) -> Result<Vec<u8>, TensorSliceError> {
179    if quins.is_empty() {
180        return Err(TensorSliceError::EmptyGraph);
181    }
182
183    let cap = TensorSliceRequest::clamp_max_nodes(req.max_nodes);
184    let mut tensors = Vec::with_capacity(cap.min(quins.len()));
185
186    let lane = req.export_lane();
187    for q in quins {
188        if !quin_matches_lane(q, lane) {
189            continue;
190        }
191        let t = bake_quin_to_tensor(q);
192        if !req.temporal_passes(t.t) {
193            continue;
194        }
195        tensors.push(t);
196        if tensors.len() >= cap {
197            break;
198        }
199    }
200
201    if tensors.is_empty() {
202        return Err(TensorSliceError::EmptyGraph);
203    }
204
205    let need = TensorBufferHeader::total_bytes(tensors.len());
206    let mut buf = vec![0u8; need];
207    write_tensor_buffer(&tensors, &mut buf).map_err(|_| TensorSliceError::BufferTooSmall)?;
208    Ok(buf)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use ed25519_dalek::Signer;
215
216    fn triple_quin(subject: &str, predicate: &str, object: &str, context: &str) -> NQuin {
217        let subject = crate::q_hash(subject);
218        let predicate = crate::q_hash(predicate);
219        let object = crate::q_hash(object);
220        let context = crate::q_hash(context) & 0x00FF_FFFF_FFFF_FFFF;
221        NQuin {
222            subject,
223            predicate,
224            object,
225            context,
226            metadata: 0,
227            parity: subject ^ predicate ^ object ^ context,
228        }
229    }
230
231    fn sample_quin() -> NQuin {
232        triple_quin(
233            "http://q.test/s/0",
234            "http://q.test/p/geo",
235            "http://q.test/o/0",
236            "did:qualia:commons",
237        )
238    }
239
240    fn test_vault() -> KeyVault {
241        KeyVault::new()
242    }
243
244    #[test]
245    fn canonical_payload_matches_spec_example() {
246        assert_eq!(
247            canonical_tensor_slice_payload("a1b2c3d4e5f6", 2, 0.5, 0.1),
248            "a1b2c3d4e5f6|2|0.5|0.1"
249        );
250    }
251
252    #[test]
253    fn verify_tensor_slice_signature_round_trip() {
254        let vault = test_vault();
255        let did = "did:qualia:alice";
256        let nonce = "a1b2c3d4e5f6";
257        let sk = vault.derive_key(did);
258        let payload = canonical_tensor_slice_payload(nonce, STANDPOINT_DID, 0.5, 0.1);
259        let sig = sk.sign(payload.as_bytes());
260        let sig_hex = hex::encode(sig.to_bytes());
261        verify_tensor_slice_signature(&vault, did, nonce, STANDPOINT_DID, 0.5, 0.1, &sig_hex)
262            .expect("valid signature");
263    }
264
265    #[test]
266    fn verify_rejects_wrong_nonce() {
267        let vault = test_vault();
268        let did = "did:qualia:alice";
269        let sk = vault.derive_key(did);
270        let payload = canonical_tensor_slice_payload("nonce-a", STANDPOINT_DID, 0.5, 0.1);
271        let sig_hex = hex::encode(sk.sign(payload.as_bytes()).to_bytes());
272        assert_eq!(
273            verify_tensor_slice_signature(
274                &vault,
275                did,
276                "nonce-b",
277                STANDPOINT_DID,
278                0.5,
279                0.1,
280                &sig_hex
281            ),
282            Err(TensorSliceAuthError::InvalidSignature)
283        );
284    }
285
286    #[test]
287    fn commons_lane_excludes_restricted_quins() {
288        let public = sample_quin();
289        let mut restricted = sample_quin();
290        restricted.set_sensitivity_byte(NQuin::SENSITIVITY_RESTRICTED);
291        let req = TensorSliceRequest {
292            lane: TensorSliceLane::Commons,
293            t_window: 0.0,
294            max_nodes: 8,
295            ..Default::default()
296        };
297        let buf = build_tensor_slice_bytes(&[public, restricted], &req).expect("public only");
298        assert_eq!(
299            crate::tensor::buffer_export::tensor_node_count(&buf).expect("count"),
300            1
301        );
302    }
303
304    #[test]
305    fn identifier_lane_includes_restricted_quins() {
306        let mut restricted = sample_quin();
307        restricted.set_sensitivity_byte(NQuin::SENSITIVITY_RESTRICTED);
308        let req = TensorSliceRequest {
309            lane: TensorSliceLane::Identifier,
310            standpoint_class: STANDPOINT_VAULT,
311            t_window: 0.0,
312            max_nodes: 8,
313            ..Default::default()
314        };
315        let buf = build_tensor_slice_bytes(&[restricted], &req).expect("vault slice");
316        assert_eq!(
317            crate::tensor::buffer_export::tensor_node_count(&buf).expect("count"),
318            1
319        );
320    }
321
322    #[test]
323    fn build_slice_respects_max_nodes() {
324        let quins = [sample_quin(); 4];
325        let req = TensorSliceRequest {
326            max_nodes: 2,
327            t_window: 0.0,
328            ..Default::default()
329        };
330        let buf = build_tensor_slice_bytes(&quins, &req).expect("slice");
331        let count = crate::tensor::buffer_export::tensor_node_count(&buf).expect("header");
332        assert_eq!(count, 2);
333    }
334
335    #[test]
336    fn temporal_filter_matches_standpoint_window() {
337        let mut q = sample_quin();
338        q.metadata = (100u64) << 32;
339        let baked = bake_quin_to_tensor(&q);
340        let req = TensorSliceRequest {
341            t_slice: baked.t,
342            t_window: 0.01,
343            max_nodes: 8,
344            ..Default::default()
345        };
346        let buf = build_tensor_slice_bytes(&[q], &req).expect("in window");
347        assert_eq!(
348            crate::tensor::buffer_export::tensor_node_count(&buf).expect("count"),
349            1
350        );
351
352        let req_out = TensorSliceRequest {
353            t_slice: baked.t + 1.0,
354            t_window: 0.01,
355            ..req
356        };
357        assert_eq!(
358            build_tensor_slice_bytes(&[q], &req_out),
359            Err(TensorSliceError::EmptyGraph)
360        );
361    }
362}