Skip to main content

qualia_core_db/q42/material_coupling/
binding.rs

1//! Cryptographic material binding (Schema 105 `MaterialBinding`), coordinate transform admission
2//! (Schema 106 `CoordinateTransform`), and exact signed-`i128` rational clock & half-open
3//! `[from, until)` validity verification (C02-C03, C02-C04, C02-C06).
4
5use crate::q42::m64_matter::{
6    BankedConstituentLut, M64Error, M64ReadError, M64ReadLimits, M64Reader, M64PayloadInterval,
7    Q42ConstituentLutEntry,
8};
9
10/// Maximum matrix orthogonality and determinant residual for Schema 106 proper rigid transforms (C02-C04).
11pub const TRANSFORM_ORTHOGONALITY_TOLERANCE: f64 = 1e-12;
12
13/// Errors arising during cryptographic material binding, frame transform, or rational clock verification.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub enum MaterialBindingError {
16    NonFiniteTransformComponent,
17    InvalidClockParameters,
18    InvalidInstantSubtick,
19    ClockOriginMismatch {
20        expected_clock_id: u32,
21        actual_clock_id: u32,
22    },
23    RationalArithmeticOverflow,
24    InvalidValidityIntervalOrder,
25    ValidityIntervalExpiredOrNotYetActive,
26    TransformFrameMismatch {
27        expected_source_frame: u32,
28        actual_source_frame: u32,
29        expected_target_frame: u32,
30        actual_target_frame: u32,
31    },
32    TransformProjectiveRowInvalid,
33    ImproperReflectionRejected {
34        determinant: f64,
35    },
36    NonOrthogonalOrShearedTransformRejected {
37        orthogonality_residual: f64,
38        determinant: f64,
39    },
40    UnsupportedGeneralAffineInInitialSolver,
41    UnsupportedMovingFrameInInitialSolver,
42    ContainerDigestMismatch {
43        expected: [u8; 32],
44        actual: [u8; 32],
45    },
46    MaterialTableDigestMismatch {
47        expected: [u8; 32],
48        actual: [u8; 32],
49    },
50    TableSchemaRevisionMismatch {
51        expected: u16,
52        actual: u16,
53    },
54    TableEpochMismatch {
55        expected_epoch: u16,
56        actual_epoch: u16,
57    },
58    MaterialIndexOutOfRange {
59        index: usize,
60        table_len: usize,
61    },
62    LutEntryCrcInvalid(M64Error),
63    M64ContainerStructuralError(M64ReadError),
64    CanonicalMaterialHashMismatch {
65        expected: u64,
66        actual: u64,
67    },
68    ProvenanceDidHashMismatch {
69        expected: u64,
70        actual: u64,
71    },
72    SpatialKeyAloneInsufficient,
73}
74
75#[inline]
76fn gcd_u64(mut a: u64, mut b: u64) -> u64 {
77    while b != 0 {
78        let r = a % b;
79        a = b;
80        b = r;
81    }
82    a
83}
84
85#[inline]
86fn gcd_u128(mut a: u128, mut b: u128) -> u128 {
87    while b != 0 {
88        let r = a % b;
89        a = b;
90        b = r;
91    }
92    a
93}
94
95/// Shared Schema 1 (`Clock`) rational clock definition per C02-C03.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub struct RationalClock {
98    pub clock_id: u32,
99    pub scale: u32,
100    pub epoch_seconds: i64,
101    pub epoch_nanoseconds: u32,
102    pub ticks_per_second_num: u64,
103    pub ticks_per_second_den: u64,
104}
105
106impl RationalClock {
107    pub fn validate(&self) -> Result<(), MaterialBindingError> {
108        if self.clock_id == 0
109            || self.scale > 2
110            || self.epoch_nanoseconds >= 1_000_000_000
111            || self.ticks_per_second_num == 0
112            || self.ticks_per_second_den == 0
113            || self.ticks_per_second_num > 1_000_000_000_000_000
114            || self.ticks_per_second_den > 1_000_000_000_000
115            || gcd_u64(self.ticks_per_second_num, self.ticks_per_second_den) != 1
116        {
117            return Err(MaterialBindingError::InvalidClockParameters);
118        }
119        Ok(())
120    }
121
122    /// Verify that two clock descriptors share identical origin, scale, and rate.
123    /// Equal rates and ticks alone do not establish simultaneity if `clock_id` or `epoch` differ (C02-C03).
124    pub fn verify_same_origin(&self, other: &Self) -> Result<(), MaterialBindingError> {
125        self.validate()?;
126        other.validate()?;
127        if self != other {
128            return Err(MaterialBindingError::ClockOriginMismatch {
129                expected_clock_id: self.clock_id,
130                actual_clock_id: other.clock_id,
131            });
132        }
133        Ok(())
134    }
135}
136
137/// Shared Schema 5 (`Instant`) rational tick + subtick timestamp per C02-C03.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct RationalInstant {
140    pub clock_id: u32,
141    pub tick: i64,
142    pub subtick_num: u64,
143    pub subtick_den: u64,
144}
145
146impl RationalInstant {
147    pub fn new(
148        clock_id: u32,
149        tick: i64,
150        subtick_num: u64,
151        subtick_den: u64,
152    ) -> Result<Self, MaterialBindingError> {
153        let s = Self {
154            clock_id,
155            tick,
156            subtick_num,
157            subtick_den,
158        };
159        s.validate()?;
160        Ok(s)
161    }
162
163    pub fn from_integral_tick(clock_id: u32, tick: i64) -> Result<Self, MaterialBindingError> {
164        Self::new(clock_id, tick, 0, 1)
165    }
166
167    pub fn validate(&self) -> Result<(), MaterialBindingError> {
168        if self.clock_id == 0
169            || self.subtick_den == 0
170            || self.subtick_den > 1_000_000_000_000
171            || self.subtick_num >= self.subtick_den
172            || gcd_u64(self.subtick_num, self.subtick_den) != 1
173        {
174            return Err(MaterialBindingError::InvalidInstantSubtick);
175        }
176        Ok(())
177    }
178
179    /// Exact checked comparison of two `RationalInstant` values on the same clock.
180    pub fn checked_cmp(&self, other: &Self) -> Result<std::cmp::Ordering, MaterialBindingError> {
181        self.validate()?;
182        other.validate()?;
183        if self.clock_id != other.clock_id {
184            return Err(MaterialBindingError::ClockOriginMismatch {
185                expected_clock_id: self.clock_id,
186                actual_clock_id: other.clock_id,
187            });
188        }
189        match self.tick.cmp(&other.tick) {
190            std::cmp::Ordering::Equal => {
191                let lhs = (self.subtick_num as u128)
192                    .checked_mul(other.subtick_den as u128)
193                    .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
194                let rhs = (other.subtick_num as u128)
195                    .checked_mul(self.subtick_den as u128)
196                    .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
197                Ok(lhs.cmp(&rhs))
198            }
199            ord => Ok(ord),
200        }
201    }
202
203    /// Compute exact elapsed seconds `(numerator, denominator)` from `clock` epoch for sample `sample_index`
204    /// at sample rate `(rate_num, rate_den)` Hz starting at `self`:
205    /// `t_i = start_tick * (tick_den / tick_num) + (subtick_num / subtick_den) * (tick_den / tick_num) + i * (rate_den / rate_num)`.
206    pub fn sample_offset_from_clock_epoch_seconds(
207        &self,
208        clock: &RationalClock,
209        sample_index: u64,
210        rate_num: u64,
211        rate_den: u64,
212    ) -> Result<(i128, u128), MaterialBindingError> {
213        clock.validate()?;
214        self.validate()?;
215        if self.clock_id != clock.clock_id {
216            return Err(MaterialBindingError::ClockOriginMismatch {
217                expected_clock_id: clock.clock_id,
218                actual_clock_id: self.clock_id,
219            });
220        }
221        if rate_num == 0 || rate_den == 0 || gcd_u64(rate_num, rate_den) != 1 {
222            return Err(MaterialBindingError::InvalidClockParameters);
223        }
224        // Total ticks in subtick units: (tick * subtick_den + subtick_num) / subtick_den
225        let sub_den = self.subtick_den as i128;
226        let total_subticks = (self.tick as i128)
227            .checked_mul(sub_den)
228            .and_then(|v| v.checked_add(self.subtick_num as i128))
229            .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
230
231        // Term 1 (seconds): total_subticks * tick_den / (subtick_den * tick_num)
232        let t1_num = total_subticks
233            .checked_mul(clock.ticks_per_second_den as i128)
234            .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
235        let t1_den = (self.subtick_den as u128)
236            .checked_mul(clock.ticks_per_second_num as u128)
237            .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
238
239        // Term 2 (seconds): sample_index * rate_den / rate_num
240        let t2_num = (sample_index as i128)
241            .checked_mul(rate_den as i128)
242            .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
243        let t2_den = rate_num as u128;
244
245        let g_den = gcd_u128(t1_den, t2_den);
246        let common_den = (t1_den / g_den)
247            .checked_mul(t2_den)
248            .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
249        let num = t1_num
250            .checked_mul((t2_den / g_den) as i128)
251            .and_then(|a| {
252                t2_num
253                    .checked_mul((t1_den / g_den) as i128)
254                    .and_then(|b| a.checked_add(b))
255            })
256            .ok_or(MaterialBindingError::RationalArithmeticOverflow)?;
257
258        let g = gcd_u128(num.unsigned_abs(), common_den);
259        Ok((num / (g as i128), common_den / g))
260    }
261}
262
263/// Half-open validity interval `[from, until)` per C02-C03 (used by Schema 106, Schema 107, Schema 202).
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub struct HalfOpenValidityInterval {
266    pub clock: RationalClock,
267    pub from: RationalInstant,
268    pub until: RationalInstant,
269}
270
271impl HalfOpenValidityInterval {
272    pub fn new(
273        clock: RationalClock,
274        from: RationalInstant,
275        until: RationalInstant,
276    ) -> Result<Self, MaterialBindingError> {
277        clock.validate()?;
278        if from.clock_id != clock.clock_id {
279            return Err(MaterialBindingError::ClockOriginMismatch {
280                expected_clock_id: clock.clock_id,
281                actual_clock_id: from.clock_id,
282            });
283        }
284        if until.clock_id != clock.clock_id {
285            return Err(MaterialBindingError::ClockOriginMismatch {
286                expected_clock_id: clock.clock_id,
287                actual_clock_id: until.clock_id,
288            });
289        }
290        if from.checked_cmp(&until)? != std::cmp::Ordering::Less {
291            return Err(MaterialBindingError::InvalidValidityIntervalOrder);
292        }
293        Ok(Self { clock, from, until })
294    }
295
296    /// Check whether `instant` lies strictly within `[from, until)` (`from <= instant < until`).
297    /// Rejects at the exact `until` endpoint with zero tolerance per C02-C03.
298    pub fn verify_contains(
299        &self,
300        instant_clock: &RationalClock,
301        instant: &RationalInstant,
302    ) -> Result<(), MaterialBindingError> {
303        self.clock.verify_same_origin(instant_clock)?;
304        let cmp_from = instant.checked_cmp(&self.from)?;
305        let cmp_until = instant.checked_cmp(&self.until)?;
306        if cmp_from == std::cmp::Ordering::Less || cmp_until != std::cmp::Ordering::Less {
307            return Err(MaterialBindingError::ValidityIntervalExpiredOrNotYetActive);
308        }
309        Ok(())
310    }
311}
312
313/// Classification of Schema 106 (`CoordinateTransform`) per C02-C04 / EMF-A07.
314#[derive(Clone, Copy, Debug, PartialEq, Eq)]
315pub enum CoordinateTransformKind {
316    /// Stationary proper rigid Euclidean isometry ($R R^T = I, \det(R) = +1$).
317    ProperRigid,
318    /// General invertible affine transformation (includes scaling, shear, or improper reflection).
319    GeneralAffine,
320    /// Time-dependent moving coordinate frame.
321    TimeDependentMoving,
322}
323
324/// Schema 106 (`CoordinateTransform`) $4\times 4$ homogeneous matrix mapping local coordinates
325/// in `source_frame_id` to `target_frame_id` over `validity`.
326#[derive(Clone, Copy, Debug, PartialEq)]
327pub struct CoordinateTransform4x4 {
328    pub source_frame_id: u32,
329    pub target_frame_id: u32,
330    pub kind: CoordinateTransformKind,
331    /// Row-major $4\times 4$ homogeneous transform matrix.
332    pub matrix_row_major: [[f64; 4]; 4],
333    pub validity: HalfOpenValidityInterval,
334}
335
336impl CoordinateTransform4x4 {
337    /// Admit a `CoordinateTransform4x4` for an initial stationary physical solver (C02-C04 / EMF-A07).
338    /// Rejects `GeneralAffine`, `TimeDependentMoving`, improper reflections ($\det(R) < 0$),
339    /// sheared/scaled upper-left $3\times 3$ blocks, and non-`[0,0,0,1]` bottom rows.
340    pub fn admit_for_initial_physical_solver(
341        &self,
342        expected_source_frame: u32,
343        expected_target_frame: u32,
344        eval_clock: &RationalClock,
345        eval_instant: &RationalInstant,
346    ) -> Result<([[f64; 3]; 3], [f64; 3]), MaterialBindingError> {
347        if self.source_frame_id == 0
348            || self.target_frame_id == 0
349            || self.source_frame_id != expected_source_frame
350            || self.target_frame_id != expected_target_frame
351        {
352            return Err(MaterialBindingError::TransformFrameMismatch {
353                expected_source_frame,
354                actual_source_frame: self.source_frame_id,
355                expected_target_frame,
356                actual_target_frame: self.target_frame_id,
357            });
358        }
359        self.validity.verify_contains(eval_clock, eval_instant)?;
360
361        for row in &self.matrix_row_major {
362            if row.iter().any(|v| !v.is_finite()) {
363                return Err(MaterialBindingError::NonFiniteTransformComponent);
364            }
365        }
366        match self.kind {
367            CoordinateTransformKind::ProperRigid => {}
368            CoordinateTransformKind::GeneralAffine => {
369                return Err(MaterialBindingError::UnsupportedGeneralAffineInInitialSolver);
370            }
371            CoordinateTransformKind::TimeDependentMoving => {
372                return Err(MaterialBindingError::UnsupportedMovingFrameInInitialSolver);
373            }
374        }
375
376        let b = &self.matrix_row_major[3];
377        if b[0].abs() > TRANSFORM_ORTHOGONALITY_TOLERANCE
378            || b[1].abs() > TRANSFORM_ORTHOGONALITY_TOLERANCE
379            || b[2].abs() > TRANSFORM_ORTHOGONALITY_TOLERANCE
380            || (b[3] - 1.0).abs() > TRANSFORM_ORTHOGONALITY_TOLERANCE
381        {
382            return Err(MaterialBindingError::TransformProjectiveRowInvalid);
383        }
384
385        let r = [
386            [
387                self.matrix_row_major[0][0],
388                self.matrix_row_major[0][1],
389                self.matrix_row_major[0][2],
390            ],
391            [
392                self.matrix_row_major[1][0],
393                self.matrix_row_major[1][1],
394                self.matrix_row_major[1][2],
395            ],
396            [
397                self.matrix_row_major[2][0],
398                self.matrix_row_major[2][1],
399                self.matrix_row_major[2][2],
400            ],
401        ];
402        let translation = [
403            self.matrix_row_major[0][3],
404            self.matrix_row_major[1][3],
405            self.matrix_row_major[2][3],
406        ];
407
408        let mut max_orth_err = 0.0f64;
409        for i in 0..3 {
410            for j in 0..3 {
411                let dot = r[i][0] * r[j][0] + r[i][1] * r[j][1] + r[i][2] * r[j][2];
412                let target = if i == j { 1.0 } else { 0.0 };
413                max_orth_err = max_orth_err.max((dot - target).abs());
414            }
415        }
416        let det = r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1])
417            - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0])
418            + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]);
419
420        if det < 0.0 && (det + 1.0).abs() <= 1e-6 && max_orth_err <= TRANSFORM_ORTHOGONALITY_TOLERANCE {
421            return Err(MaterialBindingError::ImproperReflectionRejected { determinant: det });
422        }
423        if max_orth_err > TRANSFORM_ORTHOGONALITY_TOLERANCE
424            || (det - 1.0).abs() > TRANSFORM_ORTHOGONALITY_TOLERANCE
425        {
426            return Err(
427                MaterialBindingError::NonOrthogonalOrShearedTransformRejected {
428                    orthogonality_residual: max_orth_err,
429                    determinant: det,
430                },
431            );
432        }
433
434        Ok((r, translation))
435    }
436}
437
438/// Complete material entry identity descriptor inside Schema 105 (`MaterialBinding`) per C02-C06.
439#[derive(Clone, Copy, Debug, PartialEq, Eq)]
440pub struct MaterialEntryIdentity {
441    /// Zero-based slot index into the 256-entry `BankedConstituentLut` (or bounded LUT slice).
442    pub lut_slot_index: u8,
443    /// Full 64-bit canonical FNV-1a material IRI hash (`Q42ConstituentLutEntry::canonical_q42_material_hash`).
444    pub canonical_q42_material_hash: u64,
445    /// Full 64-bit custodian/provenance DID hash (`Q42ConstituentLutEntry::provenance_did_hash`).
446    pub provenance_did_hash: u64,
447    /// Optional spatial Morton/Hilbert key associated with the chunk; never sufficient alone!
448    pub spatial_hilbert_key: u64,
449}
450
451/// Schema 105 (`MaterialBinding`) cryptographic binding between an EMF/QAC field stream and an
452/// `.m64` container + `BankedConstituentLut` material table.
453#[derive(Clone, Debug, PartialEq)]
454pub struct MaterialBinding {
455    /// Full 256-bit BLAKE3 digest of the `.m64` container bytes.
456    pub container_blake3: [u8; 32],
457    /// Full 256-bit BLAKE3 digest of the 16-KB `BankedConstituentLut` (`as_gpu_bytes()`).
458    pub material_table_blake3: [u8; 32],
459    /// Schema revision of the material table (must be 1).
460    pub table_schema_revision: u16,
461    /// Active Bank 1 recipe epoch ID (`active_bank_1_epoch_id`).
462    pub table_epoch_id: u16,
463    /// Coordinate frame ID of the `.m64` matter container.
464    pub material_frame_id: u32,
465    /// Coordinate frame ID of the consuming EMF/QAC field stream.
466    pub field_frame_id: u32,
467    /// Explicit coordinate frame transform from `material_frame_id` to `field_frame_id`.
468    pub transform: CoordinateTransform4x4,
469    /// Declared material entry identities (indexed by `1..=entries.len()` for 1-based `material_entry`).
470    pub entries: Vec<MaterialEntryIdentity>,
471}
472
473/// Verified material entry resulting from a full cryptographic and spatio-temporal binding check.
474#[derive(Clone, Copy, Debug, PartialEq)]
475pub struct VerifiedBoundMaterial {
476    pub identity: MaterialEntryIdentity,
477    pub lut_entry: Q42ConstituentLutEntry,
478    pub rotation_to_field_frame: [[f64; 3]; 3],
479    pub translation_to_field_frame_m: [f64; 3],
480}
481
482/// Compute the unkeyed BLAKE3-256 digest of a byte slice.
483#[inline]
484pub fn compute_blake3_256(bytes: &[u8]) -> [u8; 32] {
485    *blake3::hash(bytes).as_bytes()
486}
487
488impl MaterialBinding {
489    /// Verify the complete cryptographic, epoch, frame, and clock binding against raw `.m64`
490    /// container bytes and a `BankedConstituentLut`, returning the verified `Q42ConstituentLutEntry`
491    /// for the 1-based `one_based_entry_index`.
492    pub fn verify_and_resolve_entry(
493        &self,
494        m64_container_bytes: &[u8],
495        m64_limits: M64ReadLimits,
496        m64_scratch: &mut [M64PayloadInterval],
497        lut: &BankedConstituentLut,
498        actual_table_schema_revision: u16,
499        one_based_entry_index: u32,
500        eval_clock: &RationalClock,
501        eval_instant: &RationalInstant,
502    ) -> Result<VerifiedBoundMaterial, MaterialBindingError> {
503        // 1. Structural and CRC check on the .m64 container
504        let _reader = M64Reader::parse(m64_container_bytes, m64_limits, m64_scratch)
505            .map_err(MaterialBindingError::M64ContainerStructuralError)?;
506
507        // 2. Full 256-bit BLAKE3 check on the .m64 container bytes
508        let actual_container_digest = compute_blake3_256(m64_container_bytes);
509        if actual_container_digest != self.container_blake3 {
510            return Err(MaterialBindingError::ContainerDigestMismatch {
511                expected: self.container_blake3,
512                actual: actual_container_digest,
513            });
514        }
515
516        // 3. Full 256-bit BLAKE3 check on the 16-KB BankedConstituentLut
517        let actual_table_digest = compute_blake3_256(lut.as_gpu_bytes());
518        if actual_table_digest != self.material_table_blake3 {
519            return Err(MaterialBindingError::MaterialTableDigestMismatch {
520                expected: self.material_table_blake3,
521                actual: actual_table_digest,
522            });
523        }
524
525        // 4. Schema revision and Bank 1 epoch check
526        if actual_table_schema_revision != 1 || self.table_schema_revision != 1 {
527            return Err(MaterialBindingError::TableSchemaRevisionMismatch {
528                expected: self.table_schema_revision,
529                actual: actual_table_schema_revision,
530            });
531        }
532        if lut.active_bank_1_epoch_id != self.table_epoch_id {
533            return Err(MaterialBindingError::TableEpochMismatch {
534                expected_epoch: self.table_epoch_id,
535                actual_epoch: lut.active_bank_1_epoch_id,
536            });
537        }
538
539        // 5. Coordinate frame & rational clock validity interval check
540        let (rot, trans) = self.transform.admit_for_initial_physical_solver(
541            self.material_frame_id,
542            self.field_frame_id,
543            eval_clock,
544            eval_instant,
545        )?;
546
547        // 6. Entry bounds & complete identity verification
548        if one_based_entry_index == 0 || (one_based_entry_index as usize) > self.entries.len() {
549            return Err(MaterialBindingError::MaterialIndexOutOfRange {
550                index: one_based_entry_index as usize,
551                table_len: self.entries.len(),
552            });
553        }
554        let identity = self.entries[(one_based_entry_index as usize) - 1];
555        let lut_entry = *lut.entry(identity.lut_slot_index);
556        lut_entry
557            .validate()
558            .map_err(MaterialBindingError::LutEntryCrcInvalid)?;
559
560        if lut_entry.canonical_q42_material_hash != identity.canonical_q42_material_hash {
561            return Err(MaterialBindingError::CanonicalMaterialHashMismatch {
562                expected: identity.canonical_q42_material_hash,
563                actual: lut_entry.canonical_q42_material_hash,
564            });
565        }
566        if lut_entry.provenance_did_hash != identity.provenance_did_hash {
567            return Err(MaterialBindingError::ProvenanceDidHashMismatch {
568                expected: identity.provenance_did_hash,
569                actual: lut_entry.provenance_did_hash,
570            });
571        }
572
573        Ok(VerifiedBoundMaterial {
574            identity,
575            lut_entry,
576            rotation_to_field_frame: rot,
577            translation_to_field_frame_m: trans,
578        })
579    }
580}
581
582/// Explicitly reject attempts to join a field sample and an `.m64` record using only a matching
583/// Morton/Hilbert `spatial_key` without a verified `MaterialBinding` (C02-C06).
584pub fn reject_spatial_key_only_join(_spatial_key: u64) -> Result<(), MaterialBindingError> {
585    Err(MaterialBindingError::SpatialKeyAloneInsufficient)
586}