Skip to main content

qualia_core_db/tensor/
q42_integration.rs

1//! Q42 volume integration for the 10D tensor system.
2//!
3//! This module keeps runtime tensor storage and query execution zero-heap by
4//! requiring callers to supply backing slices and output buffers.
5
6use core::ops::ControlFlow;
7
8use super::Tensor10D;
9use crate::NQuin;
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum TensorVolumeError {
14    MismatchedStorage,
15    StorageCapacityExceeded,
16    OutputBufferFull,
17}
18
19/// Tensor metadata that can be stored alongside NQuin data.
20#[repr(C)]
21#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
22pub struct TensorMetadata {
23    /// 10D tensor coordinates for this NQuin.
24    pub tensor: Tensor10D,
25    /// Whether this NQuin has associated tensor data.
26    pub has_tensor: bool,
27    /// Tensor data version.
28    pub tensor_version: u32,
29}
30
31impl Default for TensorMetadata {
32    /// No tensor data: zeroed coordinates, `has_tensor = false`,
33    /// version 1.
34    fn default() -> Self {
35        Self {
36            tensor: Tensor10D::default(),
37            has_tensor: false,
38            tensor_version: 1,
39        }
40    }
41}
42
43impl TensorMetadata {
44    /// Create tensor metadata from NQuin and tensor coordinates.
45    pub fn from_nquin_and_tensor(_nquin: &NQuin, tensor: Tensor10D) -> Self {
46        Self {
47            tensor,
48            has_tensor: true,
49            tensor_version: 1,
50        }
51    }
52
53    /// Create tensor metadata from NQuin only (no tensor coordinates yet).
54    pub fn from_nquin_only(_nquin: &NQuin) -> Self {
55        Self {
56            tensor: Tensor10D::default(),
57            has_tensor: false,
58            tensor_version: 1,
59        }
60    }
61}
62
63/// Lightweight entry view used by zero-heap query APIs.
64#[derive(Debug, Clone, Copy)]
65pub struct TensorizedEntry<'a> {
66    pub nquin: &'a NQuin,
67    pub metadata: &'a TensorMetadata,
68}
69
70/// Convert NQuin to Tensor10D using semantic mapping.
71impl Tensor10D {
72    /// Convert NQuin to Tensor10D using semantic mapping.
73    pub fn from_nquin(nquin: &NQuin) -> Self {
74        let q = Self::extract_quantum_context(nquin);
75        let v = Self::extract_topological_class(nquin);
76        let w = Self::extract_manifold_index(nquin);
77        let (x, y, z) = Self::extract_semantic_coordinates(nquin);
78        let t = Self::extract_temporal_state(nquin);
79        let (alpha, mu, sigma) = Self::extract_spectral_payload(nquin);
80
81        Tensor10D::new(q, v, w, x, y, z, t, alpha, mu, sigma)
82    }
83
84    /// Normalized hyperbolic log-sum-exp distance subtracting $\ln(3)$ so $d(x, x) = 0.0$ (Packet OCS-13).
85    #[inline]
86    pub fn normalized_hyperbolic_distance(&self, other: &Self) -> f32 {
87        let dx = (self.x - other.x).abs();
88        let dy = (self.y - other.y).abs();
89        let dz = (self.z - other.z).abs();
90        let max_d = dx.max(dy).max(dz);
91        let lse = max_d + ((dx - max_d).exp() + (dy - max_d).exp() + (dz - max_d).exp()).ln();
92        (lse - core::f32::consts::LN_2 - (1.5_f32).ln()).max(0.0)
93    }
94
95    /// Full 10D distance with normalized log-sum-exp branch for hyperbolic topology (`v == 2`)
96    /// so that $d(x, x) = 0.0$ across all topological classes (Packet OCS-13).
97    #[inline]
98    pub fn normalized_full_distance(&self, other: &Self) -> f32 {
99        if self.v as u32 == 2 {
100            self.normalized_hyperbolic_distance(other)
101        } else {
102            self.full_distance(other)
103        }
104    }
105
106    /// Whether this tensor represents an empirically anchored / collapsed entity ($q < 1.0$) (Packet OCS-13).
107    #[inline]
108    pub fn is_empirically_collapsible(&self) -> bool {
109        self.q < 1.0
110    }
111
112    /// Extract quantum context from NQuin metadata and predicate modality.
113    /// q = 0.0: Collapsed Ground Truth; q > 0.0: Parallel epistemic contexts.
114    fn extract_quantum_context(nquin: &NQuin) -> f32 {
115        let q_index = ((nquin.metadata >> 24) & 0xFF) as f32;
116        if q_index > 0.0 {
117            q_index
118        } else {
119            let opcode = (nquin.predicate & 0xFF) as u8;
120            if (0x20..=0x22).contains(&opcode) {
121                // Epistemic modality active -> non-zero quantum context
122                1.0
123            } else if opcode == 0x55 {
124                // OP_ELEMENT_COLLAPSE: low nibble of metadata encodes GroundingStatus
125                // (0 = EmpiricallyAnchored -> 0.0, 1..=3 -> uncollapsed narrative realm >= 1.0)
126                (nquin.metadata & 0x0F) as f32
127            } else {
128                0.0
129            }
130        }
131    }
132
133    /// Extract topological class from NQuin metadata routing lane and object tag.
134    /// v = 0: Euclidean (Passthrough), v = 1: Cyclic/Toroidal (Commons),
135    /// v = 2: Hyperbolic/Tree (Bilateral), v = 3: Boundary Cliques (Spatial).
136    fn extract_topological_class(nquin: &NQuin) -> f32 {
137        // Universal Quin bit layout: metadata [61..62] stores PermissiveRoutingLane
138        let routing_lane = (nquin.metadata >> 61) & 0x03;
139        routing_lane as f32
140    }
141
142    /// Extract manifold index from NQuin predicate modality and context tags.
143    /// w = 0: Medical, w = 1: Legal, w = 2: Personal, w = 3: Environmental, w = 4: Socioeconomic.
144    fn extract_manifold_index(nquin: &NQuin) -> f32 {
145        let opcode = (nquin.predicate & 0xFF) as u8;
146        if (0x10..=0x12).contains(&opcode) {
147            // Deontic logic / normative contracts -> Legal
148            super::manifold::ManifoldDomain::Legal.to_index()
149        } else if (0x20..=0x32).contains(&opcode) {
150            // Epistemic / paraconsistent -> Personal
151            super::manifold::ManifoldDomain::Personal.to_index()
152        } else if (0x40..=0x44).contains(&opcode) {
153            // LTL / temporal traces -> Environmental
154            super::manifold::ManifoldDomain::Environmental.to_index()
155        } else {
156            // Decode domain tag from context bits [52..55] modulo 5
157            let tag = ((nquin.context >> 52) & 0x07) as f32;
158            if tag < 5.0 {
159                tag
160            } else {
161                super::manifold::ManifoldDomain::Medical.to_index()
162            }
163        }
164    }
165
166    /// Extract semantic coordinates from NQuin object field.
167    fn extract_semantic_coordinates(nquin: &NQuin) -> (f32, f32, f32) {
168        super::bake_pipeline::semantic_xyz_from_nquin(nquin)
169    }
170
171    /// Extract temporal state from NQuin metadata Lamport clock.
172    fn extract_temporal_state(nquin: &NQuin) -> f32 {
173        let clock = nquin.metadata >> 32;
174        clock as f32
175    }
176
177    /// Extract spectral payload from NQuin metadata.
178    fn extract_spectral_payload(nquin: &NQuin) -> (f32, f32, f32) {
179        let payload = nquin.metadata & 0xFFFF_FFFF;
180        let alpha = (payload & 0xFF) as f32 / 255.0;
181        let mu = ((payload >> 8) & 0xFF) as f32 / 255.0;
182        let sigma = ((payload >> 16) & 0xFF) as f32 / 255.0;
183        (alpha, mu, sigma)
184    }
185}
186
187/// Volume-level tensor configuration.
188#[repr(C)]
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub struct TensorVolumeConfig {
191    /// Enable 10D tensor operations.
192    pub tensor_enabled: bool,
193    /// Default manifold index for new NQuins.
194    pub default_manifold: f32,
195    /// Default topological class for new NQuins.
196    pub default_topology: f32,
197    /// Tensor version for this volume.
198    pub tensor_version: u32,
199}
200
201impl Default for TensorVolumeConfig {
202    /// Tensor operations enabled, manifold/topology defaults 0.0,
203    /// version 1.
204    fn default() -> Self {
205        Self {
206            tensor_enabled: true,
207            default_manifold: 0.0,
208            default_topology: 0.0,
209            tensor_version: 1,
210        }
211    }
212}
213
214/// Zero-heap tensor volume backed by caller-owned storage.
215pub struct Q42TensorVolume<'a> {
216    nquins: &'a mut [NQuin],
217    tensor_metadata: &'a mut [TensorMetadata],
218    len: usize,
219    volume_config: TensorVolumeConfig,
220}
221
222/// Immutable zero-heap tensor query view.
223#[derive(Debug)]
224pub struct Q42TensorView<'a> {
225    nquins: &'a [NQuin],
226    tensor_metadata: &'a [TensorMetadata],
227    volume_config: &'a TensorVolumeConfig,
228}
229
230impl<'a> Q42TensorVolume<'a> {
231    /// Create a new tensor volume over caller-supplied storage.
232    pub fn new(
233        nquins: &'a mut [NQuin],
234        tensor_metadata: &'a mut [TensorMetadata],
235    ) -> Result<Self, TensorVolumeError> {
236        Self::with_config(nquins, tensor_metadata, TensorVolumeConfig::default())
237    }
238
239    /// Create a new tensor volume with specific configuration.
240    pub fn with_config(
241        nquins: &'a mut [NQuin],
242        tensor_metadata: &'a mut [TensorMetadata],
243        config: TensorVolumeConfig,
244    ) -> Result<Self, TensorVolumeError> {
245        if nquins.len() != tensor_metadata.len() {
246            return Err(TensorVolumeError::MismatchedStorage);
247        }
248
249        Ok(Self {
250            nquins,
251            tensor_metadata,
252            len: 0,
253            volume_config: config,
254        })
255    }
256
257    /// Borrow this volume as a zero-heap query view.
258    pub fn as_view(&self) -> Q42TensorView<'_> {
259        Q42TensorView {
260            nquins: &self.nquins[..self.len],
261            tensor_metadata: &self.tensor_metadata[..self.len],
262            volume_config: &self.volume_config,
263        }
264    }
265
266    /// Add an NQuin to the volume with tensor coordinates.
267    pub fn add_nquin_with_tensor(
268        &mut self,
269        nquin: NQuin,
270        tensor: Tensor10D,
271    ) -> Result<usize, TensorVolumeError> {
272        if self.len >= self.nquins.len() {
273            return Err(TensorVolumeError::StorageCapacityExceeded);
274        }
275
276        self.nquins[self.len] = nquin;
277        self.tensor_metadata[self.len] =
278            TensorMetadata::from_nquin_and_tensor(&self.nquins[self.len], tensor);
279        self.len += 1;
280        Ok(self.len)
281    }
282
283    /// Add an NQuin to the volume without tensor coordinates.
284    pub fn add_nquin(&mut self, nquin: NQuin) -> Result<usize, TensorVolumeError> {
285        if self.len >= self.nquins.len() {
286            return Err(TensorVolumeError::StorageCapacityExceeded);
287        }
288
289        self.nquins[self.len] = nquin;
290        self.tensor_metadata[self.len] = TensorMetadata::from_nquin_only(&self.nquins[self.len]);
291        self.len += 1;
292        Ok(self.len)
293    }
294
295    /// Reset the used prefix and scrub old entries.
296    pub fn clear(&mut self) {
297        for index in 0..self.len {
298            self.nquins[index] = NQuin::default();
299            self.tensor_metadata[index] = TensorMetadata::default();
300        }
301        self.len = 0;
302    }
303
304    /// Get tensor metadata for an NQuin by index.
305    pub fn get_tensor_metadata(&self, index: usize) -> Option<&TensorMetadata> {
306        self.tensor_metadata.get(index).filter(|_| index < self.len)
307    }
308
309    /// The volume's tensor configuration.
310    pub fn config(&self) -> &TensorVolumeConfig {
311        &self.volume_config
312    }
313
314    /// Replace the volume configuration.
315    pub fn update_config(&mut self, config: TensorVolumeConfig) {
316        self.volume_config = config;
317    }
318
319    /// Number of live entries (≤ `capacity`).
320    pub fn len(&self) -> usize {
321        self.len
322    }
323
324    /// Total slots in the caller-owned backing storage.
325    pub fn capacity(&self) -> usize {
326        self.nquins.len()
327    }
328
329    /// `true` when no entries are stored.
330    pub fn is_empty(&self) -> bool {
331        self.len == 0
332    }
333
334    /// Entries whose metadata carries tensor coordinates.
335    pub fn tensor_count(&self) -> usize {
336        self.as_view().tensor_count()
337    }
338
339    /// Copy every tensorized `(NQuin, metadata)` pair into `out`;
340    /// `OutputBufferFull` when `out` can't hold all of them.
341    /// Delegates to the view.
342    pub fn get_tensorized_nquins_into<'b>(
343        &'b self,
344        out: &mut [TensorizedEntry<'b>],
345    ) -> Result<usize, TensorVolumeError> {
346        self.as_view().get_tensorized_nquins_into(out)
347    }
348
349    /// Copy only empirically anchored / collapsible entries ($q < 1.0$) into `out`,
350    /// leaving counterfactual or narrative realm entries ($q \ge 1.0$) uncollapsed (Packet OCS-13).
351    pub fn collapse_empirically_anchored_into<'b>(
352        &'b self,
353        out: &mut [TensorizedEntry<'b>],
354    ) -> Result<usize, TensorVolumeError> {
355        self.as_view().collapse_empirically_anchored_into(out)
356    }
357
358    /// Zero-allocation variant of `get_tensorized_nquins_into` —
359    /// `on_entry` per tensorized pair, `Break` to stop early.
360    pub fn visit_tensorized_nquins<F>(&self, on_entry: F) -> Result<(), TensorVolumeError>
361    where
362        F: FnMut(TensorizedEntry<'_>) -> ControlFlow<()>,
363    {
364        self.as_view().visit_tensorized_nquins(on_entry)
365    }
366
367    /// Indices of entries within `max_distance` of `query` in 10D
368    /// (full-distance metric) written to `out`. Delegates to the view.
369    pub fn tensor_search_into(
370        &self,
371        query: &Tensor10D,
372        max_distance: f32,
373        out: &mut [usize],
374    ) -> Result<usize, TensorVolumeError> {
375        self.as_view().tensor_search_into(query, max_distance, out)
376    }
377
378    /// Zero-allocation variant of `tensor_search_into` — `on_match`
379    /// per index, `Break` to stop early.
380    pub fn visit_tensor_search<F>(
381        &self,
382        query: &Tensor10D,
383        max_distance: f32,
384        on_match: F,
385    ) -> Result<(), TensorVolumeError>
386    where
387        F: FnMut(usize) -> ControlFlow<()>,
388    {
389        self.as_view()
390            .visit_tensor_search(query, max_distance, on_match)
391    }
392
393    /// Indices whose tensor `t` coordinate is within `tolerance` of
394    /// `target_t` written to `out`. Delegates to the view.
395    pub fn temporal_query_into(
396        &self,
397        target_t: f32,
398        tolerance: f32,
399        out: &mut [usize],
400    ) -> Result<usize, TensorVolumeError> {
401        self.as_view().temporal_query_into(target_t, tolerance, out)
402    }
403
404    /// Zero-allocation variant of `temporal_query_into` — `on_match`
405    /// per index, `Break` to stop early.
406    pub fn visit_temporal_query<F>(
407        &self,
408        target_t: f32,
409        tolerance: f32,
410        on_match: F,
411    ) -> Result<(), TensorVolumeError>
412    where
413        F: FnMut(usize) -> ControlFlow<()>,
414    {
415        self.as_view()
416            .visit_temporal_query(target_t, tolerance, on_match)
417    }
418
419    /// Indices matching manifold coordinate `target_w` within
420    /// `max_distance` (see `manifold_matches`) written to `out`.
421    /// Delegates to the view.
422    pub fn manifold_query_into(
423        &self,
424        target_w: f32,
425        max_distance: f32,
426        out: &mut [usize],
427    ) -> Result<usize, TensorVolumeError> {
428        self.as_view()
429            .manifold_query_into(target_w, max_distance, out)
430    }
431
432    /// Zero-allocation variant of `manifold_query_into` — `on_match`
433    /// per index, `Break` to stop early.
434    pub fn visit_manifold_query<F>(
435        &self,
436        target_w: f32,
437        max_distance: f32,
438        on_match: F,
439    ) -> Result<(), TensorVolumeError>
440    where
441        F: FnMut(usize) -> ControlFlow<()>,
442    {
443        self.as_view()
444            .visit_manifold_query(target_w, max_distance, on_match)
445    }
446}
447
448impl<'a> Q42TensorView<'a> {
449    /// Borrowed view over parallel `nquins`/`tensor_metadata` slices
450    /// plus the volume config; `MismatchedStorage` on length mismatch.
451    pub fn new(
452        nquins: &'a [NQuin],
453        tensor_metadata: &'a [TensorMetadata],
454        volume_config: &'a TensorVolumeConfig,
455    ) -> Result<Self, TensorVolumeError> {
456        if nquins.len() != tensor_metadata.len() {
457            return Err(TensorVolumeError::MismatchedStorage);
458        }
459
460        Ok(Self {
461            nquins,
462            tensor_metadata,
463            volume_config,
464        })
465    }
466
467    /// The view's borrowed tensor configuration.
468    pub fn config(&self) -> &'a TensorVolumeConfig {
469        self.volume_config
470    }
471
472    /// Total entries in the view (all NQuins, tensorized or not).
473    pub fn len(&self) -> usize {
474        self.nquins.len()
475    }
476
477    /// `true` when the view holds no entries.
478    pub fn is_empty(&self) -> bool {
479        self.nquins.is_empty()
480    }
481
482    /// Entries whose metadata carries tensor coordinates.
483    pub fn tensor_count(&self) -> usize {
484        self.tensor_metadata.iter().filter(|m| m.has_tensor).count()
485    }
486
487    /// Copy every tensorized `(NQuin, metadata)` pair into `out`;
488    /// `OutputBufferFull` when `out` can't hold all of them.
489    pub fn get_tensorized_nquins_into(
490        &self,
491        out: &mut [TensorizedEntry<'a>],
492    ) -> Result<usize, TensorVolumeError> {
493        let mut written = 0;
494
495        self.visit_tensorized_nquins(|entry| {
496            if written >= out.len() {
497                return ControlFlow::Break(());
498            }
499
500            out[written] = entry;
501            written += 1;
502            ControlFlow::Continue(())
503        })?;
504
505        if written < self.tensor_count() {
506            return Err(TensorVolumeError::OutputBufferFull);
507        }
508
509        Ok(written)
510    }
511
512    /// Granular collapse operator $\hat{\mathcal{C}}$ on a zero-heap tensor view (Packet OCS-13):
513    /// writes only empirically anchored entries (`has_tensor && tensor.q < 1.0`) into `out`,
514    /// preserving counterfactual / narrative entries (`tensor.q >= 1.0`) uncollapsed.
515    pub fn collapse_empirically_anchored_into(
516        &self,
517        out: &mut [TensorizedEntry<'a>],
518    ) -> Result<usize, TensorVolumeError> {
519        let collapsible_total = self
520            .tensor_metadata
521            .iter()
522            .filter(|m| m.has_tensor && m.tensor.is_empirically_collapsible())
523            .count();
524
525        let mut written = 0;
526        self.visit_tensorized_nquins(|entry| {
527            if !entry.metadata.tensor.is_empirically_collapsible() {
528                return ControlFlow::Continue(());
529            }
530            if written >= out.len() {
531                return ControlFlow::Break(());
532            }
533            out[written] = entry;
534            written += 1;
535            ControlFlow::Continue(())
536        })?;
537
538        if written < collapsible_total {
539            return Err(TensorVolumeError::OutputBufferFull);
540        }
541        Ok(written)
542    }
543
544    /// Iterate tensorized entries (`has_tensor`), calling `on_entry`
545    /// per pair; `Break` stops early. Zero-allocation query path.
546    pub fn visit_tensorized_nquins<F>(&self, mut on_entry: F) -> Result<(), TensorVolumeError>
547    where
548        F: FnMut(TensorizedEntry<'a>) -> ControlFlow<()>,
549    {
550        for (nquin, metadata) in self.nquins.iter().zip(self.tensor_metadata.iter()) {
551            if !metadata.has_tensor {
552                continue;
553            }
554
555            if let ControlFlow::Break(()) = on_entry(TensorizedEntry { nquin, metadata }) {
556                break;
557            }
558        }
559
560        Ok(())
561    }
562
563    /// Indices of tensorized entries within `max_distance` of `query`
564    /// in the 10D normalized full-distance metric written to `out`;
565    /// `OutputBufferFull` on overflow.
566    pub fn tensor_search_into(
567        &self,
568        query: &Tensor10D,
569        max_distance: f32,
570        out: &mut [usize],
571    ) -> Result<usize, TensorVolumeError> {
572        self.collect_matching_indices_into(out, |metadata| {
573            metadata.has_tensor && query.normalized_full_distance(&metadata.tensor) <= max_distance
574        })
575    }
576
577    /// Zero-allocation variant of `tensor_search_into` — `on_match`
578    /// per matching index, `Break` to stop early.
579    pub fn visit_tensor_search<F>(
580        &self,
581        query: &Tensor10D,
582        max_distance: f32,
583        mut on_match: F,
584    ) -> Result<(), TensorVolumeError>
585    where
586        F: FnMut(usize) -> ControlFlow<()>,
587    {
588        for (index, metadata) in self.tensor_metadata.iter().enumerate() {
589            if metadata.has_tensor
590                && query.normalized_full_distance(&metadata.tensor) <= max_distance
591            {
592                if let ControlFlow::Break(()) = on_match(index) {
593                    break;
594                }
595            }
596        }
597
598        Ok(())
599    }
600
601    /// Indices whose tensor `t` coordinate is within `tolerance` of
602    /// `target_t` written to `out`; `OutputBufferFull` on overflow.
603    pub fn temporal_query_into(
604        &self,
605        target_t: f32,
606        tolerance: f32,
607        out: &mut [usize],
608    ) -> Result<usize, TensorVolumeError> {
609        self.collect_matching_indices_into(out, |metadata| {
610            metadata.has_tensor && (metadata.tensor.t - target_t).abs() <= tolerance
611        })
612    }
613
614    /// Zero-allocation variant of `temporal_query_into` — `on_match`
615    /// per matching index, `Break` to stop early.
616    pub fn visit_temporal_query<F>(
617        &self,
618        target_t: f32,
619        tolerance: f32,
620        mut on_match: F,
621    ) -> Result<(), TensorVolumeError>
622    where
623        F: FnMut(usize) -> ControlFlow<()>,
624    {
625        for (index, metadata) in self.tensor_metadata.iter().enumerate() {
626            if metadata.has_tensor && (metadata.tensor.t - target_t).abs() <= tolerance {
627                if let ControlFlow::Break(()) = on_match(index) {
628                    break;
629                }
630            }
631        }
632
633        Ok(())
634    }
635
636    /// Indices matching manifold coordinate `target_w` within
637    /// `max_distance` (see `manifold_matches`) written to `out`;
638    /// `OutputBufferFull` on overflow.
639    pub fn manifold_query_into(
640        &self,
641        target_w: f32,
642        max_distance: f32,
643        out: &mut [usize],
644    ) -> Result<usize, TensorVolumeError> {
645        self.collect_matching_indices_into(out, |metadata| {
646            manifold_matches(metadata, target_w, max_distance)
647        })
648    }
649
650    /// Zero-allocation variant of `manifold_query_into` — `on_match`
651    /// per matching index, `Break` to stop early.
652    pub fn visit_manifold_query<F>(
653        &self,
654        target_w: f32,
655        max_distance: f32,
656        mut on_match: F,
657    ) -> Result<(), TensorVolumeError>
658    where
659        F: FnMut(usize) -> ControlFlow<()>,
660    {
661        for (index, metadata) in self.tensor_metadata.iter().enumerate() {
662            if manifold_matches(metadata, target_w, max_distance) {
663                if let ControlFlow::Break(()) = on_match(index) {
664                    break;
665                }
666            }
667        }
668
669        Ok(())
670    }
671
672    /// Shared collector behind the `*_into` queries — writes indices
673    /// satisfying `predicate` to `out`, `OutputBufferFull` on overflow.
674    fn collect_matching_indices_into<F>(
675        &self,
676        out: &mut [usize],
677        mut predicate: F,
678    ) -> Result<usize, TensorVolumeError>
679    where
680        F: FnMut(&TensorMetadata) -> bool,
681    {
682        let mut written = 0;
683
684        for (index, metadata) in self.tensor_metadata.iter().enumerate() {
685            if !predicate(metadata) {
686                continue;
687            }
688
689            if written >= out.len() {
690                return Err(TensorVolumeError::OutputBufferFull);
691            }
692
693            out[written] = index;
694            written += 1;
695        }
696
697        Ok(written)
698    }
699}
700
701/// Manifold query predicate: entry must be tensorized, within a
702/// hardcoded 0.1 neighbourhood of `target_w` on the w axis, then within
703/// `max_distance` in the full 10D metric (w substituted by `target_w`).
704fn manifold_matches(metadata: &TensorMetadata, target_w: f32, max_distance: f32) -> bool {
705    if !metadata.has_tensor {
706        return false;
707    }
708
709    let w_diff = (metadata.tensor.w - target_w).abs();
710    if w_diff > 0.1 {
711        return false;
712    }
713
714    let query = Tensor10D::new(
715        0.0,
716        metadata.tensor.v,
717        target_w,
718        metadata.tensor.x,
719        metadata.tensor.y,
720        metadata.tensor.z,
721        metadata.tensor.t,
722        metadata.tensor.alpha,
723        metadata.tensor.mu,
724        metadata.tensor.sigma,
725    );
726
727    query.spatial_distance(&metadata.tensor) <= max_distance
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733
734    #[test]
735    fn test_tensor_volume_creation() {
736        let mut nquins = [NQuin::default(); 4];
737        let mut metadata = [TensorMetadata::default(); 4];
738        let volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
739        assert!(volume.is_empty());
740        assert_eq!(volume.len(), 0);
741        assert_eq!(volume.capacity(), 4);
742    }
743
744    #[test]
745    fn test_add_nquin_with_tensor() {
746        let mut nquins = [NQuin::default(); 2];
747        let mut metadata = [TensorMetadata::default(); 2];
748        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
749
750        let nquin = create_test_nquin(1);
751        let tensor = Tensor10D::new(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.8, 0.5, 0.3);
752        volume.add_nquin_with_tensor(nquin, tensor).unwrap();
753
754        assert_eq!(volume.len(), 1);
755        assert_eq!(volume.tensor_count(), 1);
756        assert!(volume.get_tensor_metadata(0).unwrap().has_tensor);
757    }
758
759    #[test]
760    fn test_add_nquin_without_tensor() {
761        let mut nquins = [NQuin::default(); 2];
762        let mut metadata = [TensorMetadata::default(); 2];
763        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
764
765        volume.add_nquin(create_test_nquin(2)).unwrap();
766
767        assert_eq!(volume.len(), 1);
768        assert_eq!(volume.tensor_count(), 0);
769        assert!(!volume.get_tensor_metadata(0).unwrap().has_tensor);
770    }
771
772    #[test]
773    fn test_storage_capacity_is_bounded() {
774        let mut nquins = [NQuin::default(); 1];
775        let mut metadata = [TensorMetadata::default(); 1];
776        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
777
778        volume.add_nquin(create_test_nquin(1)).unwrap();
779        let result = volume.add_nquin(create_test_nquin(2));
780
781        assert_eq!(result, Err(TensorVolumeError::StorageCapacityExceeded));
782    }
783
784    #[test]
785    fn test_tensor_search_into() {
786        let mut nquins = [NQuin::default(); 8];
787        let mut metadata = [TensorMetadata::default(); 8];
788        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
789        seed_linear_tensor_points(&mut volume);
790
791        let query = Tensor10D::new(0.0, 0.0, 0.0, 2.0, 2.0, 0.0, 2.0, 1.0, 0.0, 0.0);
792        let mut out = [usize::MAX; 2];
793        let written = volume.tensor_search_into(&query, 0.5, &mut out).unwrap();
794
795        assert_eq!(written, 1);
796        assert_eq!(out[0], 2);
797    }
798
799    #[test]
800    fn test_tensor_search_into_reports_overflow() {
801        let mut nquins = [NQuin::default(); 4];
802        let mut metadata = [TensorMetadata::default(); 4];
803        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
804
805        for i in 0..3 {
806            let tensor = Tensor10D::new(0.0, 0.0, 0.0, i as f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
807            volume
808                .add_nquin_with_tensor(create_test_nquin(i), tensor)
809                .unwrap();
810        }
811
812        let query = Tensor10D::new(0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
813        let mut out = [usize::MAX; 1];
814        let result = volume.tensor_search_into(&query, 1.5, &mut out);
815
816        assert_eq!(result, Err(TensorVolumeError::OutputBufferFull));
817    }
818
819    #[test]
820    fn test_temporal_query_into() {
821        let mut nquins = [NQuin::default(); 8];
822        let mut metadata = [TensorMetadata::default(); 8];
823        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
824
825        for i in 0..5 {
826            let tensor = Tensor10D::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, i as f32, 1.0, 0.0, 0.0);
827            volume
828                .add_nquin_with_tensor(create_test_nquin(i), tensor)
829                .unwrap();
830        }
831
832        let mut out = [usize::MAX; 1];
833        let written = volume.temporal_query_into(2.0, 0.1, &mut out).unwrap();
834
835        assert_eq!(written, 1);
836        assert_eq!(out[0], 2);
837    }
838
839    #[test]
840    fn test_manifold_query_into_reports_overflow() {
841        let mut nquins = [NQuin::default(); 8];
842        let mut metadata = [TensorMetadata::default(); 8];
843        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
844
845        for i in 0..5 {
846            let w = (i % 3) as f32;
847            let tensor = Tensor10D::new(0.0, 0.0, w, i as f32, i as f32, 0.0, 0.0, 1.0, 0.0, 0.0);
848            volume
849                .add_nquin_with_tensor(create_test_nquin(i), tensor)
850                .unwrap();
851        }
852
853        let mut out = [usize::MAX; 1];
854        let result = volume.manifold_query_into(1.0, 5.0, &mut out);
855
856        assert_eq!(result, Err(TensorVolumeError::OutputBufferFull));
857    }
858
859    #[test]
860    fn test_get_tensorized_nquins_into() {
861        let mut nquins = [NQuin::default(); 4];
862        let mut metadata = [TensorMetadata::default(); 4];
863        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
864        let placeholder_nquin = NQuin::default();
865        let placeholder_metadata = TensorMetadata::default();
866
867        volume.add_nquin(create_test_nquin(0)).unwrap();
868        volume
869            .add_nquin_with_tensor(
870                create_test_nquin(1),
871                Tensor10D::new(0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0),
872            )
873            .unwrap();
874
875        let mut out = [TensorizedEntry {
876            nquin: &placeholder_nquin,
877            metadata: &placeholder_metadata,
878        }; 1];
879        let written = volume.get_tensorized_nquins_into(&mut out).unwrap();
880
881        assert_eq!(written, 1);
882        assert_eq!(out[0].nquin.subject, 1);
883        assert!(out[0].metadata.has_tensor);
884    }
885
886    #[test]
887    fn test_visit_tensor_search_stops_when_callback_breaks() {
888        let mut nquins = [NQuin::default(); 8];
889        let mut metadata = [TensorMetadata::default(); 8];
890        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
891
892        for i in 0..4 {
893            let tensor = Tensor10D::new(0.0, 0.0, 0.0, i as f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
894            volume
895                .add_nquin_with_tensor(create_test_nquin(i), tensor)
896                .unwrap();
897        }
898
899        let query = Tensor10D::new(0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
900        let mut first_hit = usize::MAX;
901        let mut count = 0usize;
902        volume
903            .visit_tensor_search(&query, 3.0, |index| {
904                first_hit = index;
905                count += 1;
906                ControlFlow::Break(())
907            })
908            .unwrap();
909
910        assert_eq!(count, 1);
911        assert_eq!(first_hit, 0);
912    }
913
914    #[test]
915    fn test_clear_scrubs_used_prefix() {
916        let mut nquins = [NQuin::default(); 2];
917        let mut metadata = [TensorMetadata::default(); 2];
918        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
919
920        volume
921            .add_nquin_with_tensor(
922                create_test_nquin(7),
923                Tensor10D::new(0.0, 0.0, 0.0, 7.0, 7.0, 0.0, 7.0, 1.0, 0.0, 0.0),
924            )
925            .unwrap();
926        volume.clear();
927
928        assert_eq!(volume.len(), 0);
929        assert_eq!(volume.nquins[0], NQuin::default());
930        assert_eq!(volume.tensor_metadata[0], TensorMetadata::default());
931    }
932
933    #[test]
934    fn test_q42_tensor_view_rejects_mismatched_storage() {
935        let nquins = [create_test_nquin(1)];
936        let metadata = [TensorMetadata::default(), TensorMetadata::default()];
937        let config = TensorVolumeConfig::default();
938
939        let result = Q42TensorView::new(&nquins, &metadata, &config);
940
941        assert!(matches!(result, Err(TensorVolumeError::MismatchedStorage)));
942    }
943
944    #[test]
945    fn test_normalized_hyperbolic_distance_is_zero_at_identity() {
946        // v = 2.0 (Hyperbolic / Tree topology): log-sum-exp branch must subtract ln(3) so d(x, x) == 0.0
947        let t = Tensor10D::new(0.0, 2.0, 1.0, 4.5, -2.25, 9.0, 1.0, 0.9, 0.5, 0.1);
948        assert!(t.normalized_hyperbolic_distance(&t) < 1e-6);
949        assert!(t.normalized_full_distance(&t) < 1e-6);
950
951        let mut nquins = [NQuin::default(); 2];
952        let mut metadata = [TensorMetadata::default(); 2];
953        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
954        volume
955            .add_nquin_with_tensor(create_test_nquin(10), t)
956            .unwrap();
957
958        let mut out = [usize::MAX; 1];
959        let written = volume.tensor_search_into(&t, 1e-5, &mut out).unwrap();
960        assert_eq!(written, 1);
961        assert_eq!(out[0], 0);
962    }
963
964    #[test]
965    fn test_collapse_empirically_anchored_preserves_narrative_entities() {
966        let mut nquins = [NQuin::default(); 4];
967        let mut metadata = [TensorMetadata::default(); 4];
968        let mut volume = Q42TensorVolume::new(&mut nquins, &mut metadata).unwrap();
969        let placeholder_nquin = NQuin::default();
970        let placeholder_metadata = TensorMetadata::default();
971
972        // Ancient Troy citadel: OP_ELEMENT_COLLAPSE (0x55), metadata low nibble = 0 (EmpiricallyAnchored -> q = 0.0)
973        let mut troy_quin = create_test_nquin(101);
974        troy_quin.predicate = 0x55;
975        troy_quin.metadata = 0;
976        let troy_tensor = Tensor10D::from_nquin(&troy_quin);
977        assert_eq!(troy_tensor.q, 0.0);
978
979        // Goddess Athena: OP_ELEMENT_COLLAPSE (0x55), metadata low nibble = 3 (CounterfactualMythos -> q = 3.0)
980        let mut athena_quin = create_test_nquin(202);
981        athena_quin.predicate = 0x55;
982        athena_quin.metadata = 3;
983        let athena_tensor = Tensor10D::from_nquin(&athena_quin);
984        assert_eq!(athena_tensor.q, 3.0);
985
986        volume
987            .add_nquin_with_tensor(troy_quin, troy_tensor)
988            .unwrap();
989        volume
990            .add_nquin_with_tensor(athena_quin, athena_tensor)
991            .unwrap();
992
993        let mut collapsed = [TensorizedEntry {
994            nquin: &placeholder_nquin,
995            metadata: &placeholder_metadata,
996        }; 2];
997        let count = volume
998            .collapse_empirically_anchored_into(&mut collapsed)
999            .unwrap();
1000        assert_eq!(count, 1);
1001        assert_eq!(collapsed[0].nquin.subject, 101);
1002    }
1003
1004    fn seed_linear_tensor_points(volume: &mut Q42TensorVolume<'_>) {
1005        for i in 0..5 {
1006            let tensor = Tensor10D::new(
1007                0.0, 0.0, 0.0, i as f32, i as f32, 0.0, i as f32, 1.0, 0.0, 0.0,
1008            );
1009            volume
1010                .add_nquin_with_tensor(create_test_nquin(i), tensor)
1011                .unwrap();
1012        }
1013    }
1014
1015    fn create_test_nquin(id: u64) -> NQuin {
1016        NQuin {
1017            subject: id,
1018            predicate: id,
1019            object: id,
1020            context: id,
1021            metadata: (id << 32) | id,
1022            parity: 0,
1023        }
1024    }
1025}