qualia_core_db/foundation/frame_layout.rs
1//! FrameLayout — the single canonical registry for the ~6 computational-support
2//! bytes of the 48-byte NQuin Frame.
3//!
4//! A Frame is `6 × u64 = 48 bytes`: roughly **42 bytes of semantics** (the
5//! subject / property-path / object / context hashes and packed literals) plus
6//! **~6 bytes of computational support** (opcode, flags, datatype tags, a clock,
7//! ECC parity) — which is what makes a Frame both *data* and *executable code* in
8//! one cell. Every modality reads and writes those computational bytes through
9//! here, so the primitive stays universal and no two conventions silently collide
10//! (enforced by the tests below).
11//!
12//! ## `predicate` — opcode | property-path | defeater (co-resident; MUST NOT overlap)
13//! `[0..7]` deontic/epistemic opcode · `[8..62]` property-path hash · `[63]` defeater.
14//! "Proposition-mode" modalities (LTL/CTL/modal/abductive/causal/…) use the WHOLE
15//! predicate as a plain `q_hash` (no opcode) — a documented mode, not a collision.
16//!
17//! ## `object` — MSB pointer flag | inline datatype tag | value (co-resident)
18//! `[63]` set ⇒ the value is a lexicon/embedded pointer. When `[63]` is clear,
19//! `[60..62]` is an inline datatype tag and `[0..59]` is the value. Canonical tags
20//! (from `resolver`): INTEGER 001 · DECIMAL 010 · BOOLEAN 011 · BLOB 100 ·
21//! **FLOAT 101** (new — raw f32 bits; resolves the prior clash where f32 squatted
22//! on the INTEGER tag).
23//!
24//! ## Tag policy — closed datatypes inline, open identifier *kinds* in the graph
25//! The `object` inline-tag region is reserved STRICTLY for the small, CLOSED set of
26//! structural **datatypes** the GPU/SIMD hot path must read in-register (the tags
27//! above: INTEGER/DECIMAL/BOOLEAN/BLOB/FLOAT + the embedded-triple / pointer flags).
28//! Open, extensible **identifier *kinds* / namespaces** (Webizen, did:q42, DID,
29//! content-hash, instrument-language, cluster-node, …) are NOT inline tags — they are
30//! scoped by **modal predicates** in the graph (`<X> <has-modality-kind> <…>`),
31//! resolved at the logic layer via `indexing::QuinIndex` point lookups, with the
32//! **lexicon as the collision backstop** (the u64 is a *handle* to a full value, so a
33//! handle collision is detectable + resolvable, never silent corruption). Rationale:
34//! datatypes are a fixed vocabulary that belongs in the bit-budget; identifier kinds
35//! are an open fabric that belongs in the relations (identifiers-not-identity). This
36//! is why a dictionary identity is 60-bit (top nibble = the datatype overlay) while
37//! identifier-kind breadth lives in predicates, not in more inline tag bits.
38//!
39//! ## `metadata` — a ROLE-KEYED OVERLAY field (read this carefully)
40//! Unlike `predicate`/`object`, the 32 high bits of `metadata` are NOT a flat set
41//! of independently-addressable sub-fields. They are a union of overlays, each
42//! valid only for a particular quin *role*, several of which share bit positions.
43//! Two overlays sharing bits is safe **iff** their roles are mutually exclusive
44//! (a quin is never both at once). The ONE invariant that always holds — and is
45//! enforced below — is that the **low-32 payload is disjoint from every high
46//! overlay**, so a degree/expiry/timestamp can never silently corrupt a type/flag.
47//!
48//! * `[0..31]` low payload (any quin): exactly ONE of expiry / f32 truth-degree /
49//! 32-bit timestamp / packed (alpha,mu,sigma) — selected by role.
50//! * `[32..59]` tensor-bake `t` clock — ONLY on Tensor10D ground-truth nodes
51//! (`tensor::bake_pipeline`).
52//! * `[50..59]` per-modality flag bits — ONLY on that modality's quins (each flag
53//! is a single distinct bit; see the pairwise-distinct test).
54//! * `[56..59]` ODRL sensitivity tier — ONLY on access-controlled quins.
55//! * `[60..63]` quin-type nibble — general typing; `[61..62]` of it doubles as the
56//! permissive-routing lane (`cbor_compiler`, `daemon_swarm`). Typed vs routed are
57//! treated as exclusive roles. quin_type was deliberately NOT relocated lower:
58//! every lower slot lands inside the `[32..59]` bake clock, which would be a worse
59//! (cross-role) collision than the documented `[61..62]` overlap.
60
61use crate::NQuin;
62
63// ════════════════════════════════════════════════════════════════════════════════
64// predicate field
65// ════════════════════════════════════════════════════════════════════════════════
66pub const OPCODE_MASK: u64 = 0xFF;
67pub const DEFEATER_BIT: u64 = 1u64 << 63;
68pub const PATH_MASK: u64 = 0x7FFF_FFFF_FFFF_FF00;
69
70#[inline]
71/// Extracts the u8 opcode from a predicate.
72pub const fn opcode(predicate: u64) -> u8 {
73 (predicate & OPCODE_MASK) as u8
74}
75#[inline]
76/// Extracts the property-path bits.
77pub const fn path_bits(predicate: u64) -> u64 {
78 predicate & PATH_MASK
79}
80#[inline]
81/// `true` when the defeater bit is set.
82pub const fn is_defeater(predicate: u64) -> bool {
83 predicate & DEFEATER_BIT != 0
84}
85/// Canonical norm-predicate packing — MUST equal `deontic::compile_norm_quin`.
86#[inline]
87pub const fn pack_predicate(opcode: u8, path_hash: u64, defeater: bool) -> u64 {
88 let d = if defeater { DEFEATER_BIT } else { 0 };
89 d | ((path_hash << 8) & PATH_MASK) | (opcode as u64)
90}
91
92// ════════════════════════════════════════════════════════════════════════════════
93// object field — inline literal datatype tags (canonical in `resolver`)
94// ════════════════════════════════════════════════════════════════════════════════
95pub use crate::resolver::{
96 INLINE_TAG_BOOLEAN, INLINE_TAG_DECIMAL, INLINE_TAG_FLOAT, INLINE_TAG_INTEGER, INLINE_TAG_MASK,
97 INLINE_VALUE_MASK, MSB_FLAG,
98};
99/// Blob/byte-offset pointer tag (canonical in `dicom`).
100pub const INLINE_TAG_BLOB: u64 = 0b100u64 << 60;
101
102/// The 3-bit inline datatype tag of an object value (only meaningful when MSB clear).
103#[inline]
104pub const fn object_tag(object: u64) -> u64 {
105 object & INLINE_TAG_MASK
106}
107/// Pack an f32 into an object field with the canonical FLOAT tag.
108#[inline]
109pub fn pack_float_object(f: f32) -> u64 {
110 INLINE_TAG_FLOAT | (f.to_bits() as u64 & INLINE_VALUE_MASK)
111}
112/// Recover an f32 from a FLOAT-tagged object field.
113#[inline]
114pub fn unpack_float_object(object: u64) -> f32 {
115 f32::from_bits((object & INLINE_VALUE_MASK) as u32)
116}
117
118// ════════════════════════════════════════════════════════════════════════════════
119// metadata field
120// ════════════════════════════════════════════════════════════════════════════════
121/// Low-32 payload mask: expiry | f32 truth-degree | 32-bit timestamp (typed).
122pub const LOW32_MASK: u64 = 0xFFFF_FFFF;
123
124#[inline]
125/// Extracts the expiry epoch.
126pub const fn expiry(metadata: u64) -> u32 {
127 (metadata & LOW32_MASK) as u32
128}
129/// CANONICAL truth/belief/confidence/fuzzy degree (IEEE-754 f32 in the low 32 bits).
130#[inline]
131pub fn truth_degree(metadata: u64) -> f32 {
132 f32::from_bits((metadata & LOW32_MASK) as u32)
133}
134#[inline]
135/// Packs a truth degree into metadata.
136pub fn with_truth_degree(d: f32) -> u64 {
137 let d = if d.is_finite() { d } else { 0.0 };
138 d.to_bits() as u64
139}
140#[inline]
141/// Extracts the Lamport timestamp.
142pub const fn timestamp(metadata: u64) -> u64 {
143 metadata
144}
145
146// ── high-overlay metadata fields (role-keyed; see module header) ──
147/// quin-type nibble `[60..63]` (general typing). Its low two bits `[61..62]` are
148/// reused as the permissive-routing lane on routed quins — typed vs routed are
149/// exclusive roles. NOT relocated lower: every lower slot collides with the
150/// `[32..59]` tensor-bake clock (a worse, cross-role collision).
151pub const QUIN_TYPE_SHIFT: u32 = 60;
152pub const QUIN_TYPE_MASK: u64 = 0xFu64 << QUIN_TYPE_SHIFT;
153/// ODRL sensitivity tier `[56..59]` (only on access-controlled quins).
154pub const SENSITIVITY_SHIFT: u32 = 56;
155pub const SENSITIVITY_MASK: u64 = 0xFu64 << SENSITIVITY_SHIFT;
156/// Permissive-routing lane `[61..62]` (only on routed quins; shares bits with the
157/// quin-type nibble by role-exclusivity).
158pub const ROUTING_LANE_SHIFT: u32 = 61;
159pub const ROUTING_LANE_MASK: u64 = 0b11u64 << ROUTING_LANE_SHIFT;
160/// Tensor-bake `t` clock (only on Tensor10D ground-truth nodes). Matches
161/// `bake_pipeline`'s `(metadata >> 32) & 0x1FFF_FFFF`, i.e. bits `[32..60]` — it
162/// even grazes quin_type's bit 60, an existing tensor-only quirk. Documentary
163/// only; never asserted disjoint (its role excludes the others).
164pub const BAKE_CLOCK_MASK: u64 = 0x1FFF_FFFFu64 << 32;
165
166#[inline]
167/// Extracts the quin type tag.
168pub const fn quin_type(metadata: u64) -> u8 {
169 ((metadata >> QUIN_TYPE_SHIFT) & 0xF) as u8
170}
171#[inline]
172/// Sets the quin type tag.
173pub const fn with_quin_type(metadata: u64, ty: u8) -> u64 {
174 (metadata & !QUIN_TYPE_MASK) | (((ty as u64) & 0xF) << QUIN_TYPE_SHIFT)
175}
176
177// ── per-modality flag bits [50..59] (each set only on its OWN modality's quins) ──
178// These are mutually exclusive by quin type (a dialectical-synthesis quin is never
179// also an argumentation node), so they may share bit positions with the ODRL
180// sensitivity tier [56..59] WITHOUT a real same-quin collision. They are pairwise
181// distinct (enforced) and disjoint from routing/quin_type (enforced).
182pub const STABILIZATION_BIT: u64 = 1u64 << 50;
183pub const FEEDBACK_BIT: u64 = 1u64 << 51;
184pub const CONTROL_BIT: u64 = 1u64 << 52;
185pub const DEFENSE_BIT: u64 = 1u64 << 53;
186pub const ATTACK_BIT: u64 = 1u64 << 54;
187pub const ARGUMENT_BIT: u64 = 1u64 << 55;
188pub const COUNTERFACTUAL_BIT: u64 = 1u64 << 56;
189pub const DO_INTERVENTION_BIT: u64 = 1u64 << 57;
190pub const SYNTHESIZED_BIT: u64 = 1u64 << 58;
191pub const CONSUMED_BIT: u64 = 1u64 << 59;
192
193// ════════════════════════════════════════════════════════════════════════════════
194// parity (canonical 5-field XOR over subject ^ predicate ^ object ^ context ^ metadata)
195// ════════════════════════════════════════════════════════════════════════════════
196#[inline]
197/// Computes the canonical 5-field parity fold (`subject ^ predicate ^ object ^ context ^ metadata`).
198pub const fn parity(
199 subject: u64,
200 predicate: u64,
201 object: u64,
202 context: u64,
203 metadata: u64,
204) -> u64 {
205 subject ^ predicate ^ object ^ context ^ metadata
206}
207#[inline]
208/// Sets the canonical 5-field parity field on `q`.
209pub fn sealed(mut q: NQuin) -> NQuin {
210 q.parity = parity(q.subject, q.predicate, q.object, q.context, q.metadata);
211 q
212}
213#[inline]
214/// `true` when the canonical 5-field parity fold is consistent.
215pub fn parity_valid(q: &NQuin) -> bool {
216 q.parity == parity(q.subject, q.predicate, q.object, q.context, q.metadata)
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 #[test]
224 fn predicate_regions_do_not_collide() {
225 assert_eq!(OPCODE_MASK & PATH_MASK, 0);
226 assert_eq!(OPCODE_MASK & DEFEATER_BIT, 0);
227 assert_eq!(PATH_MASK & DEFEATER_BIT, 0);
228 assert_eq!(OPCODE_MASK | PATH_MASK | DEFEATER_BIT, u64::MAX);
229 }
230
231 #[test]
232 fn object_datatype_tags_are_distinct() {
233 let tags = [
234 INLINE_TAG_INTEGER,
235 INLINE_TAG_DECIMAL,
236 INLINE_TAG_BOOLEAN,
237 INLINE_TAG_BLOB,
238 INLINE_TAG_FLOAT,
239 ];
240 for (i, &a) in tags.iter().enumerate() {
241 assert_eq!(
242 a & !INLINE_TAG_MASK,
243 0,
244 "tag {i} outside the [60..62] tag region"
245 );
246 for &b in &tags[i + 1..] {
247 assert_ne!(a, b, "two object datatype tags collide");
248 }
249 }
250 // value region is disjoint from the tag + MSB regions.
251 assert_eq!(INLINE_VALUE_MASK & INLINE_TAG_MASK, 0);
252 assert_eq!(INLINE_VALUE_MASK & MSB_FLAG, 0);
253 }
254
255 #[test]
256 fn low32_payload_is_disjoint_from_every_high_overlay() {
257 // The ONE always-true metadata invariant (see module header): the low-32
258 // payload (degree/expiry/timestamp/packed-moments) never overlaps any high
259 // overlay, so it can't silently corrupt a type / flag / sensitivity / clock.
260 let high = QUIN_TYPE_MASK | ROUTING_LANE_MASK | SENSITIVITY_MASK | BAKE_CLOCK_MASK;
261 assert_eq!(
262 high & LOW32_MASK,
263 0,
264 "a high overlay reaches into the low-32 payload"
265 );
266 // Routing is a sub-lane of the quin-type nibble (documented role-exclusive overlap).
267 assert_eq!(
268 ROUTING_LANE_MASK & QUIN_TYPE_MASK,
269 ROUTING_LANE_MASK,
270 "routing lane must sit inside the quin-type nibble [60..63]"
271 );
272 }
273
274 #[test]
275 fn modality_flag_bits_are_pairwise_distinct() {
276 let flags = [
277 COUNTERFACTUAL_BIT,
278 DO_INTERVENTION_BIT,
279 SYNTHESIZED_BIT,
280 CONSUMED_BIT,
281 STABILIZATION_BIT,
282 FEEDBACK_BIT,
283 CONTROL_BIT,
284 DEFENSE_BIT,
285 ATTACK_BIT,
286 ARGUMENT_BIT,
287 ];
288 for (i, &a) in flags.iter().enumerate() {
289 assert_eq!(a.count_ones(), 1, "flag {i} is not a single bit");
290 for &b in &flags[i + 1..] {
291 assert_ne!(a, b, "two modality flag bits collide");
292 }
293 }
294 // Flags are disjoint from the general fields that co-exist on any quin and
295 // from the typed payload. (They MAY share bits with the ODRL sensitivity
296 // tier [56..59] — that is a quin-type-exclusive overlap, not a same-quin
297 // collision, and is documented in the module header.)
298 let all_flags = flags.iter().fold(0u64, |acc, &f| acc | f);
299 assert_eq!(all_flags & ROUTING_LANE_MASK, 0, "a flag overlaps routing");
300 assert_eq!(all_flags & QUIN_TYPE_MASK, 0, "a flag overlaps quin_type");
301 assert_eq!(
302 all_flags & LOW32_MASK,
303 0,
304 "a flag overlaps the low-32 payload"
305 );
306 }
307
308 #[test]
309 fn predicate_and_degree_round_trip() {
310 let path = crate::q_hash("q42:disclose");
311 let p = pack_predicate(0x12, path, true);
312 assert_eq!(opcode(p), 0x12);
313 assert!(is_defeater(p));
314 for d in [0.0f32, 0.25, 0.8, 1.0] {
315 assert!((truth_degree(with_truth_degree(d)) - d).abs() < 1e-6);
316 }
317 assert!((unpack_float_object(pack_float_object(3.5)) - 3.5).abs() < 1e-6);
318 assert_eq!(object_tag(pack_float_object(3.5)), INLINE_TAG_FLOAT);
319 // quin_type round-trips and leaves the low-32 payload untouched (the
320 // always-true invariant). It deliberately overlays routing [61..62] — that
321 // overlap is role-exclusive, not a bug, so we only check payload safety.
322 let m = with_quin_type(12345, 0b1010);
323 assert_eq!(quin_type(m), 0b1010);
324 assert_eq!(
325 m & LOW32_MASK,
326 12345,
327 "quin_type must not disturb the low-32 payload"
328 );
329 }
330
331 #[test]
332 fn matches_deontic_packing() {
333 use crate::modalities::logic::deontic::{compile_norm_quin, OP_FORBID, OP_PERMIT};
334 let path = crate::q_hash("q42:x");
335 let norm = compile_norm_quin(1, OP_FORBID, path, 2, 3, 0, false);
336 assert_eq!(norm.predicate, pack_predicate(OP_FORBID, path, false));
337 let defeater = compile_norm_quin(1, OP_PERMIT, path, 2, 3, 0, true);
338 assert!(is_defeater(defeater.predicate));
339 }
340
341 #[test]
342 fn parity_enforces_canonical_five_field_xor() {
343 let q = sealed(NQuin {
344 subject: 7,
345 predicate: 8,
346 object: 9,
347 context: 10,
348 metadata: QUIN_TYPE_MASK | ROUTING_LANE_MASK | 999,
349 parity: 0,
350 });
351 assert!(parity_valid(&q));
352 assert!(q.verify_ecc_parity());
353 assert_eq!(
354 q.parity,
355 parity(q.subject, q.predicate, q.object, q.context, q.metadata)
356 );
357 let mut q2 = q;
358 q2.metadata ^= 1;
359 assert!(
360 !parity_valid(&q2),
361 "canonical 5-field parity must detect unsealed metadata mutations"
362 );
363 }
364}