Skip to main content

qualia_core_db/topology/
geometry_view.rs

1//! Zero-copy host geometry complex view (`PoetGeometryView`) harbouring $M$ graphs.
2//!
3//! Tier-1 Zero-Heap (`AGENTS.md` §0 & §0-A): inspects cellular counts ($N_0 \dots N_3$),
4//! resolves any of the $M$ harboured graphs in $O(1)$, and executes $O(1)$ cross-graph
5//! functorial hops (`hop_via_cell_anchor`) across shared geometric $k$-cells or `NQuin` hashes.
6
7use crate::topology::csr_view::{slice_pod, HarbouredCsrView};
8use crate::topology::header::{
9    AnchorDomain, GraphEmbedRole, HarbouredGraphHeader, PoetGeometryHeader, TopologyError,
10};
11
12/// Zero-copy view over a `GTOP` Geometry-Topology Complex segment harbouring $M$ graphs.
13#[derive(Copy, Clone, Debug, PartialEq, Eq)]
14pub struct PoetGeometryView<'a> {
15    segment: &'a [u8],
16    header: &'a PoetGeometryHeader,
17    graph_headers: &'a [HarbouredGraphHeader],
18}
19
20impl<'a> PoetGeometryView<'a> {
21    /// Construct a `PoetGeometryView` over a 64-byte-aligned `GTOP` segment buffer.
22    pub fn from_segment_bytes(segment: &'a [u8]) -> Result<Self, TopologyError> {
23        let hdr_size = core::mem::size_of::<PoetGeometryHeader>();
24        if segment.len() < hdr_size {
25            return Err(TopologyError::BufferTooSmall);
26        }
27        let header: &'a PoetGeometryHeader = bytemuck::try_from_bytes(&segment[..hdr_size])
28            .map_err(|_| TopologyError::UnalignedBuffer)?;
29
30        if header.complex_kind != 0 && header.complex_kind_enum().is_none() {
31            return Err(TopologyError::InvalidComplexKind(header.complex_kind));
32        }
33
34        let count = header.harboured_graph_count as usize;
35        let graph_headers =
36            slice_pod::<HarbouredGraphHeader>(segment, header.graph_dir_offset, count)?;
37
38        Ok(Self {
39            segment,
40            header,
41            graph_headers,
42        })
43    }
44
45    #[inline]
46    pub const fn segment(&self) -> &'a [u8] {
47        self.segment
48    }
49
50    #[inline]
51    pub const fn header(&self) -> &'a PoetGeometryHeader {
52        self.header
53    }
54
55    #[inline]
56    pub const fn graph_headers(&self) -> &'a [HarbouredGraphHeader] {
57        self.graph_headers
58    }
59
60    #[inline]
61    pub const fn harboured_graph_count(&self) -> usize {
62        self.graph_headers.len()
63    }
64
65    /// Resolve the currently active harboured graph (`header.active_graph_slot`) in $O(1)$.
66    #[inline]
67    pub fn active_graph(&self) -> Result<HarbouredCsrView<'a>, TopologyError> {
68        self.graph_at_slot(self.header.active_graph_slot)
69    }
70
71    /// Resolve the harboured graph at `slot` ($m \in [0, M)$) in $O(1)$.
72    #[inline]
73    pub fn graph_at_slot(&self, slot: u16) -> Result<HarbouredCsrView<'a>, TopologyError> {
74        let gh =
75            self.graph_headers
76                .get(slot as usize)
77                .ok_or(TopologyError::GraphSlotOutOfRange {
78                    slot,
79                    count: self.header.harboured_graph_count,
80                })?;
81        HarbouredCsrView::from_segment_bytes(self.segment, gh)
82    }
83
84    /// Resolve a harboured graph by its 64-bit `graph_id` (`q_hash`), returning `(slot, view)`.
85    pub fn graph_by_id(
86        &self,
87        graph_id: u64,
88    ) -> Result<(u16, HarbouredCsrView<'a>), TopologyError> {
89        let mut idx = 0usize;
90        while idx < self.graph_headers.len() {
91            let gh = &self.graph_headers[idx];
92            if gh.graph_id == graph_id {
93                let view = HarbouredCsrView::from_segment_bytes(self.segment, gh)?;
94                return Ok((idx as u16, view));
95            }
96            idx += 1;
97        }
98        Err(TopologyError::GraphSlotOutOfRange {
99            slot: u16::MAX,
100            count: self.header.harboured_graph_count,
101        })
102    }
103
104    /// Resolve the first harboured graph matching `role`, returning `(slot, view)`.
105    pub fn first_graph_by_role(
106        &self,
107        role: GraphEmbedRole,
108    ) -> Result<(u16, HarbouredCsrView<'a>), TopologyError> {
109        let role_u8 = role as u8;
110        let mut idx = 0usize;
111        while idx < self.graph_headers.len() {
112            let gh = &self.graph_headers[idx];
113            if gh.embed_role == role_u8 {
114                let view = HarbouredCsrView::from_segment_bytes(self.segment, gh)?;
115                return Ok((idx as u16, view));
116            }
117            idx += 1;
118        }
119        Err(TopologyError::GraphSlotOutOfRange {
120            slot: u16::MAX,
121            count: self.header.harboured_graph_count,
122        })
123    }
124
125    /// Functorial cross-graph hop: reads the `CellAnchor` of `from_vertex` in `from_slot`
126    /// and collects all vertices in `to_slot` sharing the same `(anchor_domain, cell_index)`
127    /// (or matching `entity_hash` when `anchor_domain == AnchorDomain::SemanticQuin`).
128    pub fn hop_via_cell_anchor(
129        &self,
130        from_slot: u16,
131        from_vertex: u32,
132        to_slot: u16,
133        out_vertices: &mut [u32],
134    ) -> Result<usize, TopologyError> {
135        let from_graph = self.graph_at_slot(from_slot)?;
136        let to_graph = self.graph_at_slot(to_slot)?;
137        let src_anchor = from_graph.cell_anchor(from_vertex)?;
138
139        let domain = src_anchor
140            .domain()
141            .ok_or(TopologyError::CellOutOfRange {
142                domain: src_anchor.anchor_domain,
143                index: src_anchor.cell_index,
144                count: 0,
145            })?;
146
147        if domain == AnchorDomain::SemanticQuin {
148            if src_anchor.entity_hash == 0 {
149                return Ok(to_graph.find_vertices_by_cell(
150                    domain,
151                    src_anchor.cell_index,
152                    out_vertices,
153                ));
154            }
155            return Ok(collect_by_entity_hash(
156                to_graph.anchors(),
157                src_anchor.entity_hash,
158                out_vertices,
159            ));
160        }
161
162        let written =
163            to_graph.find_vertices_by_cell(domain, src_anchor.cell_index, out_vertices);
164        if written == 0 && src_anchor.entity_hash != 0 {
165            return Ok(collect_by_entity_hash(
166                to_graph.anchors(),
167                src_anchor.entity_hash,
168                out_vertices,
169            ));
170        }
171        Ok(written)
172    }
173}
174
175#[inline]
176fn collect_by_entity_hash(
177    anchors: &[crate::topology::header::CellAnchor],
178    entity_hash: u64,
179    out_vertices: &mut [u32],
180) -> usize {
181    let mut written = 0usize;
182    let mut v = 0usize;
183    while v < anchors.len() {
184        if anchors[v].entity_hash == entity_hash {
185            if written >= out_vertices.len() {
186                break;
187            }
188            out_vertices[written] = v as u32;
189            written += 1;
190        }
191        v += 1;
192    }
193    written
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::topology::header::{
200        CellAnchor, GeometryComplexKind, GraphMorphology, TopologyInvariants,
201    };
202
203    #[repr(C, align(64))]
204    struct AlignedSegment([u8; 512]);
205
206    #[test]
207    fn geometry_view_cross_graph_hop_via_cell_anchor() {
208        let mut seg = AlignedSegment([0u8; 512]);
209
210        // Layout in 512B segment:
211        // [0..64]:    PoetGeometryHeader
212        // [64..128]:  HarbouredGraphHeader[0] (PoincareDual on Cell2Face)
213        // [128..192]: HarbouredGraphHeader[1] (DeonticGovernance on Cell2Face)
214        // [192..224]: Graph 0 anchors (2 * 16B = 32B)
215        // [224..256]: Graph 1 anchors (2 * 16B = 32B)
216        // [256..320]: Shared CSR/CSC arrays for 2 vertices, 1 edge (0 -> 1)
217        let geom_hdr = PoetGeometryHeader {
218            geometry_id: 0xABCD,
219            construct_schema_hash: 0x1234,
220            manifold_id: 1,
221            cell_0_count: 4,
222            cell_1_count: 5,
223            cell_2_count: 2,
224            cell_3_count: 0,
225            geometry_payload_offset: 0,
226            ddg_operators_offset: 0,
227            graph_dir_offset: 64,
228            harboured_graph_count: 2,
229            active_graph_slot: 0,
230            euler_characteristic: 1,
231            complex_kind: GeometryComplexKind::SurfaceManifold2D as u8,
232            metric_kind: 0,
233            ambient_dim: 3,
234            intrinsic_dim: 2,
235            crc32c: 0,
236        };
237        let g0 = HarbouredGraphHeader {
238            graph_id: 10,
239            parent_geometry_id: 0xABCD,
240            anchor_table_offset: 192,
241            csr_row_ptr_offset: 256,
242            csr_col_idx_offset: 268,
243            edge_anchor_offset: 272,
244            csc_col_ptr_offset: 276,
245            csc_row_idx_offset: 288,
246            edge_weight_offset: 0,
247            vertex_count: 2,
248            edge_count: 1,
249            context_and_state_mask: 0,
250            embed_role: GraphEmbedRole::PoincareDual as u8,
251            morphology: GraphMorphology::SymmetricGraph as u8,
252            invariants: TopologyInvariants::EMPTY,
253            crc32c: 0,
254        };
255        let mut g1 = g0;
256        g1.graph_id = 20;
257        g1.anchor_table_offset = 224;
258        g1.embed_role = GraphEmbedRole::DeonticGovernance as u8;
259
260        let g0_anchors = [
261            CellAnchor {
262                entity_hash: 0,
263                cell_index: 42,
264                anchor_domain: AnchorDomain::Cell2Face as u8,
265                orientation_sign: 1,
266                material_or_stratum: 0,
267            },
268            CellAnchor {
269                entity_hash: 0,
270                cell_index: 43,
271                anchor_domain: AnchorDomain::Cell2Face as u8,
272                orientation_sign: 1,
273                material_or_stratum: 0,
274            },
275        ];
276        let g1_anchors = [
277            CellAnchor {
278                entity_hash: 999,
279                cell_index: 43,
280                anchor_domain: AnchorDomain::Cell2Face as u8,
281                orientation_sign: 1,
282                material_or_stratum: 1,
283            },
284            CellAnchor {
285                entity_hash: 888,
286                cell_index: 42,
287                anchor_domain: AnchorDomain::Cell2Face as u8,
288                orientation_sign: 1,
289                material_or_stratum: 1,
290            },
291        ];
292        let row_ptr = [0u32, 1, 1];
293        let col_idx = [1u32];
294        let edge_anc = [0u32];
295        let csc_ptr = [0u32, 0, 1];
296        let csc_row = [0u32];
297
298        seg.0[0..64].copy_from_slice(bytemuck::bytes_of(&geom_hdr));
299        seg.0[64..128].copy_from_slice(bytemuck::bytes_of(&g0));
300        seg.0[128..192].copy_from_slice(bytemuck::bytes_of(&g1));
301        seg.0[192..224].copy_from_slice(bytemuck::cast_slice(&g0_anchors));
302        seg.0[224..256].copy_from_slice(bytemuck::cast_slice(&g1_anchors));
303        seg.0[256..268].copy_from_slice(bytemuck::cast_slice(&row_ptr));
304        seg.0[268..272].copy_from_slice(bytemuck::cast_slice(&col_idx));
305        seg.0[272..276].copy_from_slice(bytemuck::cast_slice(&edge_anc));
306        seg.0[276..288].copy_from_slice(bytemuck::cast_slice(&csc_ptr));
307        seg.0[288..292].copy_from_slice(bytemuck::cast_slice(&csc_row));
308
309        let view = PoetGeometryView::from_segment_bytes(&seg.0).unwrap();
310        assert_eq!(view.harboured_graph_count(), 2);
311        assert_eq!(view.active_graph().unwrap().header().graph_id, 10);
312        assert_eq!(view.graph_by_id(20).unwrap().0, 1);
313        assert_eq!(
314            view.first_graph_by_role(GraphEmbedRole::DeonticGovernance)
315                .unwrap()
316                .0,
317            1
318        );
319
320        let mut out = [0u32; 4];
321        let n = view.hop_via_cell_anchor(0, 0, 1, &mut out).unwrap();
322        assert_eq!(n, 1);
323        assert_eq!(out[0], 1); // vertex 0 in g0 (Cell2Face #42) -> vertex 1 in g1 (Cell2Face #42)
324    }
325}