Skip to main content

qualia_core_db/container_10d/
metric_check.rs

1//! Metric-completeness descriptor + the "queryability claim == code" gate.
2//!
3//! The `.10d` header carries a [`MetricCompletenessDescriptor`] declaring, per
4//! `v`-branch, which COORDINATE axes the distance metric folds. The parser
5//! rejects any descriptor that diverges from `Tensor10D::full_distance`'s
6//! actual v-branch behaviour — this is the mechanical barrier that enforces
7//! the honest-limitation contract: a developer cannot claim an axis is
8//! queryable under a metric the kernel does not actually fold.
9//!
10//! **Current reality (encoded as the proposed default):**
11//! - `v=0` Euclidean folds `x,y,z,t,α,μ,σ` (all seven COORDINATEs)
12//! - `v=1` Cyclic/Toroidal folds `x,y,z` only
13//! - `v=2` Hyperbolic folds `x,y,z` only
14//! - `v>=3` Boundary clique folds no coordinate axes (byte-equality on `v`)
15//!
16//! This is option (b) "document the limitation" per Timothy's 2026-07-04
17//! decision. P7.9 (making the non-Euclidean metrics axis-complete via product
18//! / warped-product manifolds and a clique-graph) is deferred as future
19//! geometry design work — see the progress log and the P7.9 task entry.
20//!
21//! Reference: `docs/plans/native-computational-geometry.md` §4.1 honest
22//! limitation, and the cross-cutting gate "Honest axis-role taxonomy &
23//! metric-completeness (queryability claim == code)".
24
25use bytemuck::{Pod, Zeroable};
26
27use crate::container_10d::axis_role::COORDINATE_AXES;
28use crate::tensor::Tensor10D;
29use std::fmt;
30
31/// Number of `v`-branch descriptors the header carries: the three explicit
32/// classes (0, 1, 2) plus one catch-all for `v >= 3`.
33pub const METRIC_BRANCH_COUNT: usize = 4;
34
35/// Index of the `v >= 3` catch-all branch in a [`MetricCompletenessDescriptor`].
36pub const BOUNDARY_CLIQUE_BRANCH_INDEX: usize = 3;
37
38/// A `u8` tag identifying the metric kind a branch implements. Mirrors the
39/// dispatch in `Tensor10D::full_distance`.
40#[repr(u8)]
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum MetricKind {
43    /// Sentinel — the parser rejects a branch with this kind.
44    Undefined = 0,
45    Euclidean = 1,
46    CyclicToroidal = 2,
47    Hyperbolic = 3,
48    BoundaryClique = 4,
49    SphericalHealpix = 5,
50    LorentzianSpacetime = 6,
51    MultiplyConnectedPortal = 7,
52}
53
54impl MetricKind {
55    #[inline]
56    /// Decode a metric tag; `None` for unknown values.
57    pub const fn from_u8(raw: u8) -> Option<MetricKind> {
58        match raw {
59            0 => Some(MetricKind::Undefined),
60            1 => Some(MetricKind::Euclidean),
61            2 => Some(MetricKind::CyclicToroidal),
62            3 => Some(MetricKind::Hyperbolic),
63            4 => Some(MetricKind::BoundaryClique),
64            5 => Some(MetricKind::SphericalHealpix),
65            6 => Some(MetricKind::LorentzianSpacetime),
66            7 => Some(MetricKind::MultiplyConnectedPortal),
67            _ => None,
68        }
69    }
70}
71
72/// One row of the metric-completeness table: the metric used for a single
73/// `v`-class and the bitmask of COORDINATE axes it folds.
74///
75/// `folded_axes` is a bitmask over [`super::axis_role::AXIS_ORDER`] indices —
76/// bit `i` set means axis `i` participates in this branch's distance sum. Only
77/// COORDINATE-axis bits may be set; a SELECTOR-axis bit (0,1,2) is a divergence
78/// the verifier rejects.
79///
80/// Layout: 8 bytes, no padding (`u8` + `u8` + `u16` + `u32`, all naturally
81/// aligned). POD so it embeds directly in the header.
82#[repr(C)]
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
84pub struct MetricBranchDescriptor {
85    /// The `v` class this row describes: `0`, `1`, `2`, or `255` for the
86    /// `v >= 3` catch-all.
87    pub v_class: u8,
88    /// The metric kind — see [`MetricKind`].
89    pub metric_kind: u8,
90    /// Bitmask of folded COORDINATE axes (bit `i` = axis `i` in `AXIS_ORDER`).
91    pub folded_axes: u16,
92    /// Reserved, must be zero. Future use (e.g. per-branch scale weights).
93    pub reserved: u32,
94}
95
96impl MetricBranchDescriptor {
97    /// True if axis `i` is declared folded by this branch.
98    #[inline]
99    pub const fn folds_axis(self, i: usize) -> bool {
100        (self.folded_axes >> i) & 1 == 1
101    }
102}
103
104/// The full metric-completeness table carried in the `.10d` header. One row per
105/// `v`-class; `branches[3]` is the `v >= 3` catch-all.
106///
107/// Layout: 4 × 8 = 32 bytes, no padding.
108#[repr(C)]
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
110pub struct MetricCompletenessDescriptor {
111    pub branches: [MetricBranchDescriptor; METRIC_BRANCH_COUNT],
112}
113
114/// Error raised when a descriptor diverges from `full_distance`'s actual
115/// behaviour. Carries enough detail to name the offending branch + axis in the
116/// parser's rejection message.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct MetricDivergence {
119    pub v_class: u8,
120    pub axis_index: usize,
121    pub declared_folds: bool,
122    pub actual_folds: bool,
123}
124
125impl fmt::Display for MetricDivergence {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        let axis = super::axis_role::AXIS_ORDER[self.axis_index];
128        write!(
129            f,
130            "metric-completeness divergence: v={} claims axis {} is {}folded but full_distance {}folds it",
131            self.v_class,
132            axis,
133            if self.declared_folds { "" } else { "not " },
134            if self.actual_folds { "" } else { "does not " },
135        )
136    }
137}
138
139impl std::error::Error for MetricDivergence {}
140
141/// Probe `Tensor10D::full_distance` to determine whether axis `axis_index` is
142/// folded under the branch selected by `v_class`. Returns `true` if varying
143/// only that axis (with `v` held at `v_class`) changes the distance.
144///
145/// This is the introspection step that makes the honesty gate mechanical: it
146/// reads the actual kernel behaviour, not a hardcoded claim.
147fn axis_is_folded_by_full_distance(v_class: u8, axis_index: usize) -> bool {
148    let mut base = Tensor10D::default();
149    base.v = v_class as f32;
150    let mut perturbed = base;
151    perturb_axis(&mut perturbed, axis_index);
152    let d_base = base.full_distance(&base);
153    let d_perturbed = base.full_distance(&perturbed);
154    (d_perturbed - d_base).abs() > 1e-6
155}
156
157/// Perturb a single axis lane by a non-trivial delta, leaving the other nine
158/// lanes (including `v`) untouched.
159fn perturb_axis(t: &mut Tensor10D, axis_index: usize) {
160    const DELTA: f32 = 0.25;
161    match axis_index {
162        0 => t.q += DELTA,
163        1 => t.v += DELTA,
164        2 => t.w += DELTA,
165        3 => t.x += DELTA,
166        4 => t.y += DELTA,
167        5 => t.z += DELTA,
168        6 => t.t += DELTA,
169        7 => t.alpha += DELTA,
170        8 => t.mu += DELTA,
171        9 => t.sigma += DELTA,
172        _ => unreachable!("axis_index out of range"),
173    }
174}
175
176/// Probe `full_distance` for one branch and return the bitmask of COORDINATE
177/// axes it actually folds. Only COORDINATE axes are probed — SELECTOR axes are
178/// excluded by definition and a descriptor claiming to fold one is a divergence.
179pub fn probe_folded_axes(v_class: u8) -> u16 {
180    let mut mask: u16 = 0;
181    for &i in &COORDINATE_AXES {
182        if axis_is_folded_by_full_distance(v_class, i) {
183            mask |= 1 << i;
184        }
185    }
186    mask
187}
188
189/// Helper probing folded axes for extended topology classes (v >= 4).
190pub fn probe_extended_topology_branch(v_class: u8) -> u16 {
191    probe_folded_axes(v_class)
192}
193
194/// Verify a [`MetricCompletenessDescriptor`] against the actual
195/// `Tensor10D::full_distance` behaviour. Returns the first divergence found, or
196/// `Ok(())` if every branch's declared `folded_axes` and `metric_kind` match
197/// reality.
198pub fn verify_descriptor_against_reality(
199    descriptor: &MetricCompletenessDescriptor,
200) -> Result<(), MetricDivergence> {
201    for (row_index, branch) in descriptor.branches.iter().enumerate() {
202        let v_class = if row_index == BOUNDARY_CLIQUE_BRANCH_INDEX {
203            3
204        } else {
205            branch.v_class
206        };
207
208        let declared_kind = MetricKind::from_u8(branch.metric_kind);
209        match (declared_kind, v_class) {
210            (Some(MetricKind::Euclidean), 0) => {}
211            (Some(MetricKind::CyclicToroidal), 1) => {}
212            (Some(MetricKind::Hyperbolic), 2) => {}
213            (Some(MetricKind::BoundaryClique), 3) => {}
214            (Some(MetricKind::Undefined), _) => {
215                return Err(MetricDivergence {
216                    v_class,
217                    axis_index: 0,
218                    declared_folds: false,
219                    actual_folds: false,
220                });
221            }
222            _ => {
223                return Err(MetricDivergence {
224                    v_class,
225                    axis_index: 0,
226                    declared_folds: false,
227                    actual_folds: false,
228                });
229            }
230        }
231
232        let actual = probe_folded_axes(v_class);
233        for &i in &COORDINATE_AXES {
234            let declared_folds = branch.folds_axis(i);
235            let actual_folds = (actual >> i) & 1 == 1;
236            if declared_folds != actual_folds {
237                return Err(MetricDivergence {
238                    v_class,
239                    axis_index: i,
240                    declared_folds,
241                    actual_folds,
242                });
243            }
244        }
245    }
246    Ok(())
247}
248
249/// The proposed (not-yet-frozen) metric-completeness descriptor encoding the
250/// current `full_distance` reality — option (b), the documented limitation.
251pub const fn proposed_metric_descriptor() -> MetricCompletenessDescriptor {
252    const fn branch(v: u8, kind: u8, folded: u16) -> MetricBranchDescriptor {
253        MetricBranchDescriptor {
254            v_class: v,
255            metric_kind: kind,
256            folded_axes: folded,
257            reserved: 0,
258        }
259    }
260    const XYZ: u16 = (1 << 3) | (1 << 4) | (1 << 5);
261    const ALL_SEVEN: u16 = XYZ | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9);
262    MetricCompletenessDescriptor {
263        branches: [
264            branch(0, MetricKind::Euclidean as u8, ALL_SEVEN),
265            branch(1, MetricKind::CyclicToroidal as u8, XYZ),
266            branch(2, MetricKind::Hyperbolic as u8, XYZ),
267            branch(255, MetricKind::BoundaryClique as u8, 0),
268        ],
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn probe_v0_euclidean_folds_all_seven_coordinates() {
278        let mask = probe_folded_axes(0);
279        assert_eq!(
280            mask,
281            (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9)
282        );
283    }
284
285    #[test]
286    fn probe_v1_cyclic_folds_xyz_only() {
287        let mask = probe_folded_axes(1);
288        assert_eq!(
289            mask,
290            (1 << 3) | (1 << 4) | (1 << 5),
291            "v=1 must fold only x,y,z; got {mask:#b}"
292        );
293        assert_eq!(mask & (1 << 6), 0, "t must not be folded under v=1");
294        assert_eq!(mask & (1 << 7), 0, "α must not be folded under v=1");
295        assert_eq!(mask & (1 << 8), 0, "μ must not be folded under v=1");
296        assert_eq!(mask & (1 << 9), 0, "σ must not be folded under v=1");
297    }
298
299    #[test]
300    fn probe_v2_hyperbolic_folds_xyz_only() {
301        let mask = probe_folded_axes(2);
302        assert_eq!(
303            mask,
304            (1 << 3) | (1 << 4) | (1 << 5),
305            "v=2 must fold only x,y,z; got {mask:#b}"
306        );
307    }
308
309    #[test]
310    fn probe_v3_boundary_folds_no_coordinate_axes() {
311        let mask = probe_folded_axes(3);
312        assert_eq!(
313            mask, 0,
314            "v>=3 boundary clique must fold no coordinate axes; got {mask:#b}"
315        );
316    }
317
318    #[test]
319    fn proposed_descriptor_matches_reality() {
320        let desc = proposed_metric_descriptor();
321        assert!(
322            verify_descriptor_against_reality(&desc).is_ok(),
323            "the proposed (option b) descriptor must match full_distance's actual behaviour"
324        );
325    }
326
327    #[test]
328    fn diverging_descriptor_claiming_v1_folds_t_is_rejected() {
329        let mut desc = proposed_metric_descriptor();
330        desc.branches[1].folded_axes |= 1 << 6;
331        let err =
332            verify_descriptor_against_reality(&desc).expect_err("must reject diverging claim");
333        assert_eq!(err.v_class, 1);
334        assert_eq!(err.axis_index, 6, "divergence must name axis t (index 6)");
335        assert!(err.declared_folds);
336        assert!(!err.actual_folds);
337    }
338
339    #[test]
340    fn diverging_descriptor_claiming_v0_ignores_sigma_is_rejected() {
341        let mut desc = proposed_metric_descriptor();
342        desc.branches[0].folded_axes &= !(1 << 9);
343        let err =
344            verify_descriptor_against_reality(&desc).expect_err("must reject diverging claim");
345        assert_eq!(err.v_class, 0);
346        assert_eq!(err.axis_index, 9, "divergence must name axis σ (index 9)");
347        assert!(!err.declared_folds);
348        assert!(err.actual_folds);
349    }
350
351    #[test]
352    fn diverging_descriptor_claiming_v3_folds_x_is_rejected() {
353        let mut desc = proposed_metric_descriptor();
354        desc.branches[BOUNDARY_CLIQUE_BRANCH_INDEX].folded_axes |= 1 << 3;
355        let err =
356            verify_descriptor_against_reality(&desc).expect_err("must reject diverging claim");
357        assert_eq!(err.v_class, 3);
358        assert_eq!(err.axis_index, 3);
359    }
360
361    #[test]
362    fn wrong_metric_kind_for_v_class_is_rejected() {
363        let mut desc = proposed_metric_descriptor();
364        desc.branches[0].metric_kind = MetricKind::Hyperbolic as u8;
365        assert!(verify_descriptor_against_reality(&desc).is_err());
366    }
367
368    #[test]
369    fn undefined_metric_kind_is_rejected() {
370        let mut desc = proposed_metric_descriptor();
371        desc.branches[0].metric_kind = MetricKind::Undefined as u8;
372        assert!(verify_descriptor_against_reality(&desc).is_err());
373    }
374
375    #[test]
376    fn test_extended_topology_branches_probe() {
377        const XYZ: u16 = (1 << 3) | (1 << 4) | (1 << 5);
378        const XYZT: u16 = XYZ | (1 << 6);
379
380        // v=4 SphericalHealpix folds x, y, z
381        assert_eq!(
382            probe_extended_topology_branch(4),
383            XYZ,
384            "v=4 must fold only x, y, z"
385        );
386
387        // v=5 LorentzianSpacetime folds x, y, z, t
388        assert_eq!(
389            probe_extended_topology_branch(5),
390            XYZT,
391            "v=5 must fold x, y, z, t"
392        );
393
394        // v=6 MultiplyConnectedPortal folds x, y, z
395        assert_eq!(
396            probe_extended_topology_branch(6),
397            XYZ,
398            "v=6 must fold only x, y, z"
399        );
400    }
401}